blob: 5e7cf436e2e3fabc8e4446737bce369899f56f6d [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(
64 "import-hot-multiplier", cl::init(3.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
67// FIXME: This multiplier was not really tuned up.
68static cl::opt<float> ImportColdMultiplier(
69 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
70 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +000071
Teresa Johnsond29478f2016-03-27 15:27:30 +000072static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
73 cl::desc("Print imported functions"));
74
Teresa Johnson6c475a72017-01-05 21:34:18 +000075static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
76 cl::desc("Compute dead symbols"));
77
Piotr Padlewski3b776122016-07-08 23:01:49 +000078static cl::opt<bool> EnableImportMetadata(
79 "enable-import-metadata", cl::init(
80#if !defined(NDEBUG)
81 true /*Enabled with asserts.*/
82#else
83 false
84#endif
85 ),
86 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
87
Mehdi Amini42418ab2015-11-24 06:07:49 +000088// Load lazily a module from \p FileName in \p Context.
89static std::unique_ptr<Module> loadFile(const std::string &FileName,
90 LLVMContext &Context) {
91 SMDiagnostic Err;
92 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000093 // Metadata isn't loaded until functions are imported, to minimize
94 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +000095 std::unique_ptr<Module> Result =
96 getLazyIRFileModule(FileName, Err, Context,
97 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +000098 if (!Result) {
99 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000100 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000101 }
102
Mehdi Amini42418ab2015-11-24 06:07:49 +0000103 return Result;
104}
105
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000106namespace {
Mehdi Amini40641742016-02-10 23:31:45 +0000107
Mehdi Amini01e32132016-03-26 05:40:34 +0000108/// Given a list of possible callee implementation for a call site, select one
109/// that fits the \p Threshold.
110///
111/// FIXME: select "best" instead of first that fits. But what is "best"?
112/// - The smallest: more likely to be inlined.
113/// - The one with the least outgoing edges (already well optimized).
114/// - One from a module already being imported from in order to reduce the
115/// number of source modules parsed/linked.
116/// - One that has PGO data attached.
117/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000118static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000119selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000120 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000121 unsigned Threshold, StringRef CallerModulePath) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000122 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000123 CalleeSummaryList,
124 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
125 auto *GVSummary = SummaryPtr.get();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000126 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000127 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000128 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000129 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
130 GVSummary = &AS->getAliasee();
131 // Alias can't point to "available_externally". However when we import
132 // linkOnceODR the linkage does not change. So we import the alias
133 // and aliasee only in this case.
134 // FIXME: we should import alias as available_externally *function*,
135 // the destination module does need to know it is an alias.
136 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
137 return false;
138 }
139
140 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000141
Teresa Johnson83aaf352017-01-12 22:04:45 +0000142 // If this is a local function, make sure we import the copy
143 // in the caller's module. The only time a local function can
144 // share an entry in the index is if there is a local with the same name
145 // in another module that had the same source file name (in a different
146 // directory), where each was compiled in their own directory so there
147 // was not distinguishing path.
148 // However, do the import from another module if there is only one
149 // entry in the list - in that case this must be a reference due
150 // to indirect call profile data, since a function pointer can point to
151 // a local in another module.
152 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
153 CalleeSummaryList.size() > 1 &&
154 Summary->modulePath() != CallerModulePath)
155 return false;
156
Mehdi Amini01e32132016-03-26 05:40:34 +0000157 if (Summary->instCount() > Threshold)
158 return false;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000159
Teresa Johnson519465b2017-01-05 14:32:16 +0000160 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000161 return false;
162
Mehdi Amini01e32132016-03-26 05:40:34 +0000163 return true;
164 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000165 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000166 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000167
Teresa Johnson28e457b2016-04-24 14:57:11 +0000168 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000169}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000170
Teresa Johnson475b51a2016-12-15 20:48:19 +0000171using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
172 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000173
Mehdi Amini01e32132016-03-26 05:40:34 +0000174/// Compute the list of functions to import for a given caller. Mark these
175/// imported functions and the symbols they reference in their source module as
176/// exported from their source module.
177static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000178 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000179 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000180 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000181 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000182 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000183 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000184 ValueInfo VI = Edge.first;
185 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
186 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000187
Peter Collingbourne9667b912017-05-04 18:03:25 +0000188 if (VI.getSummaryList().empty()) {
Dehao Chen4a435e02017-03-14 17:33:01 +0000189 // For SamplePGO, the indirect call targets for local functions will
190 // have its original name annotated in profile. We try to find the
191 // corresponding PGOFuncName as the GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000192 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
Dehao Chen4a435e02017-03-14 17:33:01 +0000193 if (GUID == 0)
194 continue;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000195 VI = Index.getValueInfo(GUID);
196 if (!VI)
197 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000198 }
199
Peter Collingbourne9667b912017-05-04 18:03:25 +0000200 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000201 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
202 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000203 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000204
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000205 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
206 if (Hotness == CalleeInfo::HotnessType::Hot)
207 return ImportHotMultiplier;
208 if (Hotness == CalleeInfo::HotnessType::Cold)
209 return ImportColdMultiplier;
210 return 1.0;
211 };
212
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000213 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000214 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000215
Peter Collingbourne9667b912017-05-04 18:03:25 +0000216 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
217 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000218 if (!CalleeSummary) {
219 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
220 continue;
221 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000222 // "Resolve" the summary, traversing alias,
223 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000224 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000225 ResolvedCalleeSummary = cast<FunctionSummary>(
226 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000227 assert(
228 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
229 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000230 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000231 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
232
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000233 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000234 "selectCallee() didn't honor the threshold");
235
Piotr Padlewskid2869472016-09-30 03:01:17 +0000236 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
237 // Adjust the threshold for next level of imported functions.
238 // The threshold is different for hot callsites because we can then
239 // inline chains of hot calls.
240 if (IsHotCallsite)
241 return Threshold * ImportHotInstrFactor;
242 return Threshold * ImportInstrFactor;
243 };
244
245 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000246 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
247
248 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000249 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000250 /// Since the traversal of the call graph is DFS, we can revisit a function
251 /// a second time with a higher threshold. In this case, it is added back to
252 /// the worklist with the new threshold.
253 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
254 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
255 << ProcessedThreshold << "\n");
256 continue;
257 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000258 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000259 // Mark this function as imported in this module, with the current Threshold
260 ProcessedThreshold = AdjThreshold;
261
262 // Make exports in the source module.
263 if (ExportLists) {
264 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000265 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000266 if (!PreviouslyImported) {
267 // This is the first time this function was exported from its source
268 // module, so mark all functions and globals it references as exported
269 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000270 // For efficiency, we unconditionally add all the referenced GUIDs
271 // to the ExportList for this module, and will prune out any not
272 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000273 for (auto &Edge : ResolvedCalleeSummary->calls()) {
274 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000275 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000276 }
277 for (auto &Ref : ResolvedCalleeSummary->refs()) {
278 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000279 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000280 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000281 }
282 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000283
Mehdi Amini01e32132016-03-26 05:40:34 +0000284 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000285 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000286 }
287}
288
Mehdi Amini01e32132016-03-26 05:40:34 +0000289/// Given the list of globals defined in a module, compute the list of imports
290/// as well as the list of "exports", i.e. the list of symbols referenced from
291/// another module (that may require promotion).
292static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000293 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000294 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000295 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000296 // Worklist contains the list of function imported in this module, for which
297 // we will analyse the callees and may import further down the callgraph.
298 SmallVector<EdgeInfo, 128> Worklist;
299
300 // Populate the worklist with the import for the functions in the current
301 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000302 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000303 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000304 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
305 continue;
306 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000307 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000308 if (auto *AS = dyn_cast<AliasSummary>(Summary))
309 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000310 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
311 if (!FuncSummary)
312 // Skip import for global variables
313 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000314 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000315 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000316 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000317 ExportLists);
318 }
319
Piotr Padlewskid2869472016-09-30 03:01:17 +0000320 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000321 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000322 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000323 auto *Summary = std::get<0>(FuncInfo);
324 auto Threshold = std::get<1>(FuncInfo);
325 auto GUID = std::get<2>(FuncInfo);
326
327 // Check if we later added this summary with a higher threshold.
328 // If so, skip this entry.
329 auto ExportModulePath = Summary->modulePath();
330 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
331 if (LatestProcessedThreshold > Threshold)
332 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000333
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000334 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000335 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000336 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000337}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000338
Mehdi Amini01e32132016-03-26 05:40:34 +0000339} // anonymous namespace
340
Teresa Johnsonc86af332016-04-12 21:13:11 +0000341/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000342void llvm::ComputeCrossModuleImport(
343 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000344 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000345 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000346 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000347 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000348 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000349 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000350 DEBUG(dbgs() << "Computing import for Module '"
351 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000352 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000353 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000354 }
355
Teresa Johnsonedddca22016-12-16 04:11:51 +0000356 // When computing imports we added all GUIDs referenced by anything
357 // imported from the module to its ExportList. Now we prune each ExportList
358 // of any not defined in that module. This is more efficient than checking
359 // while computing imports because some of the summary lists may be long
360 // due to linkonce (comdat) copies.
361 for (auto &ELI : ExportLists) {
362 const auto &DefinedGVSummaries =
363 ModuleToDefinedGVSummaries.lookup(ELI.first());
364 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
365 if (!DefinedGVSummaries.count(*EI))
366 EI = ELI.second.erase(EI);
367 else
368 ++EI;
369 }
370 }
371
Mehdi Amini01e32132016-03-26 05:40:34 +0000372#ifndef NDEBUG
373 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
374 << " modules:\n");
375 for (auto &ModuleImports : ImportLists) {
376 auto ModName = ModuleImports.first();
377 auto &Exports = ExportLists[ModName];
378 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
379 << " functions. Imports from " << ModuleImports.second.size()
380 << " modules.\n");
381 for (auto &Src : ModuleImports.second) {
382 auto SrcModName = Src.first();
383 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
384 << SrcModName << "\n");
385 }
386 }
387#endif
388}
389
Teresa Johnsonc86af332016-04-12 21:13:11 +0000390/// Compute all the imports for the given module in the Index.
391void llvm::ComputeCrossModuleImportForModule(
392 StringRef ModulePath, const ModuleSummaryIndex &Index,
393 FunctionImporter::ImportMapTy &ImportList) {
394
395 // Collect the list of functions this module defines.
396 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000397 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000398 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000399
400 // Compute the import list for this module.
401 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000402 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000403
404#ifndef NDEBUG
405 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
406 << ImportList.size() << " modules.\n");
407 for (auto &Src : ImportList) {
408 auto SrcModName = Src.first();
409 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
410 << SrcModName << "\n");
411 }
412#endif
413}
414
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000415void llvm::computeDeadSymbols(
416 ModuleSummaryIndex &Index,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000417 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000418 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000419 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000420 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000421 if (GUIDPreservedSymbols.empty())
422 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000423 return;
424 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000425 SmallVector<ValueInfo, 128> Worklist;
426 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
427 for (auto GUID : GUIDPreservedSymbols) {
428 ValueInfo VI = Index.getValueInfo(GUID);
429 if (!VI)
430 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000431 for (auto &S : VI.getSummaryList())
432 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000433 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000434
Teresa Johnson6c475a72017-01-05 21:34:18 +0000435 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000436 for (const auto &Entry : Index)
437 for (auto &S : Entry.second.SummaryList)
438 if (S->isLive()) {
439 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
440 Worklist.push_back(ValueInfo(&Entry));
441 ++LiveSymbols;
442 break;
443 }
444
445 // Make value live and add it to the worklist if it was not live before.
446 // FIXME: we should only make the prevailing copy live here
447 auto visit = [&](ValueInfo VI) {
448 for (auto &S : VI.getSummaryList())
449 if (S->isLive())
450 return;
451 for (auto &S : VI.getSummaryList())
452 S->setLive(true);
453 ++LiveSymbols;
454 Worklist.push_back(VI);
455 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000456
457 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000458 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000459 for (auto &Summary : VI.getSummaryList()) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000460 for (auto Ref : Summary->refs())
461 visit(Ref);
462 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
463 for (auto Call : FS->calls())
464 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000465 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
466 auto AliaseeGUID = AS->getAliasee().getOriginalName();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000467 ValueInfo AliaseeVI = Index.getValueInfo(AliaseeGUID);
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000468 if (AliaseeVI)
469 visit(AliaseeVI);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000470 }
471 }
472 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000473 Index.setWithGlobalValueDeadStripping();
474
475 unsigned DeadSymbols = Index.size() - LiveSymbols;
476 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
477 << " symbols Dead \n");
478 NumDeadSymbols += DeadSymbols;
479 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000480}
481
Teresa Johnson84174c32016-05-10 13:48:23 +0000482/// Compute the set of summaries needed for a ThinLTO backend compilation of
483/// \p ModulePath.
484void llvm::gatherImportedSummariesForModule(
485 StringRef ModulePath,
486 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000487 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000488 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
489 // Include all summaries from the importing module.
490 ModuleToSummariesForIndex[ModulePath] =
491 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000492 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000493 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000494 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
495 const auto &DefinedGVSummaries =
496 ModuleToDefinedGVSummaries.lookup(ILI.first());
497 for (auto &GI : ILI.second) {
498 const auto &DS = DefinedGVSummaries.find(GI.first);
499 assert(DS != DefinedGVSummaries.end() &&
500 "Expected a defined summary for imported global value");
501 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000502 }
503 }
504}
505
Teresa Johnson8570fe42016-05-10 15:54:09 +0000506/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000507std::error_code
508llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
509 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000510 std::error_code EC;
511 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
512 if (EC)
513 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000514 for (auto &ILI : ModuleImports)
515 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000516 return std::error_code();
517}
518
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000519/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
520void llvm::thinLTOResolveWeakForLinkerModule(
521 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000522 auto ConvertToDeclaration = [](GlobalValue &GV) {
523 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
524 if (Function *F = dyn_cast<Function>(&GV)) {
525 F->deleteBody();
526 F->clearMetadata();
527 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
528 V->setInitializer(nullptr);
529 V->setLinkage(GlobalValue::ExternalLinkage);
530 V->clearMetadata();
531 } else
532 // For now we don't resolve or drop aliases. Once we do we'll
533 // need to add support here for creating either a function or
534 // variable declaration, and return the new GlobalValue* for
535 // the caller to use.
Davide Italiano91239082017-04-14 17:22:02 +0000536 llvm_unreachable("Expected function or variable");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000537 };
538
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000539 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000540 // See if the global summary analysis computed a new resolved linkage.
541 const auto &GS = DefinedGlobals.find(GV.getGUID());
542 if (GS == DefinedGlobals.end())
543 return;
544 auto NewLinkage = GS->second->linkage();
545 if (NewLinkage == GV.getLinkage())
546 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000547
548 // Switch the linkage to weakany if asked for, e.g. we do this for
549 // linker redefined symbols (via --wrap or --defsym).
550 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
551 GV.setLinkage(NewLinkage);
552 return;
553 }
554
555 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
556 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000557 // Check for a non-prevailing def that has interposable linkage
558 // (e.g. non-odr weak or linkonce). In that case we can't simply
559 // convert to available_externally, since it would lose the
560 // interposable property and possibly get inlined. Simply drop
561 // the definition in that case.
562 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
563 GlobalValue::isInterposableLinkage(GV.getLinkage()))
564 ConvertToDeclaration(GV);
565 else {
566 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
567 << GV.getLinkage() << " to " << NewLinkage << "\n");
568 GV.setLinkage(NewLinkage);
569 }
570 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000571 // as this is a declaration for the linker, and will be dropped eventually.
572 // It is illegal for comdats to contain declarations.
573 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000574 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000575 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000576 };
577
578 // Process functions and global now
579 for (auto &GV : TheModule)
580 updateLinkage(GV);
581 for (auto &GV : TheModule.globals())
582 updateLinkage(GV);
583 for (auto &GV : TheModule.aliases())
584 updateLinkage(GV);
585}
586
587/// Run internalization on \p TheModule based on symmary analysis.
588void llvm::thinLTOInternalizeModule(Module &TheModule,
589 const GVSummaryMapTy &DefinedGlobals) {
590 // Parse inline ASM and collect the list of symbols that are not defined in
591 // the current module.
592 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000593 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnsond8204472017-03-09 00:19:49 +0000594 TheModule,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000595 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
596 if (Flags & object::BasicSymbolRef::SF_Undefined)
597 AsmUndefinedRefs.insert(Name);
598 });
599
600 // Declare a callback for the internalize pass that will ask for every
601 // candidate GlobalValue if it can be internalized or not.
602 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
603 // Can't be internalized if referenced in inline asm.
604 if (AsmUndefinedRefs.count(GV.getName()))
605 return true;
606
607 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000608 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000609 if (GS == DefinedGlobals.end()) {
610 // Must have been promoted (possibly conservatively). Find original
611 // name so that we can access the correct summary and see if it can
612 // be internalized again.
613 // FIXME: Eventually we should control promotion instead of promoting
614 // and internalizing again.
615 StringRef OrigName =
616 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
617 std::string OrigId = GlobalValue::getGlobalIdentifier(
618 OrigName, GlobalValue::InternalLinkage,
619 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000620 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000621 if (GS == DefinedGlobals.end()) {
622 // Also check the original non-promoted non-globalized name. In some
623 // cases a preempted weak value is linked in as a local copy because
624 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
625 // In that case, since it was originally not a local value, it was
626 // recorded in the index using the original name.
627 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000628 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000629 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000630 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000631 }
632 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000633 };
634
635 // FIXME: See if we can just internalize directly here via linkage changes
636 // based on the index, rather than invoking internalizeModule.
637 llvm::internalizeModule(TheModule, MustPreserveGV);
638}
639
Mehdi Aminic8c55172015-12-03 02:37:33 +0000640// Automatically import functions in Module \p DestModule based on the summaries
641// index.
642//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000643Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000644 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000645 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000646 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000647 unsigned ImportedCount = 0;
648
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000649 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000650 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000651 std::set<StringRef> ModuleNameOrderedList;
652 for (auto &FunctionsToImportPerModule : ImportList) {
653 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
654 }
655 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000656 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000657 const auto &FunctionsToImportPerModule = ImportList.find(Name);
658 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000659 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
660 if (!SrcModuleOrErr)
661 return SrcModuleOrErr.takeError();
662 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000663 assert(&DestModule.getContext() == &SrcModule->getContext() &&
664 "Context mismatch");
665
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000666 // If modules were created with lazy metadata loading, materialize it
667 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000668 if (Error Err = SrcModule->materializeMetadata())
669 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000670
Mehdi Amini01e32132016-03-26 05:40:34 +0000671 auto &ImportGUIDs = FunctionsToImportPerModule->second;
672 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000673 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000674 for (Function &F : *SrcModule) {
675 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000676 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000677 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000678 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000679 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000680 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000681 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000682 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000683 if (Error Err = F.materialize())
684 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000685 if (EnableImportMetadata) {
686 // Add 'thinlto_src_module' metadata for statistics and debugging.
687 F.setMetadata(
688 "thinlto_src_module",
689 llvm::MDNode::get(
690 DestModule.getContext(),
691 {llvm::MDString::get(DestModule.getContext(),
692 SrcModule->getSourceFileName())}));
693 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000694 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000695 }
696 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000697 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000698 if (!GV.hasName())
699 continue;
700 auto GUID = GV.getGUID();
701 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000702 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
703 << " " << GV.getName() << " from "
704 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000705 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000706 if (Error Err = GV.materialize())
707 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000708 GlobalsToImport.insert(&GV);
709 }
710 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000711 for (GlobalAlias &GA : SrcModule->aliases()) {
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000712 // FIXME: This should eventually be controlled entirely by the summary.
713 if (FunctionImportGlobalProcessing::doImportAsDefinition(
714 &GA, &GlobalsToImport)) {
715 GlobalsToImport.insert(&GA);
716 continue;
717 }
718
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000719 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000720 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000721 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000722 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000723 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000724 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000725 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000726 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000727 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000728 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000729 // and aliasee only in this case. This has been handled by
730 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000731 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000732 assert(GO->hasLinkOnceODRLinkage() &&
733 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000734#ifndef NDEBUG
735 if (!GlobalsToImport.count(GO))
736 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
737 << " " << GO->getName() << " from "
738 << SrcModule->getSourceFileName() << "\n");
739#endif
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000740 if (Error Err = GO->materialize())
741 return std::move(Err);
Mehdi Amini01e32132016-03-26 05:40:34 +0000742 GlobalsToImport.insert(GO);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000743 if (Error Err = GA.materialize())
744 return std::move(Err);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000745 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000746 }
747 }
748
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000749 // Upgrade debug info after we're done materializing all the globals and we
750 // have loaded all the required metadata!
751 UpgradeDebugInfo(*SrcModule);
752
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000753 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000754 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000755 return true;
756
Teresa Johnsond29478f2016-03-27 15:27:30 +0000757 if (PrintImports) {
758 for (const auto *GV : GlobalsToImport)
759 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
760 << " from " << SrcModule->getSourceFileName() << "\n";
761 }
762
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000763 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
764 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000765 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000766 report_fatal_error("Function Import: link error");
767
Mehdi Amini01e32132016-03-26 05:40:34 +0000768 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000769 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000770 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000771
Teresa Johnson6c475a72017-01-05 21:34:18 +0000772 NumImportedFunctions += ImportedCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000773
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000774 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000775 << DestModule.getModuleIdentifier() << "\n");
776 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000777}
778
779/// Summary file to use for function importing when using -function-import from
780/// the command line.
781static cl::opt<std::string>
782 SummaryFile("summary-file",
783 cl::desc("The summary file to use for function importing."));
784
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000785static bool doImportingForModule(Module &M) {
786 if (SummaryFile.empty())
787 report_fatal_error("error: -function-import requires -summary-file\n");
788 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
789 getModuleSummaryIndexForFile(SummaryFile);
790 if (!IndexPtrOrErr) {
791 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
792 "Error loading file '" + SummaryFile + "': ");
793 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000794 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000795 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000796
797 // First step is collecting the import list.
798 FunctionImporter::ImportMapTy ImportList;
799 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
800 ImportList);
801
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000802 // Conservatively mark all internal values as promoted. This interface is
803 // only used when doing importing via the function importing pass. The pass
804 // is only enabled when testing importing via the 'opt' tool, which does
805 // not do the ThinLink that would normally determine what values to promote.
806 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000807 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000808 if (GlobalValue::isLocalLinkage(S->linkage()))
809 S->setLinkage(GlobalValue::ExternalLinkage);
810 }
811 }
812
Teresa Johnson21241572016-07-18 21:22:24 +0000813 // Next we need to promote to global scope and rename any local values that
814 // are potentially exported to other modules.
815 if (renameModuleForThinLTO(M, *Index, nullptr)) {
816 errs() << "Error renaming module\n";
817 return false;
818 }
819
820 // Perform the import now.
821 auto ModuleLoader = [&M](StringRef Identifier) {
822 return loadFile(Identifier, M.getContext());
823 };
824 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +0000825 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000826
827 // FIXME: Probably need to propagate Errors through the pass manager.
828 if (!Result) {
829 logAllUnhandledErrors(Result.takeError(), errs(),
830 "Error importing module: ");
831 return false;
832 }
833
834 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000835}
836
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000837namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000838/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000839class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000840public:
841 /// Pass identification, replacement for typeid
842 static char ID;
843
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000844 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000845 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000846
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000847 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000848
849 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000850 if (skipModule(M))
851 return false;
852
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000853 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000854 }
855};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000856} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000857
Teresa Johnson21241572016-07-18 21:22:24 +0000858PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000859 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000860 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000861 return PreservedAnalyses::all();
862
863 return PreservedAnalyses::none();
864}
865
866char FunctionImportLegacyPass::ID = 0;
867INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
868 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000869
870namespace llvm {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000871Pass *createFunctionImportPass() {
872 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000873}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000874}