blob: bf30fec5d2001cca20f8caaa938b2d1aae8943c3 [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"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000020#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000021#include "llvm/IR/AutoUpgrade.h"
22#include "llvm/IR/DiagnosticPrinter.h"
23#include "llvm/IR/LegacyPassManager.h"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000024#include "llvm/IR/Mangler.h"
25#include "llvm/IR/Metadata.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000026#include "llvm/LTO/LTOBackend.h"
27#include "llvm/Linker/IRMover.h"
28#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000029#include "llvm/Support/Error.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000030#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000031#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000032#include "llvm/Support/Path.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000033#include "llvm/Support/SHA1.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000034#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000035#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000037#include "llvm/Support/Threading.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000038#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000039#include "llvm/Target/TargetMachine.h"
40#include "llvm/Target/TargetOptions.h"
41#include "llvm/Transforms/IPO.h"
42#include "llvm/Transforms/IPO/PassManagerBuilder.h"
43#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000044
Teresa Johnson9ba95f92016-08-11 14:58:12 +000045#include <set>
46
47using namespace llvm;
48using namespace lto;
49using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000050
Mehdi Aminiadc0e262016-08-23 21:30:12 +000051#define DEBUG_TYPE "lto"
52
53// Returns a unique hash for the Module considering the current list of
54// export/import and other global analysis results.
55// The hash is produced in \p Key.
56static void computeCacheKey(
Peter Collingbournef4257522016-12-08 05:28:30 +000057 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
58 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +000059 const FunctionImporter::ExportSetTy &ExportList,
60 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
61 const GVSummaryMapTy &DefinedGlobals) {
62 // Compute the unique hash for this entry.
63 // This is based on the current compiler version, the module itself, the
64 // export list, the hash for every single module in the import list, the
65 // list of ResolvedODR for the module, and the list of preserved symbols.
66 SHA1 Hasher;
67
68 // Start with the compiler revision
69 Hasher.update(LLVM_VERSION_STRING);
70#ifdef HAVE_LLVM_REVISION
71 Hasher.update(LLVM_REVISION);
72#endif
73
Peter Collingbournef4257522016-12-08 05:28:30 +000074 // Include the parts of the LTO configuration that affect code generation.
75 auto AddString = [&](StringRef Str) {
76 Hasher.update(Str);
77 Hasher.update(ArrayRef<uint8_t>{0});
78 };
79 auto AddUnsigned = [&](unsigned I) {
80 uint8_t Data[4];
81 Data[0] = I;
82 Data[1] = I >> 8;
83 Data[2] = I >> 16;
84 Data[3] = I >> 24;
85 Hasher.update(ArrayRef<uint8_t>{Data, 4});
86 };
87 AddString(Conf.CPU);
88 // FIXME: Hash more of Options. For now all clients initialize Options from
89 // command-line flags (which is unsupported in production), but may set
90 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
91 // DataSections and DebuggerTuning via command line flags.
92 AddUnsigned(Conf.Options.RelaxELFRelocations);
93 AddUnsigned(Conf.Options.FunctionSections);
94 AddUnsigned(Conf.Options.DataSections);
95 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
96 for (auto &A : Conf.MAttrs)
97 AddString(A);
98 AddUnsigned(Conf.RelocModel);
99 AddUnsigned(Conf.CodeModel);
100 AddUnsigned(Conf.CGOptLevel);
101 AddUnsigned(Conf.OptLevel);
102 AddString(Conf.OptPipeline);
103 AddString(Conf.AAPipeline);
104 AddString(Conf.OverrideTriple);
105 AddString(Conf.DefaultTriple);
106
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000107 // Include the hash for the current module
108 auto ModHash = Index.getModuleHash(ModuleID);
109 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
110 for (auto F : ExportList)
111 // The export list can impact the internalization, be conservative here
112 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
113
114 // Include the hash for every module we import functions from
115 for (auto &Entry : ImportList) {
116 auto ModHash = Index.getModuleHash(Entry.first());
117 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
118 }
119
120 // Include the hash for the resolved ODR.
121 for (auto &Entry : ResolvedODR) {
122 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
123 sizeof(GlobalValue::GUID)));
124 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
125 sizeof(GlobalValue::LinkageTypes)));
126 }
127
128 // Include the hash for the linkage type to reflect internalization and weak
129 // resolution.
130 for (auto &GS : DefinedGlobals) {
131 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
132 Hasher.update(
133 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
134 }
135
Dehao Chen27978002016-12-16 16:48:46 +0000136 if (!Conf.SampleProfile.empty()) {
137 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
138 if (FileOrErr)
139 Hasher.update(FileOrErr.get()->getBuffer());
140 }
141
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000142 Key = toHex(Hasher.result());
143}
144
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000145static void thinLTOResolveWeakForLinkerGUID(
146 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
147 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000148 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000149 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000150 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000151 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000152 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000153 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
154 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
155 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000156 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000157 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000158 // This is both a compile-time optimization and a correctness
159 // transformation. This is necessary for correctness when we have exported
160 // a reference - we need to convert the linkonce to weak to
161 // ensure a copy is kept to satisfy the exported reference.
162 // FIXME: We may want to split the compile time and correctness
163 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000164 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000165 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
166 S->setLinkage(GlobalValue::getWeakLinkage(
167 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000168 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000169 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000170 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000171 !GlobalInvolvedWithAlias.count(S.get()))
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000172 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
173 if (S->linkage() != OriginalLinkage)
174 recordNewLinkage(S->modulePath(), GUID, S->linkage());
175 }
176}
177
178// Resolve Weak and LinkOnce values in the \p Index.
179//
180// We'd like to drop these functions if they are no longer referenced in the
181// current module. However there is a chance that another module is still
182// referencing them because of the import. We make sure we always emit at least
183// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000184void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000185 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000186 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000187 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000188 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000189 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000190 // We won't optimize the globals that are referenced by an alias for now
191 // Ideally we should turn the alias into a global and duplicate the definition
192 // when needed.
193 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
194 for (auto &I : Index)
195 for (auto &S : I.second)
196 if (auto AS = dyn_cast<AliasSummary>(S.get()))
197 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
198
199 for (auto &I : Index)
200 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000201 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000202}
203
204static void thinLTOInternalizeAndPromoteGUID(
205 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000206 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000207 for (auto &S : GVSummaryList) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000208 if (isExported(S->modulePath(), GUID)) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000209 if (GlobalValue::isLocalLinkage(S->linkage()))
210 S->setLinkage(GlobalValue::ExternalLinkage);
211 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
212 S->setLinkage(GlobalValue::InternalLinkage);
213 }
214}
215
216// Update the linkages in the given \p Index to mark exported values
217// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000218void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000219 ModuleSummaryIndex &Index,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000220 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000221 for (auto &I : Index)
222 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
223}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000224
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000225struct InputFile::InputModule {
226 BitcodeModule BM;
227 std::unique_ptr<Module> Mod;
228
229 // The range of ModuleSymbolTable entries for this input module.
230 size_t SymBegin, SymEnd;
231};
232
233// Requires a destructor for std::vector<InputModule>.
234InputFile::~InputFile() = default;
235
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000236Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
237 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000238
Peter Collingbournead903692016-12-13 19:43:49 +0000239 ErrorOr<MemoryBufferRef> BCOrErr =
240 IRObjectFile::findBitcodeInMemBuffer(Object);
241 if (!BCOrErr)
242 return errorCodeToError(BCOrErr.getError());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000243
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000244 Expected<std::vector<BitcodeModule>> BMsOrErr =
245 getBitcodeModuleList(*BCOrErr);
246 if (!BMsOrErr)
247 return BMsOrErr.takeError();
Peter Collingbournead903692016-12-13 19:43:49 +0000248
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000249 if (BMsOrErr->empty())
250 return make_error<StringError>("Bitcode file does not contain any modules",
251 inconvertibleErrorCode());
Peter Collingbournead903692016-12-13 19:43:49 +0000252
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000253 // Create an InputModule for each module in the InputFile, and add it to the
254 // ModuleSymbolTable.
255 for (auto BM : *BMsOrErr) {
256 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000257 BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true,
258 /*IsImporting*/ false);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000259 if (!MOrErr)
260 return MOrErr.takeError();
261
262 size_t SymBegin = File->SymTab.symbols().size();
263 File->SymTab.addModule(MOrErr->get());
264 size_t SymEnd = File->SymTab.symbols().size();
265
266 for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
267 auto P = File->ComdatMap.insert(
268 std::make_pair(&C.second, File->Comdats.size()));
269 assert(P.second);
270 (void)P;
271 File->Comdats.push_back(C.first());
272 }
273
274 File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
Rafael Espindola79121102016-10-25 12:02:03 +0000275 }
276
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000277 return std::move(File);
278}
279
Rafael Espindola79121102016-10-25 12:02:03 +0000280Expected<int> InputFile::Symbol::getComdatIndex() const {
Peter Collingbournead903692016-12-13 19:43:49 +0000281 if (!isGV())
Rafael Espindola79121102016-10-25 12:02:03 +0000282 return -1;
Peter Collingbournead903692016-12-13 19:43:49 +0000283 const GlobalObject *GO = getGV()->getBaseObject();
284 if (!GO)
285 return make_error<StringError>("Unable to determine comdat of alias!",
286 inconvertibleErrorCode());
Rafael Espindola79121102016-10-25 12:02:03 +0000287 if (const Comdat *C = GO->getComdat()) {
288 auto I = File->ComdatMap.find(C);
289 assert(I != File->ComdatMap.end());
290 return I->second;
291 }
292 return -1;
293}
294
Bob Haarmandd4ebc12017-02-02 23:00:49 +0000295Expected<std::string> InputFile::getLinkerOpts() {
296 std::string LinkerOpts;
297 raw_string_ostream LOS(LinkerOpts);
298 // Extract linker options from module metadata.
299 for (InputModule &Mod : Mods) {
300 std::unique_ptr<Module> &M = Mod.Mod;
301 if (auto E = M->materializeMetadata())
302 return std::move(E);
303 if (Metadata *Val = M->getModuleFlag("Linker Options")) {
304 MDNode *LinkerOptions = cast<MDNode>(Val);
305 for (const MDOperand &MDOptions : LinkerOptions->operands())
306 for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
307 LOS << " " << cast<MDString>(MDOption)->getString();
308 }
309 }
310
311 // Synthesize export flags for symbols with dllexport storage.
312 const Triple TT(Mods[0].Mod->getTargetTriple());
313 Mangler M;
314 for (const ModuleSymbolTable::Symbol &Sym : SymTab.symbols())
315 if (auto *GV = Sym.dyn_cast<GlobalValue*>())
316 emitLinkerFlagsForGlobalCOFF(LOS, GV, TT, M);
317 LOS.flush();
318 return LinkerOpts;
319}
320
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000321StringRef InputFile::getName() const {
322 return Mods[0].BM.getModuleIdentifier();
323}
324
325StringRef InputFile::getSourceFileName() const {
326 return Mods[0].Mod->getSourceFileName();
327}
328
329iterator_range<InputFile::symbol_iterator>
330InputFile::module_symbols(InputModule &IM) {
331 return llvm::make_range(
332 symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
333 symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
334}
335
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000336LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
337 Config &Conf)
338 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000339 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000340
341LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
342 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000343 this->Backend =
344 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000345}
346
347LTO::LTO(Config Conf, ThinBackend Backend,
348 unsigned ParallelCodeGenParallelismLevel)
349 : Conf(std::move(Conf)),
350 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000351 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000352
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000353// Requires a destructor for MapVector<BitcodeModule>.
354LTO::~LTO() = default;
355
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000356// Add the given symbol to the GlobalResolutions map, and resolve its partition.
Peter Collingbournead903692016-12-13 19:43:49 +0000357void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000358 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000359 SymbolResolution Res, unsigned Partition) {
Peter Collingbournead903692016-12-13 19:43:49 +0000360 GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000361
362 auto &GlobalRes = GlobalResolutions[Sym.getName()];
363 if (GV) {
364 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
365 if (Res.Prevailing)
366 GlobalRes.IRName = GV->getName();
367 }
Teresa Johnson6c475a72017-01-05 21:34:18 +0000368 // Set the partition to external if we know it is used elsewhere, e.g.
369 // it is visible to a regular object, is referenced from llvm.compiler_used,
370 // or was already recorded as being referenced from a different partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000371 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
372 (GlobalRes.Partition != GlobalResolution::Unknown &&
Teresa Johnson6c475a72017-01-05 21:34:18 +0000373 GlobalRes.Partition != Partition)) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000374 GlobalRes.Partition = GlobalResolution::External;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000375 } else
376 // First recorded reference, save the current partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000377 GlobalRes.Partition = Partition;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000378
379 // Flag as visible outside of ThinLTO if visible from a regular object or
380 // if this is a reference in the regular LTO partition.
381 GlobalRes.VisibleOutsideThinLTO |=
382 (Res.VisibleToRegularObj || (Partition == GlobalResolution::RegularLTO));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000383}
384
Rafael Espindola7775c332016-08-26 20:19:35 +0000385static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
386 ArrayRef<SymbolResolution> Res) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000387 StringRef Path = Input->getName();
Rafael Espindola7775c332016-08-26 20:19:35 +0000388 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000389 auto ResI = Res.begin();
390 for (const InputFile::Symbol &Sym : Input->symbols()) {
391 assert(ResI != Res.end());
392 SymbolResolution Res = *ResI++;
393
Rafael Espindola7775c332016-08-26 20:19:35 +0000394 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000395 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000396 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000397 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000398 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000399 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000400 OS << 'x';
401 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000402 }
Peter Collingbourne58ffcfb2017-01-19 23:10:14 +0000403 OS.flush();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000404 assert(ResI == Res.end());
405}
406
407Error LTO::add(std::unique_ptr<InputFile> Input,
408 ArrayRef<SymbolResolution> Res) {
409 assert(!CalledGetMaxTasks);
410
411 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000412 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000413
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000414 const SymbolResolution *ResI = Res.begin();
415 for (InputFile::InputModule &IM : Input->Mods)
416 if (Error Err = addModule(*Input, IM, ResI, Res.end()))
417 return Err;
418
419 assert(ResI == Res.end());
420 return Error::success();
421}
422
423Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
424 const SymbolResolution *&ResI,
425 const SymbolResolution *ResE) {
Mehdi Amini9989f802016-08-19 15:35:44 +0000426 // FIXME: move to backend
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000427 Module &M = *IM.Mod;
Davide Italiano2ceb6282016-12-14 21:57:04 +0000428
429 if (M.getDataLayoutStr().empty())
430 return make_error<StringError>("input module has no datalayout",
431 inconvertibleErrorCode());
432
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000433 if (!Conf.OverrideTriple.empty())
434 M.setTargetTriple(Conf.OverrideTriple);
435 else if (M.getTargetTriple().empty())
436 M.setTargetTriple(Conf.DefaultTriple);
437
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000438 Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000439 if (!HasThinLTOSummary)
440 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000441
Peter Collingbournecd513a42016-11-11 19:50:24 +0000442 if (*HasThinLTOSummary)
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000443 return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000444 else
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000445 return addRegularLTO(IM.BM, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000446}
447
448// Add a regular LTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000449Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
450 const SymbolResolution *ResE) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000451 if (!RegularLTO.CombinedModule) {
452 RegularLTO.CombinedModule =
453 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
454 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
455 }
Peter Collingbournead903692016-12-13 19:43:49 +0000456 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000457 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
458 /*IsImporting*/ false);
Peter Collingbournead903692016-12-13 19:43:49 +0000459 if (!MOrErr)
460 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000461
Peter Collingbournead903692016-12-13 19:43:49 +0000462 Module &M = **MOrErr;
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000463 if (Error Err = M.materializeMetadata())
464 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000465 UpgradeDebugInfo(M);
466
Peter Collingbournead903692016-12-13 19:43:49 +0000467 ModuleSymbolTable SymTab;
468 SymTab.addModule(&M);
469
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000470 SmallPtrSet<GlobalValue *, 8> Used;
471 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
472
473 std::vector<GlobalValue *> Keep;
474
475 for (GlobalVariable &GV : M.globals())
476 if (GV.hasAppendingLinkage())
477 Keep.push_back(&GV);
478
Peter Collingbourne46136262017-02-02 05:22:42 +0000479 DenseSet<GlobalObject *> AliasedGlobals;
480 for (auto &GA : M.aliases())
481 if (GlobalObject *GO = GA.getBaseObject())
482 AliasedGlobals.insert(GO);
483
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000484 for (const InputFile::Symbol &Sym :
Peter Collingbournead903692016-12-13 19:43:49 +0000485 make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
486 nullptr),
487 InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
488 nullptr))) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000489 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000490 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000491 addSymbolToGlobalRes(Used, Sym, Res, 0);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000492
Peter Collingbournec387e702017-02-02 05:12:15 +0000493 if (Sym.isGV()) {
Peter Collingbournead903692016-12-13 19:43:49 +0000494 GlobalValue *GV = Sym.getGV();
Peter Collingbournec387e702017-02-02 05:12:15 +0000495 if (Res.Prevailing) {
496 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
497 continue;
498 Keep.push_back(GV);
499 switch (GV->getLinkage()) {
500 default:
501 break;
502 case GlobalValue::LinkOnceAnyLinkage:
503 GV->setLinkage(GlobalValue::WeakAnyLinkage);
504 break;
505 case GlobalValue::LinkOnceODRLinkage:
506 GV->setLinkage(GlobalValue::WeakODRLinkage);
507 break;
508 }
Peter Collingbourne46136262017-02-02 05:22:42 +0000509 } else if (isa<GlobalObject>(GV) &&
510 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
511 GV->hasAvailableExternallyLinkage()) &&
512 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
513 // Either of the above three types of linkage indicates that the
514 // chosen prevailing symbol will have the same semantics as this copy of
515 // the symbol, so we can link it with available_externally linkage. We
516 // only need to do this if the symbol is undefined.
Peter Collingbournec387e702017-02-02 05:12:15 +0000517 GlobalValue *CombinedGV =
518 RegularLTO.CombinedModule->getNamedValue(GV->getName());
Peter Collingbourne46136262017-02-02 05:22:42 +0000519 if (!CombinedGV || CombinedGV->isDeclaration()) {
Peter Collingbournec387e702017-02-02 05:12:15 +0000520 Keep.push_back(GV);
Peter Collingbourne46136262017-02-02 05:22:42 +0000521 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
522 cast<GlobalObject>(GV)->setComdat(nullptr);
523 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000524 }
525 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000526 // Common resolution: collect the maximum size/alignment over all commons.
527 // We also record if we see an instance of a common as prevailing, so that
528 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000529 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000530 // FIXME: We should figure out what to do about commons defined by asm.
531 // For now they aren't reported correctly by ModuleSymbolTable.
Peter Collingbournead903692016-12-13 19:43:49 +0000532 auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000533 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
534 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000535 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000536 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000537
538 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
539 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000540
Peter Collingbournead903692016-12-13 19:43:49 +0000541 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000542 [](GlobalValue &, IRMover::ValueAdder) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000543 /* LinkModuleInlineAsm */ true,
544 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000545}
546
547// Add a ThinLTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000548// FIXME: This function should not need to take as many parameters once we have
549// a bitcode symbol table.
550Error LTO::addThinLTO(BitcodeModule BM, Module &M,
551 iterator_range<InputFile::symbol_iterator> Syms,
552 const SymbolResolution *&ResI,
553 const SymbolResolution *ResE) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000554 SmallPtrSet<GlobalValue *, 8> Used;
555 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
556
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000557 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
558 if (!SummaryOrErr)
559 return SummaryOrErr.takeError();
560 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000561 ThinLTO.ModuleMap.size());
562
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000563 for (const InputFile::Symbol &Sym : Syms) {
564 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000565 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000566 addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000567
Peter Collingbournead903692016-12-13 19:43:49 +0000568 if (Res.Prevailing && Sym.isGV())
569 ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000570 BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000571 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000572
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000573 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
574 return make_error<StringError>(
575 "Expected at most one ThinLTO module per bitcode file",
576 inconvertibleErrorCode());
577
Mehdi Amini41af4302016-11-11 04:28:40 +0000578 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000579}
580
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000581unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000582 CalledGetMaxTasks = true;
583 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
584}
585
Peter Collingbourne80186a52016-09-23 21:33:43 +0000586Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000587 // Save the status of having a regularLTO combined module, as
588 // this is needed for generating the ThinLTO Task ID, and
589 // the CombinedModule will be moved at the end of runRegularLTO.
590 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000591 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000592 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000593 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000594 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000595 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000596}
597
Peter Collingbourne80186a52016-09-23 21:33:43 +0000598Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000599 // Make sure commons have the right size/alignment: we kept the largest from
600 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000601 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000602 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000603 if (!I.second.Prevailing)
604 // Don't do anything if no instance of this common was prevailing.
605 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000606 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000607 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000608 // Don't create a new global if the type is already correct, just make
609 // sure the alignment is correct.
610 OldGV->setAlignment(I.second.Align);
611 continue;
612 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000613 ArrayType *Ty =
614 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000615 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
616 GlobalValue::CommonLinkage,
617 ConstantAggregateZero::get(Ty), "");
618 GV->setAlignment(I.second.Align);
619 if (OldGV) {
620 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
621 GV->takeName(OldGV);
622 OldGV->eraseFromParent();
623 } else {
624 GV->setName(I.first);
625 }
626 }
627
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000628 if (Conf.PreOptModuleHook &&
629 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000630 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000631
Mehdi Aminid310b472016-08-22 06:25:41 +0000632 if (!Conf.CodeGenOnly) {
633 for (const auto &R : GlobalResolutions) {
634 if (R.second.IRName.empty())
635 continue;
636 if (R.second.Partition != 0 &&
637 R.second.Partition != GlobalResolution::External)
638 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000639
Mehdi Aminid310b472016-08-22 06:25:41 +0000640 GlobalValue *GV =
641 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
642 // Ignore symbols defined in other partitions.
643 if (!GV || GV->hasLocalLinkage())
644 continue;
645 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
646 : GlobalValue::UnnamedAddr::None);
647 if (R.second.Partition == 0)
648 GV->setLinkage(GlobalValue::InternalLinkage);
649 }
650
651 if (Conf.PostInternalizeModuleHook &&
652 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000653 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000654 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000655 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000656 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000657}
658
659/// This class defines the interface to the ThinLTO backend.
660class lto::ThinBackendProc {
661protected:
662 Config &Conf;
663 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000664 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000665
666public:
667 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000668 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000669 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000670 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
671
672 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000673 virtual Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000674 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000675 const FunctionImporter::ImportMapTy &ImportList,
676 const FunctionImporter::ExportSetTy &ExportList,
677 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000678 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000679 virtual Error wait() = 0;
680};
681
Benjamin Kramerffd37152016-11-19 20:44:26 +0000682namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000683class InProcessThinBackend : public ThinBackendProc {
684 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000685 AddStreamFn AddStream;
686 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000687
688 Optional<Error> Err;
689 std::mutex ErrMu;
690
691public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000692 InProcessThinBackend(
693 Config &Conf, ModuleSummaryIndex &CombinedIndex,
694 unsigned ThinLTOParallelismLevel,
695 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000696 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000697 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
698 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000699 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000700
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000701 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000702 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000703 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000704 const FunctionImporter::ImportMapTy &ImportList,
705 const FunctionImporter::ExportSetTy &ExportList,
706 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
707 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000708 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000709 auto RunThinBackend = [&](AddStreamFn AddStream) {
710 LTOLLVMContext BackendContext(Conf);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000711 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000712 if (!MOrErr)
713 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000714
Peter Collingbourne80186a52016-09-23 21:33:43 +0000715 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
716 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000717 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000718
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000719 auto ModuleID = BM.getModuleIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000720
721 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
722 all_of(CombinedIndex.getModuleHash(ModuleID),
723 [](uint32_t V) { return V == 0; }))
724 // Cache disabled or no entry for this module in the combined index or
725 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000726 return RunThinBackend(AddStream);
727
728 SmallString<40> Key;
729 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000730 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Mehdi Amini00fa1402016-10-08 04:44:18 +0000731 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000732 if (AddStreamFn CacheAddStream = Cache(Task, Key))
733 return RunThinBackend(CacheAddStream);
734
Mehdi Amini41af4302016-11-11 04:28:40 +0000735 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000736 }
737
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000738 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000739 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000740 const FunctionImporter::ImportMapTy &ImportList,
741 const FunctionImporter::ExportSetTy &ExportList,
742 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000743 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
744 StringRef ModulePath = BM.getModuleIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000745 assert(ModuleToDefinedGVSummaries.count(ModulePath));
746 const GVSummaryMapTy &DefinedGlobals =
747 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000748 BackendThreadPool.async(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000749 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000750 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000751 const FunctionImporter::ExportSetTy &ExportList,
752 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
753 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000754 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000755 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000756 Error E = runThinLTOBackendThread(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000757 AddStream, Cache, Task, BM, CombinedIndex, ImportList,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000758 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000759 if (E) {
760 std::unique_lock<std::mutex> L(ErrMu);
761 if (Err)
762 Err = joinErrors(std::move(*Err), std::move(E));
763 else
764 Err = std::move(E);
765 }
766 },
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000767 BM, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000768 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
769 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000770 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000771 }
772
773 Error wait() override {
774 BackendThreadPool.wait();
775 if (Err)
776 return std::move(*Err);
777 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000778 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000779 }
780};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000781} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000782
783ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
784 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000785 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000786 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000787 return llvm::make_unique<InProcessThinBackend>(
788 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000789 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000790 };
791}
792
Teresa Johnson3f212b82016-09-21 19:12:05 +0000793// Given the original \p Path to an output file, replace any path
794// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
795// resulting directory if it does not yet exist.
796std::string lto::getThinLTOOutputFile(const std::string &Path,
797 const std::string &OldPrefix,
798 const std::string &NewPrefix) {
799 if (OldPrefix.empty() && NewPrefix.empty())
800 return Path;
801 SmallString<128> NewPath(Path);
802 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
803 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
804 if (!ParentPath.empty()) {
805 // Make sure the new directory exists, creating it if necessary.
806 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
807 llvm::errs() << "warning: could not create directory '" << ParentPath
808 << "': " << EC.message() << '\n';
809 }
810 return NewPath.str();
811}
812
Benjamin Kramerffd37152016-11-19 20:44:26 +0000813namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000814class WriteIndexesThinBackend : public ThinBackendProc {
815 std::string OldPrefix, NewPrefix;
816 bool ShouldEmitImportsFiles;
817
818 std::string LinkedObjectsFileName;
819 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
820
821public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000822 WriteIndexesThinBackend(
823 Config &Conf, ModuleSummaryIndex &CombinedIndex,
824 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
825 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
826 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000827 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000828 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
829 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
830 LinkedObjectsFileName(LinkedObjectsFileName) {}
831
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000832 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000833 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000834 const FunctionImporter::ImportMapTy &ImportList,
835 const FunctionImporter::ExportSetTy &ExportList,
836 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000837 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
838 StringRef ModulePath = BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000839 std::string NewModulePath =
840 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
841
842 std::error_code EC;
843 if (!LinkedObjectsFileName.empty()) {
844 if (!LinkedObjectsFile) {
845 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
846 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
847 if (EC)
848 return errorCodeToError(EC);
849 }
850 *LinkedObjectsFile << NewModulePath << '\n';
851 }
852
853 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
854 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000855 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000856
857 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
858 sys::fs::OpenFlags::F_None);
859 if (EC)
860 return errorCodeToError(EC);
861 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
862
863 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000864 return errorCodeToError(
865 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000866 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000867 }
868
Mehdi Amini41af4302016-11-11 04:28:40 +0000869 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000870};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000871} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000872
873ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
874 std::string NewPrefix,
875 bool ShouldEmitImportsFiles,
876 std::string LinkedObjectsFile) {
877 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000878 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000879 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000880 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000881 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
882 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000883 };
884}
885
Peter Collingbourne80186a52016-09-23 21:33:43 +0000886Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
887 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000888 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000889 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000890
891 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000892 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000893
894 // Collect for each module the list of function it defines (GUID ->
895 // Summary).
896 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
897 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
898 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
899 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000900 // Create entries for any modules that didn't have any GV summaries
901 // (either they didn't have any GVs to start with, or we suppressed
902 // generation of the summaries because they e.g. had inline assembly
903 // uses that couldn't be promoted/renamed on export). This is so
904 // InProcessThinBackend::start can still launch a backend thread, which
905 // is passed the map of summaries for the module, without any special
906 // handling for this case.
907 for (auto &Mod : ThinLTO.ModuleMap)
908 if (!ModuleToDefinedGVSummaries.count(Mod.first))
909 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000910
911 StringMap<FunctionImporter::ImportMapTy> ImportLists(
912 ThinLTO.ModuleMap.size());
913 StringMap<FunctionImporter::ExportSetTy> ExportLists(
914 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000915 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000916
Teresa Johnson002af9b2016-10-31 22:12:21 +0000917 if (Conf.OptLevel > 0) {
Mehdi Aminif39ce992017-01-20 23:34:12 +0000918 // Compute "dead" symbols, we don't want to import/export these!
919 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
920 for (auto &Res : GlobalResolutions) {
921 if (Res.second.VisibleOutsideThinLTO &&
922 // IRName will be defined if we have seen the prevailing copy of
923 // this value. If not, no need to preserve any ThinLTO copies.
924 !Res.second.IRName.empty())
925 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Res.second.IRName));
926 }
927
928 auto DeadSymbols =
929 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
930
Teresa Johnson002af9b2016-10-31 22:12:21 +0000931 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000932 ImportLists, ExportLists, &DeadSymbols);
Teresa Johnson002af9b2016-10-31 22:12:21 +0000933
934 std::set<GlobalValue::GUID> ExportedGUIDs;
935 for (auto &Res : GlobalResolutions) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000936 // First check if the symbol was flagged as having external references.
937 if (Res.second.Partition != GlobalResolution::External)
938 continue;
939 // IRName will be defined if we have seen the prevailing copy of
940 // this value. If not, no need to mark as exported from a ThinLTO
941 // partition (and we can't get the GUID).
942 if (Res.second.IRName.empty())
943 continue;
944 auto GUID = GlobalValue::getGUID(Res.second.IRName);
945 // Mark exported unless index-based analysis determined it to be dead.
946 if (!DeadSymbols.count(GUID))
Teresa Johnson002af9b2016-10-31 22:12:21 +0000947 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
948 }
949
950 auto isPrevailing = [&](GlobalValue::GUID GUID,
951 const GlobalValueSummary *S) {
952 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
953 };
Mehdi Amini1380edf2017-02-03 07:41:43 +0000954 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson002af9b2016-10-31 22:12:21 +0000955 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000956 return (ExportList != ExportLists.end() &&
957 ExportList->second.count(GUID)) ||
958 ExportedGUIDs.count(GUID);
Teresa Johnson002af9b2016-10-31 22:12:21 +0000959 };
960 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
961
962 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
963 GlobalValue::GUID GUID,
964 GlobalValue::LinkageTypes NewLinkage) {
965 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
966 };
967
968 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
969 recordNewLinkage);
970 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000971
Peter Collingbourne80186a52016-09-23 21:33:43 +0000972 std::unique_ptr<ThinBackendProc> BackendProc =
973 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
974 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000975
Davide Italiano63098952017-01-04 20:37:57 +0000976 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
977 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
978 // are reserved for parallel code generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000979 unsigned Task =
980 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000981 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000982 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000983 ExportLists[Mod.first],
984 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000985 return E;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000986 ++Task;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000987 }
988
989 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000990}