blob: e11ad68bfa72075344b370610946a088d4f66734 [file] [log] [blame]
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001//===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
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 functions and classes used to support LTO.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000015#include "llvm/Analysis/TargetLibraryInfo.h"
16#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000017#include "llvm/Bitcode/BitcodeReader.h"
18#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000019#include "llvm/CodeGen/Analysis.h"
20#include "llvm/IR/AutoUpgrade.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/LegacyPassManager.h"
23#include "llvm/LTO/LTOBackend.h"
24#include "llvm/Linker/IRMover.h"
25#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
26#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000027#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000028#include "llvm/Support/Path.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000029#include "llvm/Support/SHA1.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000030#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031#include "llvm/Support/TargetRegistry.h"
32#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000033#include "llvm/Support/Threading.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000034#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000035#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
37#include "llvm/Transforms/IPO.h"
38#include "llvm/Transforms/IPO/PassManagerBuilder.h"
39#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000040
Teresa Johnson9ba95f92016-08-11 14:58:12 +000041#include <set>
42
43using namespace llvm;
44using namespace lto;
45using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000046
Mehdi Aminiadc0e262016-08-23 21:30:12 +000047#define DEBUG_TYPE "lto"
48
49// Returns a unique hash for the Module considering the current list of
50// export/import and other global analysis results.
51// The hash is produced in \p Key.
52static void computeCacheKey(
Peter Collingbournef4257522016-12-08 05:28:30 +000053 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
54 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +000055 const FunctionImporter::ExportSetTy &ExportList,
56 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
57 const GVSummaryMapTy &DefinedGlobals) {
58 // Compute the unique hash for this entry.
59 // This is based on the current compiler version, the module itself, the
60 // export list, the hash for every single module in the import list, the
61 // list of ResolvedODR for the module, and the list of preserved symbols.
62 SHA1 Hasher;
63
64 // Start with the compiler revision
65 Hasher.update(LLVM_VERSION_STRING);
66#ifdef HAVE_LLVM_REVISION
67 Hasher.update(LLVM_REVISION);
68#endif
69
Peter Collingbournef4257522016-12-08 05:28:30 +000070 // Include the parts of the LTO configuration that affect code generation.
71 auto AddString = [&](StringRef Str) {
72 Hasher.update(Str);
73 Hasher.update(ArrayRef<uint8_t>{0});
74 };
75 auto AddUnsigned = [&](unsigned I) {
76 uint8_t Data[4];
77 Data[0] = I;
78 Data[1] = I >> 8;
79 Data[2] = I >> 16;
80 Data[3] = I >> 24;
81 Hasher.update(ArrayRef<uint8_t>{Data, 4});
82 };
83 AddString(Conf.CPU);
84 // FIXME: Hash more of Options. For now all clients initialize Options from
85 // command-line flags (which is unsupported in production), but may set
86 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
87 // DataSections and DebuggerTuning via command line flags.
88 AddUnsigned(Conf.Options.RelaxELFRelocations);
89 AddUnsigned(Conf.Options.FunctionSections);
90 AddUnsigned(Conf.Options.DataSections);
91 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
92 for (auto &A : Conf.MAttrs)
93 AddString(A);
94 AddUnsigned(Conf.RelocModel);
95 AddUnsigned(Conf.CodeModel);
96 AddUnsigned(Conf.CGOptLevel);
97 AddUnsigned(Conf.OptLevel);
98 AddString(Conf.OptPipeline);
99 AddString(Conf.AAPipeline);
100 AddString(Conf.OverrideTriple);
101 AddString(Conf.DefaultTriple);
102
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000103 // Include the hash for the current module
104 auto ModHash = Index.getModuleHash(ModuleID);
105 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
106 for (auto F : ExportList)
107 // The export list can impact the internalization, be conservative here
108 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
109
110 // Include the hash for every module we import functions from
111 for (auto &Entry : ImportList) {
112 auto ModHash = Index.getModuleHash(Entry.first());
113 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
114 }
115
116 // Include the hash for the resolved ODR.
117 for (auto &Entry : ResolvedODR) {
118 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
119 sizeof(GlobalValue::GUID)));
120 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
121 sizeof(GlobalValue::LinkageTypes)));
122 }
123
124 // Include the hash for the linkage type to reflect internalization and weak
125 // resolution.
126 for (auto &GS : DefinedGlobals) {
127 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
128 Hasher.update(
129 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
130 }
131
Dehao Chen27978002016-12-16 16:48:46 +0000132 if (!Conf.SampleProfile.empty()) {
133 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
134 if (FileOrErr)
135 Hasher.update(FileOrErr.get()->getBuffer());
136 }
137
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000138 Key = toHex(Hasher.result());
139}
140
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000141static void thinLTOResolveWeakForLinkerGUID(
142 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
143 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000144 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000145 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000146 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000147 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000148 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000149 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
150 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
151 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000152 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000153 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000154 // This is both a compile-time optimization and a correctness
155 // transformation. This is necessary for correctness when we have exported
156 // a reference - we need to convert the linkonce to weak to
157 // ensure a copy is kept to satisfy the exported reference.
158 // FIXME: We may want to split the compile time and correctness
159 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000160 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000161 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
162 S->setLinkage(GlobalValue::getWeakLinkage(
163 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000164 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000165 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000166 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000167 !GlobalInvolvedWithAlias.count(S.get()))
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000168 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
169 if (S->linkage() != OriginalLinkage)
170 recordNewLinkage(S->modulePath(), GUID, S->linkage());
171 }
172}
173
174// Resolve Weak and LinkOnce values in the \p Index.
175//
176// We'd like to drop these functions if they are no longer referenced in the
177// current module. However there is a chance that another module is still
178// referencing them because of the import. We make sure we always emit at least
179// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000180void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000181 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000182 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000183 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000184 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000185 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000186 // We won't optimize the globals that are referenced by an alias for now
187 // Ideally we should turn the alias into a global and duplicate the definition
188 // when needed.
189 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
190 for (auto &I : Index)
191 for (auto &S : I.second)
192 if (auto AS = dyn_cast<AliasSummary>(S.get()))
193 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
194
195 for (auto &I : Index)
196 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000197 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000198}
199
200static void thinLTOInternalizeAndPromoteGUID(
201 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000202 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000203 for (auto &S : GVSummaryList) {
204 if (isExported(S->modulePath(), GUID)) {
205 if (GlobalValue::isLocalLinkage(S->linkage()))
206 S->setLinkage(GlobalValue::ExternalLinkage);
207 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
208 S->setLinkage(GlobalValue::InternalLinkage);
209 }
210}
211
212// Update the linkages in the given \p Index to mark exported values
213// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000214void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000215 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000216 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000217 for (auto &I : Index)
218 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
219}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000220
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000221struct InputFile::InputModule {
222 BitcodeModule BM;
223 std::unique_ptr<Module> Mod;
224
225 // The range of ModuleSymbolTable entries for this input module.
226 size_t SymBegin, SymEnd;
227};
228
229// Requires a destructor for std::vector<InputModule>.
230InputFile::~InputFile() = default;
231
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000232Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
233 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000234
Peter Collingbournead903692016-12-13 19:43:49 +0000235 ErrorOr<MemoryBufferRef> BCOrErr =
236 IRObjectFile::findBitcodeInMemBuffer(Object);
237 if (!BCOrErr)
238 return errorCodeToError(BCOrErr.getError());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000239
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000240 Expected<std::vector<BitcodeModule>> BMsOrErr =
241 getBitcodeModuleList(*BCOrErr);
242 if (!BMsOrErr)
243 return BMsOrErr.takeError();
Peter Collingbournead903692016-12-13 19:43:49 +0000244
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000245 if (BMsOrErr->empty())
246 return make_error<StringError>("Bitcode file does not contain any modules",
247 inconvertibleErrorCode());
Peter Collingbournead903692016-12-13 19:43:49 +0000248
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000249 // Create an InputModule for each module in the InputFile, and add it to the
250 // ModuleSymbolTable.
251 for (auto BM : *BMsOrErr) {
252 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000253 BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true,
254 /*IsImporting*/ false);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000255 if (!MOrErr)
256 return MOrErr.takeError();
257
258 size_t SymBegin = File->SymTab.symbols().size();
259 File->SymTab.addModule(MOrErr->get());
260 size_t SymEnd = File->SymTab.symbols().size();
261
262 for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
263 auto P = File->ComdatMap.insert(
264 std::make_pair(&C.second, File->Comdats.size()));
265 assert(P.second);
266 (void)P;
267 File->Comdats.push_back(C.first());
268 }
269
270 File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
Rafael Espindola79121102016-10-25 12:02:03 +0000271 }
272
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000273 return std::move(File);
274}
275
Rafael Espindola79121102016-10-25 12:02:03 +0000276Expected<int> InputFile::Symbol::getComdatIndex() const {
Peter Collingbournead903692016-12-13 19:43:49 +0000277 if (!isGV())
Rafael Espindola79121102016-10-25 12:02:03 +0000278 return -1;
Peter Collingbournead903692016-12-13 19:43:49 +0000279 const GlobalObject *GO = getGV()->getBaseObject();
280 if (!GO)
281 return make_error<StringError>("Unable to determine comdat of alias!",
282 inconvertibleErrorCode());
Rafael Espindola79121102016-10-25 12:02:03 +0000283 if (const Comdat *C = GO->getComdat()) {
284 auto I = File->ComdatMap.find(C);
285 assert(I != File->ComdatMap.end());
286 return I->second;
287 }
288 return -1;
289}
290
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000291StringRef InputFile::getName() const {
292 return Mods[0].BM.getModuleIdentifier();
293}
294
295StringRef InputFile::getSourceFileName() const {
296 return Mods[0].Mod->getSourceFileName();
297}
298
299iterator_range<InputFile::symbol_iterator>
300InputFile::module_symbols(InputModule &IM) {
301 return llvm::make_range(
302 symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
303 symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
304}
305
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000306LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
307 Config &Conf)
308 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000309 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000310
311LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
312 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000313 this->Backend =
314 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000315}
316
317LTO::LTO(Config Conf, ThinBackend Backend,
318 unsigned ParallelCodeGenParallelismLevel)
319 : Conf(std::move(Conf)),
320 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000321 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000322
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000323// Requires a destructor for MapVector<BitcodeModule>.
324LTO::~LTO() = default;
325
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000326// Add the given symbol to the GlobalResolutions map, and resolve its partition.
Peter Collingbournead903692016-12-13 19:43:49 +0000327void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000328 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000329 SymbolResolution Res, unsigned Partition) {
Peter Collingbournead903692016-12-13 19:43:49 +0000330 GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000331
332 auto &GlobalRes = GlobalResolutions[Sym.getName()];
333 if (GV) {
334 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
335 if (Res.Prevailing)
336 GlobalRes.IRName = GV->getName();
337 }
Teresa Johnson6c475a72017-01-05 21:34:18 +0000338 // Set the partition to external if we know it is used elsewhere, e.g.
339 // it is visible to a regular object, is referenced from llvm.compiler_used,
340 // or was already recorded as being referenced from a different partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000341 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
342 (GlobalRes.Partition != GlobalResolution::Unknown &&
Teresa Johnson6c475a72017-01-05 21:34:18 +0000343 GlobalRes.Partition != Partition)) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000344 GlobalRes.Partition = GlobalResolution::External;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000345 } else
346 // First recorded reference, save the current partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000347 GlobalRes.Partition = Partition;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000348
349 // Flag as visible outside of ThinLTO if visible from a regular object or
350 // if this is a reference in the regular LTO partition.
351 GlobalRes.VisibleOutsideThinLTO |=
352 (Res.VisibleToRegularObj || (Partition == GlobalResolution::RegularLTO));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000353}
354
Rafael Espindola7775c332016-08-26 20:19:35 +0000355static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
356 ArrayRef<SymbolResolution> Res) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000357 StringRef Path = Input->getName();
Rafael Espindola7775c332016-08-26 20:19:35 +0000358 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000359 auto ResI = Res.begin();
360 for (const InputFile::Symbol &Sym : Input->symbols()) {
361 assert(ResI != Res.end());
362 SymbolResolution Res = *ResI++;
363
Rafael Espindola7775c332016-08-26 20:19:35 +0000364 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000365 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000366 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000367 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000368 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000369 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000370 OS << 'x';
371 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000372 }
Peter Collingbourne58ffcfb2017-01-19 23:10:14 +0000373 OS.flush();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000374 assert(ResI == Res.end());
375}
376
377Error LTO::add(std::unique_ptr<InputFile> Input,
378 ArrayRef<SymbolResolution> Res) {
379 assert(!CalledGetMaxTasks);
380
381 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000382 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000383
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000384 const SymbolResolution *ResI = Res.begin();
385 for (InputFile::InputModule &IM : Input->Mods)
386 if (Error Err = addModule(*Input, IM, ResI, Res.end()))
387 return Err;
388
389 assert(ResI == Res.end());
390 return Error::success();
391}
392
393Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
394 const SymbolResolution *&ResI,
395 const SymbolResolution *ResE) {
Mehdi Amini9989f802016-08-19 15:35:44 +0000396 // FIXME: move to backend
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000397 Module &M = *IM.Mod;
Davide Italiano2ceb6282016-12-14 21:57:04 +0000398
399 if (M.getDataLayoutStr().empty())
400 return make_error<StringError>("input module has no datalayout",
401 inconvertibleErrorCode());
402
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000403 if (!Conf.OverrideTriple.empty())
404 M.setTargetTriple(Conf.OverrideTriple);
405 else if (M.getTargetTriple().empty())
406 M.setTargetTriple(Conf.DefaultTriple);
407
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000408 Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000409 if (!HasThinLTOSummary)
410 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000411
Peter Collingbournecd513a42016-11-11 19:50:24 +0000412 if (*HasThinLTOSummary)
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000413 return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000414 else
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000415 return addRegularLTO(IM.BM, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000416}
417
418// Add a regular LTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000419Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
420 const SymbolResolution *ResE) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000421 if (!RegularLTO.CombinedModule) {
422 RegularLTO.CombinedModule =
423 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
424 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
425 }
Peter Collingbournead903692016-12-13 19:43:49 +0000426 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000427 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
428 /*IsImporting*/ false);
Peter Collingbournead903692016-12-13 19:43:49 +0000429 if (!MOrErr)
430 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000431
Peter Collingbournead903692016-12-13 19:43:49 +0000432 Module &M = **MOrErr;
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000433 if (Error Err = M.materializeMetadata())
434 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000435 UpgradeDebugInfo(M);
436
Peter Collingbournead903692016-12-13 19:43:49 +0000437 ModuleSymbolTable SymTab;
438 SymTab.addModule(&M);
439
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000440 SmallPtrSet<GlobalValue *, 8> Used;
441 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
442
443 std::vector<GlobalValue *> Keep;
444
445 for (GlobalVariable &GV : M.globals())
446 if (GV.hasAppendingLinkage())
447 Keep.push_back(&GV);
448
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000449 for (const InputFile::Symbol &Sym :
Peter Collingbournead903692016-12-13 19:43:49 +0000450 make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
451 nullptr),
452 InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
453 nullptr))) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000454 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000455 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000456 addSymbolToGlobalRes(Used, Sym, Res, 0);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000457
Davide Italiano39ccd242016-09-13 18:45:13 +0000458 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
459 continue;
Peter Collingbournead903692016-12-13 19:43:49 +0000460 if (Res.Prevailing && Sym.isGV()) {
461 GlobalValue *GV = Sym.getGV();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000462 Keep.push_back(GV);
463 switch (GV->getLinkage()) {
464 default:
465 break;
466 case GlobalValue::LinkOnceAnyLinkage:
467 GV->setLinkage(GlobalValue::WeakAnyLinkage);
468 break;
469 case GlobalValue::LinkOnceODRLinkage:
470 GV->setLinkage(GlobalValue::WeakODRLinkage);
471 break;
472 }
473 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000474 // Common resolution: collect the maximum size/alignment over all commons.
475 // We also record if we see an instance of a common as prevailing, so that
476 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000477 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000478 // FIXME: We should figure out what to do about commons defined by asm.
479 // For now they aren't reported correctly by ModuleSymbolTable.
Peter Collingbournead903692016-12-13 19:43:49 +0000480 auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000481 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
482 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000483 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000484 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000485
486 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
487 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000488
Peter Collingbournead903692016-12-13 19:43:49 +0000489 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000490 [](GlobalValue &, IRMover::ValueAdder) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000491 /* LinkModuleInlineAsm */ true,
492 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000493}
494
495// Add a ThinLTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000496// FIXME: This function should not need to take as many parameters once we have
497// a bitcode symbol table.
498Error LTO::addThinLTO(BitcodeModule BM, Module &M,
499 iterator_range<InputFile::symbol_iterator> Syms,
500 const SymbolResolution *&ResI,
501 const SymbolResolution *ResE) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000502 SmallPtrSet<GlobalValue *, 8> Used;
503 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
504
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000505 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
506 if (!SummaryOrErr)
507 return SummaryOrErr.takeError();
508 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000509 ThinLTO.ModuleMap.size());
510
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000511 for (const InputFile::Symbol &Sym : Syms) {
512 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000513 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000514 addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000515
Peter Collingbournead903692016-12-13 19:43:49 +0000516 if (Res.Prevailing && Sym.isGV())
517 ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000518 BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000519 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000520
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000521 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
522 return make_error<StringError>(
523 "Expected at most one ThinLTO module per bitcode file",
524 inconvertibleErrorCode());
525
Mehdi Amini41af4302016-11-11 04:28:40 +0000526 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000527}
528
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000529unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000530 CalledGetMaxTasks = true;
531 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
532}
533
Peter Collingbourne80186a52016-09-23 21:33:43 +0000534Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000535 // Save the status of having a regularLTO combined module, as
536 // this is needed for generating the ThinLTO Task ID, and
537 // the CombinedModule will be moved at the end of runRegularLTO.
538 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000539 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000540 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000541 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000542 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000543 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000544}
545
Peter Collingbourne80186a52016-09-23 21:33:43 +0000546Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000547 // Make sure commons have the right size/alignment: we kept the largest from
548 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000549 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000550 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000551 if (!I.second.Prevailing)
552 // Don't do anything if no instance of this common was prevailing.
553 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000554 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000555 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000556 // Don't create a new global if the type is already correct, just make
557 // sure the alignment is correct.
558 OldGV->setAlignment(I.second.Align);
559 continue;
560 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000561 ArrayType *Ty =
562 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000563 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
564 GlobalValue::CommonLinkage,
565 ConstantAggregateZero::get(Ty), "");
566 GV->setAlignment(I.second.Align);
567 if (OldGV) {
568 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
569 GV->takeName(OldGV);
570 OldGV->eraseFromParent();
571 } else {
572 GV->setName(I.first);
573 }
574 }
575
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000576 if (Conf.PreOptModuleHook &&
577 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000578 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000579
Mehdi Aminid310b472016-08-22 06:25:41 +0000580 if (!Conf.CodeGenOnly) {
581 for (const auto &R : GlobalResolutions) {
582 if (R.second.IRName.empty())
583 continue;
584 if (R.second.Partition != 0 &&
585 R.second.Partition != GlobalResolution::External)
586 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000587
Mehdi Aminid310b472016-08-22 06:25:41 +0000588 GlobalValue *GV =
589 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
590 // Ignore symbols defined in other partitions.
591 if (!GV || GV->hasLocalLinkage())
592 continue;
593 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
594 : GlobalValue::UnnamedAddr::None);
595 if (R.second.Partition == 0)
596 GV->setLinkage(GlobalValue::InternalLinkage);
597 }
598
599 if (Conf.PostInternalizeModuleHook &&
600 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000601 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000602 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000603 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000604 std::move(RegularLTO.CombinedModule));
605}
606
607/// This class defines the interface to the ThinLTO backend.
608class lto::ThinBackendProc {
609protected:
610 Config &Conf;
611 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000612 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000613
614public:
615 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000616 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000617 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000618 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
619
620 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000621 virtual Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000622 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000623 const FunctionImporter::ImportMapTy &ImportList,
624 const FunctionImporter::ExportSetTy &ExportList,
625 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000626 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000627 virtual Error wait() = 0;
628};
629
Benjamin Kramerffd37152016-11-19 20:44:26 +0000630namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000631class InProcessThinBackend : public ThinBackendProc {
632 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000633 AddStreamFn AddStream;
634 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000635
636 Optional<Error> Err;
637 std::mutex ErrMu;
638
639public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000640 InProcessThinBackend(
641 Config &Conf, ModuleSummaryIndex &CombinedIndex,
642 unsigned ThinLTOParallelismLevel,
643 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000644 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000645 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
646 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000647 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000648
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000649 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000650 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000651 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000652 const FunctionImporter::ImportMapTy &ImportList,
653 const FunctionImporter::ExportSetTy &ExportList,
654 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
655 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000656 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000657 auto RunThinBackend = [&](AddStreamFn AddStream) {
658 LTOLLVMContext BackendContext(Conf);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000659 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000660 if (!MOrErr)
661 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000662
Peter Collingbourne80186a52016-09-23 21:33:43 +0000663 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
664 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000665 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000666
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000667 auto ModuleID = BM.getModuleIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000668
669 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
670 all_of(CombinedIndex.getModuleHash(ModuleID),
671 [](uint32_t V) { return V == 0; }))
672 // Cache disabled or no entry for this module in the combined index or
673 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000674 return RunThinBackend(AddStream);
675
676 SmallString<40> Key;
677 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000678 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Mehdi Amini00fa1402016-10-08 04:44:18 +0000679 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000680 if (AddStreamFn CacheAddStream = Cache(Task, Key))
681 return RunThinBackend(CacheAddStream);
682
Mehdi Amini41af4302016-11-11 04:28:40 +0000683 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000684 }
685
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000686 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000687 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000688 const FunctionImporter::ImportMapTy &ImportList,
689 const FunctionImporter::ExportSetTy &ExportList,
690 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000691 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
692 StringRef ModulePath = BM.getModuleIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000693 assert(ModuleToDefinedGVSummaries.count(ModulePath));
694 const GVSummaryMapTy &DefinedGlobals =
695 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000696 BackendThreadPool.async(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000697 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000698 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000699 const FunctionImporter::ExportSetTy &ExportList,
700 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
701 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000702 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000703 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000704 Error E = runThinLTOBackendThread(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000705 AddStream, Cache, Task, BM, CombinedIndex, ImportList,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000706 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000707 if (E) {
708 std::unique_lock<std::mutex> L(ErrMu);
709 if (Err)
710 Err = joinErrors(std::move(*Err), std::move(E));
711 else
712 Err = std::move(E);
713 }
714 },
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000715 BM, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000716 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
717 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000718 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000719 }
720
721 Error wait() override {
722 BackendThreadPool.wait();
723 if (Err)
724 return std::move(*Err);
725 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000726 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000727 }
728};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000729} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000730
731ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
732 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000733 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000734 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000735 return llvm::make_unique<InProcessThinBackend>(
736 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000737 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000738 };
739}
740
Teresa Johnson3f212b82016-09-21 19:12:05 +0000741// Given the original \p Path to an output file, replace any path
742// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
743// resulting directory if it does not yet exist.
744std::string lto::getThinLTOOutputFile(const std::string &Path,
745 const std::string &OldPrefix,
746 const std::string &NewPrefix) {
747 if (OldPrefix.empty() && NewPrefix.empty())
748 return Path;
749 SmallString<128> NewPath(Path);
750 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
751 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
752 if (!ParentPath.empty()) {
753 // Make sure the new directory exists, creating it if necessary.
754 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
755 llvm::errs() << "warning: could not create directory '" << ParentPath
756 << "': " << EC.message() << '\n';
757 }
758 return NewPath.str();
759}
760
Benjamin Kramerffd37152016-11-19 20:44:26 +0000761namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000762class WriteIndexesThinBackend : public ThinBackendProc {
763 std::string OldPrefix, NewPrefix;
764 bool ShouldEmitImportsFiles;
765
766 std::string LinkedObjectsFileName;
767 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
768
769public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000770 WriteIndexesThinBackend(
771 Config &Conf, ModuleSummaryIndex &CombinedIndex,
772 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
773 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
774 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000775 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000776 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
777 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
778 LinkedObjectsFileName(LinkedObjectsFileName) {}
779
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000780 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000781 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000782 const FunctionImporter::ImportMapTy &ImportList,
783 const FunctionImporter::ExportSetTy &ExportList,
784 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000785 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
786 StringRef ModulePath = BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000787 std::string NewModulePath =
788 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
789
790 std::error_code EC;
791 if (!LinkedObjectsFileName.empty()) {
792 if (!LinkedObjectsFile) {
793 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
794 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
795 if (EC)
796 return errorCodeToError(EC);
797 }
798 *LinkedObjectsFile << NewModulePath << '\n';
799 }
800
801 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
802 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000803 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000804
805 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
806 sys::fs::OpenFlags::F_None);
807 if (EC)
808 return errorCodeToError(EC);
809 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
810
811 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000812 return errorCodeToError(
813 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000814 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000815 }
816
Mehdi Amini41af4302016-11-11 04:28:40 +0000817 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000818};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000819} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000820
821ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
822 std::string NewPrefix,
823 bool ShouldEmitImportsFiles,
824 std::string LinkedObjectsFile) {
825 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000826 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000827 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000828 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000829 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
830 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000831 };
832}
833
Peter Collingbourne80186a52016-09-23 21:33:43 +0000834Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
835 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000836 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000837 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000838
839 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000840 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000841
842 // Collect for each module the list of function it defines (GUID ->
843 // Summary).
844 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
845 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
846 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
847 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000848 // Create entries for any modules that didn't have any GV summaries
849 // (either they didn't have any GVs to start with, or we suppressed
850 // generation of the summaries because they e.g. had inline assembly
851 // uses that couldn't be promoted/renamed on export). This is so
852 // InProcessThinBackend::start can still launch a backend thread, which
853 // is passed the map of summaries for the module, without any special
854 // handling for this case.
855 for (auto &Mod : ThinLTO.ModuleMap)
856 if (!ModuleToDefinedGVSummaries.count(Mod.first))
857 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000858
Teresa Johnson6c475a72017-01-05 21:34:18 +0000859 // Compute "dead" symbols, we don't want to import/export these!
860 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
861 for (auto &Res : GlobalResolutions) {
862 if (Res.second.VisibleOutsideThinLTO &&
863 // IRName will be defined if we have seen the prevailing copy of
864 // this value. If not, no need to preserve any ThinLTO copies.
865 !Res.second.IRName.empty())
866 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Res.second.IRName));
867 }
868
869 auto DeadSymbols =
870 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
871
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000872 StringMap<FunctionImporter::ImportMapTy> ImportLists(
873 ThinLTO.ModuleMap.size());
874 StringMap<FunctionImporter::ExportSetTy> ExportLists(
875 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000876 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000877
Teresa Johnson002af9b2016-10-31 22:12:21 +0000878 if (Conf.OptLevel > 0) {
879 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000880 ImportLists, ExportLists, &DeadSymbols);
Teresa Johnson002af9b2016-10-31 22:12:21 +0000881
882 std::set<GlobalValue::GUID> ExportedGUIDs;
883 for (auto &Res : GlobalResolutions) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000884 // First check if the symbol was flagged as having external references.
885 if (Res.second.Partition != GlobalResolution::External)
886 continue;
887 // IRName will be defined if we have seen the prevailing copy of
888 // this value. If not, no need to mark as exported from a ThinLTO
889 // partition (and we can't get the GUID).
890 if (Res.second.IRName.empty())
891 continue;
892 auto GUID = GlobalValue::getGUID(Res.second.IRName);
893 // Mark exported unless index-based analysis determined it to be dead.
894 if (!DeadSymbols.count(GUID))
Teresa Johnson002af9b2016-10-31 22:12:21 +0000895 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
896 }
897
898 auto isPrevailing = [&](GlobalValue::GUID GUID,
899 const GlobalValueSummary *S) {
900 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
901 };
902 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
903 const auto &ExportList = ExportLists.find(ModuleIdentifier);
904 return (ExportList != ExportLists.end() &&
905 ExportList->second.count(GUID)) ||
906 ExportedGUIDs.count(GUID);
907 };
908 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
909
910 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
911 GlobalValue::GUID GUID,
912 GlobalValue::LinkageTypes NewLinkage) {
913 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
914 };
915
916 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
917 recordNewLinkage);
918 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000919
Peter Collingbourne80186a52016-09-23 21:33:43 +0000920 std::unique_ptr<ThinBackendProc> BackendProc =
921 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
922 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000923
Davide Italiano63098952017-01-04 20:37:57 +0000924 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
925 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
926 // are reserved for parallel code generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000927 unsigned Task =
928 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000929 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000930 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000931 ExportLists[Mod.first],
932 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000933 return E;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000934 ++Task;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000935 }
936
937 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000938}