blob: a36314ca2055377f64dcfa7ed0f48b2071e6f5e0 [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
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();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000132 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000133 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000134 return false;
David Blaikie2f0cc472017-07-27 15:09:06 +0000135 if (auto *AS = dyn_cast<AliasSummary>(GVSummary))
136 // Aliases can't point to "available_externally".
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000137 // FIXME: we should import alias as available_externally *function*,
David Blaikie2f0cc472017-07-27 15:09:06 +0000138 // the destination module does not need to know it is an alias.
139 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000140
141 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000142
Teresa Johnson83aaf352017-01-12 22:04:45 +0000143 // If this is a local function, make sure we import the copy
144 // in the caller's module. The only time a local function can
145 // share an entry in the index is if there is a local with the same name
146 // in another module that had the same source file name (in a different
147 // directory), where each was compiled in their own directory so there
148 // was not distinguishing path.
149 // However, do the import from another module if there is only one
150 // entry in the list - in that case this must be a reference due
151 // to indirect call profile data, since a function pointer can point to
152 // a local in another module.
153 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
154 CalleeSummaryList.size() > 1 &&
155 Summary->modulePath() != CallerModulePath)
156 return false;
157
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000158 if (Summary->instCount() > Threshold)
159 return false;
160
Teresa Johnson519465b2017-01-05 14:32:16 +0000161 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000162 return false;
163
Mehdi Amini01e32132016-03-26 05:40:34 +0000164 return true;
165 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000166 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000167 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000168
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000169 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000170}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000171
Teresa Johnson475b51a2016-12-15 20:48:19 +0000172using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
173 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000174
Mehdi Amini01e32132016-03-26 05:40:34 +0000175/// Compute the list of functions to import for a given caller. Mark these
176/// imported functions and the symbols they reference in their source module as
177/// exported from their source module.
178static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000179 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000180 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000181 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000182 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000183 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000184 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000185 ValueInfo VI = Edge.first;
186 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
187 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000188
Peter Collingbourne9667b912017-05-04 18:03:25 +0000189 if (VI.getSummaryList().empty()) {
Dehao Chen4a435e02017-03-14 17:33:01 +0000190 // For SamplePGO, the indirect call targets for local functions will
191 // have its original name annotated in profile. We try to find the
192 // corresponding PGOFuncName as the GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000193 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
Dehao Chen4a435e02017-03-14 17:33:01 +0000194 if (GUID == 0)
195 continue;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000196 VI = Index.getValueInfo(GUID);
197 if (!VI)
198 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000199 }
200
Peter Collingbourne9667b912017-05-04 18:03:25 +0000201 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000202 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
203 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000204 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000205
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000206 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
207 if (Hotness == CalleeInfo::HotnessType::Hot)
208 return ImportHotMultiplier;
209 if (Hotness == CalleeInfo::HotnessType::Cold)
210 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000211 if (Hotness == CalleeInfo::HotnessType::Critical)
212 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000213 return 1.0;
214 };
215
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000216 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000217 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000218
Peter Collingbourne9667b912017-05-04 18:03:25 +0000219 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
220 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000221 if (!CalleeSummary) {
222 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
223 continue;
224 }
David Blaikie2f0cc472017-07-27 15:09:06 +0000225
226 // "Resolve" the summary
227 assert(!isa<AliasSummary>(CalleeSummary) &&
228 "Unexpected alias in import list");
229 const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000230
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000231 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000232 "selectCallee() didn't honor the threshold");
233
Piotr Padlewskid2869472016-09-30 03:01:17 +0000234 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
235 // Adjust the threshold for next level of imported functions.
236 // The threshold is different for hot callsites because we can then
237 // inline chains of hot calls.
238 if (IsHotCallsite)
239 return Threshold * ImportHotInstrFactor;
240 return Threshold * ImportInstrFactor;
241 };
242
243 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000244 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
245
246 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000247 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000248 /// Since the traversal of the call graph is DFS, we can revisit a function
249 /// a second time with a higher threshold. In this case, it is added back to
250 /// the worklist with the new threshold.
251 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
252 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
253 << ProcessedThreshold << "\n");
254 continue;
255 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000256 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000257 // Mark this function as imported in this module, with the current Threshold
258 ProcessedThreshold = AdjThreshold;
259
260 // Make exports in the source module.
261 if (ExportLists) {
262 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000263 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000264 if (!PreviouslyImported) {
265 // This is the first time this function was exported from its source
266 // module, so mark all functions and globals it references as exported
267 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000268 // For efficiency, we unconditionally add all the referenced GUIDs
269 // to the ExportList for this module, and will prune out any not
270 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000271 for (auto &Edge : ResolvedCalleeSummary->calls()) {
272 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000273 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000274 }
275 for (auto &Ref : ResolvedCalleeSummary->refs()) {
276 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000277 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000278 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000279 }
280 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000281
Mehdi Amini01e32132016-03-26 05:40:34 +0000282 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000283 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000284 }
285}
286
Mehdi Amini01e32132016-03-26 05:40:34 +0000287/// Given the list of globals defined in a module, compute the list of imports
288/// as well as the list of "exports", i.e. the list of symbols referenced from
289/// another module (that may require promotion).
290static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000291 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000292 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000293 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000294 // Worklist contains the list of function imported in this module, for which
295 // we will analyse the callees and may import further down the callgraph.
296 SmallVector<EdgeInfo, 128> Worklist;
297
298 // Populate the worklist with the import for the functions in the current
299 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000300 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000301 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000302 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
303 continue;
304 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000305 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000306 if (auto *AS = dyn_cast<AliasSummary>(Summary))
307 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000308 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
309 if (!FuncSummary)
310 // Skip import for global variables
311 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000312 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000313 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000314 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000315 ExportLists);
316 }
317
Piotr Padlewskid2869472016-09-30 03:01:17 +0000318 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000319 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000320 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000321 auto *Summary = std::get<0>(FuncInfo);
322 auto Threshold = std::get<1>(FuncInfo);
323 auto GUID = std::get<2>(FuncInfo);
324
325 // Check if we later added this summary with a higher threshold.
326 // If so, skip this entry.
327 auto ExportModulePath = Summary->modulePath();
328 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
329 if (LatestProcessedThreshold > Threshold)
330 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000331
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000332 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000333 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000334 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000335}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000336
Mehdi Amini01e32132016-03-26 05:40:34 +0000337} // anonymous namespace
338
Teresa Johnsonc86af332016-04-12 21:13:11 +0000339/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000340void llvm::ComputeCrossModuleImport(
341 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000342 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000343 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000344 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000345 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000346 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000347 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000348 DEBUG(dbgs() << "Computing import for Module '"
349 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000350 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000351 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000352 }
353
Teresa Johnsonedddca22016-12-16 04:11:51 +0000354 // When computing imports we added all GUIDs referenced by anything
355 // imported from the module to its ExportList. Now we prune each ExportList
356 // of any not defined in that module. This is more efficient than checking
357 // while computing imports because some of the summary lists may be long
358 // due to linkonce (comdat) copies.
359 for (auto &ELI : ExportLists) {
360 const auto &DefinedGVSummaries =
361 ModuleToDefinedGVSummaries.lookup(ELI.first());
362 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
363 if (!DefinedGVSummaries.count(*EI))
364 EI = ELI.second.erase(EI);
365 else
366 ++EI;
367 }
368 }
369
Mehdi Amini01e32132016-03-26 05:40:34 +0000370#ifndef NDEBUG
371 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
372 << " modules:\n");
373 for (auto &ModuleImports : ImportLists) {
374 auto ModName = ModuleImports.first();
375 auto &Exports = ExportLists[ModName];
376 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
377 << " functions. Imports from " << ModuleImports.second.size()
378 << " modules.\n");
379 for (auto &Src : ModuleImports.second) {
380 auto SrcModName = Src.first();
381 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
382 << SrcModName << "\n");
383 }
384 }
385#endif
386}
387
Teresa Johnsonc86af332016-04-12 21:13:11 +0000388/// Compute all the imports for the given module in the Index.
389void llvm::ComputeCrossModuleImportForModule(
390 StringRef ModulePath, const ModuleSummaryIndex &Index,
391 FunctionImporter::ImportMapTy &ImportList) {
392
393 // Collect the list of functions this module defines.
394 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000395 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000396 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000397
398 // Compute the import list for this module.
399 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000400 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000401
402#ifndef NDEBUG
403 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
404 << ImportList.size() << " modules.\n");
405 for (auto &Src : ImportList) {
406 auto SrcModName = Src.first();
407 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
408 << SrcModName << "\n");
409 }
410#endif
411}
412
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000413void llvm::computeDeadSymbols(
414 ModuleSummaryIndex &Index,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000415 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000416 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000417 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000418 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000419 if (GUIDPreservedSymbols.empty())
420 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000421 return;
422 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000423 SmallVector<ValueInfo, 128> Worklist;
424 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
425 for (auto GUID : GUIDPreservedSymbols) {
426 ValueInfo VI = Index.getValueInfo(GUID);
427 if (!VI)
428 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000429 for (auto &S : VI.getSummaryList())
430 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000431 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000432
Teresa Johnson6c475a72017-01-05 21:34:18 +0000433 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000434 for (const auto &Entry : Index)
435 for (auto &S : Entry.second.SummaryList)
436 if (S->isLive()) {
437 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
438 Worklist.push_back(ValueInfo(&Entry));
439 ++LiveSymbols;
440 break;
441 }
442
443 // Make value live and add it to the worklist if it was not live before.
444 // FIXME: we should only make the prevailing copy live here
445 auto visit = [&](ValueInfo VI) {
446 for (auto &S : VI.getSummaryList())
447 if (S->isLive())
448 return;
449 for (auto &S : VI.getSummaryList())
450 S->setLive(true);
451 ++LiveSymbols;
452 Worklist.push_back(VI);
453 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000454
455 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000456 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000457 for (auto &Summary : VI.getSummaryList()) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000458 for (auto Ref : Summary->refs())
459 visit(Ref);
460 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
461 for (auto Call : FS->calls())
462 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000463 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
464 auto AliaseeGUID = AS->getAliasee().getOriginalName();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000465 ValueInfo AliaseeVI = Index.getValueInfo(AliaseeGUID);
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000466 if (AliaseeVI)
467 visit(AliaseeVI);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000468 }
469 }
470 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000471 Index.setWithGlobalValueDeadStripping();
472
473 unsigned DeadSymbols = Index.size() - LiveSymbols;
474 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
475 << " symbols Dead \n");
476 NumDeadSymbols += DeadSymbols;
477 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000478}
479
Teresa Johnson84174c32016-05-10 13:48:23 +0000480/// Compute the set of summaries needed for a ThinLTO backend compilation of
481/// \p ModulePath.
482void llvm::gatherImportedSummariesForModule(
483 StringRef ModulePath,
484 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000485 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000486 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
487 // Include all summaries from the importing module.
488 ModuleToSummariesForIndex[ModulePath] =
489 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000490 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000491 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000492 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
493 const auto &DefinedGVSummaries =
494 ModuleToDefinedGVSummaries.lookup(ILI.first());
495 for (auto &GI : ILI.second) {
496 const auto &DS = DefinedGVSummaries.find(GI.first);
497 assert(DS != DefinedGVSummaries.end() &&
498 "Expected a defined summary for imported global value");
499 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000500 }
501 }
502}
503
Teresa Johnson8570fe42016-05-10 15:54:09 +0000504/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000505std::error_code
506llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
507 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000508 std::error_code EC;
509 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
510 if (EC)
511 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000512 for (auto &ILI : ModuleImports)
513 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000514 return std::error_code();
515}
516
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000517/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
518void llvm::thinLTOResolveWeakForLinkerModule(
519 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000520 auto ConvertToDeclaration = [](GlobalValue &GV) {
521 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
522 if (Function *F = dyn_cast<Function>(&GV)) {
523 F->deleteBody();
524 F->clearMetadata();
525 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
526 V->setInitializer(nullptr);
527 V->setLinkage(GlobalValue::ExternalLinkage);
528 V->clearMetadata();
529 } else
530 // For now we don't resolve or drop aliases. Once we do we'll
531 // need to add support here for creating either a function or
532 // variable declaration, and return the new GlobalValue* for
533 // the caller to use.
Davide Italiano91239082017-04-14 17:22:02 +0000534 llvm_unreachable("Expected function or variable");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000535 };
536
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000537 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000538 // See if the global summary analysis computed a new resolved linkage.
539 const auto &GS = DefinedGlobals.find(GV.getGUID());
540 if (GS == DefinedGlobals.end())
541 return;
542 auto NewLinkage = GS->second->linkage();
543 if (NewLinkage == GV.getLinkage())
544 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000545
546 // Switch the linkage to weakany if asked for, e.g. we do this for
547 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000548 // We record that the visibility should be changed here in `addThinLTO`
549 // as we need access to the resolution vectors for each input file in
550 // order to find which symbols have been redefined.
551 // We may consider reorganizing this code and moving the linkage recording
552 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000553 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
554 GV.setLinkage(NewLinkage);
555 return;
556 }
557
558 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
559 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000560 // Check for a non-prevailing def that has interposable linkage
561 // (e.g. non-odr weak or linkonce). In that case we can't simply
562 // convert to available_externally, since it would lose the
563 // interposable property and possibly get inlined. Simply drop
564 // the definition in that case.
565 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
566 GlobalValue::isInterposableLinkage(GV.getLinkage()))
567 ConvertToDeclaration(GV);
568 else {
569 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
570 << GV.getLinkage() << " to " << NewLinkage << "\n");
571 GV.setLinkage(NewLinkage);
572 }
573 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000574 // as this is a declaration for the linker, and will be dropped eventually.
575 // It is illegal for comdats to contain declarations.
576 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000577 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000578 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000579 };
580
581 // Process functions and global now
582 for (auto &GV : TheModule)
583 updateLinkage(GV);
584 for (auto &GV : TheModule.globals())
585 updateLinkage(GV);
586 for (auto &GV : TheModule.aliases())
587 updateLinkage(GV);
588}
589
590/// Run internalization on \p TheModule based on symmary analysis.
591void llvm::thinLTOInternalizeModule(Module &TheModule,
592 const GVSummaryMapTy &DefinedGlobals) {
593 // Parse inline ASM and collect the list of symbols that are not defined in
594 // the current module.
595 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000596 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnsond8204472017-03-09 00:19:49 +0000597 TheModule,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000598 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
599 if (Flags & object::BasicSymbolRef::SF_Undefined)
600 AsmUndefinedRefs.insert(Name);
601 });
602
603 // Declare a callback for the internalize pass that will ask for every
604 // candidate GlobalValue if it can be internalized or not.
605 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
606 // Can't be internalized if referenced in inline asm.
607 if (AsmUndefinedRefs.count(GV.getName()))
608 return true;
609
610 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000611 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000612 if (GS == DefinedGlobals.end()) {
613 // Must have been promoted (possibly conservatively). Find original
614 // name so that we can access the correct summary and see if it can
615 // be internalized again.
616 // FIXME: Eventually we should control promotion instead of promoting
617 // and internalizing again.
618 StringRef OrigName =
619 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
620 std::string OrigId = GlobalValue::getGlobalIdentifier(
621 OrigName, GlobalValue::InternalLinkage,
622 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000623 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000624 if (GS == DefinedGlobals.end()) {
625 // Also check the original non-promoted non-globalized name. In some
626 // cases a preempted weak value is linked in as a local copy because
627 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
628 // In that case, since it was originally not a local value, it was
629 // recorded in the index using the original name.
630 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000631 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000632 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000633 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000634 }
635 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000636 };
637
638 // FIXME: See if we can just internalize directly here via linkage changes
639 // based on the index, rather than invoking internalizeModule.
640 llvm::internalizeModule(TheModule, MustPreserveGV);
641}
642
Mehdi Aminic8c55172015-12-03 02:37:33 +0000643// Automatically import functions in Module \p DestModule based on the summaries
644// index.
645//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000646Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000647 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000648 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000649 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000650 unsigned ImportedCount = 0;
651
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000652 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000653 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000654 std::set<StringRef> ModuleNameOrderedList;
655 for (auto &FunctionsToImportPerModule : ImportList) {
656 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
657 }
658 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000659 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000660 const auto &FunctionsToImportPerModule = ImportList.find(Name);
661 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000662 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
663 if (!SrcModuleOrErr)
664 return SrcModuleOrErr.takeError();
665 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000666 assert(&DestModule.getContext() == &SrcModule->getContext() &&
667 "Context mismatch");
668
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000669 // If modules were created with lazy metadata loading, materialize it
670 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000671 if (Error Err = SrcModule->materializeMetadata())
672 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000673
Mehdi Amini01e32132016-03-26 05:40:34 +0000674 auto &ImportGUIDs = FunctionsToImportPerModule->second;
675 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000676 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000677 for (Function &F : *SrcModule) {
678 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000679 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000680 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000681 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000682 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000683 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000684 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000685 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000686 if (Error Err = F.materialize())
687 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000688 if (EnableImportMetadata) {
689 // Add 'thinlto_src_module' metadata for statistics and debugging.
690 F.setMetadata(
691 "thinlto_src_module",
692 llvm::MDNode::get(
693 DestModule.getContext(),
694 {llvm::MDString::get(DestModule.getContext(),
695 SrcModule->getSourceFileName())}));
696 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000697 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000698 }
699 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000700 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000701 if (!GV.hasName())
702 continue;
703 auto GUID = GV.getGUID();
704 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000705 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
706 << " " << GV.getName() << " from "
707 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000708 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000709 if (Error Err = GV.materialize())
710 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000711 GlobalsToImport.insert(&GV);
712 }
713 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000714 for (GlobalAlias &GA : SrcModule->aliases()) {
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000715 // FIXME: This should eventually be controlled entirely by the summary.
716 if (FunctionImportGlobalProcessing::doImportAsDefinition(
717 &GA, &GlobalsToImport)) {
718 GlobalsToImport.insert(&GA);
719 continue;
720 }
721
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000722 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000723 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000724 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000725 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000726 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000727 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000728 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000729 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000730 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000731 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000732 // and aliasee only in this case. This has been handled by
733 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000734 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000735 assert(GO->hasLinkOnceODRLinkage() &&
736 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000737#ifndef NDEBUG
738 if (!GlobalsToImport.count(GO))
739 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
740 << " " << GO->getName() << " from "
741 << SrcModule->getSourceFileName() << "\n");
742#endif
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000743 if (Error Err = GO->materialize())
744 return std::move(Err);
Mehdi Amini01e32132016-03-26 05:40:34 +0000745 GlobalsToImport.insert(GO);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000746 if (Error Err = GA.materialize())
747 return std::move(Err);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000748 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000749 }
750 }
751
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}