blob: bc1bbcb1fdad7a5a093af798403f17e5e785a426 [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"
Simon Pilgrim0efed322018-02-18 00:01:36 +000021#include "llvm/ADT/StringRef.h"
Charles Saternosb040fcc2018-02-19 15:14:50 +000022#include "llvm/ADT/StringSet.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");
Eugene Leviant19e23872018-03-12 10:30:50 +000064STATISTIC(NumImportedGlobalVars, "Number of global variables imported");
Teresa Johnson6c475a72017-01-05 21:34:18 +000065STATISTIC(NumImportedModules, "Number of modules imported from");
66STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
67STATISTIC(NumLiveSymbols, "Number of live symbols in index");
Teresa Johnsond29478f2016-03-27 15:27:30 +000068
Teresa Johnson39303612015-11-24 22:55:46 +000069/// Limit on instruction count of imported functions.
70static cl::opt<unsigned> ImportInstrLimit(
71 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
72 cl::desc("Only import functions with less than N instructions"));
73
Teresa Johnson974706e2018-04-01 15:54:40 +000074static cl::opt<int> ImportCutoff(
75 "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
76 cl::desc("Only import first N functions if N>=0 (default -1)"));
77
Mehdi Amini40641742016-02-10 23:31:45 +000078static cl::opt<float>
79 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
80 cl::Hidden, cl::value_desc("x"),
81 cl::desc("As we import functions, multiply the "
82 "`import-instr-limit` threshold by this factor "
83 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000084
Piotr Padlewskid2869472016-09-30 03:01:17 +000085static cl::opt<float> ImportHotInstrFactor(
86 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
87 cl::value_desc("x"),
88 cl::desc("As we import functions called from hot callsite, multiply the "
89 "`import-instr-limit` threshold by this factor "
90 "before processing newly imported functions"));
91
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000092static cl::opt<float> ImportHotMultiplier(
Dehao Chen8260d662017-07-28 01:02:34 +000093 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000094 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
95
Dehao Chen64c46572017-07-07 21:01:00 +000096static cl::opt<float> ImportCriticalMultiplier(
97 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
98 cl::value_desc("x"),
99 cl::desc(
100 "Multiply the `import-instr-limit` threshold for critical callsites"));
101
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000102// FIXME: This multiplier was not really tuned up.
103static cl::opt<float> ImportColdMultiplier(
104 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
105 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +0000106
Teresa Johnsond29478f2016-03-27 15:27:30 +0000107static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
108 cl::desc("Print imported functions"));
109
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000110static cl::opt<bool> PrintImportFailures(
111 "print-import-failures", cl::init(false), cl::Hidden,
112 cl::desc("Print information for functions rejected for importing"));
113
Teresa Johnson6c475a72017-01-05 21:34:18 +0000114static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
115 cl::desc("Compute dead symbols"));
116
Piotr Padlewski3b776122016-07-08 23:01:49 +0000117static cl::opt<bool> EnableImportMetadata(
118 "enable-import-metadata", cl::init(
119#if !defined(NDEBUG)
120 true /*Enabled with asserts.*/
121#else
122 false
123#endif
124 ),
125 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
126
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000127/// Summary file to use for function importing when using -function-import from
128/// the command line.
129static cl::opt<std::string>
130 SummaryFile("summary-file",
131 cl::desc("The summary file to use for function importing."));
132
Teresa Johnson81bbf742017-12-16 00:18:12 +0000133/// Used when testing importing from distributed indexes via opt
134// -function-import.
135static cl::opt<bool>
136 ImportAllIndex("import-all-index",
137 cl::desc("Import all external functions in index."));
138
Mehdi Amini42418ab2015-11-24 06:07:49 +0000139// Load lazily a module from \p FileName in \p Context.
140static std::unique_ptr<Module> loadFile(const std::string &FileName,
141 LLVMContext &Context) {
142 SMDiagnostic Err;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000143 LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000144 // Metadata isn't loaded until functions are imported, to minimize
145 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000146 std::unique_ptr<Module> Result =
147 getLazyIRFileModule(FileName, Err, Context,
148 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000149 if (!Result) {
150 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000151 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000152 }
153
Mehdi Amini42418ab2015-11-24 06:07:49 +0000154 return Result;
155}
156
Mehdi Amini01e32132016-03-26 05:40:34 +0000157/// Given a list of possible callee implementation for a call site, select one
158/// that fits the \p Threshold.
159///
160/// FIXME: select "best" instead of first that fits. But what is "best"?
161/// - The smallest: more likely to be inlined.
162/// - The one with the least outgoing edges (already well optimized).
163/// - One from a module already being imported from in order to reduce the
164/// number of source modules parsed/linked.
165/// - One that has PGO data attached.
166/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000167static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000168selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000169 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000170 unsigned Threshold, StringRef CallerModulePath,
171 FunctionImporter::ImportFailureReason &Reason,
172 GlobalValue::GUID GUID) {
173 Reason = FunctionImporter::ImportFailureReason::None;
Mehdi Amini01e32132016-03-26 05:40:34 +0000174 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000175 CalleeSummaryList,
176 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
177 auto *GVSummary = SummaryPtr.get();
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000178 if (!Index.isGlobalValueLive(GVSummary)) {
179 Reason = FunctionImporter::ImportFailureReason::NotLive;
George Rimareaf51722018-01-29 08:03:30 +0000180 return false;
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000181 }
George Rimareaf51722018-01-29 08:03:30 +0000182
Teresa Johnson73305f82017-08-19 18:04:25 +0000183 // For SamplePGO, in computeImportForFunction the OriginalId
184 // may have been used to locate the callee summary list (See
185 // comment there).
186 // The mapping from OriginalId to GUID may return a GUID
187 // that corresponds to a static variable. Filter it out here.
188 // This can happen when
189 // 1) There is a call to a library function which is not defined
190 // in the index.
191 // 2) There is a static variable with the OriginalGUID identical
192 // to the GUID of the library function in 1);
193 // When this happens, the logic for SamplePGO kicks in and
194 // the static variable in 2) will be found, which needs to be
195 // filtered out.
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000196 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) {
197 Reason = FunctionImporter::ImportFailureReason::GlobalVar;
Teresa Johnson73305f82017-08-19 18:04:25 +0000198 return false;
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000199 }
200 if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) {
201 Reason = FunctionImporter::ImportFailureReason::InterposableLinkage;
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000202 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000203 return false;
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000204 }
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000205
Teresa Johnson81bbf742017-12-16 00:18:12 +0000206 auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000207
Teresa Johnson83aaf352017-01-12 22:04:45 +0000208 // If this is a local function, make sure we import the copy
209 // in the caller's module. The only time a local function can
210 // share an entry in the index is if there is a local with the same name
211 // in another module that had the same source file name (in a different
212 // directory), where each was compiled in their own directory so there
213 // was not distinguishing path.
214 // However, do the import from another module if there is only one
215 // entry in the list - in that case this must be a reference due
216 // to indirect call profile data, since a function pointer can point to
217 // a local in another module.
218 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
219 CalleeSummaryList.size() > 1 &&
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000220 Summary->modulePath() != CallerModulePath) {
221 Reason =
222 FunctionImporter::ImportFailureReason::LocalLinkageNotInModule;
Teresa Johnson83aaf352017-01-12 22:04:45 +0000223 return false;
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000224 }
Teresa Johnson83aaf352017-01-12 22:04:45 +0000225
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000226 if (Summary->instCount() > Threshold) {
227 Reason = FunctionImporter::ImportFailureReason::TooLarge;
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000228 return false;
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000229 }
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000230
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000231 if (Summary->notEligibleToImport()) {
232 Reason = FunctionImporter::ImportFailureReason::NotEligible;
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000233 return false;
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000234 }
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000235
Mehdi Amini01e32132016-03-26 05:40:34 +0000236 return true;
237 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000238 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000239 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000240
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000241 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000242}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000243
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000244namespace {
245
Teresa Johnson475b51a2016-12-15 20:48:19 +0000246using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
247 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000248
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000249} // anonymous namespace
250
Teresa Johnson19580832017-09-13 15:16:38 +0000251static ValueInfo
252updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
253 if (!VI.getSummaryList().empty())
254 return VI;
255 // For SamplePGO, the indirect call targets for local functions will
256 // have its original name annotated in profile. We try to find the
257 // corresponding PGOFuncName as the GUID.
258 // FIXME: Consider updating the edges in the graph after building
259 // it, rather than needing to perform this mapping on each walk.
260 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
261 if (GUID == 0)
Eugene Leviant28d8a492018-01-22 13:35:40 +0000262 return ValueInfo();
Teresa Johnson19580832017-09-13 15:16:38 +0000263 return Index.getValueInfo(GUID);
264}
265
Eugene Leviant19e23872018-03-12 10:30:50 +0000266static void computeImportForReferencedGlobals(
267 const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries,
268 FunctionImporter::ImportMapTy &ImportList,
269 StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
270 for (auto &VI : Summary.refs()) {
271 if (DefinedGVSummaries.count(VI.getGUID())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000272 LLVM_DEBUG(
273 dbgs() << "Ref ignored! Target already in destination module.\n");
Eugene Leviant19e23872018-03-12 10:30:50 +0000274 continue;
275 }
276
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000277 LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
Eugene Leviant19e23872018-03-12 10:30:50 +0000278
279 for (auto &RefSummary : VI.getSummaryList())
280 if (RefSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind &&
281 // Don't try to import regular LTO summaries added to dummy module.
282 !RefSummary->modulePath().empty() &&
283 !GlobalValue::isInterposableLinkage(RefSummary->linkage()) &&
284 RefSummary->refs().empty()) {
Teresa Johnsond68935c2018-07-16 15:30:27 +0000285 ImportList[RefSummary->modulePath()].insert(VI.getGUID());
Eugene Leviant19e23872018-03-12 10:30:50 +0000286 if (ExportLists)
287 (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID());
288 break;
289 }
290 }
291}
292
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000293static const char *
294getFailureName(FunctionImporter::ImportFailureReason Reason) {
295 switch (Reason) {
296 case FunctionImporter::ImportFailureReason::None:
297 return "None";
298 case FunctionImporter::ImportFailureReason::GlobalVar:
299 return "GlobalVar";
300 case FunctionImporter::ImportFailureReason::NotLive:
301 return "NotLive";
302 case FunctionImporter::ImportFailureReason::TooLarge:
303 return "TooLarge";
304 case FunctionImporter::ImportFailureReason::InterposableLinkage:
305 return "InterposableLinkage";
306 case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
307 return "LocalLinkageNotInModule";
308 case FunctionImporter::ImportFailureReason::NotEligible:
309 return "NotEligible";
310 }
311 llvm_unreachable("invalid reason");
312}
313
Mehdi Amini01e32132016-03-26 05:40:34 +0000314/// Compute the list of functions to import for a given caller. Mark these
315/// imported functions and the symbols they reference in their source module as
316/// exported from their source module.
317static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000318 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000319 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000320 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000321 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsond68935c2018-07-16 15:30:27 +0000322 StringMap<FunctionImporter::ExportSetTy> *ExportLists,
323 FunctionImporter::ImportThresholdsTy &ImportThresholds) {
Eugene Leviant19e23872018-03-12 10:30:50 +0000324 computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList,
325 ExportLists);
Teresa Johnson974706e2018-04-01 15:54:40 +0000326 static int ImportCount = 0;
Mehdi Amini01e32132016-03-26 05:40:34 +0000327 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000328 ValueInfo VI = Edge.first;
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000329 LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
330 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000331
Teresa Johnson974706e2018-04-01 15:54:40 +0000332 if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000333 LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
334 << " reached.\n");
Teresa Johnson974706e2018-04-01 15:54:40 +0000335 continue;
336 }
337
Teresa Johnson19580832017-09-13 15:16:38 +0000338 VI = updateValueInfoForIndirectCalls(Index, VI);
339 if (!VI)
340 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000341
Peter Collingbourne9667b912017-05-04 18:03:25 +0000342 if (DefinedGVSummaries.count(VI.getGUID())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000343 LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000344 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000345 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000346
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000347 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
348 if (Hotness == CalleeInfo::HotnessType::Hot)
349 return ImportHotMultiplier;
350 if (Hotness == CalleeInfo::HotnessType::Cold)
351 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000352 if (Hotness == CalleeInfo::HotnessType::Critical)
353 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000354 return 1.0;
355 };
356
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000357 const auto NewThreshold =
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000358 Threshold * GetBonusMultiplier(Edge.second.getHotness());
Piotr Padlewskid2869472016-09-30 03:01:17 +0000359
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000360 auto IT = ImportThresholds.insert(std::make_pair(
361 VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
Teresa Johnsond68935c2018-07-16 15:30:27 +0000362 bool PreviouslyVisited = !IT.second;
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000363 auto &ProcessedThreshold = std::get<0>(IT.first->second);
364 auto &CalleeSummary = std::get<1>(IT.first->second);
365 auto &FailureInfo = std::get<2>(IT.first->second);
Teresa Johnsond68935c2018-07-16 15:30:27 +0000366
367 const FunctionSummary *ResolvedCalleeSummary = nullptr;
368 if (CalleeSummary) {
369 assert(PreviouslyVisited);
370 // Since the traversal of the call graph is DFS, we can revisit a function
371 // a second time with a higher threshold. In this case, it is added back
372 // to the worklist with the new threshold (so that its own callee chains
373 // can be considered with the higher threshold).
374 if (NewThreshold <= ProcessedThreshold) {
375 LLVM_DEBUG(
376 dbgs() << "ignored! Target was already imported with Threshold "
377 << ProcessedThreshold << "\n");
378 continue;
379 }
380 // Update with new larger threshold.
381 ProcessedThreshold = NewThreshold;
382 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
383 } else {
384 // If we already rejected importing a callee at the same or higher
385 // threshold, don't waste time calling selectCallee.
386 if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
387 LLVM_DEBUG(
388 dbgs() << "ignored! Target was already rejected with Threshold "
389 << ProcessedThreshold << "\n");
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000390 if (PrintImportFailures) {
391 assert(FailureInfo &&
392 "Expected FailureInfo for previously rejected candidate");
393 FailureInfo->Attempts++;
394 }
Teresa Johnsond68935c2018-07-16 15:30:27 +0000395 continue;
396 }
397
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000398 FunctionImporter::ImportFailureReason Reason;
Teresa Johnsond68935c2018-07-16 15:30:27 +0000399 CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000400 Summary.modulePath(), Reason, VI.getGUID());
Teresa Johnsond68935c2018-07-16 15:30:27 +0000401 if (!CalleeSummary) {
402 // Update with new larger threshold if this was a retry (otherwise
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000403 // we would have already inserted with NewThreshold above). Also
404 // update failure info if requested.
405 if (PreviouslyVisited) {
Teresa Johnsond68935c2018-07-16 15:30:27 +0000406 ProcessedThreshold = NewThreshold;
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000407 if (PrintImportFailures) {
408 assert(FailureInfo &&
409 "Expected FailureInfo for previously rejected candidate");
410 FailureInfo->Reason = Reason;
411 FailureInfo->Attempts++;
412 FailureInfo->MaxHotness =
413 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
414 }
415 } else if (PrintImportFailures) {
416 assert(!FailureInfo &&
417 "Expected no FailureInfo for newly rejected candidate");
418 FailureInfo = llvm::make_unique<FunctionImporter::ImportFailureInfo>(
419 VI, Edge.second.getHotness(), Reason, 1);
420 }
Teresa Johnsond68935c2018-07-16 15:30:27 +0000421 LLVM_DEBUG(
422 dbgs() << "ignored! No qualifying callee with summary found.\n");
423 continue;
424 }
425
426 // "Resolve" the summary
427 CalleeSummary = CalleeSummary->getBaseObject();
428 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
429
430 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
431 "selectCallee() didn't honor the threshold");
432
433 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
434 auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
435 // We previously decided to import this GUID definition if it was already
436 // inserted in the set of imports from the exporting module.
437 bool PreviouslyImported = !ILI.second;
438
439 // Make exports in the source module.
440 if (ExportLists) {
441 auto &ExportList = (*ExportLists)[ExportModulePath];
442 ExportList.insert(VI.getGUID());
443 if (!PreviouslyImported) {
444 // This is the first time this function was exported from its source
445 // module, so mark all functions and globals it references as exported
446 // to the outside if they are defined in the same source module.
447 // For efficiency, we unconditionally add all the referenced GUIDs
448 // to the ExportList for this module, and will prune out any not
449 // defined in the module later in a single pass.
450 for (auto &Edge : ResolvedCalleeSummary->calls()) {
451 auto CalleeGUID = Edge.first.getGUID();
452 ExportList.insert(CalleeGUID);
453 }
454 for (auto &Ref : ResolvedCalleeSummary->refs()) {
455 auto GUID = Ref.getGUID();
456 ExportList.insert(GUID);
457 }
458 }
459 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000460 }
David Blaikie2f0cc472017-07-27 15:09:06 +0000461
Piotr Padlewskid2869472016-09-30 03:01:17 +0000462 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
463 // Adjust the threshold for next level of imported functions.
464 // The threshold is different for hot callsites because we can then
465 // inline chains of hot calls.
466 if (IsHotCallsite)
467 return Threshold * ImportHotInstrFactor;
468 return Threshold * ImportInstrFactor;
469 };
470
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000471 bool IsHotCallsite =
472 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000473 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
474
Teresa Johnson974706e2018-04-01 15:54:40 +0000475 ImportCount++;
476
Mehdi Amini01e32132016-03-26 05:40:34 +0000477 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000478 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000479 }
480}
481
Mehdi Amini01e32132016-03-26 05:40:34 +0000482/// Given the list of globals defined in a module, compute the list of imports
483/// as well as the list of "exports", i.e. the list of symbols referenced from
484/// another module (that may require promotion).
485static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000486 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000487 StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000488 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000489 // Worklist contains the list of function imported in this module, for which
490 // we will analyse the callees and may import further down the callgraph.
491 SmallVector<EdgeInfo, 128> Worklist;
Teresa Johnsond68935c2018-07-16 15:30:27 +0000492 FunctionImporter::ImportThresholdsTy ImportThresholds;
Mehdi Amini01e32132016-03-26 05:40:34 +0000493
494 // Populate the worklist with the import for the functions in the current
495 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000496 for (auto &GVSummary : DefinedGVSummaries) {
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000497#ifndef NDEBUG
498 // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
499 // so this map look up (and possibly others) can be avoided.
500 auto VI = Index.getValueInfo(GVSummary.first);
501#endif
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000502 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000503 LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
Teresa Johnson6c475a72017-01-05 21:34:18 +0000504 continue;
505 }
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000506 auto *FuncSummary =
507 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000508 if (!FuncSummary)
509 // Skip import for global variables
510 continue;
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000511 LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000512 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000513 DefinedGVSummaries, Worklist, ImportList,
Teresa Johnsond68935c2018-07-16 15:30:27 +0000514 ExportLists, ImportThresholds);
Mehdi Amini01e32132016-03-26 05:40:34 +0000515 }
516
Piotr Padlewskid2869472016-09-30 03:01:17 +0000517 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000518 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000519 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000520 auto *Summary = std::get<0>(FuncInfo);
521 auto Threshold = std::get<1>(FuncInfo);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000522
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000523 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Teresa Johnsond68935c2018-07-16 15:30:27 +0000524 Worklist, ImportList, ExportLists,
525 ImportThresholds);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000526 }
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000527
528 // Print stats about functions considered but rejected for importing
529 // when requested.
530 if (PrintImportFailures) {
531 dbgs() << "Missed imports into module " << ModName << "\n";
532 for (auto &I : ImportThresholds) {
533 auto &ProcessedThreshold = std::get<0>(I.second);
534 auto &CalleeSummary = std::get<1>(I.second);
535 auto &FailureInfo = std::get<2>(I.second);
536 if (CalleeSummary)
537 continue; // We are going to import.
538 assert(FailureInfo);
539 FunctionSummary *FS = nullptr;
540 if (!FailureInfo->VI.getSummaryList().empty())
541 FS = dyn_cast<FunctionSummary>(
542 FailureInfo->VI.getSummaryList()[0]->getBaseObject());
543 dbgs() << FailureInfo->VI
544 << ": Reason = " << getFailureName(FailureInfo->Reason)
545 << ", Threshold = " << ProcessedThreshold
546 << ", Size = " << (FS ? (int)FS->instCount() : -1)
547 << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
548 << ", Attempts = " << FailureInfo->Attempts << "\n";
549 }
550 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000551}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000552
Eugene Leviant19e23872018-03-12 10:30:50 +0000553#ifndef NDEBUG
554static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
555 GlobalValue::GUID G) {
556 if (const auto &VI = Index.getValueInfo(G)) {
557 auto SL = VI.getSummaryList();
558 if (!SL.empty())
559 return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
560 }
561 return false;
562}
563
564static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
565
Eugene Leviant19e23872018-03-12 10:30:50 +0000566template <class T>
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000567static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
568 T &Cont) {
Eugene Leviant19e23872018-03-12 10:30:50 +0000569 unsigned NumGVS = 0;
570 for (auto &V : Cont)
571 if (isGlobalVarSummary(Index, getGUID(V)))
572 ++NumGVS;
573 return NumGVS;
574}
575#endif
576
Teresa Johnsonc86af332016-04-12 21:13:11 +0000577/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000578void llvm::ComputeCrossModuleImport(
579 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000580 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000581 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000582 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000583 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000584 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000585 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000586 LLVM_DEBUG(dbgs() << "Computing import for Module '"
587 << DefinedGVSummaries.first() << "'\n");
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000588 ComputeImportForModule(DefinedGVSummaries.second, Index,
589 DefinedGVSummaries.first(), ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000590 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000591 }
592
Teresa Johnsonedddca22016-12-16 04:11:51 +0000593 // When computing imports we added all GUIDs referenced by anything
594 // imported from the module to its ExportList. Now we prune each ExportList
595 // of any not defined in that module. This is more efficient than checking
596 // while computing imports because some of the summary lists may be long
597 // due to linkonce (comdat) copies.
598 for (auto &ELI : ExportLists) {
599 const auto &DefinedGVSummaries =
600 ModuleToDefinedGVSummaries.lookup(ELI.first());
601 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
602 if (!DefinedGVSummaries.count(*EI))
603 EI = ELI.second.erase(EI);
604 else
605 ++EI;
606 }
607 }
608
Mehdi Amini01e32132016-03-26 05:40:34 +0000609#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000610 LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
611 << " modules:\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000612 for (auto &ModuleImports : ImportLists) {
613 auto ModName = ModuleImports.first();
614 auto &Exports = ExportLists[ModName];
Eugene Leviant19e23872018-03-12 10:30:50 +0000615 unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000616 LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
617 << Exports.size() - NumGVS << " functions and " << NumGVS
618 << " vars. Imports from " << ModuleImports.second.size()
619 << " modules.\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000620 for (auto &Src : ModuleImports.second) {
621 auto SrcModName = Src.first();
Eugene Leviant19e23872018-03-12 10:30:50 +0000622 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000623 LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
624 << " functions imported from " << SrcModName << "\n");
625 LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
626 << " global vars imported from " << SrcModName << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000627 }
628 }
629#endif
630}
631
Teresa Johnson81bbf742017-12-16 00:18:12 +0000632#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000633static void dumpImportListForModule(const ModuleSummaryIndex &Index,
634 StringRef ModulePath,
Teresa Johnson81bbf742017-12-16 00:18:12 +0000635 FunctionImporter::ImportMapTy &ImportList) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000636 LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
637 << ImportList.size() << " modules.\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +0000638 for (auto &Src : ImportList) {
639 auto SrcModName = Src.first();
Eugene Leviant19e23872018-03-12 10:30:50 +0000640 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000641 LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
642 << " functions imported from " << SrcModName << "\n");
643 LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
644 << SrcModName << "\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +0000645 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000646}
Teresa Johnson69b2de82017-12-16 00:29:31 +0000647#endif
Teresa Johnson81bbf742017-12-16 00:18:12 +0000648
Teresa Johnsonc86af332016-04-12 21:13:11 +0000649/// Compute all the imports for the given module in the Index.
650void llvm::ComputeCrossModuleImportForModule(
651 StringRef ModulePath, const ModuleSummaryIndex &Index,
652 FunctionImporter::ImportMapTy &ImportList) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000653 // Collect the list of functions this module defines.
654 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000655 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000656 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000657
658 // Compute the import list for this module.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000659 LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnsoncb9a82f2018-08-17 16:53:47 +0000660 ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000661
662#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000663 dumpImportListForModule(Index, ModulePath, ImportList);
Teresa Johnson81bbf742017-12-16 00:18:12 +0000664#endif
665}
666
667// Mark all external summaries in Index for import into the given module.
668// Used for distributed builds using a distributed index.
669void llvm::ComputeCrossModuleImportForModuleFromIndex(
670 StringRef ModulePath, const ModuleSummaryIndex &Index,
671 FunctionImporter::ImportMapTy &ImportList) {
672 for (auto &GlobalList : Index) {
673 // Ignore entries for undefined references.
674 if (GlobalList.second.SummaryList.empty())
675 continue;
676
677 auto GUID = GlobalList.first;
678 assert(GlobalList.second.SummaryList.size() == 1 &&
679 "Expected individual combined index to have one summary per GUID");
680 auto &Summary = GlobalList.second.SummaryList[0];
681 // Skip the summaries for the importing module. These are included to
682 // e.g. record required linkage changes.
683 if (Summary->modulePath() == ModulePath)
684 continue;
Teresa Johnsond68935c2018-07-16 15:30:27 +0000685 // Add an entry to provoke importing by thinBackend.
686 ImportList[Summary->modulePath()].insert(GUID);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000687 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000688#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000689 dumpImportListForModule(Index, ModulePath, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000690#endif
691}
692
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000693void llvm::computeDeadSymbols(
694 ModuleSummaryIndex &Index,
George Rimareaf51722018-01-29 08:03:30 +0000695 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
696 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000697 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000698 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000699 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000700 if (GUIDPreservedSymbols.empty())
701 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000702 return;
703 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000704 SmallVector<ValueInfo, 128> Worklist;
705 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
706 for (auto GUID : GUIDPreservedSymbols) {
707 ValueInfo VI = Index.getValueInfo(GUID);
708 if (!VI)
709 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000710 for (auto &S : VI.getSummaryList())
711 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000712 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000713
Teresa Johnson6c475a72017-01-05 21:34:18 +0000714 // Add values flagged in the index as live roots to the worklist.
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000715 for (const auto &Entry : Index) {
716 auto VI = Index.getValueInfo(Entry);
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000717 for (auto &S : Entry.second.SummaryList)
718 if (S->isLive()) {
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000719 LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
720 Worklist.push_back(VI);
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000721 ++LiveSymbols;
722 break;
723 }
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000724 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000725
726 // Make value live and add it to the worklist if it was not live before.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000727 auto visit = [&](ValueInfo VI) {
Teresa Johnson19580832017-09-13 15:16:38 +0000728 // FIXME: If we knew which edges were created for indirect call profiles,
729 // we could skip them here. Any that are live should be reached via
730 // other edges, e.g. reference edges. Otherwise, using a profile collected
731 // on a slightly different binary might provoke preserving, importing
732 // and ultimately promoting calls to functions not linked into this
733 // binary, which increases the binary size unnecessarily. Note that
734 // if this code changes, the importer needs to change so that edges
735 // to functions marked dead are skipped.
736 VI = updateValueInfoForIndirectCalls(Index, VI);
737 if (!VI)
738 return;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000739 for (auto &S : VI.getSummaryList())
Teresa Johnsonf6251182017-09-20 17:09:47 +0000740 if (S->isLive())
741 return;
George Rimareaf51722018-01-29 08:03:30 +0000742
Vlad Tsyrklevichaab60002018-03-13 05:08:48 +0000743 // We only keep live symbols that are known to be non-prevailing if any are
744 // available_externally. Those symbols are discarded later in the
745 // EliminateAvailableExternally pass and setting them to not-live breaks
746 // downstreams users of liveness information (PR36483).
747 if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
748 bool AvailableExternally = false;
749 bool Interposable = false;
750 for (auto &S : VI.getSummaryList()) {
751 if (S->linkage() == GlobalValue::AvailableExternallyLinkage)
752 AvailableExternally = true;
753 else if (GlobalValue::isInterposableLinkage(S->linkage()))
754 Interposable = true;
755 }
756
757 if (!AvailableExternally)
758 return;
759
760 if (Interposable)
761 report_fatal_error("Interposable and available_externally symbol");
762 }
George Rimareaf51722018-01-29 08:03:30 +0000763
Teresa Johnsonf6251182017-09-20 17:09:47 +0000764 for (auto &S : VI.getSummaryList())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000765 S->setLive(true);
766 ++LiveSymbols;
767 Worklist.push_back(VI);
768 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000769
770 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000771 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000772 for (auto &Summary : VI.getSummaryList()) {
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000773 GlobalValueSummary *Base = Summary->getBaseObject();
George Rimareaf51722018-01-29 08:03:30 +0000774 // Set base value live in case it is an alias.
775 Base->setLive(true);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000776 for (auto Ref : Base->refs())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000777 visit(Ref);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000778 if (auto *FS = dyn_cast<FunctionSummary>(Base))
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000779 for (auto Call : FS->calls())
780 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000781 }
782 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000783 Index.setWithGlobalValueDeadStripping();
784
785 unsigned DeadSymbols = Index.size() - LiveSymbols;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000786 LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
787 << " symbols Dead \n");
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000788 NumDeadSymbols += DeadSymbols;
789 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000790}
791
Teresa Johnson84174c32016-05-10 13:48:23 +0000792/// Compute the set of summaries needed for a ThinLTO backend compilation of
793/// \p ModulePath.
794void llvm::gatherImportedSummariesForModule(
795 StringRef ModulePath,
796 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000797 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000798 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
799 // Include all summaries from the importing module.
800 ModuleToSummariesForIndex[ModulePath] =
801 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000802 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000803 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000804 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
805 const auto &DefinedGVSummaries =
806 ModuleToDefinedGVSummaries.lookup(ILI.first());
807 for (auto &GI : ILI.second) {
Teresa Johnsond68935c2018-07-16 15:30:27 +0000808 const auto &DS = DefinedGVSummaries.find(GI);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000809 assert(DS != DefinedGVSummaries.end() &&
810 "Expected a defined summary for imported global value");
Teresa Johnsond68935c2018-07-16 15:30:27 +0000811 SummariesForIndex[GI] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000812 }
813 }
814}
815
Teresa Johnson8570fe42016-05-10 15:54:09 +0000816/// Emit the files \p ModulePath will import from into \p OutputFilename.
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000817std::error_code llvm::EmitImportsFiles(
818 StringRef ModulePath, StringRef OutputFilename,
819 const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000820 std::error_code EC;
821 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
822 if (EC)
823 return EC;
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000824 for (auto &ILI : ModuleToSummariesForIndex)
825 // The ModuleToSummariesForIndex map includes an entry for the current
826 // Module (needed for writing out the index files). We don't want to
827 // include it in the imports file, however, so filter it out.
828 if (ILI.first != ModulePath)
829 ImportsOS << ILI.first << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000830 return std::error_code();
831}
832
Teresa Johnson5a95c472018-02-05 15:44:27 +0000833bool llvm::convertToDeclaration(GlobalValue &GV) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000834 LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
835 << "\n");
George Rimareaf51722018-01-29 08:03:30 +0000836 if (Function *F = dyn_cast<Function>(&GV)) {
837 F->deleteBody();
838 F->clearMetadata();
Peter Collingbourne78736692018-01-31 02:51:03 +0000839 F->setComdat(nullptr);
George Rimareaf51722018-01-29 08:03:30 +0000840 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
841 V->setInitializer(nullptr);
842 V->setLinkage(GlobalValue::ExternalLinkage);
843 V->clearMetadata();
Peter Collingbourne78736692018-01-31 02:51:03 +0000844 V->setComdat(nullptr);
Teresa Johnson5a95c472018-02-05 15:44:27 +0000845 } else {
846 GlobalValue *NewGV;
847 if (GV.getValueType()->isFunctionTy())
848 NewGV =
849 Function::Create(cast<FunctionType>(GV.getValueType()),
850 GlobalValue::ExternalLinkage, "", GV.getParent());
851 else
852 NewGV =
853 new GlobalVariable(*GV.getParent(), GV.getValueType(),
854 /*isConstant*/ false, GlobalValue::ExternalLinkage,
855 /*init*/ nullptr, "",
856 /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
857 GV.getType()->getAddressSpace());
858 NewGV->takeName(&GV);
859 GV.replaceAllUsesWith(NewGV);
860 return false;
861 }
862 return true;
George Rimareaf51722018-01-29 08:03:30 +0000863}
864
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000865/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
866void llvm::thinLTOResolveWeakForLinkerModule(
867 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
868 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000869 // See if the global summary analysis computed a new resolved linkage.
870 const auto &GS = DefinedGlobals.find(GV.getGUID());
871 if (GS == DefinedGlobals.end())
872 return;
873 auto NewLinkage = GS->second->linkage();
874 if (NewLinkage == GV.getLinkage())
875 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000876
877 // Switch the linkage to weakany if asked for, e.g. we do this for
878 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000879 // We record that the visibility should be changed here in `addThinLTO`
880 // as we need access to the resolution vectors for each input file in
881 // order to find which symbols have been redefined.
882 // We may consider reorganizing this code and moving the linkage recording
883 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000884 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
885 GV.setLinkage(NewLinkage);
886 return;
887 }
888
889 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
890 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000891 // Check for a non-prevailing def that has interposable linkage
892 // (e.g. non-odr weak or linkonce). In that case we can't simply
893 // convert to available_externally, since it would lose the
894 // interposable property and possibly get inlined. Simply drop
895 // the definition in that case.
896 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
Teresa Johnson5a95c472018-02-05 15:44:27 +0000897 GlobalValue::isInterposableLinkage(GV.getLinkage())) {
898 if (!convertToDeclaration(GV))
899 // FIXME: Change this to collect replaced GVs and later erase
900 // them from the parent module once thinLTOResolveWeakForLinkerGUID is
901 // changed to enable this for aliases.
902 llvm_unreachable("Expected GV to be converted");
903 } else {
Steven Wu33ba93c2018-02-09 18:34:08 +0000904 // If the original symbols has global unnamed addr and linkonce_odr linkage,
905 // it should be an auto hide symbol. Add hidden visibility to the symbol to
906 // preserve the property.
907 if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() &&
908 NewLinkage == GlobalValue::WeakODRLinkage)
909 GV.setVisibility(GlobalValue::HiddenVisibility);
910
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000911 LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
912 << "` from " << GV.getLinkage() << " to " << NewLinkage
913 << "\n");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000914 GV.setLinkage(NewLinkage);
915 }
916 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000917 // as this is a declaration for the linker, and will be dropped eventually.
918 // It is illegal for comdats to contain declarations.
919 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000920 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000921 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000922 };
923
924 // Process functions and global now
925 for (auto &GV : TheModule)
926 updateLinkage(GV);
927 for (auto &GV : TheModule.globals())
928 updateLinkage(GV);
929 for (auto &GV : TheModule.aliases())
930 updateLinkage(GV);
931}
932
933/// Run internalization on \p TheModule based on symmary analysis.
934void llvm::thinLTOInternalizeModule(Module &TheModule,
935 const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000936 // Declare a callback for the internalize pass that will ask for every
937 // candidate GlobalValue if it can be internalized or not.
938 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000939 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000940 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000941 if (GS == DefinedGlobals.end()) {
942 // Must have been promoted (possibly conservatively). Find original
943 // name so that we can access the correct summary and see if it can
944 // be internalized again.
945 // FIXME: Eventually we should control promotion instead of promoting
946 // and internalizing again.
947 StringRef OrigName =
948 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
949 std::string OrigId = GlobalValue::getGlobalIdentifier(
950 OrigName, GlobalValue::InternalLinkage,
951 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000952 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000953 if (GS == DefinedGlobals.end()) {
954 // Also check the original non-promoted non-globalized name. In some
955 // cases a preempted weak value is linked in as a local copy because
956 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
957 // In that case, since it was originally not a local value, it was
958 // recorded in the index using the original name.
959 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000960 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000961 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000962 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000963 }
964 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000965 };
966
967 // FIXME: See if we can just internalize directly here via linkage changes
968 // based on the index, rather than invoking internalizeModule.
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000969 internalizeModule(TheModule, MustPreserveGV);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000970}
971
Teresa Johnson81bbf742017-12-16 00:18:12 +0000972/// Make alias a clone of its aliasee.
973static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
974 Function *Fn = cast<Function>(GA->getBaseObject());
975
976 ValueToValueMapTy VMap;
977 Function *NewFn = CloneFunction(Fn, VMap);
978 // Clone should use the original alias's linkage and name, and we ensure
979 // all uses of alias instead use the new clone (casted if necessary).
980 NewFn->setLinkage(GA->getLinkage());
981 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
982 NewFn->takeName(GA);
983 return NewFn;
984}
985
Mehdi Aminic8c55172015-12-03 02:37:33 +0000986// Automatically import functions in Module \p DestModule based on the summaries
987// index.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000988Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000989 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000990 LLVM_DEBUG(dbgs() << "Starting import for Module "
991 << DestModule.getModuleIdentifier() << "\n");
Eugene Leviant19e23872018-03-12 10:30:50 +0000992 unsigned ImportedCount = 0, ImportedGVCount = 0;
Mehdi Aminic8c55172015-12-03 02:37:33 +0000993
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000994 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000995 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000996 std::set<StringRef> ModuleNameOrderedList;
997 for (auto &FunctionsToImportPerModule : ImportList) {
998 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
999 }
1000 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +00001001 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +00001002 const auto &FunctionsToImportPerModule = ImportList.find(Name);
1003 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +00001004 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
1005 if (!SrcModuleOrErr)
1006 return SrcModuleOrErr.takeError();
1007 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +00001008 assert(&DestModule.getContext() == &SrcModule->getContext() &&
1009 "Context mismatch");
1010
Teresa Johnson6cba37c2016-01-22 00:15:53 +00001011 // If modules were created with lazy metadata loading, materialize it
1012 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00001013 if (Error Err = SrcModule->materializeMetadata())
1014 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +00001015
Mehdi Amini01e32132016-03-26 05:40:34 +00001016 auto &ImportGUIDs = FunctionsToImportPerModule->second;
1017 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +00001018 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +00001019 for (Function &F : *SrcModule) {
1020 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +00001021 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +00001022 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +00001023 auto Import = ImportGUIDs.count(GUID);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001024 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
1025 << GUID << " " << F.getName() << " from "
1026 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +00001027 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00001028 if (Error Err = F.materialize())
1029 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +00001030 if (EnableImportMetadata) {
1031 // Add 'thinlto_src_module' metadata for statistics and debugging.
1032 F.setMetadata(
1033 "thinlto_src_module",
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001034 MDNode::get(DestModule.getContext(),
1035 {MDString::get(DestModule.getContext(),
1036 SrcModule->getSourceFileName())}));
Piotr Padlewski3b776122016-07-08 23:01:49 +00001037 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +00001038 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +00001039 }
1040 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +00001041 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00001042 if (!GV.hasName())
1043 continue;
1044 auto GUID = GV.getGUID();
1045 auto Import = ImportGUIDs.count(GUID);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001046 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
1047 << GUID << " " << GV.getName() << " from "
1048 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00001049 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00001050 if (Error Err = GV.materialize())
1051 return std::move(Err);
Eugene Leviant19e23872018-03-12 10:30:50 +00001052 ImportedGVCount += GlobalsToImport.insert(&GV);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00001053 }
1054 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +00001055 for (GlobalAlias &GA : SrcModule->aliases()) {
1056 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +00001057 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +00001058 auto GUID = GA.getGUID();
Teresa Johnson81bbf742017-12-16 00:18:12 +00001059 auto Import = ImportGUIDs.count(GUID);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001060 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
1061 << GUID << " " << GA.getName() << " from "
1062 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +00001063 if (Import) {
1064 if (Error Err = GA.materialize())
1065 return std::move(Err);
1066 // Import alias as a copy of its aliasee.
1067 GlobalObject *Base = GA.getBaseObject();
1068 if (Error Err = Base->materialize())
1069 return std::move(Err);
1070 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001071 LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
1072 << " " << Base->getName() << " from "
1073 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +00001074 if (EnableImportMetadata) {
1075 // Add 'thinlto_src_module' metadata for statistics and debugging.
1076 Fn->setMetadata(
1077 "thinlto_src_module",
1078 MDNode::get(DestModule.getContext(),
1079 {MDString::get(DestModule.getContext(),
1080 SrcModule->getSourceFileName())}));
1081 }
1082 GlobalsToImport.insert(Fn);
1083 }
Mehdi Amini01e32132016-03-26 05:40:34 +00001084 }
1085
Mehdi Amini19ef4fa2017-01-04 22:54:33 +00001086 // Upgrade debug info after we're done materializing all the globals and we
1087 // have loaded all the required metadata!
1088 UpgradeDebugInfo(*SrcModule);
1089
Mehdi Amini7e88d0d2015-12-09 08:17:35 +00001090 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +00001091 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +00001092 return true;
1093
Teresa Johnsond29478f2016-03-27 15:27:30 +00001094 if (PrintImports) {
1095 for (const auto *GV : GlobalsToImport)
1096 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
1097 << " from " << SrcModule->getSourceFileName() << "\n";
1098 }
1099
Peter Collingbourne6d8f8172017-02-03 16:56:27 +00001100 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
1101 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +00001102 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +00001103 report_fatal_error("Function Import: link error");
1104
Mehdi Amini01e32132016-03-26 05:40:34 +00001105 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +00001106 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +00001107 }
Teresa Johnsone5a61912015-12-17 17:14:09 +00001108
Eugene Leviant19e23872018-03-12 10:30:50 +00001109 NumImportedFunctions += (ImportedCount - ImportedGVCount);
1110 NumImportedGlobalVars += ImportedGVCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +00001111
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001112 LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
1113 << " functions for Module "
1114 << DestModule.getModuleIdentifier() << "\n");
1115 LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
1116 << " global variables for Module "
1117 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +00001118 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +00001119}
1120
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001121static bool doImportingForModule(Module &M) {
1122 if (SummaryFile.empty())
1123 report_fatal_error("error: -function-import requires -summary-file\n");
1124 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
1125 getModuleSummaryIndexForFile(SummaryFile);
1126 if (!IndexPtrOrErr) {
1127 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
1128 "Error loading file '" + SummaryFile + "': ");
1129 return false;
Teresa Johnson21241572016-07-18 21:22:24 +00001130 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001131 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +00001132
1133 // First step is collecting the import list.
1134 FunctionImporter::ImportMapTy ImportList;
Teresa Johnson81bbf742017-12-16 00:18:12 +00001135 // If requested, simply import all functions in the index. This is used
1136 // when testing distributed backend handling via the opt tool, when
1137 // we have distributed indexes containing exactly the summaries to import.
1138 if (ImportAllIndex)
1139 ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
1140 ImportList);
1141 else
1142 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
1143 ImportList);
Teresa Johnson21241572016-07-18 21:22:24 +00001144
Teresa Johnson4fef68c2016-11-14 19:21:41 +00001145 // Conservatively mark all internal values as promoted. This interface is
1146 // only used when doing importing via the function importing pass. The pass
1147 // is only enabled when testing importing via the 'opt' tool, which does
1148 // not do the ThinLink that would normally determine what values to promote.
1149 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001150 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +00001151 if (GlobalValue::isLocalLinkage(S->linkage()))
1152 S->setLinkage(GlobalValue::ExternalLinkage);
1153 }
1154 }
1155
Teresa Johnson21241572016-07-18 21:22:24 +00001156 // Next we need to promote to global scope and rename any local values that
1157 // are potentially exported to other modules.
1158 if (renameModuleForThinLTO(M, *Index, nullptr)) {
1159 errs() << "Error renaming module\n";
1160 return false;
1161 }
1162
1163 // Perform the import now.
1164 auto ModuleLoader = [&M](StringRef Identifier) {
1165 return loadFile(Identifier, M.getContext());
1166 };
1167 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +00001168 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00001169
1170 // FIXME: Probably need to propagate Errors through the pass manager.
1171 if (!Result) {
1172 logAllUnhandledErrors(Result.takeError(), errs(),
1173 "Error importing module: ");
1174 return false;
1175 }
1176
1177 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +00001178}
1179
Benjamin Kramerfe2b5412015-12-24 10:03:35 +00001180namespace {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001181
Mehdi Amini42418ab2015-11-24 06:07:49 +00001182/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +00001183class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +00001184public:
1185 /// Pass identification, replacement for typeid
1186 static char ID;
1187
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001188 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
1189
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001190 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +00001191 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001192
Mehdi Amini42418ab2015-11-24 06:07:49 +00001193 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001194 if (skipModule(M))
1195 return false;
1196
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001197 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +00001198 }
1199};
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001200
1201} // end anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +00001202
Teresa Johnson21241572016-07-18 21:22:24 +00001203PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001204 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001205 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +00001206 return PreservedAnalyses::all();
1207
1208 return PreservedAnalyses::none();
1209}
1210
1211char FunctionImportLegacyPass::ID = 0;
1212INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
1213 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +00001214
1215namespace llvm {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001216
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001217Pass *createFunctionImportPass() {
1218 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001219}
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001220
1221} // end namespace llvm