blob: 3a1d6de342fe275ef76718ad850ae80f6f2415f2 [file] [log] [blame]
Mehdi Amini42418ab2015-11-24 06:07:49 +00001//===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Function import based on summaries.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/IPO/FunctionImport.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
Mehdi Amini01e32132016-03-26 05:40:34 +000018#include "llvm/ADT/SmallVector.h"
Teresa Johnsond29478f2016-03-27 15:27:30 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000020#include "llvm/ADT/StringMap.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000021#include "llvm/ADT/StringSet.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000022#include "llvm/ADT/StringRef.h"
Peter Collingbournec15d60b2017-05-01 20:42:32 +000023#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000024#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000025#include "llvm/IR/Function.h"
26#include "llvm/IR/GlobalAlias.h"
27#include "llvm/IR/GlobalObject.h"
28#include "llvm/IR/GlobalValue.h"
29#include "llvm/IR/GlobalVariable.h"
30#include "llvm/IR/Metadata.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000031#include "llvm/IR/Module.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000032#include "llvm/IR/ModuleSummaryIndex.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000033#include "llvm/IRReader/IRReader.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000034#include "llvm/Linker/IRMover.h"
35#include "llvm/Object/ModuleSymbolTable.h"
36#include "llvm/Object/SymbolicFile.h"
37#include "llvm/Pass.h"
38#include "llvm/Support/Casting.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000039#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/Debug.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000041#include "llvm/Support/Error.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/FileSystem.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000044#include "llvm/Support/SourceMgr.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000045#include "llvm/Support/raw_ostream.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000046#include "llvm/Transforms/IPO/Internalize.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000047#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000048#include <cassert>
49#include <memory>
50#include <set>
51#include <string>
52#include <system_error>
53#include <tuple>
54#include <utility>
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000055
Mehdi Amini42418ab2015-11-24 06:07:49 +000056using namespace llvm;
57
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +000058#define DEBUG_TYPE "function-import"
59
Teresa Johnson6c475a72017-01-05 21:34:18 +000060STATISTIC(NumImportedFunctions, "Number of functions imported");
61STATISTIC(NumImportedModules, "Number of modules imported from");
62STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
63STATISTIC(NumLiveSymbols, "Number of live symbols in index");
Teresa Johnsond29478f2016-03-27 15:27:30 +000064
Teresa Johnson39303612015-11-24 22:55:46 +000065/// Limit on instruction count of imported functions.
66static cl::opt<unsigned> ImportInstrLimit(
67 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
68 cl::desc("Only import functions with less than N instructions"));
69
Mehdi Amini40641742016-02-10 23:31:45 +000070static cl::opt<float>
71 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
72 cl::Hidden, cl::value_desc("x"),
73 cl::desc("As we import functions, multiply the "
74 "`import-instr-limit` threshold by this factor "
75 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000076
Piotr Padlewskid2869472016-09-30 03:01:17 +000077static cl::opt<float> ImportHotInstrFactor(
78 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
79 cl::value_desc("x"),
80 cl::desc("As we import functions called from hot callsite, multiply the "
81 "`import-instr-limit` threshold by this factor "
82 "before processing newly imported functions"));
83
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000084static cl::opt<float> ImportHotMultiplier(
Dehao Chen8260d662017-07-28 01:02:34 +000085 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000086 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
87
Dehao Chen64c46572017-07-07 21:01:00 +000088static cl::opt<float> ImportCriticalMultiplier(
89 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
90 cl::value_desc("x"),
91 cl::desc(
92 "Multiply the `import-instr-limit` threshold for critical callsites"));
93
Piotr Padlewskiba72b952016-09-29 17:32:07 +000094// FIXME: This multiplier was not really tuned up.
95static cl::opt<float> ImportColdMultiplier(
96 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
97 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +000098
Teresa Johnsond29478f2016-03-27 15:27:30 +000099static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
100 cl::desc("Print imported functions"));
101
Teresa Johnson6c475a72017-01-05 21:34:18 +0000102static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
103 cl::desc("Compute dead symbols"));
104
Piotr Padlewski3b776122016-07-08 23:01:49 +0000105static cl::opt<bool> EnableImportMetadata(
106 "enable-import-metadata", cl::init(
107#if !defined(NDEBUG)
108 true /*Enabled with asserts.*/
109#else
110 false
111#endif
112 ),
113 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
114
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000115/// Summary file to use for function importing when using -function-import from
116/// the command line.
117static cl::opt<std::string>
118 SummaryFile("summary-file",
119 cl::desc("The summary file to use for function importing."));
120
Mehdi Amini42418ab2015-11-24 06:07:49 +0000121// Load lazily a module from \p FileName in \p Context.
122static std::unique_ptr<Module> loadFile(const std::string &FileName,
123 LLVMContext &Context) {
124 SMDiagnostic Err;
125 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000126 // Metadata isn't loaded until functions are imported, to minimize
127 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000128 std::unique_ptr<Module> Result =
129 getLazyIRFileModule(FileName, Err, Context,
130 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000131 if (!Result) {
132 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000133 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000134 }
135
Mehdi Amini42418ab2015-11-24 06:07:49 +0000136 return Result;
137}
138
Mehdi Amini01e32132016-03-26 05:40:34 +0000139/// Given a list of possible callee implementation for a call site, select one
140/// that fits the \p Threshold.
141///
142/// FIXME: select "best" instead of first that fits. But what is "best"?
143/// - The smallest: more likely to be inlined.
144/// - The one with the least outgoing edges (already well optimized).
145/// - One from a module already being imported from in order to reduce the
146/// number of source modules parsed/linked.
147/// - One that has PGO data attached.
148/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000149static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000150selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000151 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000152 unsigned Threshold, StringRef CallerModulePath) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000153 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000154 CalleeSummaryList,
155 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
156 auto *GVSummary = SummaryPtr.get();
Teresa Johnson73305f82017-08-19 18:04:25 +0000157 // For SamplePGO, in computeImportForFunction the OriginalId
158 // may have been used to locate the callee summary list (See
159 // comment there).
160 // The mapping from OriginalId to GUID may return a GUID
161 // that corresponds to a static variable. Filter it out here.
162 // This can happen when
163 // 1) There is a call to a library function which is not defined
164 // in the index.
165 // 2) There is a static variable with the OriginalGUID identical
166 // to the GUID of the library function in 1);
167 // When this happens, the logic for SamplePGO kicks in and
168 // the static variable in 2) will be found, which needs to be
169 // filtered out.
170 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
171 return false;
Rafael Espindolaf329be82016-05-11 01:26:06 +0000172 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000173 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000174 return false;
Davide Italiano82c7d372017-07-27 18:38:09 +0000175 if (isa<AliasSummary>(GVSummary))
David Blaikie2f0cc472017-07-27 15:09:06 +0000176 // Aliases can't point to "available_externally".
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000177 // FIXME: we should import alias as available_externally *function*,
David Blaikie2f0cc472017-07-27 15:09:06 +0000178 // the destination module does not need to know it is an alias.
179 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000180
181 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000182
Teresa Johnson83aaf352017-01-12 22:04:45 +0000183 // If this is a local function, make sure we import the copy
184 // in the caller's module. The only time a local function can
185 // share an entry in the index is if there is a local with the same name
186 // in another module that had the same source file name (in a different
187 // directory), where each was compiled in their own directory so there
188 // was not distinguishing path.
189 // However, do the import from another module if there is only one
190 // entry in the list - in that case this must be a reference due
191 // to indirect call profile data, since a function pointer can point to
192 // a local in another module.
193 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
194 CalleeSummaryList.size() > 1 &&
195 Summary->modulePath() != CallerModulePath)
196 return false;
197
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000198 if (Summary->instCount() > Threshold)
199 return false;
200
Teresa Johnson519465b2017-01-05 14:32:16 +0000201 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000202 return false;
203
Mehdi Amini01e32132016-03-26 05:40:34 +0000204 return true;
205 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000206 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000207 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000208
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000209 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000210}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000211
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000212namespace {
213
Teresa Johnson475b51a2016-12-15 20:48:19 +0000214using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
215 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000216
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000217} // anonymous namespace
218
Teresa Johnson19580832017-09-13 15:16:38 +0000219static ValueInfo
220updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
221 if (!VI.getSummaryList().empty())
222 return VI;
223 // For SamplePGO, the indirect call targets for local functions will
224 // have its original name annotated in profile. We try to find the
225 // corresponding PGOFuncName as the GUID.
226 // FIXME: Consider updating the edges in the graph after building
227 // it, rather than needing to perform this mapping on each walk.
228 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
229 if (GUID == 0)
230 return nullptr;
231 return Index.getValueInfo(GUID);
232}
233
Mehdi Amini01e32132016-03-26 05:40:34 +0000234/// Compute the list of functions to import for a given caller. Mark these
235/// imported functions and the symbols they reference in their source module as
236/// exported from their source module.
237static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000238 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000239 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000240 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000241 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000242 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000243 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000244 ValueInfo VI = Edge.first;
245 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
246 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000247
Teresa Johnson19580832017-09-13 15:16:38 +0000248 VI = updateValueInfoForIndirectCalls(Index, VI);
249 if (!VI)
250 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000251
Peter Collingbourne9667b912017-05-04 18:03:25 +0000252 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000253 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
254 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000255 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000256
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000257 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
258 if (Hotness == CalleeInfo::HotnessType::Hot)
259 return ImportHotMultiplier;
260 if (Hotness == CalleeInfo::HotnessType::Cold)
261 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000262 if (Hotness == CalleeInfo::HotnessType::Critical)
263 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000264 return 1.0;
265 };
266
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000267 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000268 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000269
Peter Collingbourne9667b912017-05-04 18:03:25 +0000270 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
271 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000272 if (!CalleeSummary) {
273 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
274 continue;
275 }
David Blaikie2f0cc472017-07-27 15:09:06 +0000276
277 // "Resolve" the summary
278 assert(!isa<AliasSummary>(CalleeSummary) &&
279 "Unexpected alias in import list");
280 const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000281
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000282 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000283 "selectCallee() didn't honor the threshold");
284
Piotr Padlewskid2869472016-09-30 03:01:17 +0000285 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
286 // Adjust the threshold for next level of imported functions.
287 // The threshold is different for hot callsites because we can then
288 // inline chains of hot calls.
289 if (IsHotCallsite)
290 return Threshold * ImportHotInstrFactor;
291 return Threshold * ImportInstrFactor;
292 };
293
294 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000295 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
296
297 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000298 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000299 /// Since the traversal of the call graph is DFS, we can revisit a function
300 /// a second time with a higher threshold. In this case, it is added back to
301 /// the worklist with the new threshold.
302 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
303 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
304 << ProcessedThreshold << "\n");
305 continue;
306 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000307 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000308 // Mark this function as imported in this module, with the current Threshold
309 ProcessedThreshold = AdjThreshold;
310
311 // Make exports in the source module.
312 if (ExportLists) {
313 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000314 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000315 if (!PreviouslyImported) {
316 // This is the first time this function was exported from its source
317 // module, so mark all functions and globals it references as exported
318 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000319 // For efficiency, we unconditionally add all the referenced GUIDs
320 // to the ExportList for this module, and will prune out any not
321 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000322 for (auto &Edge : ResolvedCalleeSummary->calls()) {
323 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000324 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000325 }
326 for (auto &Ref : ResolvedCalleeSummary->refs()) {
327 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000328 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000329 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000330 }
331 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000332
Mehdi Amini01e32132016-03-26 05:40:34 +0000333 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000334 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000335 }
336}
337
Mehdi Amini01e32132016-03-26 05:40:34 +0000338/// Given the list of globals defined in a module, compute the list of imports
339/// as well as the list of "exports", i.e. the list of symbols referenced from
340/// another module (that may require promotion).
341static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000342 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000343 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000344 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000345 // Worklist contains the list of function imported in this module, for which
346 // we will analyse the callees and may import further down the callgraph.
347 SmallVector<EdgeInfo, 128> Worklist;
348
349 // Populate the worklist with the import for the functions in the current
350 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000351 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000352 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000353 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
354 continue;
355 }
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000356 auto *FuncSummary =
357 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000358 if (!FuncSummary)
359 // Skip import for global variables
360 continue;
Xinliang David Li24524f32017-08-11 17:49:20 +0000361 DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000362 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000363 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000364 ExportLists);
365 }
366
Piotr Padlewskid2869472016-09-30 03:01:17 +0000367 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000368 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000369 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000370 auto *Summary = std::get<0>(FuncInfo);
371 auto Threshold = std::get<1>(FuncInfo);
372 auto GUID = std::get<2>(FuncInfo);
373
374 // Check if we later added this summary with a higher threshold.
375 // If so, skip this entry.
376 auto ExportModulePath = Summary->modulePath();
377 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
378 if (LatestProcessedThreshold > Threshold)
379 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000380
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000381 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000382 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000383 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000384}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000385
Teresa Johnsonc86af332016-04-12 21:13:11 +0000386/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000387void llvm::ComputeCrossModuleImport(
388 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000389 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000390 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000391 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000392 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000393 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000394 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000395 DEBUG(dbgs() << "Computing import for Module '"
396 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000397 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000398 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000399 }
400
Teresa Johnsonedddca22016-12-16 04:11:51 +0000401 // When computing imports we added all GUIDs referenced by anything
402 // imported from the module to its ExportList. Now we prune each ExportList
403 // of any not defined in that module. This is more efficient than checking
404 // while computing imports because some of the summary lists may be long
405 // due to linkonce (comdat) copies.
406 for (auto &ELI : ExportLists) {
407 const auto &DefinedGVSummaries =
408 ModuleToDefinedGVSummaries.lookup(ELI.first());
409 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
410 if (!DefinedGVSummaries.count(*EI))
411 EI = ELI.second.erase(EI);
412 else
413 ++EI;
414 }
415 }
416
Mehdi Amini01e32132016-03-26 05:40:34 +0000417#ifndef NDEBUG
418 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
419 << " modules:\n");
420 for (auto &ModuleImports : ImportLists) {
421 auto ModName = ModuleImports.first();
422 auto &Exports = ExportLists[ModName];
423 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
424 << " functions. Imports from " << ModuleImports.second.size()
425 << " modules.\n");
426 for (auto &Src : ModuleImports.second) {
427 auto SrcModName = Src.first();
428 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
429 << SrcModName << "\n");
430 }
431 }
432#endif
433}
434
Teresa Johnsonc86af332016-04-12 21:13:11 +0000435/// Compute all the imports for the given module in the Index.
436void llvm::ComputeCrossModuleImportForModule(
437 StringRef ModulePath, const ModuleSummaryIndex &Index,
438 FunctionImporter::ImportMapTy &ImportList) {
Teresa Johnsonc86af332016-04-12 21:13:11 +0000439 // Collect the list of functions this module defines.
440 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000441 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000442 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000443
444 // Compute the import list for this module.
445 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000446 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000447
448#ifndef NDEBUG
449 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
450 << ImportList.size() << " modules.\n");
451 for (auto &Src : ImportList) {
452 auto SrcModName = Src.first();
453 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
454 << SrcModName << "\n");
455 }
456#endif
457}
458
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000459void llvm::computeDeadSymbols(
460 ModuleSummaryIndex &Index,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000461 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000462 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000463 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000464 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000465 if (GUIDPreservedSymbols.empty())
466 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000467 return;
468 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000469 SmallVector<ValueInfo, 128> Worklist;
470 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
471 for (auto GUID : GUIDPreservedSymbols) {
472 ValueInfo VI = Index.getValueInfo(GUID);
473 if (!VI)
474 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000475 for (auto &S : VI.getSummaryList())
476 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000477 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000478
Teresa Johnson6c475a72017-01-05 21:34:18 +0000479 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000480 for (const auto &Entry : Index)
481 for (auto &S : Entry.second.SummaryList)
482 if (S->isLive()) {
483 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
484 Worklist.push_back(ValueInfo(&Entry));
485 ++LiveSymbols;
486 break;
487 }
488
489 // Make value live and add it to the worklist if it was not live before.
490 // FIXME: we should only make the prevailing copy live here
491 auto visit = [&](ValueInfo VI) {
Teresa Johnson19580832017-09-13 15:16:38 +0000492 // FIXME: If we knew which edges were created for indirect call profiles,
493 // we could skip them here. Any that are live should be reached via
494 // other edges, e.g. reference edges. Otherwise, using a profile collected
495 // on a slightly different binary might provoke preserving, importing
496 // and ultimately promoting calls to functions not linked into this
497 // binary, which increases the binary size unnecessarily. Note that
498 // if this code changes, the importer needs to change so that edges
499 // to functions marked dead are skipped.
500 VI = updateValueInfoForIndirectCalls(Index, VI);
501 if (!VI)
502 return;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000503 for (auto &S : VI.getSummaryList())
Teresa Johnsonf6251182017-09-20 17:09:47 +0000504 if (S->isLive())
505 return;
506 for (auto &S : VI.getSummaryList())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000507 S->setLive(true);
508 ++LiveSymbols;
509 Worklist.push_back(VI);
510 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000511
512 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000513 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000514 for (auto &Summary : VI.getSummaryList()) {
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000515 GlobalValueSummary *Base = Summary->getBaseObject();
516 for (auto Ref : Base->refs())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000517 visit(Ref);
Peter Collingbournecfbd0892017-09-14 05:02:59 +0000518 if (auto *FS = dyn_cast<FunctionSummary>(Base))
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000519 for (auto Call : FS->calls())
520 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000521 }
522 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000523 Index.setWithGlobalValueDeadStripping();
524
525 unsigned DeadSymbols = Index.size() - LiveSymbols;
526 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
527 << " symbols Dead \n");
528 NumDeadSymbols += DeadSymbols;
529 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000530}
531
Teresa Johnson84174c32016-05-10 13:48:23 +0000532/// Compute the set of summaries needed for a ThinLTO backend compilation of
533/// \p ModulePath.
534void llvm::gatherImportedSummariesForModule(
535 StringRef ModulePath,
536 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000537 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000538 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
539 // Include all summaries from the importing module.
540 ModuleToSummariesForIndex[ModulePath] =
541 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000542 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000543 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000544 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
545 const auto &DefinedGVSummaries =
546 ModuleToDefinedGVSummaries.lookup(ILI.first());
547 for (auto &GI : ILI.second) {
548 const auto &DS = DefinedGVSummaries.find(GI.first);
549 assert(DS != DefinedGVSummaries.end() &&
550 "Expected a defined summary for imported global value");
551 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000552 }
553 }
554}
555
Teresa Johnson8570fe42016-05-10 15:54:09 +0000556/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000557std::error_code
558llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
559 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000560 std::error_code EC;
561 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
562 if (EC)
563 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000564 for (auto &ILI : ModuleImports)
565 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000566 return std::error_code();
567}
568
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000569/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
570void llvm::thinLTOResolveWeakForLinkerModule(
571 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000572 auto ConvertToDeclaration = [](GlobalValue &GV) {
573 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
574 if (Function *F = dyn_cast<Function>(&GV)) {
575 F->deleteBody();
576 F->clearMetadata();
577 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
578 V->setInitializer(nullptr);
579 V->setLinkage(GlobalValue::ExternalLinkage);
580 V->clearMetadata();
581 } else
582 // For now we don't resolve or drop aliases. Once we do we'll
583 // need to add support here for creating either a function or
584 // variable declaration, and return the new GlobalValue* for
585 // the caller to use.
Davide Italiano91239082017-04-14 17:22:02 +0000586 llvm_unreachable("Expected function or variable");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000587 };
588
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000589 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000590 // See if the global summary analysis computed a new resolved linkage.
591 const auto &GS = DefinedGlobals.find(GV.getGUID());
592 if (GS == DefinedGlobals.end())
593 return;
594 auto NewLinkage = GS->second->linkage();
595 if (NewLinkage == GV.getLinkage())
596 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000597
598 // Switch the linkage to weakany if asked for, e.g. we do this for
599 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000600 // We record that the visibility should be changed here in `addThinLTO`
601 // as we need access to the resolution vectors for each input file in
602 // order to find which symbols have been redefined.
603 // We may consider reorganizing this code and moving the linkage recording
604 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000605 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
606 GV.setLinkage(NewLinkage);
607 return;
608 }
609
610 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
611 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000612 // Check for a non-prevailing def that has interposable linkage
613 // (e.g. non-odr weak or linkonce). In that case we can't simply
614 // convert to available_externally, since it would lose the
615 // interposable property and possibly get inlined. Simply drop
616 // the definition in that case.
617 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
618 GlobalValue::isInterposableLinkage(GV.getLinkage()))
619 ConvertToDeclaration(GV);
620 else {
621 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
622 << GV.getLinkage() << " to " << NewLinkage << "\n");
623 GV.setLinkage(NewLinkage);
624 }
625 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000626 // as this is a declaration for the linker, and will be dropped eventually.
627 // It is illegal for comdats to contain declarations.
628 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000629 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000630 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000631 };
632
633 // Process functions and global now
634 for (auto &GV : TheModule)
635 updateLinkage(GV);
636 for (auto &GV : TheModule.globals())
637 updateLinkage(GV);
638 for (auto &GV : TheModule.aliases())
639 updateLinkage(GV);
640}
641
642/// Run internalization on \p TheModule based on symmary analysis.
643void llvm::thinLTOInternalizeModule(Module &TheModule,
644 const GVSummaryMapTy &DefinedGlobals) {
645 // Parse inline ASM and collect the list of symbols that are not defined in
646 // the current module.
647 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000648 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnsond8204472017-03-09 00:19:49 +0000649 TheModule,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000650 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
651 if (Flags & object::BasicSymbolRef::SF_Undefined)
652 AsmUndefinedRefs.insert(Name);
653 });
654
655 // Declare a callback for the internalize pass that will ask for every
656 // candidate GlobalValue if it can be internalized or not.
657 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
658 // Can't be internalized if referenced in inline asm.
659 if (AsmUndefinedRefs.count(GV.getName()))
660 return true;
661
662 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000663 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000664 if (GS == DefinedGlobals.end()) {
665 // Must have been promoted (possibly conservatively). Find original
666 // name so that we can access the correct summary and see if it can
667 // be internalized again.
668 // FIXME: Eventually we should control promotion instead of promoting
669 // and internalizing again.
670 StringRef OrigName =
671 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
672 std::string OrigId = GlobalValue::getGlobalIdentifier(
673 OrigName, GlobalValue::InternalLinkage,
674 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000675 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000676 if (GS == DefinedGlobals.end()) {
677 // Also check the original non-promoted non-globalized name. In some
678 // cases a preempted weak value is linked in as a local copy because
679 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
680 // In that case, since it was originally not a local value, it was
681 // recorded in the index using the original name.
682 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000683 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000684 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000685 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000686 }
687 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000688 };
689
690 // FIXME: See if we can just internalize directly here via linkage changes
691 // based on the index, rather than invoking internalizeModule.
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000692 internalizeModule(TheModule, MustPreserveGV);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000693}
694
Mehdi Aminic8c55172015-12-03 02:37:33 +0000695// Automatically import functions in Module \p DestModule based on the summaries
696// index.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000697Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000698 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000699 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000700 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000701 unsigned ImportedCount = 0;
702
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000703 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000704 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000705 std::set<StringRef> ModuleNameOrderedList;
706 for (auto &FunctionsToImportPerModule : ImportList) {
707 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
708 }
709 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000710 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000711 const auto &FunctionsToImportPerModule = ImportList.find(Name);
712 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000713 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
714 if (!SrcModuleOrErr)
715 return SrcModuleOrErr.takeError();
716 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000717 assert(&DestModule.getContext() == &SrcModule->getContext() &&
718 "Context mismatch");
719
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000720 // If modules were created with lazy metadata loading, materialize it
721 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000722 if (Error Err = SrcModule->materializeMetadata())
723 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000724
Mehdi Amini01e32132016-03-26 05:40:34 +0000725 auto &ImportGUIDs = FunctionsToImportPerModule->second;
726 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000727 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000728 for (Function &F : *SrcModule) {
729 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000730 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000731 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000732 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000733 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000734 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000735 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000736 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000737 if (Error Err = F.materialize())
738 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000739 if (EnableImportMetadata) {
740 // Add 'thinlto_src_module' metadata for statistics and debugging.
741 F.setMetadata(
742 "thinlto_src_module",
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000743 MDNode::get(DestModule.getContext(),
744 {MDString::get(DestModule.getContext(),
745 SrcModule->getSourceFileName())}));
Piotr Padlewski3b776122016-07-08 23:01:49 +0000746 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000747 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000748 }
749 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000750 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000751 if (!GV.hasName())
752 continue;
753 auto GUID = GV.getGUID();
754 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000755 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
756 << " " << GV.getName() << " from "
757 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000758 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000759 if (Error Err = GV.materialize())
760 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000761 GlobalsToImport.insert(&GV);
762 }
763 }
Benjamin Kramer154411e2017-08-29 20:24:39 +0000764#ifndef NDEBUG
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000765 for (GlobalAlias &GA : SrcModule->aliases()) {
766 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000767 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000768 auto GUID = GA.getGUID();
Teresa Johnson2df7fc72017-08-29 18:15:34 +0000769 assert(!ImportGUIDs.count(GUID) && "Unexpected alias in import list");
770 DEBUG(dbgs() << "Not importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000771 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000772 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000773 }
Benjamin Kramer154411e2017-08-29 20:24:39 +0000774#endif
Mehdi Amini01e32132016-03-26 05:40:34 +0000775
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000776 // Upgrade debug info after we're done materializing all the globals and we
777 // have loaded all the required metadata!
778 UpgradeDebugInfo(*SrcModule);
779
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000780 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000781 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000782 return true;
783
Teresa Johnsond29478f2016-03-27 15:27:30 +0000784 if (PrintImports) {
785 for (const auto *GV : GlobalsToImport)
786 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
787 << " from " << SrcModule->getSourceFileName() << "\n";
788 }
789
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000790 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
791 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000792 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000793 report_fatal_error("Function Import: link error");
794
Mehdi Amini01e32132016-03-26 05:40:34 +0000795 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000796 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000797 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000798
Teresa Johnson6c475a72017-01-05 21:34:18 +0000799 NumImportedFunctions += ImportedCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000800
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000801 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000802 << DestModule.getModuleIdentifier() << "\n");
803 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000804}
805
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000806static bool doImportingForModule(Module &M) {
807 if (SummaryFile.empty())
808 report_fatal_error("error: -function-import requires -summary-file\n");
809 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
810 getModuleSummaryIndexForFile(SummaryFile);
811 if (!IndexPtrOrErr) {
812 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
813 "Error loading file '" + SummaryFile + "': ");
814 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000815 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000816 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000817
818 // First step is collecting the import list.
819 FunctionImporter::ImportMapTy ImportList;
820 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
821 ImportList);
822
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000823 // Conservatively mark all internal values as promoted. This interface is
824 // only used when doing importing via the function importing pass. The pass
825 // is only enabled when testing importing via the 'opt' tool, which does
826 // not do the ThinLink that would normally determine what values to promote.
827 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000828 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000829 if (GlobalValue::isLocalLinkage(S->linkage()))
830 S->setLinkage(GlobalValue::ExternalLinkage);
831 }
832 }
833
Teresa Johnson21241572016-07-18 21:22:24 +0000834 // Next we need to promote to global scope and rename any local values that
835 // are potentially exported to other modules.
836 if (renameModuleForThinLTO(M, *Index, nullptr)) {
837 errs() << "Error renaming module\n";
838 return false;
839 }
840
841 // Perform the import now.
842 auto ModuleLoader = [&M](StringRef Identifier) {
843 return loadFile(Identifier, M.getContext());
844 };
845 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +0000846 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000847
848 // FIXME: Probably need to propagate Errors through the pass manager.
849 if (!Result) {
850 logAllUnhandledErrors(Result.takeError(), errs(),
851 "Error importing module: ");
852 return false;
853 }
854
855 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000856}
857
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000858namespace {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000859
Mehdi Amini42418ab2015-11-24 06:07:49 +0000860/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000861class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000862public:
863 /// Pass identification, replacement for typeid
864 static char ID;
865
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000866 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
867
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000868 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000869 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000870
Mehdi Amini42418ab2015-11-24 06:07:49 +0000871 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000872 if (skipModule(M))
873 return false;
874
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000875 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000876 }
877};
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000878
879} // end anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000880
Teresa Johnson21241572016-07-18 21:22:24 +0000881PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000882 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000883 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000884 return PreservedAnalyses::all();
885
886 return PreservedAnalyses::none();
887}
888
889char FunctionImportLegacyPass::ID = 0;
890INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
891 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000892
893namespace llvm {
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000894
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000895Pass *createFunctionImportPass() {
896 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000897}
Eugene Zelenkoe9ea08a2017-10-10 22:49:55 +0000898
899} // end namespace llvm