blob: c73b6b6b15c168330930096c3610112cf69eaf92 [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"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000023#include "llvm/IR/Mangler.h"
24#include "llvm/IR/Metadata.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000025#include "llvm/LTO/LTOBackend.h"
26#include "llvm/Linker/IRMover.h"
Peter Collingbourne192d8522017-03-28 23:35:34 +000027#include "llvm/Object/IRObjectFile.h"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000028#include "llvm/Support/Error.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000029#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000030#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031#include "llvm/Support/Path.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000032#include "llvm/Support/SHA1.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000033#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000034#include "llvm/Support/TargetRegistry.h"
35#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000036#include "llvm/Support/Threading.h"
Peter Collingbourne942fa562017-04-13 01:26:12 +000037#include "llvm/Support/VCSRevision.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
Peter Collingbourne780a4dd2017-03-10 21:35:17 +000053// The values are (type identifier, summary) pairs.
54typedef DenseMap<
55 GlobalValue::GUID,
56 TinyPtrVector<const std::pair<const std::string, TypeIdSummary> *>>
57 TypeIdSummariesByGuidTy;
58
Mehdi Aminiadc0e262016-08-23 21:30:12 +000059// Returns a unique hash for the Module considering the current list of
60// export/import and other global analysis results.
61// The hash is produced in \p Key.
62static void computeCacheKey(
Peter Collingbournef4257522016-12-08 05:28:30 +000063 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
64 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +000065 const FunctionImporter::ExportSetTy &ExportList,
66 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +000067 const GVSummaryMapTy &DefinedGlobals,
68 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +000069 // Compute the unique hash for this entry.
70 // This is based on the current compiler version, the module itself, the
71 // export list, the hash for every single module in the import list, the
72 // list of ResolvedODR for the module, and the list of preserved symbols.
73 SHA1 Hasher;
74
75 // Start with the compiler revision
76 Hasher.update(LLVM_VERSION_STRING);
Peter Collingbourne942fa562017-04-13 01:26:12 +000077#ifdef LLVM_REVISION
Mehdi Aminiadc0e262016-08-23 21:30:12 +000078 Hasher.update(LLVM_REVISION);
79#endif
80
Peter Collingbournef4257522016-12-08 05:28:30 +000081 // Include the parts of the LTO configuration that affect code generation.
82 auto AddString = [&](StringRef Str) {
83 Hasher.update(Str);
84 Hasher.update(ArrayRef<uint8_t>{0});
85 };
86 auto AddUnsigned = [&](unsigned I) {
87 uint8_t Data[4];
88 Data[0] = I;
89 Data[1] = I >> 8;
90 Data[2] = I >> 16;
91 Data[3] = I >> 24;
92 Hasher.update(ArrayRef<uint8_t>{Data, 4});
93 };
Peter Collingbourne54a52b72017-03-03 20:25:30 +000094 auto AddUint64 = [&](uint64_t I) {
95 uint8_t Data[8];
96 Data[0] = I;
97 Data[1] = I >> 8;
98 Data[2] = I >> 16;
99 Data[3] = I >> 24;
100 Data[4] = I >> 32;
101 Data[5] = I >> 40;
102 Data[6] = I >> 48;
103 Data[7] = I >> 56;
104 Hasher.update(ArrayRef<uint8_t>{Data, 8});
105 };
Peter Collingbournef4257522016-12-08 05:28:30 +0000106 AddString(Conf.CPU);
107 // FIXME: Hash more of Options. For now all clients initialize Options from
108 // command-line flags (which is unsupported in production), but may set
109 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
110 // DataSections and DebuggerTuning via command line flags.
111 AddUnsigned(Conf.Options.RelaxELFRelocations);
112 AddUnsigned(Conf.Options.FunctionSections);
113 AddUnsigned(Conf.Options.DataSections);
114 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
115 for (auto &A : Conf.MAttrs)
116 AddString(A);
117 AddUnsigned(Conf.RelocModel);
118 AddUnsigned(Conf.CodeModel);
119 AddUnsigned(Conf.CGOptLevel);
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000120 AddUnsigned(Conf.CGFileType);
Peter Collingbournef4257522016-12-08 05:28:30 +0000121 AddUnsigned(Conf.OptLevel);
122 AddString(Conf.OptPipeline);
123 AddString(Conf.AAPipeline);
124 AddString(Conf.OverrideTriple);
125 AddString(Conf.DefaultTriple);
126
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000127 // Include the hash for the current module
128 auto ModHash = Index.getModuleHash(ModuleID);
129 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
130 for (auto F : ExportList)
131 // The export list can impact the internalization, be conservative here
132 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
133
Peter Collingbourne54a52b72017-03-03 20:25:30 +0000134 // Include the hash for every module we import functions from. The set of
135 // imported symbols for each module may affect code generation and is
136 // sensitive to link order, so include that as well.
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000137 for (auto &Entry : ImportList) {
138 auto ModHash = Index.getModuleHash(Entry.first());
139 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
Peter Collingbourne54a52b72017-03-03 20:25:30 +0000140
141 AddUint64(Entry.second.size());
142 for (auto &Fn : Entry.second)
143 AddUint64(Fn.first);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000144 }
145
146 // Include the hash for the resolved ODR.
147 for (auto &Entry : ResolvedODR) {
148 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
149 sizeof(GlobalValue::GUID)));
150 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
151 sizeof(GlobalValue::LinkageTypes)));
152 }
153
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000154 std::set<GlobalValue::GUID> UsedTypeIds;
155
156 auto AddUsedTypeIds = [&](GlobalValueSummary *GS) {
157 auto *FS = dyn_cast_or_null<FunctionSummary>(GS);
158 if (!FS)
159 return;
160 for (auto &TT : FS->type_tests())
161 UsedTypeIds.insert(TT);
162 for (auto &TT : FS->type_test_assume_vcalls())
163 UsedTypeIds.insert(TT.GUID);
164 for (auto &TT : FS->type_checked_load_vcalls())
165 UsedTypeIds.insert(TT.GUID);
166 for (auto &TT : FS->type_test_assume_const_vcalls())
167 UsedTypeIds.insert(TT.VFunc.GUID);
168 for (auto &TT : FS->type_checked_load_const_vcalls())
169 UsedTypeIds.insert(TT.VFunc.GUID);
170 };
171
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000172 // Include the hash for the linkage type to reflect internalization and weak
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000173 // resolution, and collect any used type identifier resolutions.
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000174 for (auto &GS : DefinedGlobals) {
175 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
176 Hasher.update(
177 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000178 AddUsedTypeIds(GS.second);
179 }
180
181 // Imported functions may introduce new uses of type identifier resolutions,
182 // so we need to collect their used resolutions as well.
183 for (auto &ImpM : ImportList)
184 for (auto &ImpF : ImpM.second)
185 AddUsedTypeIds(Index.findSummaryInModule(ImpF.first, ImpM.first()));
186
187 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
188 AddString(TId);
189
190 AddUnsigned(S.TTRes.TheKind);
191 AddUnsigned(S.TTRes.SizeM1BitWidth);
Peter Collingbourne711284b2017-03-10 21:37:10 +0000192
193 AddUint64(S.WPDRes.size());
194 for (auto &WPD : S.WPDRes) {
195 AddUnsigned(WPD.first);
196 AddUnsigned(WPD.second.TheKind);
197 AddString(WPD.second.SingleImplName);
198
199 AddUint64(WPD.second.ResByArg.size());
200 for (auto &ByArg : WPD.second.ResByArg) {
201 AddUint64(ByArg.first.size());
202 for (uint64_t Arg : ByArg.first)
203 AddUint64(Arg);
204 AddUnsigned(ByArg.second.TheKind);
205 AddUint64(ByArg.second.Info);
206 }
207 }
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000208 };
209
210 // Include the hash for all type identifiers used by this module.
211 for (GlobalValue::GUID TId : UsedTypeIds) {
212 auto SummariesI = TypeIdSummariesByGuid.find(TId);
213 if (SummariesI != TypeIdSummariesByGuid.end())
214 for (auto *Summary : SummariesI->second)
215 AddTypeIdSummary(Summary->first, Summary->second);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000216 }
217
Dehao Chen27978002016-12-16 16:48:46 +0000218 if (!Conf.SampleProfile.empty()) {
219 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
220 if (FileOrErr)
221 Hasher.update(FileOrErr.get()->getBuffer());
222 }
223
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000224 Key = toHex(Hasher.result());
225}
226
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000227static void thinLTOResolveWeakForLinkerGUID(
228 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
229 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000230 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000231 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000232 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000233 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000234 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000235 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
236 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
237 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000238 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000239 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000240 // This is both a compile-time optimization and a correctness
241 // transformation. This is necessary for correctness when we have exported
242 // a reference - we need to convert the linkonce to weak to
243 // ensure a copy is kept to satisfy the exported reference.
244 // FIXME: We may want to split the compile time and correctness
245 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000246 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000247 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
248 S->setLinkage(GlobalValue::getWeakLinkage(
249 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000250 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000251 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000252 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000253 !GlobalInvolvedWithAlias.count(S.get()))
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000254 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
255 if (S->linkage() != OriginalLinkage)
256 recordNewLinkage(S->modulePath(), GUID, S->linkage());
257 }
258}
259
260// Resolve Weak and LinkOnce values in the \p Index.
261//
262// We'd like to drop these functions if they are no longer referenced in the
263// current module. However there is a chance that another module is still
264// referencing them because of the import. We make sure we always emit at least
265// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000266void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000267 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000268 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000269 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000270 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000271 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000272 // We won't optimize the globals that are referenced by an alias for now
273 // Ideally we should turn the alias into a global and duplicate the definition
274 // when needed.
275 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
276 for (auto &I : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000277 for (auto &S : I.second.SummaryList)
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000278 if (auto AS = dyn_cast<AliasSummary>(S.get()))
279 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
280
281 for (auto &I : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000282 thinLTOResolveWeakForLinkerGUID(I.second.SummaryList, I.first,
283 GlobalInvolvedWithAlias, isPrevailing,
284 recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000285}
286
287static void thinLTOInternalizeAndPromoteGUID(
288 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000289 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000290 for (auto &S : GVSummaryList) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000291 if (isExported(S->modulePath(), GUID)) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000292 if (GlobalValue::isLocalLinkage(S->linkage()))
293 S->setLinkage(GlobalValue::ExternalLinkage);
294 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
295 S->setLinkage(GlobalValue::InternalLinkage);
296 }
297}
298
299// Update the linkages in the given \p Index to mark exported values
300// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000301void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000302 ModuleSummaryIndex &Index,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000303 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000304 for (auto &I : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000305 thinLTOInternalizeAndPromoteGUID(I.second.SummaryList, I.first, isExported);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000306}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000307
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000308// Requires a destructor for std::vector<InputModule>.
309InputFile::~InputFile() = default;
310
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000311Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
312 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000313
Peter Collingbournead903692016-12-13 19:43:49 +0000314 ErrorOr<MemoryBufferRef> BCOrErr =
315 IRObjectFile::findBitcodeInMemBuffer(Object);
316 if (!BCOrErr)
317 return errorCodeToError(BCOrErr.getError());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000318
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000319 Expected<std::vector<BitcodeModule>> BMsOrErr =
320 getBitcodeModuleList(*BCOrErr);
321 if (!BMsOrErr)
322 return BMsOrErr.takeError();
Peter Collingbournead903692016-12-13 19:43:49 +0000323
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000324 if (BMsOrErr->empty())
325 return make_error<StringError>("Bitcode file does not contain any modules",
326 inconvertibleErrorCode());
Peter Collingbournead903692016-12-13 19:43:49 +0000327
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000328 File->Mods = *BMsOrErr;
329
330 LLVMContext Ctx;
331 std::vector<Module *> Mods;
332 std::vector<std::unique_ptr<Module>> OwnedMods;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000333 for (auto BM : *BMsOrErr) {
334 Expected<std::unique_ptr<Module>> MOrErr =
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000335 BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000336 /*IsImporting*/ false);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000337 if (!MOrErr)
338 return MOrErr.takeError();
339
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000340 if ((*MOrErr)->getDataLayoutStr().empty())
341 return make_error<StringError>("input module has no datalayout",
342 inconvertibleErrorCode());
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000343
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000344 Mods.push_back(MOrErr->get());
345 OwnedMods.push_back(std::move(*MOrErr));
346 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000347
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000348 SmallVector<char, 0> Symtab;
349 if (Error E = irsymtab::build(Mods, Symtab, File->Strtab))
350 return std::move(E);
351
352 irsymtab::Reader R({Symtab.data(), Symtab.size()},
353 {File->Strtab.data(), File->Strtab.size()});
Peter Collingbourne8446f1f2017-04-14 02:55:06 +0000354 File->TargetTriple = R.getTargetTriple();
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000355 File->SourceFileName = R.getSourceFileName();
356 File->COFFLinkerOpts = R.getCOFFLinkerOpts();
357 File->ComdatTable = R.getComdatTable();
358
359 for (unsigned I = 0; I != Mods.size(); ++I) {
360 size_t Begin = File->Symbols.size();
361 for (const irsymtab::Reader::SymbolRef &Sym : R.module_symbols(I))
362 // Skip symbols that are irrelevant to LTO. Note that this condition needs
363 // to match the one in Skip() in LTO::addRegularLTO().
364 if (Sym.isGlobal() && !Sym.isFormatSpecific())
365 File->Symbols.push_back(Sym);
366 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
Rafael Espindola79121102016-10-25 12:02:03 +0000367 }
368
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000369 return std::move(File);
370}
371
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000372StringRef InputFile::getName() const {
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000373 return Mods[0].getModuleIdentifier();
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000374}
375
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000376LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
377 Config &Conf)
378 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000379 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000380
381LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
382 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000383 this->Backend =
384 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000385}
386
387LTO::LTO(Config Conf, ThinBackend Backend,
388 unsigned ParallelCodeGenParallelismLevel)
389 : Conf(std::move(Conf)),
390 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000391 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000392
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000393// Requires a destructor for MapVector<BitcodeModule>.
394LTO::~LTO() = default;
395
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000396// Add the given symbol to the GlobalResolutions map, and resolve its partition.
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000397void LTO::addSymbolToGlobalRes(const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000398 SymbolResolution Res, unsigned Partition) {
Peter Collingbournef10698b2017-03-31 02:44:50 +0000399 auto &GlobalRes = GlobalResolutions[Sym.getName()];
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000400 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
401 if (Res.Prevailing)
402 GlobalRes.IRName = Sym.getIRName();
403
Teresa Johnson6c475a72017-01-05 21:34:18 +0000404 // Set the partition to external if we know it is used elsewhere, e.g.
405 // it is visible to a regular object, is referenced from llvm.compiler_used,
406 // or was already recorded as being referenced from a different partition.
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000407 if (Res.VisibleToRegularObj || Sym.isUsed() ||
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000408 (GlobalRes.Partition != GlobalResolution::Unknown &&
Teresa Johnson6c475a72017-01-05 21:34:18 +0000409 GlobalRes.Partition != Partition)) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000410 GlobalRes.Partition = GlobalResolution::External;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000411 } else
412 // First recorded reference, save the current partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000413 GlobalRes.Partition = Partition;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000414
415 // Flag as visible outside of ThinLTO if visible from a regular object or
416 // if this is a reference in the regular LTO partition.
417 GlobalRes.VisibleOutsideThinLTO |=
Peter Collingbournefa58f752017-04-26 17:53:39 +0000418 (Res.VisibleToRegularObj || Sym.isUsed() ||
419 Partition == GlobalResolution::RegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000420}
421
Rafael Espindola7775c332016-08-26 20:19:35 +0000422static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
423 ArrayRef<SymbolResolution> Res) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000424 StringRef Path = Input->getName();
Rafael Espindola7775c332016-08-26 20:19:35 +0000425 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000426 auto ResI = Res.begin();
427 for (const InputFile::Symbol &Sym : Input->symbols()) {
428 assert(ResI != Res.end());
429 SymbolResolution Res = *ResI++;
430
Rafael Espindola7775c332016-08-26 20:19:35 +0000431 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000432 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000433 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000434 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000435 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000436 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000437 OS << 'x';
438 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000439 }
Peter Collingbourne58ffcfb2017-01-19 23:10:14 +0000440 OS.flush();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000441 assert(ResI == Res.end());
442}
443
444Error LTO::add(std::unique_ptr<InputFile> Input,
445 ArrayRef<SymbolResolution> Res) {
446 assert(!CalledGetMaxTasks);
447
448 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000449 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000450
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000451 const SymbolResolution *ResI = Res.begin();
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000452 for (unsigned I = 0; I != Input->Mods.size(); ++I)
453 if (Error Err = addModule(*Input, I, ResI, Res.end()))
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000454 return Err;
455
456 assert(ResI == Res.end());
457 return Error::success();
458}
459
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000460Error LTO::addModule(InputFile &Input, unsigned ModI,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000461 const SymbolResolution *&ResI,
462 const SymbolResolution *ResE) {
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000463 Expected<bool> HasThinLTOSummary = Input.Mods[ModI].hasSummary();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000464 if (!HasThinLTOSummary)
465 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000466
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000467 auto ModSyms = Input.module_symbols(ModI);
Peter Collingbournecd513a42016-11-11 19:50:24 +0000468 if (*HasThinLTOSummary)
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000469 return addThinLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000470 else
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000471 return addRegularLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000472}
473
474// Add a regular LTO object to the link.
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000475Error LTO::addRegularLTO(BitcodeModule BM,
476 ArrayRef<InputFile::Symbol> Syms,
477 const SymbolResolution *&ResI,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000478 const SymbolResolution *ResE) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000479 if (!RegularLTO.CombinedModule) {
480 RegularLTO.CombinedModule =
481 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
482 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
483 }
Peter Collingbournead903692016-12-13 19:43:49 +0000484 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000485 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
486 /*IsImporting*/ false);
Peter Collingbournead903692016-12-13 19:43:49 +0000487 if (!MOrErr)
488 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000489
Peter Collingbournead903692016-12-13 19:43:49 +0000490 Module &M = **MOrErr;
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000491 if (Error Err = M.materializeMetadata())
492 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000493 UpgradeDebugInfo(M);
494
Peter Collingbournead903692016-12-13 19:43:49 +0000495 ModuleSymbolTable SymTab;
496 SymTab.addModule(&M);
497
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000498 std::vector<GlobalValue *> Keep;
499
500 for (GlobalVariable &GV : M.globals())
501 if (GV.hasAppendingLinkage())
502 Keep.push_back(&GV);
503
Peter Collingbourne46136262017-02-02 05:22:42 +0000504 DenseSet<GlobalObject *> AliasedGlobals;
505 for (auto &GA : M.aliases())
506 if (GlobalObject *GO = GA.getBaseObject())
507 AliasedGlobals.insert(GO);
508
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000509 // In this function we need IR GlobalValues matching the symbols in Syms
510 // (which is not backed by a module), so we need to enumerate them in the same
511 // order. The symbol enumeration order of a ModuleSymbolTable intentionally
512 // matches the order of an irsymtab, but when we read the irsymtab in
513 // InputFile::create we omit some symbols that are irrelevant to LTO. The
514 // Skip() function skips the same symbols from the module as InputFile does
515 // from the symbol table.
516 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
517 auto Skip = [&]() {
518 while (MsymI != MsymE) {
519 auto Flags = SymTab.getSymbolFlags(*MsymI);
520 if ((Flags & object::BasicSymbolRef::SF_Global) &&
521 !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
522 return;
523 ++MsymI;
524 }
525 };
526 Skip();
527
528 for (const InputFile::Symbol &Sym : Syms) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000529 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000530 SymbolResolution Res = *ResI++;
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000531 addSymbolToGlobalRes(Sym, Res, 0);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000532
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000533 assert(MsymI != MsymE);
534 ModuleSymbolTable::Symbol Msym = *MsymI++;
535 Skip();
536
537 if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
Peter Collingbournec387e702017-02-02 05:12:15 +0000538 if (Res.Prevailing) {
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000539 if (Sym.isUndefined())
Peter Collingbournec387e702017-02-02 05:12:15 +0000540 continue;
541 Keep.push_back(GV);
542 switch (GV->getLinkage()) {
543 default:
544 break;
545 case GlobalValue::LinkOnceAnyLinkage:
546 GV->setLinkage(GlobalValue::WeakAnyLinkage);
547 break;
548 case GlobalValue::LinkOnceODRLinkage:
549 GV->setLinkage(GlobalValue::WeakODRLinkage);
550 break;
551 }
Peter Collingbourne46136262017-02-02 05:22:42 +0000552 } else if (isa<GlobalObject>(GV) &&
553 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
554 GV->hasAvailableExternallyLinkage()) &&
555 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
556 // Either of the above three types of linkage indicates that the
557 // chosen prevailing symbol will have the same semantics as this copy of
558 // the symbol, so we can link it with available_externally linkage. We
559 // only need to do this if the symbol is undefined.
Peter Collingbournec387e702017-02-02 05:12:15 +0000560 GlobalValue *CombinedGV =
561 RegularLTO.CombinedModule->getNamedValue(GV->getName());
Peter Collingbourne46136262017-02-02 05:22:42 +0000562 if (!CombinedGV || CombinedGV->isDeclaration()) {
Peter Collingbournec387e702017-02-02 05:12:15 +0000563 Keep.push_back(GV);
Peter Collingbourne46136262017-02-02 05:22:42 +0000564 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
565 cast<GlobalObject>(GV)->setComdat(nullptr);
566 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000567 }
568 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000569 // Common resolution: collect the maximum size/alignment over all commons.
570 // We also record if we see an instance of a common as prevailing, so that
571 // if none is prevailing we can ignore it later.
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000572 if (Sym.isCommon()) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000573 // FIXME: We should figure out what to do about commons defined by asm.
574 // For now they aren't reported correctly by ModuleSymbolTable.
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000575 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000576 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
577 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000578 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000579 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000580
581 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
582 }
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000583 assert(MsymI == MsymE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000584
Peter Collingbournead903692016-12-13 19:43:49 +0000585 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000586 [](GlobalValue &, IRMover::ValueAdder) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000587 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000588}
589
590// Add a ThinLTO object to the link.
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000591Error LTO::addThinLTO(BitcodeModule BM,
592 ArrayRef<InputFile::Symbol> Syms,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000593 const SymbolResolution *&ResI,
594 const SymbolResolution *ResE) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000595 if (Error Err =
596 BM.readSummary(ThinLTO.CombinedIndex, ThinLTO.ModuleMap.size()))
597 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000598
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000599 for (const InputFile::Symbol &Sym : Syms) {
600 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000601 SymbolResolution Res = *ResI++;
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000602 addSymbolToGlobalRes(Sym, Res, ThinLTO.ModuleMap.size() + 1);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000603
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000604 if (Res.Prevailing) {
605 if (!Sym.getIRName().empty()) {
606 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
607 Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
608 ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
609 }
610 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000611 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000612
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000613 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
614 return make_error<StringError>(
615 "Expected at most one ThinLTO module per bitcode file",
616 inconvertibleErrorCode());
617
Mehdi Amini41af4302016-11-11 04:28:40 +0000618 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000619}
620
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000621unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000622 CalledGetMaxTasks = true;
623 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
624}
625
Peter Collingbourne80186a52016-09-23 21:33:43 +0000626Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000627 // Save the status of having a regularLTO combined module, as
628 // this is needed for generating the ThinLTO Task ID, and
629 // the CombinedModule will be moved at the end of runRegularLTO.
630 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000631 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000632 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000633 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000634 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000635 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000636}
637
Peter Collingbourne80186a52016-09-23 21:33:43 +0000638Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000639 // Make sure commons have the right size/alignment: we kept the largest from
640 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000641 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000642 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000643 if (!I.second.Prevailing)
644 // Don't do anything if no instance of this common was prevailing.
645 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000646 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000647 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000648 // Don't create a new global if the type is already correct, just make
649 // sure the alignment is correct.
650 OldGV->setAlignment(I.second.Align);
651 continue;
652 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000653 ArrayType *Ty =
654 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000655 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
656 GlobalValue::CommonLinkage,
657 ConstantAggregateZero::get(Ty), "");
658 GV->setAlignment(I.second.Align);
659 if (OldGV) {
660 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
661 GV->takeName(OldGV);
662 OldGV->eraseFromParent();
663 } else {
664 GV->setName(I.first);
665 }
666 }
667
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000668 if (Conf.PreOptModuleHook &&
669 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000670 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000671
Mehdi Aminid310b472016-08-22 06:25:41 +0000672 if (!Conf.CodeGenOnly) {
673 for (const auto &R : GlobalResolutions) {
674 if (R.second.IRName.empty())
675 continue;
676 if (R.second.Partition != 0 &&
677 R.second.Partition != GlobalResolution::External)
678 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000679
Mehdi Aminid310b472016-08-22 06:25:41 +0000680 GlobalValue *GV =
681 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
682 // Ignore symbols defined in other partitions.
683 if (!GV || GV->hasLocalLinkage())
684 continue;
685 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
686 : GlobalValue::UnnamedAddr::None);
687 if (R.second.Partition == 0)
688 GV->setLinkage(GlobalValue::InternalLinkage);
689 }
690
691 if (Conf.PostInternalizeModuleHook &&
692 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000693 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000694 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000695 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000696 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000697}
698
699/// This class defines the interface to the ThinLTO backend.
700class lto::ThinBackendProc {
701protected:
702 Config &Conf;
703 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000704 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000705
706public:
707 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000708 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000709 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000710 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
711
712 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000713 virtual Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000714 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000715 const FunctionImporter::ImportMapTy &ImportList,
716 const FunctionImporter::ExportSetTy &ExportList,
717 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000718 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000719 virtual Error wait() = 0;
720};
721
Benjamin Kramerffd37152016-11-19 20:44:26 +0000722namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000723class InProcessThinBackend : public ThinBackendProc {
724 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000725 AddStreamFn AddStream;
726 NativeObjectCache Cache;
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000727 TypeIdSummariesByGuidTy TypeIdSummariesByGuid;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000728
729 Optional<Error> Err;
730 std::mutex ErrMu;
731
732public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000733 InProcessThinBackend(
734 Config &Conf, ModuleSummaryIndex &CombinedIndex,
735 unsigned ThinLTOParallelismLevel,
736 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000737 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000738 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
739 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000740 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
741 // Create a mapping from type identifier GUIDs to type identifier summaries.
742 // This allows backends to use the type identifier GUIDs stored in the
743 // function summaries to determine which type identifier summaries affect
744 // each function without needing to compute GUIDs in each backend.
745 for (auto &TId : CombinedIndex.typeIds())
746 TypeIdSummariesByGuid[GlobalValue::getGUID(TId.first)].push_back(&TId);
747 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000748
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000749 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000750 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000751 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000752 const FunctionImporter::ImportMapTy &ImportList,
753 const FunctionImporter::ExportSetTy &ExportList,
754 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
755 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000756 MapVector<StringRef, BitcodeModule> &ModuleMap,
757 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000758 auto RunThinBackend = [&](AddStreamFn AddStream) {
759 LTOLLVMContext BackendContext(Conf);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000760 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000761 if (!MOrErr)
762 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000763
Peter Collingbourne80186a52016-09-23 21:33:43 +0000764 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
765 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000766 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000767
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000768 auto ModuleID = BM.getModuleIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000769
770 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
771 all_of(CombinedIndex.getModuleHash(ModuleID),
772 [](uint32_t V) { return V == 0; }))
773 // Cache disabled or no entry for this module in the combined index or
774 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000775 return RunThinBackend(AddStream);
776
777 SmallString<40> Key;
778 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000779 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000780 ResolvedODR, DefinedGlobals, TypeIdSummariesByGuid);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000781 if (AddStreamFn CacheAddStream = Cache(Task, Key))
782 return RunThinBackend(CacheAddStream);
783
Mehdi Amini41af4302016-11-11 04:28:40 +0000784 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000785 }
786
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000787 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000788 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000789 const FunctionImporter::ImportMapTy &ImportList,
790 const FunctionImporter::ExportSetTy &ExportList,
791 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000792 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
793 StringRef ModulePath = BM.getModuleIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000794 assert(ModuleToDefinedGVSummaries.count(ModulePath));
795 const GVSummaryMapTy &DefinedGlobals =
796 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000797 BackendThreadPool.async(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000798 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000799 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000800 const FunctionImporter::ExportSetTy &ExportList,
801 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
802 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000803 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000804 MapVector<StringRef, BitcodeModule> &ModuleMap,
805 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000806 Error E = runThinLTOBackendThread(
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000807 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
808 ResolvedODR, DefinedGlobals, ModuleMap, TypeIdSummariesByGuid);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000809 if (E) {
810 std::unique_lock<std::mutex> L(ErrMu);
811 if (Err)
812 Err = joinErrors(std::move(*Err), std::move(E));
813 else
814 Err = std::move(E);
815 }
816 },
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000817 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
818 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap),
819 std::ref(TypeIdSummariesByGuid));
Mehdi Amini41af4302016-11-11 04:28:40 +0000820 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000821 }
822
823 Error wait() override {
824 BackendThreadPool.wait();
825 if (Err)
826 return std::move(*Err);
827 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000828 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000829 }
830};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000831} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000832
833ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
834 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000835 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000836 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000837 return llvm::make_unique<InProcessThinBackend>(
838 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000839 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000840 };
841}
842
Teresa Johnson3f212b82016-09-21 19:12:05 +0000843// Given the original \p Path to an output file, replace any path
844// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
845// resulting directory if it does not yet exist.
846std::string lto::getThinLTOOutputFile(const std::string &Path,
847 const std::string &OldPrefix,
848 const std::string &NewPrefix) {
849 if (OldPrefix.empty() && NewPrefix.empty())
850 return Path;
851 SmallString<128> NewPath(Path);
852 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
853 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
854 if (!ParentPath.empty()) {
855 // Make sure the new directory exists, creating it if necessary.
856 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
857 llvm::errs() << "warning: could not create directory '" << ParentPath
858 << "': " << EC.message() << '\n';
859 }
860 return NewPath.str();
861}
862
Benjamin Kramerffd37152016-11-19 20:44:26 +0000863namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000864class WriteIndexesThinBackend : public ThinBackendProc {
865 std::string OldPrefix, NewPrefix;
866 bool ShouldEmitImportsFiles;
867
868 std::string LinkedObjectsFileName;
869 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
870
871public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000872 WriteIndexesThinBackend(
873 Config &Conf, ModuleSummaryIndex &CombinedIndex,
874 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
875 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
876 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000877 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000878 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
879 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
880 LinkedObjectsFileName(LinkedObjectsFileName) {}
881
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000882 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000883 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000884 const FunctionImporter::ImportMapTy &ImportList,
885 const FunctionImporter::ExportSetTy &ExportList,
886 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000887 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
888 StringRef ModulePath = BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000889 std::string NewModulePath =
890 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
891
892 std::error_code EC;
893 if (!LinkedObjectsFileName.empty()) {
894 if (!LinkedObjectsFile) {
895 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
896 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
897 if (EC)
898 return errorCodeToError(EC);
899 }
900 *LinkedObjectsFile << NewModulePath << '\n';
901 }
902
903 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
904 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000905 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000906
907 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
908 sys::fs::OpenFlags::F_None);
909 if (EC)
910 return errorCodeToError(EC);
911 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
912
913 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000914 return errorCodeToError(
915 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000916 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000917 }
918
Mehdi Amini41af4302016-11-11 04:28:40 +0000919 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000920};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000921} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000922
923ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
924 std::string NewPrefix,
925 bool ShouldEmitImportsFiles,
926 std::string LinkedObjectsFile) {
927 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000928 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000929 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000930 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000931 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
932 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000933 };
934}
935
Peter Collingbourne80186a52016-09-23 21:33:43 +0000936Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
937 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000938 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000939 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000940
941 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000942 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000943
944 // Collect for each module the list of function it defines (GUID ->
945 // Summary).
946 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
947 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
948 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
949 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000950 // Create entries for any modules that didn't have any GV summaries
951 // (either they didn't have any GVs to start with, or we suppressed
952 // generation of the summaries because they e.g. had inline assembly
953 // uses that couldn't be promoted/renamed on export). This is so
954 // InProcessThinBackend::start can still launch a backend thread, which
955 // is passed the map of summaries for the module, without any special
956 // handling for this case.
957 for (auto &Mod : ThinLTO.ModuleMap)
958 if (!ModuleToDefinedGVSummaries.count(Mod.first))
959 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000960
961 StringMap<FunctionImporter::ImportMapTy> ImportLists(
962 ThinLTO.ModuleMap.size());
963 StringMap<FunctionImporter::ExportSetTy> ExportLists(
964 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000965 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000966
Teresa Johnson002af9b2016-10-31 22:12:21 +0000967 if (Conf.OptLevel > 0) {
Mehdi Aminif39ce992017-01-20 23:34:12 +0000968 // Compute "dead" symbols, we don't want to import/export these!
969 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
970 for (auto &Res : GlobalResolutions) {
971 if (Res.second.VisibleOutsideThinLTO &&
972 // IRName will be defined if we have seen the prevailing copy of
973 // this value. If not, no need to preserve any ThinLTO copies.
974 !Res.second.IRName.empty())
Bob Haarmand6aea712017-03-31 21:56:30 +0000975 GUIDPreservedSymbols.insert(GlobalValue::getGUID(
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000976 GlobalValue::dropLLVMManglingEscape(Res.second.IRName)));
Mehdi Aminif39ce992017-01-20 23:34:12 +0000977 }
978
979 auto DeadSymbols =
980 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
981
Teresa Johnson002af9b2016-10-31 22:12:21 +0000982 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000983 ImportLists, ExportLists, &DeadSymbols);
Teresa Johnson002af9b2016-10-31 22:12:21 +0000984
985 std::set<GlobalValue::GUID> ExportedGUIDs;
986 for (auto &Res : GlobalResolutions) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000987 // First check if the symbol was flagged as having external references.
988 if (Res.second.Partition != GlobalResolution::External)
989 continue;
990 // IRName will be defined if we have seen the prevailing copy of
991 // this value. If not, no need to mark as exported from a ThinLTO
992 // partition (and we can't get the GUID).
993 if (Res.second.IRName.empty())
994 continue;
Bob Haarmand6aea712017-03-31 21:56:30 +0000995 auto GUID = GlobalValue::getGUID(
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000996 GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
Teresa Johnson6c475a72017-01-05 21:34:18 +0000997 // Mark exported unless index-based analysis determined it to be dead.
998 if (!DeadSymbols.count(GUID))
Bob Haarmand6aea712017-03-31 21:56:30 +0000999 ExportedGUIDs.insert(GUID);
Teresa Johnson002af9b2016-10-31 22:12:21 +00001000 }
1001
1002 auto isPrevailing = [&](GlobalValue::GUID GUID,
1003 const GlobalValueSummary *S) {
1004 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1005 };
Mehdi Amini1380edf2017-02-03 07:41:43 +00001006 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson002af9b2016-10-31 22:12:21 +00001007 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +00001008 return (ExportList != ExportLists.end() &&
1009 ExportList->second.count(GUID)) ||
1010 ExportedGUIDs.count(GUID);
Teresa Johnson002af9b2016-10-31 22:12:21 +00001011 };
1012 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
1013
1014 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1015 GlobalValue::GUID GUID,
1016 GlobalValue::LinkageTypes NewLinkage) {
1017 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1018 };
1019
1020 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
1021 recordNewLinkage);
1022 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001023
Peter Collingbourne80186a52016-09-23 21:33:43 +00001024 std::unique_ptr<ThinBackendProc> BackendProc =
1025 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1026 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001027
Davide Italiano63098952017-01-04 20:37:57 +00001028 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
1029 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
1030 // are reserved for parallel code generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +00001031 unsigned Task =
1032 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001033 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +00001034 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +00001035 ExportLists[Mod.first],
1036 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001037 return E;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001038 ++Task;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001039 }
1040
1041 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001042}
Davide Italiano690ed9d2017-02-10 23:49:38 +00001043
1044Expected<std::unique_ptr<tool_output_file>>
1045lto::setupOptimizationRemarks(LLVMContext &Context,
1046 StringRef LTORemarksFilename,
1047 bool LTOPassRemarksWithHotness, int Count) {
1048 if (LTORemarksFilename.empty())
1049 return nullptr;
1050
1051 std::string Filename = LTORemarksFilename;
1052 if (Count != -1)
1053 Filename += ".thin." + llvm::utostr(Count) + ".yaml";
1054
1055 std::error_code EC;
1056 auto DiagnosticFile =
1057 llvm::make_unique<tool_output_file>(Filename, EC, sys::fs::F_None);
1058 if (EC)
1059 return errorCodeToError(EC);
1060 Context.setDiagnosticsOutputFile(
1061 llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1062 if (LTOPassRemarksWithHotness)
1063 Context.setDiagnosticHotnessRequested(true);
1064 DiagnosticFile->keep();
1065 return std::move(DiagnosticFile);
1066}