blob: 0f22207c3faf4eb457934d2b2c1c9eb9c009cd28 [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 Johnson3bc8abd2016-10-30 05:15:23 +0000167 !GlobalInvolvedWithAlias.count(S.get()) &&
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000168 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
169 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
170 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
171 if (S->linkage() != OriginalLinkage)
172 recordNewLinkage(S->modulePath(), GUID, S->linkage());
173 }
174}
175
176// Resolve Weak and LinkOnce values in the \p Index.
177//
178// We'd like to drop these functions if they are no longer referenced in the
179// current module. However there is a chance that another module is still
180// referencing them because of the import. We make sure we always emit at least
181// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000182void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000183 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000184 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000185 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000186 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000187 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000188 // We won't optimize the globals that are referenced by an alias for now
189 // Ideally we should turn the alias into a global and duplicate the definition
190 // when needed.
191 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
192 for (auto &I : Index)
193 for (auto &S : I.second)
194 if (auto AS = dyn_cast<AliasSummary>(S.get()))
195 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
196
197 for (auto &I : Index)
198 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000199 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000200}
201
202static void thinLTOInternalizeAndPromoteGUID(
203 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000204 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000205 for (auto &S : GVSummaryList) {
206 if (isExported(S->modulePath(), GUID)) {
207 if (GlobalValue::isLocalLinkage(S->linkage()))
208 S->setLinkage(GlobalValue::ExternalLinkage);
209 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
210 S->setLinkage(GlobalValue::InternalLinkage);
211 }
212}
213
214// Update the linkages in the given \p Index to mark exported values
215// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000216void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000217 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000218 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000219 for (auto &I : Index)
220 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
221}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000222
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000223struct InputFile::InputModule {
224 BitcodeModule BM;
225 std::unique_ptr<Module> Mod;
226
227 // The range of ModuleSymbolTable entries for this input module.
228 size_t SymBegin, SymEnd;
229};
230
231// Requires a destructor for std::vector<InputModule>.
232InputFile::~InputFile() = default;
233
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000234Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
235 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000236
Peter Collingbournead903692016-12-13 19:43:49 +0000237 ErrorOr<MemoryBufferRef> BCOrErr =
238 IRObjectFile::findBitcodeInMemBuffer(Object);
239 if (!BCOrErr)
240 return errorCodeToError(BCOrErr.getError());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000241
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000242 Expected<std::vector<BitcodeModule>> BMsOrErr =
243 getBitcodeModuleList(*BCOrErr);
244 if (!BMsOrErr)
245 return BMsOrErr.takeError();
Peter Collingbournead903692016-12-13 19:43:49 +0000246
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000247 if (BMsOrErr->empty())
248 return make_error<StringError>("Bitcode file does not contain any modules",
249 inconvertibleErrorCode());
Peter Collingbournead903692016-12-13 19:43:49 +0000250
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000251 // Create an InputModule for each module in the InputFile, and add it to the
252 // ModuleSymbolTable.
253 for (auto BM : *BMsOrErr) {
254 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000255 BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true,
256 /*IsImporting*/ false);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000257 if (!MOrErr)
258 return MOrErr.takeError();
259
260 size_t SymBegin = File->SymTab.symbols().size();
261 File->SymTab.addModule(MOrErr->get());
262 size_t SymEnd = File->SymTab.symbols().size();
263
264 for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
265 auto P = File->ComdatMap.insert(
266 std::make_pair(&C.second, File->Comdats.size()));
267 assert(P.second);
268 (void)P;
269 File->Comdats.push_back(C.first());
270 }
271
272 File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
Rafael Espindola79121102016-10-25 12:02:03 +0000273 }
274
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000275 return std::move(File);
276}
277
Rafael Espindola79121102016-10-25 12:02:03 +0000278Expected<int> InputFile::Symbol::getComdatIndex() const {
Peter Collingbournead903692016-12-13 19:43:49 +0000279 if (!isGV())
Rafael Espindola79121102016-10-25 12:02:03 +0000280 return -1;
Peter Collingbournead903692016-12-13 19:43:49 +0000281 const GlobalObject *GO = getGV()->getBaseObject();
282 if (!GO)
283 return make_error<StringError>("Unable to determine comdat of alias!",
284 inconvertibleErrorCode());
Rafael Espindola79121102016-10-25 12:02:03 +0000285 if (const Comdat *C = GO->getComdat()) {
286 auto I = File->ComdatMap.find(C);
287 assert(I != File->ComdatMap.end());
288 return I->second;
289 }
290 return -1;
291}
292
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000293StringRef InputFile::getName() const {
294 return Mods[0].BM.getModuleIdentifier();
295}
296
297StringRef InputFile::getSourceFileName() const {
298 return Mods[0].Mod->getSourceFileName();
299}
300
301iterator_range<InputFile::symbol_iterator>
302InputFile::module_symbols(InputModule &IM) {
303 return llvm::make_range(
304 symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
305 symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
306}
307
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000308LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
309 Config &Conf)
310 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000311 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000312
313LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
314 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000315 this->Backend =
316 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000317}
318
319LTO::LTO(Config Conf, ThinBackend Backend,
320 unsigned ParallelCodeGenParallelismLevel)
321 : Conf(std::move(Conf)),
322 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000323 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000324
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000325// Requires a destructor for MapVector<BitcodeModule>.
326LTO::~LTO() = default;
327
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000328// Add the given symbol to the GlobalResolutions map, and resolve its partition.
Peter Collingbournead903692016-12-13 19:43:49 +0000329void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000330 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000331 SymbolResolution Res, unsigned Partition) {
Peter Collingbournead903692016-12-13 19:43:49 +0000332 GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000333
334 auto &GlobalRes = GlobalResolutions[Sym.getName()];
335 if (GV) {
336 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
337 if (Res.Prevailing)
338 GlobalRes.IRName = GV->getName();
339 }
Teresa Johnson6c475a72017-01-05 21:34:18 +0000340 // Set the partition to external if we know it is used elsewhere, e.g.
341 // it is visible to a regular object, is referenced from llvm.compiler_used,
342 // or was already recorded as being referenced from a different partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000343 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
344 (GlobalRes.Partition != GlobalResolution::Unknown &&
Teresa Johnson6c475a72017-01-05 21:34:18 +0000345 GlobalRes.Partition != Partition)) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000346 GlobalRes.Partition = GlobalResolution::External;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000347 } else
348 // First recorded reference, save the current partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000349 GlobalRes.Partition = Partition;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000350
351 // Flag as visible outside of ThinLTO if visible from a regular object or
352 // if this is a reference in the regular LTO partition.
353 GlobalRes.VisibleOutsideThinLTO |=
354 (Res.VisibleToRegularObj || (Partition == GlobalResolution::RegularLTO));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000355}
356
Rafael Espindola7775c332016-08-26 20:19:35 +0000357static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
358 ArrayRef<SymbolResolution> Res) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000359 StringRef Path = Input->getName();
Rafael Espindola7775c332016-08-26 20:19:35 +0000360 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000361 auto ResI = Res.begin();
362 for (const InputFile::Symbol &Sym : Input->symbols()) {
363 assert(ResI != Res.end());
364 SymbolResolution Res = *ResI++;
365
Rafael Espindola7775c332016-08-26 20:19:35 +0000366 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000367 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000368 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000369 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000370 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000371 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000372 OS << 'x';
373 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000374 }
Peter Collingbourne58ffcfb2017-01-19 23:10:14 +0000375 OS.flush();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000376 assert(ResI == Res.end());
377}
378
379Error LTO::add(std::unique_ptr<InputFile> Input,
380 ArrayRef<SymbolResolution> Res) {
381 assert(!CalledGetMaxTasks);
382
383 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000384 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000385
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000386 const SymbolResolution *ResI = Res.begin();
387 for (InputFile::InputModule &IM : Input->Mods)
388 if (Error Err = addModule(*Input, IM, ResI, Res.end()))
389 return Err;
390
391 assert(ResI == Res.end());
392 return Error::success();
393}
394
395Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
396 const SymbolResolution *&ResI,
397 const SymbolResolution *ResE) {
Mehdi Amini9989f802016-08-19 15:35:44 +0000398 // FIXME: move to backend
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000399 Module &M = *IM.Mod;
Davide Italiano2ceb6282016-12-14 21:57:04 +0000400
401 if (M.getDataLayoutStr().empty())
402 return make_error<StringError>("input module has no datalayout",
403 inconvertibleErrorCode());
404
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000405 if (!Conf.OverrideTriple.empty())
406 M.setTargetTriple(Conf.OverrideTriple);
407 else if (M.getTargetTriple().empty())
408 M.setTargetTriple(Conf.DefaultTriple);
409
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000410 Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000411 if (!HasThinLTOSummary)
412 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000413
Peter Collingbournecd513a42016-11-11 19:50:24 +0000414 if (*HasThinLTOSummary)
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000415 return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000416 else
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000417 return addRegularLTO(IM.BM, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000418}
419
420// Add a regular LTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000421Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
422 const SymbolResolution *ResE) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000423 if (!RegularLTO.CombinedModule) {
424 RegularLTO.CombinedModule =
425 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
426 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
427 }
Peter Collingbournead903692016-12-13 19:43:49 +0000428 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000429 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
430 /*IsImporting*/ false);
Peter Collingbournead903692016-12-13 19:43:49 +0000431 if (!MOrErr)
432 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000433
Peter Collingbournead903692016-12-13 19:43:49 +0000434 Module &M = **MOrErr;
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000435 if (Error Err = M.materializeMetadata())
436 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000437 UpgradeDebugInfo(M);
438
Peter Collingbournead903692016-12-13 19:43:49 +0000439 ModuleSymbolTable SymTab;
440 SymTab.addModule(&M);
441
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000442 SmallPtrSet<GlobalValue *, 8> Used;
443 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
444
445 std::vector<GlobalValue *> Keep;
446
447 for (GlobalVariable &GV : M.globals())
448 if (GV.hasAppendingLinkage())
449 Keep.push_back(&GV);
450
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000451 for (const InputFile::Symbol &Sym :
Peter Collingbournead903692016-12-13 19:43:49 +0000452 make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
453 nullptr),
454 InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
455 nullptr))) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000456 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000457 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000458 addSymbolToGlobalRes(Used, Sym, Res, 0);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000459
Davide Italiano39ccd242016-09-13 18:45:13 +0000460 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
461 continue;
Peter Collingbournead903692016-12-13 19:43:49 +0000462 if (Res.Prevailing && Sym.isGV()) {
463 GlobalValue *GV = Sym.getGV();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000464 Keep.push_back(GV);
465 switch (GV->getLinkage()) {
466 default:
467 break;
468 case GlobalValue::LinkOnceAnyLinkage:
469 GV->setLinkage(GlobalValue::WeakAnyLinkage);
470 break;
471 case GlobalValue::LinkOnceODRLinkage:
472 GV->setLinkage(GlobalValue::WeakODRLinkage);
473 break;
474 }
475 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000476 // Common resolution: collect the maximum size/alignment over all commons.
477 // We also record if we see an instance of a common as prevailing, so that
478 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000479 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000480 // FIXME: We should figure out what to do about commons defined by asm.
481 // For now they aren't reported correctly by ModuleSymbolTable.
Peter Collingbournead903692016-12-13 19:43:49 +0000482 auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000483 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
484 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000485 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000486 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000487
488 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
489 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000490
Peter Collingbournead903692016-12-13 19:43:49 +0000491 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000492 [](GlobalValue &, IRMover::ValueAdder) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000493 /* LinkModuleInlineAsm */ true,
494 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000495}
496
497// Add a ThinLTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000498// FIXME: This function should not need to take as many parameters once we have
499// a bitcode symbol table.
500Error LTO::addThinLTO(BitcodeModule BM, Module &M,
501 iterator_range<InputFile::symbol_iterator> Syms,
502 const SymbolResolution *&ResI,
503 const SymbolResolution *ResE) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000504 SmallPtrSet<GlobalValue *, 8> Used;
505 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
506
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000507 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
508 if (!SummaryOrErr)
509 return SummaryOrErr.takeError();
510 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000511 ThinLTO.ModuleMap.size());
512
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000513 for (const InputFile::Symbol &Sym : Syms) {
514 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000515 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000516 addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000517
Peter Collingbournead903692016-12-13 19:43:49 +0000518 if (Res.Prevailing && Sym.isGV())
519 ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000520 BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000521 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000522
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000523 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
524 return make_error<StringError>(
525 "Expected at most one ThinLTO module per bitcode file",
526 inconvertibleErrorCode());
527
Mehdi Amini41af4302016-11-11 04:28:40 +0000528 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000529}
530
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000531unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000532 CalledGetMaxTasks = true;
533 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
534}
535
Peter Collingbourne80186a52016-09-23 21:33:43 +0000536Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000537 // Save the status of having a regularLTO combined module, as
538 // this is needed for generating the ThinLTO Task ID, and
539 // the CombinedModule will be moved at the end of runRegularLTO.
540 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000541 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000542 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000543 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000544 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000545 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000546}
547
Peter Collingbourne80186a52016-09-23 21:33:43 +0000548Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000549 // Make sure commons have the right size/alignment: we kept the largest from
550 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000551 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000552 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000553 if (!I.second.Prevailing)
554 // Don't do anything if no instance of this common was prevailing.
555 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000556 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000557 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000558 // Don't create a new global if the type is already correct, just make
559 // sure the alignment is correct.
560 OldGV->setAlignment(I.second.Align);
561 continue;
562 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000563 ArrayType *Ty =
564 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000565 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
566 GlobalValue::CommonLinkage,
567 ConstantAggregateZero::get(Ty), "");
568 GV->setAlignment(I.second.Align);
569 if (OldGV) {
570 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
571 GV->takeName(OldGV);
572 OldGV->eraseFromParent();
573 } else {
574 GV->setName(I.first);
575 }
576 }
577
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000578 if (Conf.PreOptModuleHook &&
579 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000580 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000581
Mehdi Aminid310b472016-08-22 06:25:41 +0000582 if (!Conf.CodeGenOnly) {
583 for (const auto &R : GlobalResolutions) {
584 if (R.second.IRName.empty())
585 continue;
586 if (R.second.Partition != 0 &&
587 R.second.Partition != GlobalResolution::External)
588 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000589
Mehdi Aminid310b472016-08-22 06:25:41 +0000590 GlobalValue *GV =
591 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
592 // Ignore symbols defined in other partitions.
593 if (!GV || GV->hasLocalLinkage())
594 continue;
595 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
596 : GlobalValue::UnnamedAddr::None);
597 if (R.second.Partition == 0)
598 GV->setLinkage(GlobalValue::InternalLinkage);
599 }
600
601 if (Conf.PostInternalizeModuleHook &&
602 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000603 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000604 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000605 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000606 std::move(RegularLTO.CombinedModule));
607}
608
609/// This class defines the interface to the ThinLTO backend.
610class lto::ThinBackendProc {
611protected:
612 Config &Conf;
613 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000614 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000615
616public:
617 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000618 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000619 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000620 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
621
622 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000623 virtual Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000624 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000625 const FunctionImporter::ImportMapTy &ImportList,
626 const FunctionImporter::ExportSetTy &ExportList,
627 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000628 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000629 virtual Error wait() = 0;
630};
631
Benjamin Kramerffd37152016-11-19 20:44:26 +0000632namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000633class InProcessThinBackend : public ThinBackendProc {
634 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000635 AddStreamFn AddStream;
636 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000637
638 Optional<Error> Err;
639 std::mutex ErrMu;
640
641public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000642 InProcessThinBackend(
643 Config &Conf, ModuleSummaryIndex &CombinedIndex,
644 unsigned ThinLTOParallelismLevel,
645 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000646 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000647 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
648 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000649 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000650
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000651 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000652 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000653 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000654 const FunctionImporter::ImportMapTy &ImportList,
655 const FunctionImporter::ExportSetTy &ExportList,
656 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
657 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000658 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000659 auto RunThinBackend = [&](AddStreamFn AddStream) {
660 LTOLLVMContext BackendContext(Conf);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000661 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000662 if (!MOrErr)
663 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000664
Peter Collingbourne80186a52016-09-23 21:33:43 +0000665 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
666 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000667 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000668
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000669 auto ModuleID = BM.getModuleIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000670
671 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
672 all_of(CombinedIndex.getModuleHash(ModuleID),
673 [](uint32_t V) { return V == 0; }))
674 // Cache disabled or no entry for this module in the combined index or
675 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000676 return RunThinBackend(AddStream);
677
678 SmallString<40> Key;
679 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000680 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Mehdi Amini00fa1402016-10-08 04:44:18 +0000681 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000682 if (AddStreamFn CacheAddStream = Cache(Task, Key))
683 return RunThinBackend(CacheAddStream);
684
Mehdi Amini41af4302016-11-11 04:28:40 +0000685 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000686 }
687
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000688 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000689 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000690 const FunctionImporter::ImportMapTy &ImportList,
691 const FunctionImporter::ExportSetTy &ExportList,
692 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000693 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
694 StringRef ModulePath = BM.getModuleIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000695 assert(ModuleToDefinedGVSummaries.count(ModulePath));
696 const GVSummaryMapTy &DefinedGlobals =
697 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000698 BackendThreadPool.async(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000699 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000700 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000701 const FunctionImporter::ExportSetTy &ExportList,
702 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
703 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000704 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000705 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000706 Error E = runThinLTOBackendThread(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000707 AddStream, Cache, Task, BM, CombinedIndex, ImportList,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000708 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000709 if (E) {
710 std::unique_lock<std::mutex> L(ErrMu);
711 if (Err)
712 Err = joinErrors(std::move(*Err), std::move(E));
713 else
714 Err = std::move(E);
715 }
716 },
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000717 BM, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000718 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
719 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000720 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000721 }
722
723 Error wait() override {
724 BackendThreadPool.wait();
725 if (Err)
726 return std::move(*Err);
727 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000728 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000729 }
730};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000731} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000732
733ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
734 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000735 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000736 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000737 return llvm::make_unique<InProcessThinBackend>(
738 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000739 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000740 };
741}
742
Teresa Johnson3f212b82016-09-21 19:12:05 +0000743// Given the original \p Path to an output file, replace any path
744// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
745// resulting directory if it does not yet exist.
746std::string lto::getThinLTOOutputFile(const std::string &Path,
747 const std::string &OldPrefix,
748 const std::string &NewPrefix) {
749 if (OldPrefix.empty() && NewPrefix.empty())
750 return Path;
751 SmallString<128> NewPath(Path);
752 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
753 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
754 if (!ParentPath.empty()) {
755 // Make sure the new directory exists, creating it if necessary.
756 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
757 llvm::errs() << "warning: could not create directory '" << ParentPath
758 << "': " << EC.message() << '\n';
759 }
760 return NewPath.str();
761}
762
Benjamin Kramerffd37152016-11-19 20:44:26 +0000763namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000764class WriteIndexesThinBackend : public ThinBackendProc {
765 std::string OldPrefix, NewPrefix;
766 bool ShouldEmitImportsFiles;
767
768 std::string LinkedObjectsFileName;
769 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
770
771public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000772 WriteIndexesThinBackend(
773 Config &Conf, ModuleSummaryIndex &CombinedIndex,
774 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
775 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
776 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000777 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000778 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
779 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
780 LinkedObjectsFileName(LinkedObjectsFileName) {}
781
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000782 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000783 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000784 const FunctionImporter::ImportMapTy &ImportList,
785 const FunctionImporter::ExportSetTy &ExportList,
786 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000787 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
788 StringRef ModulePath = BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000789 std::string NewModulePath =
790 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
791
792 std::error_code EC;
793 if (!LinkedObjectsFileName.empty()) {
794 if (!LinkedObjectsFile) {
795 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
796 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
797 if (EC)
798 return errorCodeToError(EC);
799 }
800 *LinkedObjectsFile << NewModulePath << '\n';
801 }
802
803 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
804 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000805 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000806
807 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
808 sys::fs::OpenFlags::F_None);
809 if (EC)
810 return errorCodeToError(EC);
811 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
812
813 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000814 return errorCodeToError(
815 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000816 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000817 }
818
Mehdi Amini41af4302016-11-11 04:28:40 +0000819 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000820};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000821} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000822
823ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
824 std::string NewPrefix,
825 bool ShouldEmitImportsFiles,
826 std::string LinkedObjectsFile) {
827 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000828 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000829 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000830 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000831 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
832 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000833 };
834}
835
Peter Collingbourne80186a52016-09-23 21:33:43 +0000836Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
837 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000838 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000839 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000840
841 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000842 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000843
844 // Collect for each module the list of function it defines (GUID ->
845 // Summary).
846 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
847 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
848 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
849 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000850 // Create entries for any modules that didn't have any GV summaries
851 // (either they didn't have any GVs to start with, or we suppressed
852 // generation of the summaries because they e.g. had inline assembly
853 // uses that couldn't be promoted/renamed on export). This is so
854 // InProcessThinBackend::start can still launch a backend thread, which
855 // is passed the map of summaries for the module, without any special
856 // handling for this case.
857 for (auto &Mod : ThinLTO.ModuleMap)
858 if (!ModuleToDefinedGVSummaries.count(Mod.first))
859 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000860
Teresa Johnson6c475a72017-01-05 21:34:18 +0000861 // Compute "dead" symbols, we don't want to import/export these!
862 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
863 for (auto &Res : GlobalResolutions) {
864 if (Res.second.VisibleOutsideThinLTO &&
865 // IRName will be defined if we have seen the prevailing copy of
866 // this value. If not, no need to preserve any ThinLTO copies.
867 !Res.second.IRName.empty())
868 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Res.second.IRName));
869 }
870
871 auto DeadSymbols =
872 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
873
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000874 StringMap<FunctionImporter::ImportMapTy> ImportLists(
875 ThinLTO.ModuleMap.size());
876 StringMap<FunctionImporter::ExportSetTy> ExportLists(
877 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000878 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000879
Teresa Johnson002af9b2016-10-31 22:12:21 +0000880 if (Conf.OptLevel > 0) {
881 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000882 ImportLists, ExportLists, &DeadSymbols);
Teresa Johnson002af9b2016-10-31 22:12:21 +0000883
884 std::set<GlobalValue::GUID> ExportedGUIDs;
885 for (auto &Res : GlobalResolutions) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000886 // First check if the symbol was flagged as having external references.
887 if (Res.second.Partition != GlobalResolution::External)
888 continue;
889 // IRName will be defined if we have seen the prevailing copy of
890 // this value. If not, no need to mark as exported from a ThinLTO
891 // partition (and we can't get the GUID).
892 if (Res.second.IRName.empty())
893 continue;
894 auto GUID = GlobalValue::getGUID(Res.second.IRName);
895 // Mark exported unless index-based analysis determined it to be dead.
896 if (!DeadSymbols.count(GUID))
Teresa Johnson002af9b2016-10-31 22:12:21 +0000897 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
898 }
899
900 auto isPrevailing = [&](GlobalValue::GUID GUID,
901 const GlobalValueSummary *S) {
902 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
903 };
904 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
905 const auto &ExportList = ExportLists.find(ModuleIdentifier);
906 return (ExportList != ExportLists.end() &&
907 ExportList->second.count(GUID)) ||
908 ExportedGUIDs.count(GUID);
909 };
910 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
911
912 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
913 GlobalValue::GUID GUID,
914 GlobalValue::LinkageTypes NewLinkage) {
915 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
916 };
917
918 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
919 recordNewLinkage);
920 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000921
Peter Collingbourne80186a52016-09-23 21:33:43 +0000922 std::unique_ptr<ThinBackendProc> BackendProc =
923 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
924 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000925
Davide Italiano63098952017-01-04 20:37:57 +0000926 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
927 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
928 // are reserved for parallel code generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000929 unsigned Task =
930 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000931 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000932 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000933 ExportLists[Mod.first],
934 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000935 return E;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000936 ++Task;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000937 }
938
939 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000940}