blob: 670a84862e0adb9c469d2c9725d0d96d7e2b4a54 [file] [log] [blame]
Mehdi Amini42418ab2015-11-24 06:07:49 +00001//===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Function import based on summaries.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/IPO/FunctionImport.h"
15
Mehdi Amini01e32132016-03-26 05:40:34 +000016#include "llvm/ADT/SmallVector.h"
Teresa Johnsond29478f2016-03-27 15:27:30 +000017#include "llvm/ADT/Statistic.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000018#include "llvm/ADT/StringSet.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000019#include "llvm/ADT/Triple.h"
Peter Collingbournec15d60b2017-05-01 20:42:32 +000020#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000021#include "llvm/IR/AutoUpgrade.h"
22#include "llvm/IR/DiagnosticPrinter.h"
23#include "llvm/IR/IntrinsicInst.h"
24#include "llvm/IR/Module.h"
Mehdi Aminifc06b832016-12-23 18:04:51 +000025#include "llvm/IR/Verifier.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000026#include "llvm/IRReader/IRReader.h"
27#include "llvm/Linker/Linker.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000028#include "llvm/Object/IRObjectFile.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/SourceMgr.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000032#include "llvm/Transforms/IPO/Internalize.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000033#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000034
Mehdi Amini01e32132016-03-26 05:40:34 +000035#define DEBUG_TYPE "function-import"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000036
Mehdi Amini42418ab2015-11-24 06:07:49 +000037using namespace llvm;
38
Teresa Johnson6c475a72017-01-05 21:34:18 +000039STATISTIC(NumImportedFunctions, "Number of functions imported");
40STATISTIC(NumImportedModules, "Number of modules imported from");
41STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
42STATISTIC(NumLiveSymbols, "Number of live symbols in index");
Teresa Johnsond29478f2016-03-27 15:27:30 +000043
Teresa Johnson39303612015-11-24 22:55:46 +000044/// Limit on instruction count of imported functions.
45static cl::opt<unsigned> ImportInstrLimit(
46 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
47 cl::desc("Only import functions with less than N instructions"));
48
Mehdi Amini40641742016-02-10 23:31:45 +000049static cl::opt<float>
50 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
51 cl::Hidden, cl::value_desc("x"),
52 cl::desc("As we import functions, multiply the "
53 "`import-instr-limit` threshold by this factor "
54 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000055
Piotr Padlewskid2869472016-09-30 03:01:17 +000056static cl::opt<float> ImportHotInstrFactor(
57 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
58 cl::value_desc("x"),
59 cl::desc("As we import functions called from hot callsite, multiply the "
60 "`import-instr-limit` threshold by this factor "
61 "before processing newly imported functions"));
62
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000063static cl::opt<float> ImportHotMultiplier(
Dehao Chen8260d662017-07-28 01:02:34 +000064 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000065 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
66
Dehao Chen64c46572017-07-07 21:01:00 +000067static cl::opt<float> ImportCriticalMultiplier(
68 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
69 cl::value_desc("x"),
70 cl::desc(
71 "Multiply the `import-instr-limit` threshold for critical callsites"));
72
Piotr Padlewskiba72b952016-09-29 17:32:07 +000073// FIXME: This multiplier was not really tuned up.
74static cl::opt<float> ImportColdMultiplier(
75 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
76 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +000077
Teresa Johnsond29478f2016-03-27 15:27:30 +000078static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
79 cl::desc("Print imported functions"));
80
Teresa Johnson6c475a72017-01-05 21:34:18 +000081static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
82 cl::desc("Compute dead symbols"));
83
Piotr Padlewski3b776122016-07-08 23:01:49 +000084static cl::opt<bool> EnableImportMetadata(
85 "enable-import-metadata", cl::init(
86#if !defined(NDEBUG)
87 true /*Enabled with asserts.*/
88#else
89 false
90#endif
91 ),
92 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
93
Mehdi Amini42418ab2015-11-24 06:07:49 +000094// Load lazily a module from \p FileName in \p Context.
95static std::unique_ptr<Module> loadFile(const std::string &FileName,
96 LLVMContext &Context) {
97 SMDiagnostic Err;
98 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000099 // Metadata isn't loaded until functions are imported, to minimize
100 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000101 std::unique_ptr<Module> Result =
102 getLazyIRFileModule(FileName, Err, Context,
103 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000104 if (!Result) {
105 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000106 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000107 }
108
Mehdi Amini42418ab2015-11-24 06:07:49 +0000109 return Result;
110}
111
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000112namespace {
Mehdi Amini40641742016-02-10 23:31:45 +0000113
Mehdi Amini01e32132016-03-26 05:40:34 +0000114/// Given a list of possible callee implementation for a call site, select one
115/// that fits the \p Threshold.
116///
117/// FIXME: select "best" instead of first that fits. But what is "best"?
118/// - The smallest: more likely to be inlined.
119/// - The one with the least outgoing edges (already well optimized).
120/// - One from a module already being imported from in order to reduce the
121/// number of source modules parsed/linked.
122/// - One that has PGO data attached.
123/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000124static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000125selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000126 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000127 unsigned Threshold, StringRef CallerModulePath) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000128 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000129 CalleeSummaryList,
130 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
131 auto *GVSummary = SummaryPtr.get();
Teresa Johnson73305f82017-08-19 18:04:25 +0000132 // For SamplePGO, in computeImportForFunction the OriginalId
133 // may have been used to locate the callee summary list (See
134 // comment there).
135 // The mapping from OriginalId to GUID may return a GUID
136 // that corresponds to a static variable. Filter it out here.
137 // This can happen when
138 // 1) There is a call to a library function which is not defined
139 // in the index.
140 // 2) There is a static variable with the OriginalGUID identical
141 // to the GUID of the library function in 1);
142 // When this happens, the logic for SamplePGO kicks in and
143 // the static variable in 2) will be found, which needs to be
144 // filtered out.
145 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
146 return false;
Rafael Espindolaf329be82016-05-11 01:26:06 +0000147 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000148 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000149 return false;
Davide Italiano82c7d372017-07-27 18:38:09 +0000150 if (isa<AliasSummary>(GVSummary))
David Blaikie2f0cc472017-07-27 15:09:06 +0000151 // Aliases can't point to "available_externally".
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000152 // FIXME: we should import alias as available_externally *function*,
David Blaikie2f0cc472017-07-27 15:09:06 +0000153 // the destination module does not need to know it is an alias.
154 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000155
156 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000157
Teresa Johnson83aaf352017-01-12 22:04:45 +0000158 // If this is a local function, make sure we import the copy
159 // in the caller's module. The only time a local function can
160 // share an entry in the index is if there is a local with the same name
161 // in another module that had the same source file name (in a different
162 // directory), where each was compiled in their own directory so there
163 // was not distinguishing path.
164 // However, do the import from another module if there is only one
165 // entry in the list - in that case this must be a reference due
166 // to indirect call profile data, since a function pointer can point to
167 // a local in another module.
168 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
169 CalleeSummaryList.size() > 1 &&
170 Summary->modulePath() != CallerModulePath)
171 return false;
172
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000173 if (Summary->instCount() > Threshold)
174 return false;
175
Teresa Johnson519465b2017-01-05 14:32:16 +0000176 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000177 return false;
178
Mehdi Amini01e32132016-03-26 05:40:34 +0000179 return true;
180 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000181 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000182 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000183
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000184 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000185}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000186
Teresa Johnson475b51a2016-12-15 20:48:19 +0000187using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
188 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000189
Teresa Johnson19580832017-09-13 15:16:38 +0000190static ValueInfo
191updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
192 if (!VI.getSummaryList().empty())
193 return VI;
194 // For SamplePGO, the indirect call targets for local functions will
195 // have its original name annotated in profile. We try to find the
196 // corresponding PGOFuncName as the GUID.
197 // FIXME: Consider updating the edges in the graph after building
198 // it, rather than needing to perform this mapping on each walk.
199 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
200 if (GUID == 0)
201 return nullptr;
202 return Index.getValueInfo(GUID);
203}
204
Mehdi Amini01e32132016-03-26 05:40:34 +0000205/// Compute the list of functions to import for a given caller. Mark these
206/// imported functions and the symbols they reference in their source module as
207/// exported from their source module.
208static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000209 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000210 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000211 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000212 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000213 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000214 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000215 ValueInfo VI = Edge.first;
216 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
217 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000218
Teresa Johnson19580832017-09-13 15:16:38 +0000219 VI = updateValueInfoForIndirectCalls(Index, VI);
220 if (!VI)
221 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000222
Peter Collingbourne9667b912017-05-04 18:03:25 +0000223 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000224 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
225 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000226 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000227
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000228 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
229 if (Hotness == CalleeInfo::HotnessType::Hot)
230 return ImportHotMultiplier;
231 if (Hotness == CalleeInfo::HotnessType::Cold)
232 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000233 if (Hotness == CalleeInfo::HotnessType::Critical)
234 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000235 return 1.0;
236 };
237
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000238 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000239 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000240
Peter Collingbourne9667b912017-05-04 18:03:25 +0000241 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
242 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000243 if (!CalleeSummary) {
244 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
245 continue;
246 }
David Blaikie2f0cc472017-07-27 15:09:06 +0000247
248 // "Resolve" the summary
249 assert(!isa<AliasSummary>(CalleeSummary) &&
250 "Unexpected alias in import list");
251 const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000252
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000253 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000254 "selectCallee() didn't honor the threshold");
255
Piotr Padlewskid2869472016-09-30 03:01:17 +0000256 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
257 // Adjust the threshold for next level of imported functions.
258 // The threshold is different for hot callsites because we can then
259 // inline chains of hot calls.
260 if (IsHotCallsite)
261 return Threshold * ImportHotInstrFactor;
262 return Threshold * ImportInstrFactor;
263 };
264
265 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000266 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
267
268 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000269 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000270 /// Since the traversal of the call graph is DFS, we can revisit a function
271 /// a second time with a higher threshold. In this case, it is added back to
272 /// the worklist with the new threshold.
273 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
274 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
275 << ProcessedThreshold << "\n");
276 continue;
277 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000278 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000279 // Mark this function as imported in this module, with the current Threshold
280 ProcessedThreshold = AdjThreshold;
281
282 // Make exports in the source module.
283 if (ExportLists) {
284 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000285 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000286 if (!PreviouslyImported) {
287 // This is the first time this function was exported from its source
288 // module, so mark all functions and globals it references as exported
289 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000290 // For efficiency, we unconditionally add all the referenced GUIDs
291 // to the ExportList for this module, and will prune out any not
292 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000293 for (auto &Edge : ResolvedCalleeSummary->calls()) {
294 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000295 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000296 }
297 for (auto &Ref : ResolvedCalleeSummary->refs()) {
298 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000299 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000300 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000301 }
302 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000303
Mehdi Amini01e32132016-03-26 05:40:34 +0000304 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000305 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000306 }
307}
308
Mehdi Amini01e32132016-03-26 05:40:34 +0000309/// Given the list of globals defined in a module, compute the list of imports
310/// as well as the list of "exports", i.e. the list of symbols referenced from
311/// another module (that may require promotion).
312static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000313 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000314 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000315 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000316 // Worklist contains the list of function imported in this module, for which
317 // we will analyse the callees and may import further down the callgraph.
318 SmallVector<EdgeInfo, 128> Worklist;
319
320 // Populate the worklist with the import for the functions in the current
321 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000322 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000323 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000324 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
325 continue;
326 }
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000327 auto *FuncSummary =
328 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000329 if (!FuncSummary)
330 // Skip import for global variables
331 continue;
Xinliang David Li24524f32017-08-11 17:49:20 +0000332 DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000333 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000334 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000335 ExportLists);
336 }
337
Piotr Padlewskid2869472016-09-30 03:01:17 +0000338 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000339 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000340 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000341 auto *Summary = std::get<0>(FuncInfo);
342 auto Threshold = std::get<1>(FuncInfo);
343 auto GUID = std::get<2>(FuncInfo);
344
345 // Check if we later added this summary with a higher threshold.
346 // If so, skip this entry.
347 auto ExportModulePath = Summary->modulePath();
348 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
349 if (LatestProcessedThreshold > Threshold)
350 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000351
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000352 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000353 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000354 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000355}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000356
Mehdi Amini01e32132016-03-26 05:40:34 +0000357} // anonymous namespace
358
Teresa Johnsonc86af332016-04-12 21:13:11 +0000359/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000360void llvm::ComputeCrossModuleImport(
361 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000362 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000363 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000364 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000365 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000366 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000367 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000368 DEBUG(dbgs() << "Computing import for Module '"
369 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000370 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000371 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000372 }
373
Teresa Johnsonedddca22016-12-16 04:11:51 +0000374 // When computing imports we added all GUIDs referenced by anything
375 // imported from the module to its ExportList. Now we prune each ExportList
376 // of any not defined in that module. This is more efficient than checking
377 // while computing imports because some of the summary lists may be long
378 // due to linkonce (comdat) copies.
379 for (auto &ELI : ExportLists) {
380 const auto &DefinedGVSummaries =
381 ModuleToDefinedGVSummaries.lookup(ELI.first());
382 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
383 if (!DefinedGVSummaries.count(*EI))
384 EI = ELI.second.erase(EI);
385 else
386 ++EI;
387 }
388 }
389
Mehdi Amini01e32132016-03-26 05:40:34 +0000390#ifndef NDEBUG
391 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
392 << " modules:\n");
393 for (auto &ModuleImports : ImportLists) {
394 auto ModName = ModuleImports.first();
395 auto &Exports = ExportLists[ModName];
396 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
397 << " functions. Imports from " << ModuleImports.second.size()
398 << " modules.\n");
399 for (auto &Src : ModuleImports.second) {
400 auto SrcModName = Src.first();
401 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
402 << SrcModName << "\n");
403 }
404 }
405#endif
406}
407
Teresa Johnsonc86af332016-04-12 21:13:11 +0000408/// Compute all the imports for the given module in the Index.
409void llvm::ComputeCrossModuleImportForModule(
410 StringRef ModulePath, const ModuleSummaryIndex &Index,
411 FunctionImporter::ImportMapTy &ImportList) {
412
413 // Collect the list of functions this module defines.
414 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000415 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000416 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000417
418 // Compute the import list for this module.
419 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000420 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000421
422#ifndef NDEBUG
423 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
424 << ImportList.size() << " modules.\n");
425 for (auto &Src : ImportList) {
426 auto SrcModName = Src.first();
427 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
428 << SrcModName << "\n");
429 }
430#endif
431}
432
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000433void llvm::computeDeadSymbols(
434 ModuleSummaryIndex &Index,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000435 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000436 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000437 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000438 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000439 if (GUIDPreservedSymbols.empty())
440 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000441 return;
442 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000443 SmallVector<ValueInfo, 128> Worklist;
444 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
445 for (auto GUID : GUIDPreservedSymbols) {
446 ValueInfo VI = Index.getValueInfo(GUID);
447 if (!VI)
448 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000449 for (auto &S : VI.getSummaryList())
450 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000451 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000452
Teresa Johnson6c475a72017-01-05 21:34:18 +0000453 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000454 for (const auto &Entry : Index)
455 for (auto &S : Entry.second.SummaryList)
456 if (S->isLive()) {
457 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
458 Worklist.push_back(ValueInfo(&Entry));
459 ++LiveSymbols;
460 break;
461 }
462
463 // Make value live and add it to the worklist if it was not live before.
464 // FIXME: we should only make the prevailing copy live here
465 auto visit = [&](ValueInfo VI) {
Teresa Johnson19580832017-09-13 15:16:38 +0000466 // FIXME: If we knew which edges were created for indirect call profiles,
467 // we could skip them here. Any that are live should be reached via
468 // other edges, e.g. reference edges. Otherwise, using a profile collected
469 // on a slightly different binary might provoke preserving, importing
470 // and ultimately promoting calls to functions not linked into this
471 // binary, which increases the binary size unnecessarily. Note that
472 // if this code changes, the importer needs to change so that edges
473 // to functions marked dead are skipped.
474 VI = updateValueInfoForIndirectCalls(Index, VI);
475 if (!VI)
476 return;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000477 for (auto &S : VI.getSummaryList())
Teresa Johnsonf6251182017-09-20 17:09:47 +0000478 if (S->isLive())
479 return;
480 for (auto &S : VI.getSummaryList())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000481 S->setLive(true);
482 ++LiveSymbols;
483 Worklist.push_back(VI);
484 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000485
486 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000487 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000488 for (auto &Summary : VI.getSummaryList()) {
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000489 GlobalValueSummary *Base = Summary->getBaseObject();
490 for (auto Ref : Base->refs())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000491 visit(Ref);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000492 if (auto *FS = dyn_cast<FunctionSummary>(Base))
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000493 for (auto Call : FS->calls())
494 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000495 }
496 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000497 Index.setWithGlobalValueDeadStripping();
498
499 unsigned DeadSymbols = Index.size() - LiveSymbols;
500 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
501 << " symbols Dead \n");
502 NumDeadSymbols += DeadSymbols;
503 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000504}
505
Teresa Johnson84174c32016-05-10 13:48:23 +0000506/// Compute the set of summaries needed for a ThinLTO backend compilation of
507/// \p ModulePath.
508void llvm::gatherImportedSummariesForModule(
509 StringRef ModulePath,
510 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000511 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000512 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
513 // Include all summaries from the importing module.
514 ModuleToSummariesForIndex[ModulePath] =
515 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000516 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000517 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000518 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
519 const auto &DefinedGVSummaries =
520 ModuleToDefinedGVSummaries.lookup(ILI.first());
521 for (auto &GI : ILI.second) {
522 const auto &DS = DefinedGVSummaries.find(GI.first);
523 assert(DS != DefinedGVSummaries.end() &&
524 "Expected a defined summary for imported global value");
525 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000526 }
527 }
528}
529
Teresa Johnson8570fe42016-05-10 15:54:09 +0000530/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000531std::error_code
532llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
533 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000534 std::error_code EC;
535 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
536 if (EC)
537 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000538 for (auto &ILI : ModuleImports)
539 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000540 return std::error_code();
541}
542
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000543/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
544void llvm::thinLTOResolveWeakForLinkerModule(
545 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000546 auto ConvertToDeclaration = [](GlobalValue &GV) {
547 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
548 if (Function *F = dyn_cast<Function>(&GV)) {
549 F->deleteBody();
550 F->clearMetadata();
551 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
552 V->setInitializer(nullptr);
553 V->setLinkage(GlobalValue::ExternalLinkage);
554 V->clearMetadata();
555 } else
556 // For now we don't resolve or drop aliases. Once we do we'll
557 // need to add support here for creating either a function or
558 // variable declaration, and return the new GlobalValue* for
559 // the caller to use.
Davide Italiano91239082017-04-14 17:22:02 +0000560 llvm_unreachable("Expected function or variable");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000561 };
562
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000563 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000564 // See if the global summary analysis computed a new resolved linkage.
565 const auto &GS = DefinedGlobals.find(GV.getGUID());
566 if (GS == DefinedGlobals.end())
567 return;
568 auto NewLinkage = GS->second->linkage();
569 if (NewLinkage == GV.getLinkage())
570 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000571
572 // Switch the linkage to weakany if asked for, e.g. we do this for
573 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000574 // We record that the visibility should be changed here in `addThinLTO`
575 // as we need access to the resolution vectors for each input file in
576 // order to find which symbols have been redefined.
577 // We may consider reorganizing this code and moving the linkage recording
578 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000579 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
580 GV.setLinkage(NewLinkage);
581 return;
582 }
583
584 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
585 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000586 // Check for a non-prevailing def that has interposable linkage
587 // (e.g. non-odr weak or linkonce). In that case we can't simply
588 // convert to available_externally, since it would lose the
589 // interposable property and possibly get inlined. Simply drop
590 // the definition in that case.
591 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
592 GlobalValue::isInterposableLinkage(GV.getLinkage()))
593 ConvertToDeclaration(GV);
594 else {
595 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
596 << GV.getLinkage() << " to " << NewLinkage << "\n");
597 GV.setLinkage(NewLinkage);
598 }
599 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000600 // as this is a declaration for the linker, and will be dropped eventually.
601 // It is illegal for comdats to contain declarations.
602 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000603 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000604 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000605 };
606
607 // Process functions and global now
608 for (auto &GV : TheModule)
609 updateLinkage(GV);
610 for (auto &GV : TheModule.globals())
611 updateLinkage(GV);
612 for (auto &GV : TheModule.aliases())
613 updateLinkage(GV);
614}
615
616/// Run internalization on \p TheModule based on symmary analysis.
617void llvm::thinLTOInternalizeModule(Module &TheModule,
618 const GVSummaryMapTy &DefinedGlobals) {
619 // Parse inline ASM and collect the list of symbols that are not defined in
620 // the current module.
621 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000622 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnsond8204472017-03-09 00:19:49 +0000623 TheModule,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000624 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
625 if (Flags & object::BasicSymbolRef::SF_Undefined)
626 AsmUndefinedRefs.insert(Name);
627 });
628
629 // Declare a callback for the internalize pass that will ask for every
630 // candidate GlobalValue if it can be internalized or not.
631 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
632 // Can't be internalized if referenced in inline asm.
633 if (AsmUndefinedRefs.count(GV.getName()))
634 return true;
635
636 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000637 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000638 if (GS == DefinedGlobals.end()) {
639 // Must have been promoted (possibly conservatively). Find original
640 // name so that we can access the correct summary and see if it can
641 // be internalized again.
642 // FIXME: Eventually we should control promotion instead of promoting
643 // and internalizing again.
644 StringRef OrigName =
645 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
646 std::string OrigId = GlobalValue::getGlobalIdentifier(
647 OrigName, GlobalValue::InternalLinkage,
648 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000649 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000650 if (GS == DefinedGlobals.end()) {
651 // Also check the original non-promoted non-globalized name. In some
652 // cases a preempted weak value is linked in as a local copy because
653 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
654 // In that case, since it was originally not a local value, it was
655 // recorded in the index using the original name.
656 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000657 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000658 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000659 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000660 }
661 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000662 };
663
664 // FIXME: See if we can just internalize directly here via linkage changes
665 // based on the index, rather than invoking internalizeModule.
666 llvm::internalizeModule(TheModule, MustPreserveGV);
667}
668
Mehdi Aminic8c55172015-12-03 02:37:33 +0000669// Automatically import functions in Module \p DestModule based on the summaries
670// index.
671//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000672Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000673 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000674 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000675 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000676 unsigned ImportedCount = 0;
677
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000678 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000679 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000680 std::set<StringRef> ModuleNameOrderedList;
681 for (auto &FunctionsToImportPerModule : ImportList) {
682 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
683 }
684 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000685 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000686 const auto &FunctionsToImportPerModule = ImportList.find(Name);
687 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000688 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
689 if (!SrcModuleOrErr)
690 return SrcModuleOrErr.takeError();
691 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000692 assert(&DestModule.getContext() == &SrcModule->getContext() &&
693 "Context mismatch");
694
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000695 // If modules were created with lazy metadata loading, materialize it
696 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000697 if (Error Err = SrcModule->materializeMetadata())
698 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000699
Mehdi Amini01e32132016-03-26 05:40:34 +0000700 auto &ImportGUIDs = FunctionsToImportPerModule->second;
701 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000702 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000703 for (Function &F : *SrcModule) {
704 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000705 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000706 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000707 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000708 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000709 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000710 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000711 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000712 if (Error Err = F.materialize())
713 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000714 if (EnableImportMetadata) {
715 // Add 'thinlto_src_module' metadata for statistics and debugging.
716 F.setMetadata(
717 "thinlto_src_module",
718 llvm::MDNode::get(
719 DestModule.getContext(),
720 {llvm::MDString::get(DestModule.getContext(),
721 SrcModule->getSourceFileName())}));
722 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000723 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000724 }
725 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000726 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000727 if (!GV.hasName())
728 continue;
729 auto GUID = GV.getGUID();
730 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000731 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
732 << " " << GV.getName() << " from "
733 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000734 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000735 if (Error Err = GV.materialize())
736 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000737 GlobalsToImport.insert(&GV);
738 }
739 }
Benjamin Kramer154411e2017-08-29 20:24:39 +0000740#ifndef NDEBUG
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000741 for (GlobalAlias &GA : SrcModule->aliases()) {
742 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000743 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000744 auto GUID = GA.getGUID();
Teresa Johnson2df7fc72017-08-29 18:15:34 +0000745 assert(!ImportGUIDs.count(GUID) && "Unexpected alias in import list");
746 DEBUG(dbgs() << "Not importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000747 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000748 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000749 }
Benjamin Kramer154411e2017-08-29 20:24:39 +0000750#endif
Mehdi Amini01e32132016-03-26 05:40:34 +0000751
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000752 // Upgrade debug info after we're done materializing all the globals and we
753 // have loaded all the required metadata!
754 UpgradeDebugInfo(*SrcModule);
755
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000756 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000757 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000758 return true;
759
Teresa Johnsond29478f2016-03-27 15:27:30 +0000760 if (PrintImports) {
761 for (const auto *GV : GlobalsToImport)
762 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
763 << " from " << SrcModule->getSourceFileName() << "\n";
764 }
765
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000766 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
767 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000768 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000769 report_fatal_error("Function Import: link error");
770
Mehdi Amini01e32132016-03-26 05:40:34 +0000771 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000772 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000773 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000774
Teresa Johnson6c475a72017-01-05 21:34:18 +0000775 NumImportedFunctions += ImportedCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000776
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000777 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000778 << DestModule.getModuleIdentifier() << "\n");
779 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000780}
781
782/// Summary file to use for function importing when using -function-import from
783/// the command line.
784static cl::opt<std::string>
785 SummaryFile("summary-file",
786 cl::desc("The summary file to use for function importing."));
787
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000788static bool doImportingForModule(Module &M) {
789 if (SummaryFile.empty())
790 report_fatal_error("error: -function-import requires -summary-file\n");
791 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
792 getModuleSummaryIndexForFile(SummaryFile);
793 if (!IndexPtrOrErr) {
794 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
795 "Error loading file '" + SummaryFile + "': ");
796 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000797 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000798 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000799
800 // First step is collecting the import list.
801 FunctionImporter::ImportMapTy ImportList;
802 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
803 ImportList);
804
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000805 // Conservatively mark all internal values as promoted. This interface is
806 // only used when doing importing via the function importing pass. The pass
807 // is only enabled when testing importing via the 'opt' tool, which does
808 // not do the ThinLink that would normally determine what values to promote.
809 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000810 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000811 if (GlobalValue::isLocalLinkage(S->linkage()))
812 S->setLinkage(GlobalValue::ExternalLinkage);
813 }
814 }
815
Teresa Johnson21241572016-07-18 21:22:24 +0000816 // Next we need to promote to global scope and rename any local values that
817 // are potentially exported to other modules.
818 if (renameModuleForThinLTO(M, *Index, nullptr)) {
819 errs() << "Error renaming module\n";
820 return false;
821 }
822
823 // Perform the import now.
824 auto ModuleLoader = [&M](StringRef Identifier) {
825 return loadFile(Identifier, M.getContext());
826 };
827 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +0000828 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000829
830 // FIXME: Probably need to propagate Errors through the pass manager.
831 if (!Result) {
832 logAllUnhandledErrors(Result.takeError(), errs(),
833 "Error importing module: ");
834 return false;
835 }
836
837 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000838}
839
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000840namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000841/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000842class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000843public:
844 /// Pass identification, replacement for typeid
845 static char ID;
846
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000847 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000848 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000849
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000850 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000851
852 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000853 if (skipModule(M))
854 return false;
855
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000856 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000857 }
858};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000859} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000860
Teresa Johnson21241572016-07-18 21:22:24 +0000861PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000862 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000863 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000864 return PreservedAnalyses::all();
865
866 return PreservedAnalyses::none();
867}
868
869char FunctionImportLegacyPass::ID = 0;
870INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
871 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000872
873namespace llvm {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000874Pass *createFunctionImportPass() {
875 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000876}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000877}