blob: c2907937e70f14935dd2d579dea5afc034e0ad83 [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 Johnson6c475a72017-01-05 21:34:18 +0000110static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
111 cl::desc("Compute dead symbols"));
112
Piotr Padlewski3b776122016-07-08 23:01:49 +0000113static cl::opt<bool> EnableImportMetadata(
114 "enable-import-metadata", cl::init(
115#if !defined(NDEBUG)
116 true /*Enabled with asserts.*/
117#else
118 false
119#endif
120 ),
121 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
122
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000123/// Summary file to use for function importing when using -function-import from
124/// the command line.
125static cl::opt<std::string>
126 SummaryFile("summary-file",
127 cl::desc("The summary file to use for function importing."));
128
Teresa Johnson81bbf742017-12-16 00:18:12 +0000129/// Used when testing importing from distributed indexes via opt
130// -function-import.
131static cl::opt<bool>
132 ImportAllIndex("import-all-index",
133 cl::desc("Import all external functions in index."));
134
Mehdi Amini42418ab2015-11-24 06:07:49 +0000135// Load lazily a module from \p FileName in \p Context.
136static std::unique_ptr<Module> loadFile(const std::string &FileName,
137 LLVMContext &Context) {
138 SMDiagnostic Err;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000139 LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000140 // Metadata isn't loaded until functions are imported, to minimize
141 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000142 std::unique_ptr<Module> Result =
143 getLazyIRFileModule(FileName, Err, Context,
144 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000145 if (!Result) {
146 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000147 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000148 }
149
Mehdi Amini42418ab2015-11-24 06:07:49 +0000150 return Result;
151}
152
Mehdi Amini01e32132016-03-26 05:40:34 +0000153/// Given a list of possible callee implementation for a call site, select one
154/// that fits the \p Threshold.
155///
156/// FIXME: select "best" instead of first that fits. But what is "best"?
157/// - The smallest: more likely to be inlined.
158/// - The one with the least outgoing edges (already well optimized).
159/// - One from a module already being imported from in order to reduce the
160/// number of source modules parsed/linked.
161/// - One that has PGO data attached.
162/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000163static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000164selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000165 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000166 unsigned Threshold, StringRef CallerModulePath) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000167 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000168 CalleeSummaryList,
169 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
170 auto *GVSummary = SummaryPtr.get();
George Rimareaf51722018-01-29 08:03:30 +0000171 if (!Index.isGlobalValueLive(GVSummary))
172 return false;
173
Teresa Johnson73305f82017-08-19 18:04:25 +0000174 // For SamplePGO, in computeImportForFunction the OriginalId
175 // may have been used to locate the callee summary list (See
176 // comment there).
177 // The mapping from OriginalId to GUID may return a GUID
178 // that corresponds to a static variable. Filter it out here.
179 // This can happen when
180 // 1) There is a call to a library function which is not defined
181 // in the index.
182 // 2) There is a static variable with the OriginalGUID identical
183 // to the GUID of the library function in 1);
184 // When this happens, the logic for SamplePGO kicks in and
185 // the static variable in 2) will be found, which needs to be
186 // filtered out.
187 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
188 return false;
Rafael Espindolaf329be82016-05-11 01:26:06 +0000189 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000190 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000191 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000192
Teresa Johnson81bbf742017-12-16 00:18:12 +0000193 auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000194
Teresa Johnson83aaf352017-01-12 22:04:45 +0000195 // If this is a local function, make sure we import the copy
196 // in the caller's module. The only time a local function can
197 // share an entry in the index is if there is a local with the same name
198 // in another module that had the same source file name (in a different
199 // directory), where each was compiled in their own directory so there
200 // was not distinguishing path.
201 // However, do the import from another module if there is only one
202 // entry in the list - in that case this must be a reference due
203 // to indirect call profile data, since a function pointer can point to
204 // a local in another module.
205 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
206 CalleeSummaryList.size() > 1 &&
207 Summary->modulePath() != CallerModulePath)
208 return false;
209
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000210 if (Summary->instCount() > Threshold)
211 return false;
212
Teresa Johnson519465b2017-01-05 14:32:16 +0000213 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000214 return false;
215
Mehdi Amini01e32132016-03-26 05:40:34 +0000216 return true;
217 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000218 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000219 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000220
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000221 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000222}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000223
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000224namespace {
225
Teresa Johnson475b51a2016-12-15 20:48:19 +0000226using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
227 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000228
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000229} // anonymous namespace
230
Teresa Johnson19580832017-09-13 15:16:38 +0000231static ValueInfo
232updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
233 if (!VI.getSummaryList().empty())
234 return VI;
235 // For SamplePGO, the indirect call targets for local functions will
236 // have its original name annotated in profile. We try to find the
237 // corresponding PGOFuncName as the GUID.
238 // FIXME: Consider updating the edges in the graph after building
239 // it, rather than needing to perform this mapping on each walk.
240 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
241 if (GUID == 0)
Eugene Leviant28d8a492018-01-22 13:35:40 +0000242 return ValueInfo();
Teresa Johnson19580832017-09-13 15:16:38 +0000243 return Index.getValueInfo(GUID);
244}
245
Eugene Leviant19e23872018-03-12 10:30:50 +0000246static void computeImportForReferencedGlobals(
247 const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries,
248 FunctionImporter::ImportMapTy &ImportList,
249 StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
250 for (auto &VI : Summary.refs()) {
251 if (DefinedGVSummaries.count(VI.getGUID())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000252 LLVM_DEBUG(
253 dbgs() << "Ref ignored! Target already in destination module.\n");
Eugene Leviant19e23872018-03-12 10:30:50 +0000254 continue;
255 }
256
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000257 LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
Eugene Leviant19e23872018-03-12 10:30:50 +0000258
259 for (auto &RefSummary : VI.getSummaryList())
260 if (RefSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind &&
261 // Don't try to import regular LTO summaries added to dummy module.
262 !RefSummary->modulePath().empty() &&
263 !GlobalValue::isInterposableLinkage(RefSummary->linkage()) &&
264 RefSummary->refs().empty()) {
265 ImportList[RefSummary->modulePath()][VI.getGUID()] = 1;
266 if (ExportLists)
267 (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID());
268 break;
269 }
270 }
271}
272
Mehdi Amini01e32132016-03-26 05:40:34 +0000273/// Compute the list of functions to import for a given caller. Mark these
274/// imported functions and the symbols they reference in their source module as
275/// exported from their source module.
276static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000277 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000278 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000279 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000280 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000281 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Eugene Leviant19e23872018-03-12 10:30:50 +0000282 computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList,
283 ExportLists);
Teresa Johnson974706e2018-04-01 15:54:40 +0000284 static int ImportCount = 0;
Mehdi Amini01e32132016-03-26 05:40:34 +0000285 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000286 ValueInfo VI = Edge.first;
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000287 LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
288 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000289
Teresa Johnson974706e2018-04-01 15:54:40 +0000290 if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000291 LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
292 << " reached.\n");
Teresa Johnson974706e2018-04-01 15:54:40 +0000293 continue;
294 }
295
Teresa Johnson19580832017-09-13 15:16:38 +0000296 VI = updateValueInfoForIndirectCalls(Index, VI);
297 if (!VI)
298 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000299
Peter Collingbourne9667b912017-05-04 18:03:25 +0000300 if (DefinedGVSummaries.count(VI.getGUID())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000301 LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000302 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000303 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000304
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000305 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
306 if (Hotness == CalleeInfo::HotnessType::Hot)
307 return ImportHotMultiplier;
308 if (Hotness == CalleeInfo::HotnessType::Cold)
309 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000310 if (Hotness == CalleeInfo::HotnessType::Critical)
311 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000312 return 1.0;
313 };
314
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000315 const auto NewThreshold =
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000316 Threshold * GetBonusMultiplier(Edge.second.getHotness());
Piotr Padlewskid2869472016-09-30 03:01:17 +0000317
Peter Collingbourne9667b912017-05-04 18:03:25 +0000318 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
319 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000320 if (!CalleeSummary) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000321 LLVM_DEBUG(
322 dbgs() << "ignored! No qualifying callee with summary found.\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000323 continue;
324 }
David Blaikie2f0cc472017-07-27 15:09:06 +0000325
326 // "Resolve" the summary
Teresa Johnson81bbf742017-12-16 00:18:12 +0000327 const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary->getBaseObject());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000328
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000329 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000330 "selectCallee() didn't honor the threshold");
331
Piotr Padlewskid2869472016-09-30 03:01:17 +0000332 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
333 // Adjust the threshold for next level of imported functions.
334 // The threshold is different for hot callsites because we can then
335 // inline chains of hot calls.
336 if (IsHotCallsite)
337 return Threshold * ImportHotInstrFactor;
338 return Threshold * ImportInstrFactor;
339 };
340
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000341 bool IsHotCallsite =
342 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000343 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
344
345 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000346 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000347 /// Since the traversal of the call graph is DFS, we can revisit a function
348 /// a second time with a higher threshold. In this case, it is added back to
349 /// the worklist with the new threshold.
350 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000351 LLVM_DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
352 << ProcessedThreshold << "\n");
Teresa Johnson1b859a22016-12-15 18:21:01 +0000353 continue;
354 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000355 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000356 // Mark this function as imported in this module, with the current Threshold
357 ProcessedThreshold = AdjThreshold;
358
Teresa Johnson974706e2018-04-01 15:54:40 +0000359 ImportCount++;
360
Teresa Johnson1b859a22016-12-15 18:21:01 +0000361 // Make exports in the source module.
362 if (ExportLists) {
363 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000364 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000365 if (!PreviouslyImported) {
366 // This is the first time this function was exported from its source
367 // module, so mark all functions and globals it references as exported
368 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000369 // For efficiency, we unconditionally add all the referenced GUIDs
370 // to the ExportList for this module, and will prune out any not
371 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000372 for (auto &Edge : ResolvedCalleeSummary->calls()) {
373 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000374 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000375 }
376 for (auto &Ref : ResolvedCalleeSummary->refs()) {
377 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000378 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000379 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000380 }
381 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000382
Mehdi Amini01e32132016-03-26 05:40:34 +0000383 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000384 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000385 }
386}
387
Mehdi Amini01e32132016-03-26 05:40:34 +0000388/// Given the list of globals defined in a module, compute the list of imports
389/// as well as the list of "exports", i.e. the list of symbols referenced from
390/// another module (that may require promotion).
391static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000392 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000393 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000394 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000395 // Worklist contains the list of function imported in this module, for which
396 // we will analyse the callees and may import further down the callgraph.
397 SmallVector<EdgeInfo, 128> Worklist;
398
399 // Populate the worklist with the import for the functions in the current
400 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000401 for (auto &GVSummary : DefinedGVSummaries) {
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000402#ifndef NDEBUG
403 // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
404 // so this map look up (and possibly others) can be avoided.
405 auto VI = Index.getValueInfo(GVSummary.first);
406#endif
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000407 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000408 LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
Teresa Johnson6c475a72017-01-05 21:34:18 +0000409 continue;
410 }
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000411 auto *FuncSummary =
412 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000413 if (!FuncSummary)
414 // Skip import for global variables
415 continue;
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000416 LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000417 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000418 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000419 ExportLists);
420 }
421
Piotr Padlewskid2869472016-09-30 03:01:17 +0000422 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000423 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000424 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000425 auto *Summary = std::get<0>(FuncInfo);
426 auto Threshold = std::get<1>(FuncInfo);
427 auto GUID = std::get<2>(FuncInfo);
428
429 // Check if we later added this summary with a higher threshold.
430 // If so, skip this entry.
431 auto ExportModulePath = Summary->modulePath();
432 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
433 if (LatestProcessedThreshold > Threshold)
434 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000435
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000436 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000437 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000438 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000439}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000440
Eugene Leviant19e23872018-03-12 10:30:50 +0000441#ifndef NDEBUG
442static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
443 GlobalValue::GUID G) {
444 if (const auto &VI = Index.getValueInfo(G)) {
445 auto SL = VI.getSummaryList();
446 if (!SL.empty())
447 return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
448 }
449 return false;
450}
451
452static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
453
454static GlobalValue::GUID
455getGUID(const std::pair<const GlobalValue::GUID, unsigned> &P) {
456 return P.first;
457}
458
459template <class T>
Benjamin Kramer1fc0da42018-04-04 11:45:11 +0000460static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
461 T &Cont) {
Eugene Leviant19e23872018-03-12 10:30:50 +0000462 unsigned NumGVS = 0;
463 for (auto &V : Cont)
464 if (isGlobalVarSummary(Index, getGUID(V)))
465 ++NumGVS;
466 return NumGVS;
467}
468#endif
469
Teresa Johnsonc86af332016-04-12 21:13:11 +0000470/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000471void llvm::ComputeCrossModuleImport(
472 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000473 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000474 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000475 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000476 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000477 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000478 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000479 LLVM_DEBUG(dbgs() << "Computing import for Module '"
480 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000481 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000482 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000483 }
484
Teresa Johnsonedddca22016-12-16 04:11:51 +0000485 // When computing imports we added all GUIDs referenced by anything
486 // imported from the module to its ExportList. Now we prune each ExportList
487 // of any not defined in that module. This is more efficient than checking
488 // while computing imports because some of the summary lists may be long
489 // due to linkonce (comdat) copies.
490 for (auto &ELI : ExportLists) {
491 const auto &DefinedGVSummaries =
492 ModuleToDefinedGVSummaries.lookup(ELI.first());
493 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
494 if (!DefinedGVSummaries.count(*EI))
495 EI = ELI.second.erase(EI);
496 else
497 ++EI;
498 }
499 }
500
Mehdi Amini01e32132016-03-26 05:40:34 +0000501#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000502 LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
503 << " modules:\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000504 for (auto &ModuleImports : ImportLists) {
505 auto ModName = ModuleImports.first();
506 auto &Exports = ExportLists[ModName];
Eugene Leviant19e23872018-03-12 10:30:50 +0000507 unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000508 LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
509 << Exports.size() - NumGVS << " functions and " << NumGVS
510 << " vars. Imports from " << ModuleImports.second.size()
511 << " modules.\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000512 for (auto &Src : ModuleImports.second) {
513 auto SrcModName = Src.first();
Eugene Leviant19e23872018-03-12 10:30:50 +0000514 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000515 LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
516 << " functions imported from " << SrcModName << "\n");
517 LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
518 << " global vars imported from " << SrcModName << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000519 }
520 }
521#endif
522}
523
Teresa Johnson81bbf742017-12-16 00:18:12 +0000524#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000525static void dumpImportListForModule(const ModuleSummaryIndex &Index,
526 StringRef ModulePath,
Teresa Johnson81bbf742017-12-16 00:18:12 +0000527 FunctionImporter::ImportMapTy &ImportList) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000528 LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
529 << ImportList.size() << " modules.\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +0000530 for (auto &Src : ImportList) {
531 auto SrcModName = Src.first();
Eugene Leviant19e23872018-03-12 10:30:50 +0000532 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000533 LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
534 << " functions imported from " << SrcModName << "\n");
535 LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
536 << SrcModName << "\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +0000537 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000538}
Teresa Johnson69b2de82017-12-16 00:29:31 +0000539#endif
Teresa Johnson81bbf742017-12-16 00:18:12 +0000540
Teresa Johnsonc86af332016-04-12 21:13:11 +0000541/// Compute all the imports for the given module in the Index.
542void llvm::ComputeCrossModuleImportForModule(
543 StringRef ModulePath, const ModuleSummaryIndex &Index,
544 FunctionImporter::ImportMapTy &ImportList) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000545 // Collect the list of functions this module defines.
546 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000547 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000548 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000549
550 // Compute the import list for this module.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000551 LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000552 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000553
554#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000555 dumpImportListForModule(Index, ModulePath, ImportList);
Teresa Johnson81bbf742017-12-16 00:18:12 +0000556#endif
557}
558
559// Mark all external summaries in Index for import into the given module.
560// Used for distributed builds using a distributed index.
561void llvm::ComputeCrossModuleImportForModuleFromIndex(
562 StringRef ModulePath, const ModuleSummaryIndex &Index,
563 FunctionImporter::ImportMapTy &ImportList) {
564 for (auto &GlobalList : Index) {
565 // Ignore entries for undefined references.
566 if (GlobalList.second.SummaryList.empty())
567 continue;
568
569 auto GUID = GlobalList.first;
570 assert(GlobalList.second.SummaryList.size() == 1 &&
571 "Expected individual combined index to have one summary per GUID");
572 auto &Summary = GlobalList.second.SummaryList[0];
573 // Skip the summaries for the importing module. These are included to
574 // e.g. record required linkage changes.
575 if (Summary->modulePath() == ModulePath)
576 continue;
577 // Doesn't matter what value we plug in to the map, just needs an entry
578 // to provoke importing by thinBackend.
579 ImportList[Summary->modulePath()][GUID] = 1;
Teresa Johnsonc86af332016-04-12 21:13:11 +0000580 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000581#ifndef NDEBUG
Eugene Leviant19e23872018-03-12 10:30:50 +0000582 dumpImportListForModule(Index, ModulePath, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000583#endif
584}
585
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000586void llvm::computeDeadSymbols(
587 ModuleSummaryIndex &Index,
George Rimareaf51722018-01-29 08:03:30 +0000588 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
589 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000590 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000591 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000592 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000593 if (GUIDPreservedSymbols.empty())
594 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000595 return;
596 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000597 SmallVector<ValueInfo, 128> Worklist;
598 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
599 for (auto GUID : GUIDPreservedSymbols) {
600 ValueInfo VI = Index.getValueInfo(GUID);
601 if (!VI)
602 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000603 for (auto &S : VI.getSummaryList())
604 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000605 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000606
Teresa Johnson6c475a72017-01-05 21:34:18 +0000607 // Add values flagged in the index as live roots to the worklist.
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000608 for (const auto &Entry : Index) {
609 auto VI = Index.getValueInfo(Entry);
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000610 for (auto &S : Entry.second.SummaryList)
611 if (S->isLive()) {
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000612 LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
613 Worklist.push_back(VI);
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000614 ++LiveSymbols;
615 break;
616 }
Teresa Johnson7e7b13d2018-06-27 18:03:39 +0000617 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000618
619 // Make value live and add it to the worklist if it was not live before.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000620 auto visit = [&](ValueInfo VI) {
Teresa Johnson19580832017-09-13 15:16:38 +0000621 // FIXME: If we knew which edges were created for indirect call profiles,
622 // we could skip them here. Any that are live should be reached via
623 // other edges, e.g. reference edges. Otherwise, using a profile collected
624 // on a slightly different binary might provoke preserving, importing
625 // and ultimately promoting calls to functions not linked into this
626 // binary, which increases the binary size unnecessarily. Note that
627 // if this code changes, the importer needs to change so that edges
628 // to functions marked dead are skipped.
629 VI = updateValueInfoForIndirectCalls(Index, VI);
630 if (!VI)
631 return;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000632 for (auto &S : VI.getSummaryList())
Teresa Johnsonf6251182017-09-20 17:09:47 +0000633 if (S->isLive())
634 return;
George Rimareaf51722018-01-29 08:03:30 +0000635
Vlad Tsyrklevichaab60002018-03-13 05:08:48 +0000636 // We only keep live symbols that are known to be non-prevailing if any are
637 // available_externally. Those symbols are discarded later in the
638 // EliminateAvailableExternally pass and setting them to not-live breaks
639 // downstreams users of liveness information (PR36483).
640 if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
641 bool AvailableExternally = false;
642 bool Interposable = false;
643 for (auto &S : VI.getSummaryList()) {
644 if (S->linkage() == GlobalValue::AvailableExternallyLinkage)
645 AvailableExternally = true;
646 else if (GlobalValue::isInterposableLinkage(S->linkage()))
647 Interposable = true;
648 }
649
650 if (!AvailableExternally)
651 return;
652
653 if (Interposable)
654 report_fatal_error("Interposable and available_externally symbol");
655 }
George Rimareaf51722018-01-29 08:03:30 +0000656
Teresa Johnsonf6251182017-09-20 17:09:47 +0000657 for (auto &S : VI.getSummaryList())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000658 S->setLive(true);
659 ++LiveSymbols;
660 Worklist.push_back(VI);
661 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000662
663 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000664 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000665 for (auto &Summary : VI.getSummaryList()) {
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000666 GlobalValueSummary *Base = Summary->getBaseObject();
George Rimareaf51722018-01-29 08:03:30 +0000667 // Set base value live in case it is an alias.
668 Base->setLive(true);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000669 for (auto Ref : Base->refs())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000670 visit(Ref);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000671 if (auto *FS = dyn_cast<FunctionSummary>(Base))
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000672 for (auto Call : FS->calls())
673 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000674 }
675 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000676 Index.setWithGlobalValueDeadStripping();
677
678 unsigned DeadSymbols = Index.size() - LiveSymbols;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000679 LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
680 << " symbols Dead \n");
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000681 NumDeadSymbols += DeadSymbols;
682 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000683}
684
Teresa Johnson84174c32016-05-10 13:48:23 +0000685/// Compute the set of summaries needed for a ThinLTO backend compilation of
686/// \p ModulePath.
687void llvm::gatherImportedSummariesForModule(
688 StringRef ModulePath,
689 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000690 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000691 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
692 // Include all summaries from the importing module.
693 ModuleToSummariesForIndex[ModulePath] =
694 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000695 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000696 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000697 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
698 const auto &DefinedGVSummaries =
699 ModuleToDefinedGVSummaries.lookup(ILI.first());
700 for (auto &GI : ILI.second) {
701 const auto &DS = DefinedGVSummaries.find(GI.first);
702 assert(DS != DefinedGVSummaries.end() &&
703 "Expected a defined summary for imported global value");
704 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000705 }
706 }
707}
708
Teresa Johnson8570fe42016-05-10 15:54:09 +0000709/// Emit the files \p ModulePath will import from into \p OutputFilename.
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000710std::error_code llvm::EmitImportsFiles(
711 StringRef ModulePath, StringRef OutputFilename,
712 const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000713 std::error_code EC;
714 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
715 if (EC)
716 return EC;
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000717 for (auto &ILI : ModuleToSummariesForIndex)
718 // The ModuleToSummariesForIndex map includes an entry for the current
719 // Module (needed for writing out the index files). We don't want to
720 // include it in the imports file, however, so filter it out.
721 if (ILI.first != ModulePath)
722 ImportsOS << ILI.first << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000723 return std::error_code();
724}
725
Teresa Johnson5a95c472018-02-05 15:44:27 +0000726bool llvm::convertToDeclaration(GlobalValue &GV) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000727 LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
728 << "\n");
George Rimareaf51722018-01-29 08:03:30 +0000729 if (Function *F = dyn_cast<Function>(&GV)) {
730 F->deleteBody();
731 F->clearMetadata();
Peter Collingbourne78736692018-01-31 02:51:03 +0000732 F->setComdat(nullptr);
George Rimareaf51722018-01-29 08:03:30 +0000733 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
734 V->setInitializer(nullptr);
735 V->setLinkage(GlobalValue::ExternalLinkage);
736 V->clearMetadata();
Peter Collingbourne78736692018-01-31 02:51:03 +0000737 V->setComdat(nullptr);
Teresa Johnson5a95c472018-02-05 15:44:27 +0000738 } else {
739 GlobalValue *NewGV;
740 if (GV.getValueType()->isFunctionTy())
741 NewGV =
742 Function::Create(cast<FunctionType>(GV.getValueType()),
743 GlobalValue::ExternalLinkage, "", GV.getParent());
744 else
745 NewGV =
746 new GlobalVariable(*GV.getParent(), GV.getValueType(),
747 /*isConstant*/ false, GlobalValue::ExternalLinkage,
748 /*init*/ nullptr, "",
749 /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
750 GV.getType()->getAddressSpace());
751 NewGV->takeName(&GV);
752 GV.replaceAllUsesWith(NewGV);
753 return false;
754 }
755 return true;
George Rimareaf51722018-01-29 08:03:30 +0000756}
757
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000758/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
759void llvm::thinLTOResolveWeakForLinkerModule(
760 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
761 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000762 // See if the global summary analysis computed a new resolved linkage.
763 const auto &GS = DefinedGlobals.find(GV.getGUID());
764 if (GS == DefinedGlobals.end())
765 return;
766 auto NewLinkage = GS->second->linkage();
767 if (NewLinkage == GV.getLinkage())
768 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000769
770 // Switch the linkage to weakany if asked for, e.g. we do this for
771 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000772 // We record that the visibility should be changed here in `addThinLTO`
773 // as we need access to the resolution vectors for each input file in
774 // order to find which symbols have been redefined.
775 // We may consider reorganizing this code and moving the linkage recording
776 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000777 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
778 GV.setLinkage(NewLinkage);
779 return;
780 }
781
782 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
783 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000784 // Check for a non-prevailing def that has interposable linkage
785 // (e.g. non-odr weak or linkonce). In that case we can't simply
786 // convert to available_externally, since it would lose the
787 // interposable property and possibly get inlined. Simply drop
788 // the definition in that case.
789 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
Teresa Johnson5a95c472018-02-05 15:44:27 +0000790 GlobalValue::isInterposableLinkage(GV.getLinkage())) {
791 if (!convertToDeclaration(GV))
792 // FIXME: Change this to collect replaced GVs and later erase
793 // them from the parent module once thinLTOResolveWeakForLinkerGUID is
794 // changed to enable this for aliases.
795 llvm_unreachable("Expected GV to be converted");
796 } else {
Steven Wu33ba93c2018-02-09 18:34:08 +0000797 // If the original symbols has global unnamed addr and linkonce_odr linkage,
798 // it should be an auto hide symbol. Add hidden visibility to the symbol to
799 // preserve the property.
800 if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() &&
801 NewLinkage == GlobalValue::WeakODRLinkage)
802 GV.setVisibility(GlobalValue::HiddenVisibility);
803
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000804 LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
805 << "` from " << GV.getLinkage() << " to " << NewLinkage
806 << "\n");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000807 GV.setLinkage(NewLinkage);
808 }
809 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000810 // as this is a declaration for the linker, and will be dropped eventually.
811 // It is illegal for comdats to contain declarations.
812 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000813 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000814 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000815 };
816
817 // Process functions and global now
818 for (auto &GV : TheModule)
819 updateLinkage(GV);
820 for (auto &GV : TheModule.globals())
821 updateLinkage(GV);
822 for (auto &GV : TheModule.aliases())
823 updateLinkage(GV);
824}
825
826/// Run internalization on \p TheModule based on symmary analysis.
827void llvm::thinLTOInternalizeModule(Module &TheModule,
828 const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000829 // Declare a callback for the internalize pass that will ask for every
830 // candidate GlobalValue if it can be internalized or not.
831 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000832 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000833 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000834 if (GS == DefinedGlobals.end()) {
835 // Must have been promoted (possibly conservatively). Find original
836 // name so that we can access the correct summary and see if it can
837 // be internalized again.
838 // FIXME: Eventually we should control promotion instead of promoting
839 // and internalizing again.
840 StringRef OrigName =
841 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
842 std::string OrigId = GlobalValue::getGlobalIdentifier(
843 OrigName, GlobalValue::InternalLinkage,
844 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000845 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000846 if (GS == DefinedGlobals.end()) {
847 // Also check the original non-promoted non-globalized name. In some
848 // cases a preempted weak value is linked in as a local copy because
849 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
850 // In that case, since it was originally not a local value, it was
851 // recorded in the index using the original name.
852 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000853 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000854 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000855 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000856 }
857 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000858 };
859
860 // FIXME: See if we can just internalize directly here via linkage changes
861 // based on the index, rather than invoking internalizeModule.
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000862 internalizeModule(TheModule, MustPreserveGV);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000863}
864
Teresa Johnson81bbf742017-12-16 00:18:12 +0000865/// Make alias a clone of its aliasee.
866static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
867 Function *Fn = cast<Function>(GA->getBaseObject());
868
869 ValueToValueMapTy VMap;
870 Function *NewFn = CloneFunction(Fn, VMap);
871 // Clone should use the original alias's linkage and name, and we ensure
872 // all uses of alias instead use the new clone (casted if necessary).
873 NewFn->setLinkage(GA->getLinkage());
874 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
875 NewFn->takeName(GA);
876 return NewFn;
877}
878
Mehdi Aminic8c55172015-12-03 02:37:33 +0000879// Automatically import functions in Module \p DestModule based on the summaries
880// index.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000881Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000882 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000883 LLVM_DEBUG(dbgs() << "Starting import for Module "
884 << DestModule.getModuleIdentifier() << "\n");
Eugene Leviant19e23872018-03-12 10:30:50 +0000885 unsigned ImportedCount = 0, ImportedGVCount = 0;
Mehdi Aminic8c55172015-12-03 02:37:33 +0000886
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000887 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000888 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000889 std::set<StringRef> ModuleNameOrderedList;
890 for (auto &FunctionsToImportPerModule : ImportList) {
891 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
892 }
893 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000894 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000895 const auto &FunctionsToImportPerModule = ImportList.find(Name);
896 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000897 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
898 if (!SrcModuleOrErr)
899 return SrcModuleOrErr.takeError();
900 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000901 assert(&DestModule.getContext() == &SrcModule->getContext() &&
902 "Context mismatch");
903
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000904 // If modules were created with lazy metadata loading, materialize it
905 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000906 if (Error Err = SrcModule->materializeMetadata())
907 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000908
Mehdi Amini01e32132016-03-26 05:40:34 +0000909 auto &ImportGUIDs = FunctionsToImportPerModule->second;
910 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000911 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000912 for (Function &F : *SrcModule) {
913 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000914 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000915 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000916 auto Import = ImportGUIDs.count(GUID);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000917 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
918 << GUID << " " << F.getName() << " from "
919 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000920 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000921 if (Error Err = F.materialize())
922 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000923 if (EnableImportMetadata) {
924 // Add 'thinlto_src_module' metadata for statistics and debugging.
925 F.setMetadata(
926 "thinlto_src_module",
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000927 MDNode::get(DestModule.getContext(),
928 {MDString::get(DestModule.getContext(),
929 SrcModule->getSourceFileName())}));
Piotr Padlewski3b776122016-07-08 23:01:49 +0000930 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000931 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000932 }
933 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000934 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000935 if (!GV.hasName())
936 continue;
937 auto GUID = GV.getGUID();
938 auto Import = ImportGUIDs.count(GUID);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000939 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
940 << GUID << " " << GV.getName() << " from "
941 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000942 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000943 if (Error Err = GV.materialize())
944 return std::move(Err);
Eugene Leviant19e23872018-03-12 10:30:50 +0000945 ImportedGVCount += GlobalsToImport.insert(&GV);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000946 }
947 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000948 for (GlobalAlias &GA : SrcModule->aliases()) {
949 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000950 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000951 auto GUID = GA.getGUID();
Teresa Johnson81bbf742017-12-16 00:18:12 +0000952 auto Import = ImportGUIDs.count(GUID);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000953 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
954 << GUID << " " << GA.getName() << " from "
955 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +0000956 if (Import) {
957 if (Error Err = GA.materialize())
958 return std::move(Err);
959 // Import alias as a copy of its aliasee.
960 GlobalObject *Base = GA.getBaseObject();
961 if (Error Err = Base->materialize())
962 return std::move(Err);
963 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000964 LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
965 << " " << Base->getName() << " from "
966 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +0000967 if (EnableImportMetadata) {
968 // Add 'thinlto_src_module' metadata for statistics and debugging.
969 Fn->setMetadata(
970 "thinlto_src_module",
971 MDNode::get(DestModule.getContext(),
972 {MDString::get(DestModule.getContext(),
973 SrcModule->getSourceFileName())}));
974 }
975 GlobalsToImport.insert(Fn);
976 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000977 }
978
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000979 // Upgrade debug info after we're done materializing all the globals and we
980 // have loaded all the required metadata!
981 UpgradeDebugInfo(*SrcModule);
982
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000983 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000984 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000985 return true;
986
Teresa Johnsond29478f2016-03-27 15:27:30 +0000987 if (PrintImports) {
988 for (const auto *GV : GlobalsToImport)
989 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
990 << " from " << SrcModule->getSourceFileName() << "\n";
991 }
992
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000993 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
994 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000995 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000996 report_fatal_error("Function Import: link error");
997
Mehdi Amini01e32132016-03-26 05:40:34 +0000998 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000999 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +00001000 }
Teresa Johnsone5a61912015-12-17 17:14:09 +00001001
Eugene Leviant19e23872018-03-12 10:30:50 +00001002 NumImportedFunctions += (ImportedCount - ImportedGVCount);
1003 NumImportedGlobalVars += ImportedGVCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +00001004
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001005 LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
1006 << " functions for Module "
1007 << DestModule.getModuleIdentifier() << "\n");
1008 LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
1009 << " global variables for Module "
1010 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +00001011 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +00001012}
1013
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001014static bool doImportingForModule(Module &M) {
1015 if (SummaryFile.empty())
1016 report_fatal_error("error: -function-import requires -summary-file\n");
1017 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
1018 getModuleSummaryIndexForFile(SummaryFile);
1019 if (!IndexPtrOrErr) {
1020 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
1021 "Error loading file '" + SummaryFile + "': ");
1022 return false;
Teresa Johnson21241572016-07-18 21:22:24 +00001023 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001024 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +00001025
1026 // First step is collecting the import list.
1027 FunctionImporter::ImportMapTy ImportList;
Teresa Johnson81bbf742017-12-16 00:18:12 +00001028 // If requested, simply import all functions in the index. This is used
1029 // when testing distributed backend handling via the opt tool, when
1030 // we have distributed indexes containing exactly the summaries to import.
1031 if (ImportAllIndex)
1032 ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
1033 ImportList);
1034 else
1035 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
1036 ImportList);
Teresa Johnson21241572016-07-18 21:22:24 +00001037
Teresa Johnson4fef68c2016-11-14 19:21:41 +00001038 // Conservatively mark all internal values as promoted. This interface is
1039 // only used when doing importing via the function importing pass. The pass
1040 // is only enabled when testing importing via the 'opt' tool, which does
1041 // not do the ThinLink that would normally determine what values to promote.
1042 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001043 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +00001044 if (GlobalValue::isLocalLinkage(S->linkage()))
1045 S->setLinkage(GlobalValue::ExternalLinkage);
1046 }
1047 }
1048
Teresa Johnson21241572016-07-18 21:22:24 +00001049 // Next we need to promote to global scope and rename any local values that
1050 // are potentially exported to other modules.
1051 if (renameModuleForThinLTO(M, *Index, nullptr)) {
1052 errs() << "Error renaming module\n";
1053 return false;
1054 }
1055
1056 // Perform the import now.
1057 auto ModuleLoader = [&M](StringRef Identifier) {
1058 return loadFile(Identifier, M.getContext());
1059 };
1060 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +00001061 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00001062
1063 // FIXME: Probably need to propagate Errors through the pass manager.
1064 if (!Result) {
1065 logAllUnhandledErrors(Result.takeError(), errs(),
1066 "Error importing module: ");
1067 return false;
1068 }
1069
1070 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +00001071}
1072
Benjamin Kramerfe2b5412015-12-24 10:03:35 +00001073namespace {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001074
Mehdi Amini42418ab2015-11-24 06:07:49 +00001075/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +00001076class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +00001077public:
1078 /// Pass identification, replacement for typeid
1079 static char ID;
1080
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001081 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
1082
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001083 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +00001084 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001085
Mehdi Amini42418ab2015-11-24 06:07:49 +00001086 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001087 if (skipModule(M))
1088 return false;
1089
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001090 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +00001091 }
1092};
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001093
1094} // end anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +00001095
Teresa Johnson21241572016-07-18 21:22:24 +00001096PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001097 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001098 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +00001099 return PreservedAnalyses::all();
1100
1101 return PreservedAnalyses::none();
1102}
1103
1104char FunctionImportLegacyPass::ID = 0;
1105INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
1106 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +00001107
1108namespace llvm {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001109
Peter Collingbourne598bd2a2016-12-21 00:50:12 +00001110Pass *createFunctionImportPass() {
1111 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +00001112}
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +00001113
1114} // end namespace llvm