blob: b92f798c4ab0e4a7cb1dffb95100c10e2c978327 [file] [log] [blame]
Mehdi Amini42418ab2015-11-24 06:07:49 +00001//===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Function import based on summaries.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/IPO/FunctionImport.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
Mehdi Amini01e32132016-03-26 05:40:34 +000018#include "llvm/ADT/SmallVector.h"
Teresa Johnsond29478f2016-03-27 15:27:30 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000020#include "llvm/ADT/StringMap.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000021#include "llvm/ADT/StringSet.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000022#include "llvm/ADT/StringRef.h"
Peter Collingbournec15d60b2017-05-01 20:42:32 +000023#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000024#include "llvm/IR/AutoUpgrade.h"
Teresa Johnson81bbf742017-12-16 00:18:12 +000025#include "llvm/IR/Constants.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000026#include "llvm/IR/Function.h"
27#include "llvm/IR/GlobalAlias.h"
28#include "llvm/IR/GlobalObject.h"
29#include "llvm/IR/GlobalValue.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/Metadata.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000032#include "llvm/IR/Module.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000033#include "llvm/IR/ModuleSummaryIndex.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000034#include "llvm/IRReader/IRReader.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000035#include "llvm/Linker/IRMover.h"
36#include "llvm/Object/ModuleSymbolTable.h"
37#include "llvm/Object/SymbolicFile.h"
38#include "llvm/Pass.h"
39#include "llvm/Support/Casting.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000040#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/Debug.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000042#include "llvm/Support/Error.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/FileSystem.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000045#include "llvm/Support/SourceMgr.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000046#include "llvm/Support/raw_ostream.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000047#include "llvm/Transforms/IPO/Internalize.h"
Teresa Johnson81bbf742017-12-16 00:18:12 +000048#include "llvm/Transforms/Utils/Cloning.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000049#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Teresa Johnson81bbf742017-12-16 00:18:12 +000050#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000051#include <cassert>
52#include <memory>
53#include <set>
54#include <string>
55#include <system_error>
56#include <tuple>
57#include <utility>
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000058
Mehdi Amini42418ab2015-11-24 06:07:49 +000059using namespace llvm;
60
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000061#define DEBUG_TYPE "function-import"
62
Teresa Johnson6c475a72017-01-05 21:34:18 +000063STATISTIC(NumImportedFunctions, "Number of functions imported");
64STATISTIC(NumImportedModules, "Number of modules imported from");
65STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
66STATISTIC(NumLiveSymbols, "Number of live symbols in index");
Teresa Johnsond29478f2016-03-27 15:27:30 +000067
Teresa Johnson39303612015-11-24 22:55:46 +000068/// Limit on instruction count of imported functions.
69static cl::opt<unsigned> ImportInstrLimit(
70 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
71 cl::desc("Only import functions with less than N instructions"));
72
Mehdi Amini40641742016-02-10 23:31:45 +000073static cl::opt<float>
74 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
75 cl::Hidden, cl::value_desc("x"),
76 cl::desc("As we import functions, multiply the "
77 "`import-instr-limit` threshold by this factor "
78 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000079
Piotr Padlewskid2869472016-09-30 03:01:17 +000080static cl::opt<float> ImportHotInstrFactor(
81 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
82 cl::value_desc("x"),
83 cl::desc("As we import functions called from hot callsite, multiply the "
84 "`import-instr-limit` threshold by this factor "
85 "before processing newly imported functions"));
86
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000087static cl::opt<float> ImportHotMultiplier(
Dehao Chen8260d662017-07-28 01:02:34 +000088 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000089 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
90
Dehao Chen64c46572017-07-07 21:01:00 +000091static cl::opt<float> ImportCriticalMultiplier(
92 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
93 cl::value_desc("x"),
94 cl::desc(
95 "Multiply the `import-instr-limit` threshold for critical callsites"));
96
Piotr Padlewskiba72b952016-09-29 17:32:07 +000097// FIXME: This multiplier was not really tuned up.
98static cl::opt<float> ImportColdMultiplier(
99 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
100 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +0000101
Teresa Johnsond29478f2016-03-27 15:27:30 +0000102static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
103 cl::desc("Print imported functions"));
104
Teresa Johnson6c475a72017-01-05 21:34:18 +0000105static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
106 cl::desc("Compute dead symbols"));
107
Piotr Padlewski3b776122016-07-08 23:01:49 +0000108static cl::opt<bool> EnableImportMetadata(
109 "enable-import-metadata", cl::init(
110#if !defined(NDEBUG)
111 true /*Enabled with asserts.*/
112#else
113 false
114#endif
115 ),
116 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
117
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000118/// Summary file to use for function importing when using -function-import from
119/// the command line.
120static cl::opt<std::string>
121 SummaryFile("summary-file",
122 cl::desc("The summary file to use for function importing."));
123
Teresa Johnson81bbf742017-12-16 00:18:12 +0000124/// Used when testing importing from distributed indexes via opt
125// -function-import.
126static cl::opt<bool>
127 ImportAllIndex("import-all-index",
128 cl::desc("Import all external functions in index."));
129
Mehdi Amini42418ab2015-11-24 06:07:49 +0000130// Load lazily a module from \p FileName in \p Context.
131static std::unique_ptr<Module> loadFile(const std::string &FileName,
132 LLVMContext &Context) {
133 SMDiagnostic Err;
134 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000135 // Metadata isn't loaded until functions are imported, to minimize
136 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000137 std::unique_ptr<Module> Result =
138 getLazyIRFileModule(FileName, Err, Context,
139 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000140 if (!Result) {
141 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000142 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000143 }
144
Mehdi Amini42418ab2015-11-24 06:07:49 +0000145 return Result;
146}
147
Mehdi Amini01e32132016-03-26 05:40:34 +0000148/// Given a list of possible callee implementation for a call site, select one
149/// that fits the \p Threshold.
150///
151/// FIXME: select "best" instead of first that fits. But what is "best"?
152/// - The smallest: more likely to be inlined.
153/// - The one with the least outgoing edges (already well optimized).
154/// - One from a module already being imported from in order to reduce the
155/// number of source modules parsed/linked.
156/// - One that has PGO data attached.
157/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000158static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000159selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000160 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000161 unsigned Threshold, StringRef CallerModulePath) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000162 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000163 CalleeSummaryList,
164 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
165 auto *GVSummary = SummaryPtr.get();
George Rimareaf51722018-01-29 08:03:30 +0000166 if (!Index.isGlobalValueLive(GVSummary))
167 return false;
168
Teresa Johnson73305f82017-08-19 18:04:25 +0000169 // For SamplePGO, in computeImportForFunction the OriginalId
170 // may have been used to locate the callee summary list (See
171 // comment there).
172 // The mapping from OriginalId to GUID may return a GUID
173 // that corresponds to a static variable. Filter it out here.
174 // This can happen when
175 // 1) There is a call to a library function which is not defined
176 // in the index.
177 // 2) There is a static variable with the OriginalGUID identical
178 // to the GUID of the library function in 1);
179 // When this happens, the logic for SamplePGO kicks in and
180 // the static variable in 2) will be found, which needs to be
181 // filtered out.
182 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
183 return false;
Rafael Espindolaf329be82016-05-11 01:26:06 +0000184 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000185 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000186 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000187
Teresa Johnson81bbf742017-12-16 00:18:12 +0000188 auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000189
Teresa Johnson83aaf352017-01-12 22:04:45 +0000190 // If this is a local function, make sure we import the copy
191 // in the caller's module. The only time a local function can
192 // share an entry in the index is if there is a local with the same name
193 // in another module that had the same source file name (in a different
194 // directory), where each was compiled in their own directory so there
195 // was not distinguishing path.
196 // However, do the import from another module if there is only one
197 // entry in the list - in that case this must be a reference due
198 // to indirect call profile data, since a function pointer can point to
199 // a local in another module.
200 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
201 CalleeSummaryList.size() > 1 &&
202 Summary->modulePath() != CallerModulePath)
203 return false;
204
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000205 if (Summary->instCount() > Threshold)
206 return false;
207
Teresa Johnson519465b2017-01-05 14:32:16 +0000208 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000209 return false;
210
Mehdi Amini01e32132016-03-26 05:40:34 +0000211 return true;
212 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000213 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000214 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000215
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000216 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000217}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000218
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000219namespace {
220
Teresa Johnson475b51a2016-12-15 20:48:19 +0000221using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
222 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000223
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000224} // anonymous namespace
225
Teresa Johnson19580832017-09-13 15:16:38 +0000226static ValueInfo
227updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
228 if (!VI.getSummaryList().empty())
229 return VI;
230 // For SamplePGO, the indirect call targets for local functions will
231 // have its original name annotated in profile. We try to find the
232 // corresponding PGOFuncName as the GUID.
233 // FIXME: Consider updating the edges in the graph after building
234 // it, rather than needing to perform this mapping on each walk.
235 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
236 if (GUID == 0)
Eugene Leviant28d8a492018-01-22 13:35:40 +0000237 return ValueInfo();
Teresa Johnson19580832017-09-13 15:16:38 +0000238 return Index.getValueInfo(GUID);
239}
240
Mehdi Amini01e32132016-03-26 05:40:34 +0000241/// Compute the list of functions to import for a given caller. Mark these
242/// imported functions and the symbols they reference in their source module as
243/// exported from their source module.
244static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000245 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000246 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000247 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000248 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000249 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000250 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000251 ValueInfo VI = Edge.first;
252 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
253 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000254
Teresa Johnson19580832017-09-13 15:16:38 +0000255 VI = updateValueInfoForIndirectCalls(Index, VI);
256 if (!VI)
257 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000258
Peter Collingbourne9667b912017-05-04 18:03:25 +0000259 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000260 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
261 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000262 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000263
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000264 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
265 if (Hotness == CalleeInfo::HotnessType::Hot)
266 return ImportHotMultiplier;
267 if (Hotness == CalleeInfo::HotnessType::Cold)
268 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000269 if (Hotness == CalleeInfo::HotnessType::Critical)
270 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000271 return 1.0;
272 };
273
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000274 const auto NewThreshold =
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000275 Threshold * GetBonusMultiplier(Edge.second.getHotness());
Piotr Padlewskid2869472016-09-30 03:01:17 +0000276
Peter Collingbourne9667b912017-05-04 18:03:25 +0000277 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
278 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000279 if (!CalleeSummary) {
280 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
281 continue;
282 }
David Blaikie2f0cc472017-07-27 15:09:06 +0000283
284 // "Resolve" the summary
Teresa Johnson81bbf742017-12-16 00:18:12 +0000285 const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary->getBaseObject());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000286
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000287 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000288 "selectCallee() didn't honor the threshold");
289
Piotr Padlewskid2869472016-09-30 03:01:17 +0000290 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
291 // Adjust the threshold for next level of imported functions.
292 // The threshold is different for hot callsites because we can then
293 // inline chains of hot calls.
294 if (IsHotCallsite)
295 return Threshold * ImportHotInstrFactor;
296 return Threshold * ImportInstrFactor;
297 };
298
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000299 bool IsHotCallsite =
300 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000301 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
302
303 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000304 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000305 /// Since the traversal of the call graph is DFS, we can revisit a function
306 /// a second time with a higher threshold. In this case, it is added back to
307 /// the worklist with the new threshold.
308 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
309 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
310 << ProcessedThreshold << "\n");
311 continue;
312 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000313 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000314 // Mark this function as imported in this module, with the current Threshold
315 ProcessedThreshold = AdjThreshold;
316
317 // Make exports in the source module.
318 if (ExportLists) {
319 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000320 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000321 if (!PreviouslyImported) {
322 // This is the first time this function was exported from its source
323 // module, so mark all functions and globals it references as exported
324 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000325 // For efficiency, we unconditionally add all the referenced GUIDs
326 // to the ExportList for this module, and will prune out any not
327 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000328 for (auto &Edge : ResolvedCalleeSummary->calls()) {
329 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000330 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000331 }
332 for (auto &Ref : ResolvedCalleeSummary->refs()) {
333 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000334 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000335 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000336 }
337 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000338
Mehdi Amini01e32132016-03-26 05:40:34 +0000339 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000340 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000341 }
342}
343
Mehdi Amini01e32132016-03-26 05:40:34 +0000344/// Given the list of globals defined in a module, compute the list of imports
345/// as well as the list of "exports", i.e. the list of symbols referenced from
346/// another module (that may require promotion).
347static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000348 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000349 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000350 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000351 // Worklist contains the list of function imported in this module, for which
352 // we will analyse the callees and may import further down the callgraph.
353 SmallVector<EdgeInfo, 128> Worklist;
354
355 // Populate the worklist with the import for the functions in the current
356 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000357 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000358 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000359 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
360 continue;
361 }
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000362 auto *FuncSummary =
363 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000364 if (!FuncSummary)
365 // Skip import for global variables
366 continue;
Xinliang David Li24524f32017-08-11 17:49:20 +0000367 DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000368 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000369 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000370 ExportLists);
371 }
372
Piotr Padlewskid2869472016-09-30 03:01:17 +0000373 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000374 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000375 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000376 auto *Summary = std::get<0>(FuncInfo);
377 auto Threshold = std::get<1>(FuncInfo);
378 auto GUID = std::get<2>(FuncInfo);
379
380 // Check if we later added this summary with a higher threshold.
381 // If so, skip this entry.
382 auto ExportModulePath = Summary->modulePath();
383 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
384 if (LatestProcessedThreshold > Threshold)
385 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000386
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000387 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000388 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000389 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000390}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000391
Teresa Johnsonc86af332016-04-12 21:13:11 +0000392/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000393void llvm::ComputeCrossModuleImport(
394 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000395 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000396 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000397 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000398 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000399 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000400 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000401 DEBUG(dbgs() << "Computing import for Module '"
402 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000403 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000404 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000405 }
406
Teresa Johnsonedddca22016-12-16 04:11:51 +0000407 // When computing imports we added all GUIDs referenced by anything
408 // imported from the module to its ExportList. Now we prune each ExportList
409 // of any not defined in that module. This is more efficient than checking
410 // while computing imports because some of the summary lists may be long
411 // due to linkonce (comdat) copies.
412 for (auto &ELI : ExportLists) {
413 const auto &DefinedGVSummaries =
414 ModuleToDefinedGVSummaries.lookup(ELI.first());
415 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
416 if (!DefinedGVSummaries.count(*EI))
417 EI = ELI.second.erase(EI);
418 else
419 ++EI;
420 }
421 }
422
Mehdi Amini01e32132016-03-26 05:40:34 +0000423#ifndef NDEBUG
424 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
425 << " modules:\n");
426 for (auto &ModuleImports : ImportLists) {
427 auto ModName = ModuleImports.first();
428 auto &Exports = ExportLists[ModName];
429 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
430 << " functions. Imports from " << ModuleImports.second.size()
431 << " modules.\n");
432 for (auto &Src : ModuleImports.second) {
433 auto SrcModName = Src.first();
434 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
435 << SrcModName << "\n");
436 }
437 }
438#endif
439}
440
Teresa Johnson81bbf742017-12-16 00:18:12 +0000441#ifndef NDEBUG
442static void dumpImportListForModule(StringRef ModulePath,
443 FunctionImporter::ImportMapTy &ImportList) {
444 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
445 << ImportList.size() << " modules.\n");
446 for (auto &Src : ImportList) {
447 auto SrcModName = Src.first();
448 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
449 << SrcModName << "\n");
450 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000451}
Teresa Johnson69b2de82017-12-16 00:29:31 +0000452#endif
Teresa Johnson81bbf742017-12-16 00:18:12 +0000453
Teresa Johnsonc86af332016-04-12 21:13:11 +0000454/// Compute all the imports for the given module in the Index.
455void llvm::ComputeCrossModuleImportForModule(
456 StringRef ModulePath, const ModuleSummaryIndex &Index,
457 FunctionImporter::ImportMapTy &ImportList) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000458 // Collect the list of functions this module defines.
459 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000460 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000461 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000462
463 // Compute the import list for this module.
464 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000465 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000466
467#ifndef NDEBUG
Teresa Johnson81bbf742017-12-16 00:18:12 +0000468 dumpImportListForModule(ModulePath, ImportList);
469#endif
470}
471
472// Mark all external summaries in Index for import into the given module.
473// Used for distributed builds using a distributed index.
474void llvm::ComputeCrossModuleImportForModuleFromIndex(
475 StringRef ModulePath, const ModuleSummaryIndex &Index,
476 FunctionImporter::ImportMapTy &ImportList) {
477 for (auto &GlobalList : Index) {
478 // Ignore entries for undefined references.
479 if (GlobalList.second.SummaryList.empty())
480 continue;
481
482 auto GUID = GlobalList.first;
483 assert(GlobalList.second.SummaryList.size() == 1 &&
484 "Expected individual combined index to have one summary per GUID");
485 auto &Summary = GlobalList.second.SummaryList[0];
486 // Skip the summaries for the importing module. These are included to
487 // e.g. record required linkage changes.
488 if (Summary->modulePath() == ModulePath)
489 continue;
490 // Doesn't matter what value we plug in to the map, just needs an entry
491 // to provoke importing by thinBackend.
492 ImportList[Summary->modulePath()][GUID] = 1;
Teresa Johnsonc86af332016-04-12 21:13:11 +0000493 }
Teresa Johnson81bbf742017-12-16 00:18:12 +0000494#ifndef NDEBUG
495 dumpImportListForModule(ModulePath, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000496#endif
497}
498
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000499void llvm::computeDeadSymbols(
500 ModuleSummaryIndex &Index,
George Rimareaf51722018-01-29 08:03:30 +0000501 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
502 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000503 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000504 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000505 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000506 if (GUIDPreservedSymbols.empty())
507 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000508 return;
509 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000510 SmallVector<ValueInfo, 128> Worklist;
511 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
512 for (auto GUID : GUIDPreservedSymbols) {
513 ValueInfo VI = Index.getValueInfo(GUID);
514 if (!VI)
515 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000516 for (auto &S : VI.getSummaryList())
517 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000518 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000519
Teresa Johnson6c475a72017-01-05 21:34:18 +0000520 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000521 for (const auto &Entry : Index)
522 for (auto &S : Entry.second.SummaryList)
523 if (S->isLive()) {
524 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
Eugene Leviant28d8a492018-01-22 13:35:40 +0000525 Worklist.push_back(ValueInfo(/*IsAnalysis=*/false, &Entry));
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000526 ++LiveSymbols;
527 break;
528 }
529
530 // Make value live and add it to the worklist if it was not live before.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000531 auto visit = [&](ValueInfo VI) {
Teresa Johnson19580832017-09-13 15:16:38 +0000532 // FIXME: If we knew which edges were created for indirect call profiles,
533 // we could skip them here. Any that are live should be reached via
534 // other edges, e.g. reference edges. Otherwise, using a profile collected
535 // on a slightly different binary might provoke preserving, importing
536 // and ultimately promoting calls to functions not linked into this
537 // binary, which increases the binary size unnecessarily. Note that
538 // if this code changes, the importer needs to change so that edges
539 // to functions marked dead are skipped.
540 VI = updateValueInfoForIndirectCalls(Index, VI);
541 if (!VI)
542 return;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000543 for (auto &S : VI.getSummaryList())
Teresa Johnsonf6251182017-09-20 17:09:47 +0000544 if (S->isLive())
545 return;
George Rimareaf51722018-01-29 08:03:30 +0000546
547 // We do not keep live symbols that are known to be non-prevailing.
548 if (isPrevailing(VI.getGUID()) == PrevailingType::No)
549 return;
550
Teresa Johnsonf6251182017-09-20 17:09:47 +0000551 for (auto &S : VI.getSummaryList())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000552 S->setLive(true);
553 ++LiveSymbols;
554 Worklist.push_back(VI);
555 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000556
557 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000558 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000559 for (auto &Summary : VI.getSummaryList()) {
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000560 GlobalValueSummary *Base = Summary->getBaseObject();
George Rimareaf51722018-01-29 08:03:30 +0000561 // Set base value live in case it is an alias.
562 Base->setLive(true);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000563 for (auto Ref : Base->refs())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000564 visit(Ref);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000565 if (auto *FS = dyn_cast<FunctionSummary>(Base))
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000566 for (auto Call : FS->calls())
567 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000568 }
569 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000570 Index.setWithGlobalValueDeadStripping();
571
572 unsigned DeadSymbols = Index.size() - LiveSymbols;
573 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
574 << " symbols Dead \n");
575 NumDeadSymbols += DeadSymbols;
576 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000577}
578
Teresa Johnson84174c32016-05-10 13:48:23 +0000579/// Compute the set of summaries needed for a ThinLTO backend compilation of
580/// \p ModulePath.
581void llvm::gatherImportedSummariesForModule(
582 StringRef ModulePath,
583 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000584 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000585 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
586 // Include all summaries from the importing module.
587 ModuleToSummariesForIndex[ModulePath] =
588 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000589 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000590 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000591 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
592 const auto &DefinedGVSummaries =
593 ModuleToDefinedGVSummaries.lookup(ILI.first());
594 for (auto &GI : ILI.second) {
595 const auto &DS = DefinedGVSummaries.find(GI.first);
596 assert(DS != DefinedGVSummaries.end() &&
597 "Expected a defined summary for imported global value");
598 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000599 }
600 }
601}
602
Teresa Johnson8570fe42016-05-10 15:54:09 +0000603/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000604std::error_code
605llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
606 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000607 std::error_code EC;
608 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
609 if (EC)
610 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000611 for (auto &ILI : ModuleImports)
612 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000613 return std::error_code();
614}
615
Teresa Johnson5a95c472018-02-05 15:44:27 +0000616bool llvm::convertToDeclaration(GlobalValue &GV) {
George Rimareaf51722018-01-29 08:03:30 +0000617 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
618 if (Function *F = dyn_cast<Function>(&GV)) {
619 F->deleteBody();
620 F->clearMetadata();
Peter Collingbourne78736692018-01-31 02:51:03 +0000621 F->setComdat(nullptr);
George Rimareaf51722018-01-29 08:03:30 +0000622 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
623 V->setInitializer(nullptr);
624 V->setLinkage(GlobalValue::ExternalLinkage);
625 V->clearMetadata();
Peter Collingbourne78736692018-01-31 02:51:03 +0000626 V->setComdat(nullptr);
Teresa Johnson5a95c472018-02-05 15:44:27 +0000627 } else {
628 GlobalValue *NewGV;
629 if (GV.getValueType()->isFunctionTy())
630 NewGV =
631 Function::Create(cast<FunctionType>(GV.getValueType()),
632 GlobalValue::ExternalLinkage, "", GV.getParent());
633 else
634 NewGV =
635 new GlobalVariable(*GV.getParent(), GV.getValueType(),
636 /*isConstant*/ false, GlobalValue::ExternalLinkage,
637 /*init*/ nullptr, "",
638 /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
639 GV.getType()->getAddressSpace());
640 NewGV->takeName(&GV);
641 GV.replaceAllUsesWith(NewGV);
642 return false;
643 }
644 return true;
George Rimareaf51722018-01-29 08:03:30 +0000645}
646
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000647/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
648void llvm::thinLTOResolveWeakForLinkerModule(
649 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
650 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000651 // See if the global summary analysis computed a new resolved linkage.
652 const auto &GS = DefinedGlobals.find(GV.getGUID());
653 if (GS == DefinedGlobals.end())
654 return;
655 auto NewLinkage = GS->second->linkage();
656 if (NewLinkage == GV.getLinkage())
657 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000658
659 // Switch the linkage to weakany if asked for, e.g. we do this for
660 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000661 // We record that the visibility should be changed here in `addThinLTO`
662 // as we need access to the resolution vectors for each input file in
663 // order to find which symbols have been redefined.
664 // We may consider reorganizing this code and moving the linkage recording
665 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000666 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
667 GV.setLinkage(NewLinkage);
668 return;
669 }
670
671 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
672 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000673 // Check for a non-prevailing def that has interposable linkage
674 // (e.g. non-odr weak or linkonce). In that case we can't simply
675 // convert to available_externally, since it would lose the
676 // interposable property and possibly get inlined. Simply drop
677 // the definition in that case.
678 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
Teresa Johnson5a95c472018-02-05 15:44:27 +0000679 GlobalValue::isInterposableLinkage(GV.getLinkage())) {
680 if (!convertToDeclaration(GV))
681 // FIXME: Change this to collect replaced GVs and later erase
682 // them from the parent module once thinLTOResolveWeakForLinkerGUID is
683 // changed to enable this for aliases.
684 llvm_unreachable("Expected GV to be converted");
685 } else {
Steven Wu33ba93c2018-02-09 18:34:08 +0000686 // If the original symbols has global unnamed addr and linkonce_odr linkage,
687 // it should be an auto hide symbol. Add hidden visibility to the symbol to
688 // preserve the property.
689 if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() &&
690 NewLinkage == GlobalValue::WeakODRLinkage)
691 GV.setVisibility(GlobalValue::HiddenVisibility);
692
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000693 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
694 << GV.getLinkage() << " to " << NewLinkage << "\n");
695 GV.setLinkage(NewLinkage);
696 }
697 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000698 // as this is a declaration for the linker, and will be dropped eventually.
699 // It is illegal for comdats to contain declarations.
700 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000701 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000702 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000703 };
704
705 // Process functions and global now
706 for (auto &GV : TheModule)
707 updateLinkage(GV);
708 for (auto &GV : TheModule.globals())
709 updateLinkage(GV);
710 for (auto &GV : TheModule.aliases())
711 updateLinkage(GV);
712}
713
714/// Run internalization on \p TheModule based on symmary analysis.
715void llvm::thinLTOInternalizeModule(Module &TheModule,
716 const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000717 // Declare a callback for the internalize pass that will ask for every
718 // candidate GlobalValue if it can be internalized or not.
719 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000720 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000721 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000722 if (GS == DefinedGlobals.end()) {
723 // Must have been promoted (possibly conservatively). Find original
724 // name so that we can access the correct summary and see if it can
725 // be internalized again.
726 // FIXME: Eventually we should control promotion instead of promoting
727 // and internalizing again.
728 StringRef OrigName =
729 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
730 std::string OrigId = GlobalValue::getGlobalIdentifier(
731 OrigName, GlobalValue::InternalLinkage,
732 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000733 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000734 if (GS == DefinedGlobals.end()) {
735 // Also check the original non-promoted non-globalized name. In some
736 // cases a preempted weak value is linked in as a local copy because
737 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
738 // In that case, since it was originally not a local value, it was
739 // recorded in the index using the original name.
740 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000741 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000742 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000743 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000744 }
745 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000746 };
747
748 // FIXME: See if we can just internalize directly here via linkage changes
749 // based on the index, rather than invoking internalizeModule.
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000750 internalizeModule(TheModule, MustPreserveGV);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000751}
752
Teresa Johnson81bbf742017-12-16 00:18:12 +0000753/// Make alias a clone of its aliasee.
754static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
755 Function *Fn = cast<Function>(GA->getBaseObject());
756
757 ValueToValueMapTy VMap;
758 Function *NewFn = CloneFunction(Fn, VMap);
759 // Clone should use the original alias's linkage and name, and we ensure
760 // all uses of alias instead use the new clone (casted if necessary).
761 NewFn->setLinkage(GA->getLinkage());
762 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
763 NewFn->takeName(GA);
764 return NewFn;
765}
766
Mehdi Aminic8c55172015-12-03 02:37:33 +0000767// Automatically import functions in Module \p DestModule based on the summaries
768// index.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000769Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000770 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000771 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000772 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000773 unsigned ImportedCount = 0;
774
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000775 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000776 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000777 std::set<StringRef> ModuleNameOrderedList;
778 for (auto &FunctionsToImportPerModule : ImportList) {
779 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
780 }
781 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000782 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000783 const auto &FunctionsToImportPerModule = ImportList.find(Name);
784 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000785 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
786 if (!SrcModuleOrErr)
787 return SrcModuleOrErr.takeError();
788 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000789 assert(&DestModule.getContext() == &SrcModule->getContext() &&
790 "Context mismatch");
791
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000792 // If modules were created with lazy metadata loading, materialize it
793 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000794 if (Error Err = SrcModule->materializeMetadata())
795 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000796
Mehdi Amini01e32132016-03-26 05:40:34 +0000797 auto &ImportGUIDs = FunctionsToImportPerModule->second;
798 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000799 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000800 for (Function &F : *SrcModule) {
801 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000802 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000803 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000804 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000805 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000806 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000807 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000808 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000809 if (Error Err = F.materialize())
810 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000811 if (EnableImportMetadata) {
812 // Add 'thinlto_src_module' metadata for statistics and debugging.
813 F.setMetadata(
814 "thinlto_src_module",
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000815 MDNode::get(DestModule.getContext(),
816 {MDString::get(DestModule.getContext(),
817 SrcModule->getSourceFileName())}));
Piotr Padlewski3b776122016-07-08 23:01:49 +0000818 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000819 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000820 }
821 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000822 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000823 if (!GV.hasName())
824 continue;
825 auto GUID = GV.getGUID();
826 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000827 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
828 << " " << GV.getName() << " from "
829 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000830 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000831 if (Error Err = GV.materialize())
832 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000833 GlobalsToImport.insert(&GV);
834 }
835 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000836 for (GlobalAlias &GA : SrcModule->aliases()) {
837 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000838 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000839 auto GUID = GA.getGUID();
Teresa Johnson81bbf742017-12-16 00:18:12 +0000840 auto Import = ImportGUIDs.count(GUID);
841 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000842 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000843 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson81bbf742017-12-16 00:18:12 +0000844 if (Import) {
845 if (Error Err = GA.materialize())
846 return std::move(Err);
847 // Import alias as a copy of its aliasee.
848 GlobalObject *Base = GA.getBaseObject();
849 if (Error Err = Base->materialize())
850 return std::move(Err);
851 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
852 DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
853 << " " << Base->getName() << " from "
854 << SrcModule->getSourceFileName() << "\n");
855 if (EnableImportMetadata) {
856 // Add 'thinlto_src_module' metadata for statistics and debugging.
857 Fn->setMetadata(
858 "thinlto_src_module",
859 MDNode::get(DestModule.getContext(),
860 {MDString::get(DestModule.getContext(),
861 SrcModule->getSourceFileName())}));
862 }
863 GlobalsToImport.insert(Fn);
864 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000865 }
866
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000867 // Upgrade debug info after we're done materializing all the globals and we
868 // have loaded all the required metadata!
869 UpgradeDebugInfo(*SrcModule);
870
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000871 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000872 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000873 return true;
874
Teresa Johnsond29478f2016-03-27 15:27:30 +0000875 if (PrintImports) {
876 for (const auto *GV : GlobalsToImport)
877 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
878 << " from " << SrcModule->getSourceFileName() << "\n";
879 }
880
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000881 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
882 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000883 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000884 report_fatal_error("Function Import: link error");
885
Mehdi Amini01e32132016-03-26 05:40:34 +0000886 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000887 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000888 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000889
Teresa Johnson6c475a72017-01-05 21:34:18 +0000890 NumImportedFunctions += ImportedCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000891
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000892 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000893 << DestModule.getModuleIdentifier() << "\n");
894 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000895}
896
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000897static bool doImportingForModule(Module &M) {
898 if (SummaryFile.empty())
899 report_fatal_error("error: -function-import requires -summary-file\n");
900 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
901 getModuleSummaryIndexForFile(SummaryFile);
902 if (!IndexPtrOrErr) {
903 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
904 "Error loading file '" + SummaryFile + "': ");
905 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000906 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000907 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000908
909 // First step is collecting the import list.
910 FunctionImporter::ImportMapTy ImportList;
Teresa Johnson81bbf742017-12-16 00:18:12 +0000911 // If requested, simply import all functions in the index. This is used
912 // when testing distributed backend handling via the opt tool, when
913 // we have distributed indexes containing exactly the summaries to import.
914 if (ImportAllIndex)
915 ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
916 ImportList);
917 else
918 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
919 ImportList);
Teresa Johnson21241572016-07-18 21:22:24 +0000920
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000921 // Conservatively mark all internal values as promoted. This interface is
922 // only used when doing importing via the function importing pass. The pass
923 // is only enabled when testing importing via the 'opt' tool, which does
924 // not do the ThinLink that would normally determine what values to promote.
925 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000926 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000927 if (GlobalValue::isLocalLinkage(S->linkage()))
928 S->setLinkage(GlobalValue::ExternalLinkage);
929 }
930 }
931
Teresa Johnson21241572016-07-18 21:22:24 +0000932 // Next we need to promote to global scope and rename any local values that
933 // are potentially exported to other modules.
934 if (renameModuleForThinLTO(M, *Index, nullptr)) {
935 errs() << "Error renaming module\n";
936 return false;
937 }
938
939 // Perform the import now.
940 auto ModuleLoader = [&M](StringRef Identifier) {
941 return loadFile(Identifier, M.getContext());
942 };
943 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +0000944 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000945
946 // FIXME: Probably need to propagate Errors through the pass manager.
947 if (!Result) {
948 logAllUnhandledErrors(Result.takeError(), errs(),
949 "Error importing module: ");
950 return false;
951 }
952
953 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000954}
955
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000956namespace {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000957
Mehdi Amini42418ab2015-11-24 06:07:49 +0000958/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000959class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000960public:
961 /// Pass identification, replacement for typeid
962 static char ID;
963
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000964 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
965
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000966 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000967 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000968
Mehdi Amini42418ab2015-11-24 06:07:49 +0000969 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000970 if (skipModule(M))
971 return false;
972
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000973 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000974 }
975};
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000976
977} // end anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000978
Teresa Johnson21241572016-07-18 21:22:24 +0000979PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000980 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000981 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000982 return PreservedAnalyses::all();
983
984 return PreservedAnalyses::none();
985}
986
987char FunctionImportLegacyPass::ID = 0;
988INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
989 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000990
991namespace llvm {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000992
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000993Pass *createFunctionImportPass() {
994 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000995}
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000996
997} // end namespace llvm