blob: cc3d96401ab7c29efba1a1d734d3a24d1dfcd7d6 [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)
277 for (auto &S : I.second)
278 if (auto AS = dyn_cast<AliasSummary>(S.get()))
279 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
280
281 for (auto &I : Index)
282 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000283 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000284}
285
286static void thinLTOInternalizeAndPromoteGUID(
287 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000288 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000289 for (auto &S : GVSummaryList) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000290 if (isExported(S->modulePath(), GUID)) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000291 if (GlobalValue::isLocalLinkage(S->linkage()))
292 S->setLinkage(GlobalValue::ExternalLinkage);
293 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
294 S->setLinkage(GlobalValue::InternalLinkage);
295 }
296}
297
298// Update the linkages in the given \p Index to mark exported values
299// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000300void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000301 ModuleSummaryIndex &Index,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000302 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000303 for (auto &I : Index)
304 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
305}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000306
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000307// Requires a destructor for std::vector<InputModule>.
308InputFile::~InputFile() = default;
309
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000310Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
311 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000312
Peter Collingbournead903692016-12-13 19:43:49 +0000313 ErrorOr<MemoryBufferRef> BCOrErr =
314 IRObjectFile::findBitcodeInMemBuffer(Object);
315 if (!BCOrErr)
316 return errorCodeToError(BCOrErr.getError());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000317
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000318 Expected<std::vector<BitcodeModule>> BMsOrErr =
319 getBitcodeModuleList(*BCOrErr);
320 if (!BMsOrErr)
321 return BMsOrErr.takeError();
Peter Collingbournead903692016-12-13 19:43:49 +0000322
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000323 if (BMsOrErr->empty())
324 return make_error<StringError>("Bitcode file does not contain any modules",
325 inconvertibleErrorCode());
Peter Collingbournead903692016-12-13 19:43:49 +0000326
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000327 File->Mods = *BMsOrErr;
328
329 LLVMContext Ctx;
330 std::vector<Module *> Mods;
331 std::vector<std::unique_ptr<Module>> OwnedMods;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000332 for (auto BM : *BMsOrErr) {
333 Expected<std::unique_ptr<Module>> MOrErr =
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000334 BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000335 /*IsImporting*/ false);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000336 if (!MOrErr)
337 return MOrErr.takeError();
338
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000339 if ((*MOrErr)->getDataLayoutStr().empty())
340 return make_error<StringError>("input module has no datalayout",
341 inconvertibleErrorCode());
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000342
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000343 Mods.push_back(MOrErr->get());
344 OwnedMods.push_back(std::move(*MOrErr));
345 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000346
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000347 SmallVector<char, 0> Symtab;
348 if (Error E = irsymtab::build(Mods, Symtab, File->Strtab))
349 return std::move(E);
350
351 irsymtab::Reader R({Symtab.data(), Symtab.size()},
352 {File->Strtab.data(), File->Strtab.size()});
Peter Collingbourne8446f1f2017-04-14 02:55:06 +0000353 File->TargetTriple = R.getTargetTriple();
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000354 File->SourceFileName = R.getSourceFileName();
355 File->COFFLinkerOpts = R.getCOFFLinkerOpts();
356 File->ComdatTable = R.getComdatTable();
357
358 for (unsigned I = 0; I != Mods.size(); ++I) {
359 size_t Begin = File->Symbols.size();
360 for (const irsymtab::Reader::SymbolRef &Sym : R.module_symbols(I))
361 // Skip symbols that are irrelevant to LTO. Note that this condition needs
362 // to match the one in Skip() in LTO::addRegularLTO().
363 if (Sym.isGlobal() && !Sym.isFormatSpecific())
364 File->Symbols.push_back(Sym);
365 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
Rafael Espindola79121102016-10-25 12:02:03 +0000366 }
367
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000368 return std::move(File);
369}
370
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000371StringRef InputFile::getName() const {
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000372 return Mods[0].getModuleIdentifier();
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000373}
374
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000375LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
376 Config &Conf)
377 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000378 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000379
380LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
381 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000382 this->Backend =
383 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000384}
385
386LTO::LTO(Config Conf, ThinBackend Backend,
387 unsigned ParallelCodeGenParallelismLevel)
388 : Conf(std::move(Conf)),
389 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000390 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000391
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000392// Requires a destructor for MapVector<BitcodeModule>.
393LTO::~LTO() = default;
394
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000395// Add the given symbol to the GlobalResolutions map, and resolve its partition.
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000396void LTO::addSymbolToGlobalRes(const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000397 SymbolResolution Res, unsigned Partition) {
Peter Collingbournef10698b2017-03-31 02:44:50 +0000398 auto &GlobalRes = GlobalResolutions[Sym.getName()];
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000399 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
400 if (Res.Prevailing)
401 GlobalRes.IRName = Sym.getIRName();
402
Teresa Johnson6c475a72017-01-05 21:34:18 +0000403 // Set the partition to external if we know it is used elsewhere, e.g.
404 // it is visible to a regular object, is referenced from llvm.compiler_used,
405 // or was already recorded as being referenced from a different partition.
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000406 if (Res.VisibleToRegularObj || Sym.isUsed() ||
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000407 (GlobalRes.Partition != GlobalResolution::Unknown &&
Teresa Johnson6c475a72017-01-05 21:34:18 +0000408 GlobalRes.Partition != Partition)) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000409 GlobalRes.Partition = GlobalResolution::External;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000410 } else
411 // First recorded reference, save the current partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000412 GlobalRes.Partition = Partition;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000413
414 // Flag as visible outside of ThinLTO if visible from a regular object or
415 // if this is a reference in the regular LTO partition.
416 GlobalRes.VisibleOutsideThinLTO |=
Peter Collingbournefa58f752017-04-26 17:53:39 +0000417 (Res.VisibleToRegularObj || Sym.isUsed() ||
418 Partition == GlobalResolution::RegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000419}
420
Rafael Espindola7775c332016-08-26 20:19:35 +0000421static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
422 ArrayRef<SymbolResolution> Res) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000423 StringRef Path = Input->getName();
Rafael Espindola7775c332016-08-26 20:19:35 +0000424 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000425 auto ResI = Res.begin();
426 for (const InputFile::Symbol &Sym : Input->symbols()) {
427 assert(ResI != Res.end());
428 SymbolResolution Res = *ResI++;
429
Rafael Espindola7775c332016-08-26 20:19:35 +0000430 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000431 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000432 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000433 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000434 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000435 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000436 OS << 'x';
437 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000438 }
Peter Collingbourne58ffcfb2017-01-19 23:10:14 +0000439 OS.flush();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000440 assert(ResI == Res.end());
441}
442
443Error LTO::add(std::unique_ptr<InputFile> Input,
444 ArrayRef<SymbolResolution> Res) {
445 assert(!CalledGetMaxTasks);
446
447 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000448 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000449
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000450 const SymbolResolution *ResI = Res.begin();
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000451 for (unsigned I = 0; I != Input->Mods.size(); ++I)
452 if (Error Err = addModule(*Input, I, ResI, Res.end()))
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000453 return Err;
454
455 assert(ResI == Res.end());
456 return Error::success();
457}
458
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000459Error LTO::addModule(InputFile &Input, unsigned ModI,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000460 const SymbolResolution *&ResI,
461 const SymbolResolution *ResE) {
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000462 Expected<bool> HasThinLTOSummary = Input.Mods[ModI].hasSummary();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000463 if (!HasThinLTOSummary)
464 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000465
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000466 auto ModSyms = Input.module_symbols(ModI);
Peter Collingbournecd513a42016-11-11 19:50:24 +0000467 if (*HasThinLTOSummary)
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000468 return addThinLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000469 else
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000470 return addRegularLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000471}
472
473// Add a regular LTO object to the link.
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000474Error LTO::addRegularLTO(BitcodeModule BM,
475 ArrayRef<InputFile::Symbol> Syms,
476 const SymbolResolution *&ResI,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000477 const SymbolResolution *ResE) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000478 if (!RegularLTO.CombinedModule) {
479 RegularLTO.CombinedModule =
480 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
481 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
482 }
Peter Collingbournead903692016-12-13 19:43:49 +0000483 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000484 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
485 /*IsImporting*/ false);
Peter Collingbournead903692016-12-13 19:43:49 +0000486 if (!MOrErr)
487 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000488
Peter Collingbournead903692016-12-13 19:43:49 +0000489 Module &M = **MOrErr;
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000490 if (Error Err = M.materializeMetadata())
491 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000492 UpgradeDebugInfo(M);
493
Peter Collingbournead903692016-12-13 19:43:49 +0000494 ModuleSymbolTable SymTab;
495 SymTab.addModule(&M);
496
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000497 std::vector<GlobalValue *> Keep;
498
499 for (GlobalVariable &GV : M.globals())
500 if (GV.hasAppendingLinkage())
501 Keep.push_back(&GV);
502
Peter Collingbourne46136262017-02-02 05:22:42 +0000503 DenseSet<GlobalObject *> AliasedGlobals;
504 for (auto &GA : M.aliases())
505 if (GlobalObject *GO = GA.getBaseObject())
506 AliasedGlobals.insert(GO);
507
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000508 // In this function we need IR GlobalValues matching the symbols in Syms
509 // (which is not backed by a module), so we need to enumerate them in the same
510 // order. The symbol enumeration order of a ModuleSymbolTable intentionally
511 // matches the order of an irsymtab, but when we read the irsymtab in
512 // InputFile::create we omit some symbols that are irrelevant to LTO. The
513 // Skip() function skips the same symbols from the module as InputFile does
514 // from the symbol table.
515 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
516 auto Skip = [&]() {
517 while (MsymI != MsymE) {
518 auto Flags = SymTab.getSymbolFlags(*MsymI);
519 if ((Flags & object::BasicSymbolRef::SF_Global) &&
520 !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
521 return;
522 ++MsymI;
523 }
524 };
525 Skip();
526
527 for (const InputFile::Symbol &Sym : Syms) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000528 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000529 SymbolResolution Res = *ResI++;
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000530 addSymbolToGlobalRes(Sym, Res, 0);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000531
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000532 assert(MsymI != MsymE);
533 ModuleSymbolTable::Symbol Msym = *MsymI++;
534 Skip();
535
536 if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
Peter Collingbournec387e702017-02-02 05:12:15 +0000537 if (Res.Prevailing) {
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000538 if (Sym.isUndefined())
Peter Collingbournec387e702017-02-02 05:12:15 +0000539 continue;
540 Keep.push_back(GV);
541 switch (GV->getLinkage()) {
542 default:
543 break;
544 case GlobalValue::LinkOnceAnyLinkage:
545 GV->setLinkage(GlobalValue::WeakAnyLinkage);
546 break;
547 case GlobalValue::LinkOnceODRLinkage:
548 GV->setLinkage(GlobalValue::WeakODRLinkage);
549 break;
550 }
Peter Collingbourne46136262017-02-02 05:22:42 +0000551 } else if (isa<GlobalObject>(GV) &&
552 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
553 GV->hasAvailableExternallyLinkage()) &&
554 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
555 // Either of the above three types of linkage indicates that the
556 // chosen prevailing symbol will have the same semantics as this copy of
557 // the symbol, so we can link it with available_externally linkage. We
558 // only need to do this if the symbol is undefined.
Peter Collingbournec387e702017-02-02 05:12:15 +0000559 GlobalValue *CombinedGV =
560 RegularLTO.CombinedModule->getNamedValue(GV->getName());
Peter Collingbourne46136262017-02-02 05:22:42 +0000561 if (!CombinedGV || CombinedGV->isDeclaration()) {
Peter Collingbournec387e702017-02-02 05:12:15 +0000562 Keep.push_back(GV);
Peter Collingbourne46136262017-02-02 05:22:42 +0000563 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
564 cast<GlobalObject>(GV)->setComdat(nullptr);
565 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000566 }
567 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000568 // Common resolution: collect the maximum size/alignment over all commons.
569 // We also record if we see an instance of a common as prevailing, so that
570 // if none is prevailing we can ignore it later.
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000571 if (Sym.isCommon()) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000572 // FIXME: We should figure out what to do about commons defined by asm.
573 // For now they aren't reported correctly by ModuleSymbolTable.
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000574 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000575 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
576 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000577 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000578 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000579
580 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
581 }
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000582 assert(MsymI == MsymE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000583
Peter Collingbournead903692016-12-13 19:43:49 +0000584 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000585 [](GlobalValue &, IRMover::ValueAdder) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000586 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000587}
588
589// Add a ThinLTO object to the link.
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000590Error LTO::addThinLTO(BitcodeModule BM,
591 ArrayRef<InputFile::Symbol> Syms,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000592 const SymbolResolution *&ResI,
593 const SymbolResolution *ResE) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000594 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
595 if (!SummaryOrErr)
596 return SummaryOrErr.takeError();
597 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000598 ThinLTO.ModuleMap.size());
599
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000600 for (const InputFile::Symbol &Sym : Syms) {
601 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000602 SymbolResolution Res = *ResI++;
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000603 addSymbolToGlobalRes(Sym, Res, ThinLTO.ModuleMap.size() + 1);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000604
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000605 if (Res.Prevailing) {
606 if (!Sym.getIRName().empty()) {
607 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
608 Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
609 ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
610 }
611 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000612 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000613
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000614 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
615 return make_error<StringError>(
616 "Expected at most one ThinLTO module per bitcode file",
617 inconvertibleErrorCode());
618
Mehdi Amini41af4302016-11-11 04:28:40 +0000619 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000620}
621
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000622unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000623 CalledGetMaxTasks = true;
624 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
625}
626
Peter Collingbourne80186a52016-09-23 21:33:43 +0000627Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000628 // Save the status of having a regularLTO combined module, as
629 // this is needed for generating the ThinLTO Task ID, and
630 // the CombinedModule will be moved at the end of runRegularLTO.
631 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000632 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000633 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000634 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000635 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000636 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000637}
638
Peter Collingbourne80186a52016-09-23 21:33:43 +0000639Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000640 // Make sure commons have the right size/alignment: we kept the largest from
641 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000642 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000643 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000644 if (!I.second.Prevailing)
645 // Don't do anything if no instance of this common was prevailing.
646 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000647 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000648 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000649 // Don't create a new global if the type is already correct, just make
650 // sure the alignment is correct.
651 OldGV->setAlignment(I.second.Align);
652 continue;
653 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000654 ArrayType *Ty =
655 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000656 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
657 GlobalValue::CommonLinkage,
658 ConstantAggregateZero::get(Ty), "");
659 GV->setAlignment(I.second.Align);
660 if (OldGV) {
661 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
662 GV->takeName(OldGV);
663 OldGV->eraseFromParent();
664 } else {
665 GV->setName(I.first);
666 }
667 }
668
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000669 if (Conf.PreOptModuleHook &&
670 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000671 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000672
Mehdi Aminid310b472016-08-22 06:25:41 +0000673 if (!Conf.CodeGenOnly) {
674 for (const auto &R : GlobalResolutions) {
675 if (R.second.IRName.empty())
676 continue;
677 if (R.second.Partition != 0 &&
678 R.second.Partition != GlobalResolution::External)
679 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000680
Mehdi Aminid310b472016-08-22 06:25:41 +0000681 GlobalValue *GV =
682 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
683 // Ignore symbols defined in other partitions.
684 if (!GV || GV->hasLocalLinkage())
685 continue;
686 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
687 : GlobalValue::UnnamedAddr::None);
688 if (R.second.Partition == 0)
689 GV->setLinkage(GlobalValue::InternalLinkage);
690 }
691
692 if (Conf.PostInternalizeModuleHook &&
693 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000694 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000695 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000696 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000697 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000698}
699
700/// This class defines the interface to the ThinLTO backend.
701class lto::ThinBackendProc {
702protected:
703 Config &Conf;
704 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000705 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000706
707public:
708 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000709 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000710 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000711 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
712
713 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000714 virtual Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000715 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000716 const FunctionImporter::ImportMapTy &ImportList,
717 const FunctionImporter::ExportSetTy &ExportList,
718 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000719 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000720 virtual Error wait() = 0;
721};
722
Benjamin Kramerffd37152016-11-19 20:44:26 +0000723namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000724class InProcessThinBackend : public ThinBackendProc {
725 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000726 AddStreamFn AddStream;
727 NativeObjectCache Cache;
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000728 TypeIdSummariesByGuidTy TypeIdSummariesByGuid;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000729
730 Optional<Error> Err;
731 std::mutex ErrMu;
732
733public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000734 InProcessThinBackend(
735 Config &Conf, ModuleSummaryIndex &CombinedIndex,
736 unsigned ThinLTOParallelismLevel,
737 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000738 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000739 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
740 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000741 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
742 // Create a mapping from type identifier GUIDs to type identifier summaries.
743 // This allows backends to use the type identifier GUIDs stored in the
744 // function summaries to determine which type identifier summaries affect
745 // each function without needing to compute GUIDs in each backend.
746 for (auto &TId : CombinedIndex.typeIds())
747 TypeIdSummariesByGuid[GlobalValue::getGUID(TId.first)].push_back(&TId);
748 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000749
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000750 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000751 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000752 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000753 const FunctionImporter::ImportMapTy &ImportList,
754 const FunctionImporter::ExportSetTy &ExportList,
755 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
756 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000757 MapVector<StringRef, BitcodeModule> &ModuleMap,
758 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000759 auto RunThinBackend = [&](AddStreamFn AddStream) {
760 LTOLLVMContext BackendContext(Conf);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000761 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000762 if (!MOrErr)
763 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000764
Peter Collingbourne80186a52016-09-23 21:33:43 +0000765 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
766 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000767 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000768
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000769 auto ModuleID = BM.getModuleIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000770
771 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
772 all_of(CombinedIndex.getModuleHash(ModuleID),
773 [](uint32_t V) { return V == 0; }))
774 // Cache disabled or no entry for this module in the combined index or
775 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000776 return RunThinBackend(AddStream);
777
778 SmallString<40> Key;
779 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000780 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000781 ResolvedODR, DefinedGlobals, TypeIdSummariesByGuid);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000782 if (AddStreamFn CacheAddStream = Cache(Task, Key))
783 return RunThinBackend(CacheAddStream);
784
Mehdi Amini41af4302016-11-11 04:28:40 +0000785 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000786 }
787
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000788 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000789 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000790 const FunctionImporter::ImportMapTy &ImportList,
791 const FunctionImporter::ExportSetTy &ExportList,
792 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000793 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
794 StringRef ModulePath = BM.getModuleIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000795 assert(ModuleToDefinedGVSummaries.count(ModulePath));
796 const GVSummaryMapTy &DefinedGlobals =
797 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000798 BackendThreadPool.async(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000799 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000800 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000801 const FunctionImporter::ExportSetTy &ExportList,
802 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
803 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000804 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000805 MapVector<StringRef, BitcodeModule> &ModuleMap,
806 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000807 Error E = runThinLTOBackendThread(
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000808 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
809 ResolvedODR, DefinedGlobals, ModuleMap, TypeIdSummariesByGuid);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000810 if (E) {
811 std::unique_lock<std::mutex> L(ErrMu);
812 if (Err)
813 Err = joinErrors(std::move(*Err), std::move(E));
814 else
815 Err = std::move(E);
816 }
817 },
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000818 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
819 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap),
820 std::ref(TypeIdSummariesByGuid));
Mehdi Amini41af4302016-11-11 04:28:40 +0000821 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000822 }
823
824 Error wait() override {
825 BackendThreadPool.wait();
826 if (Err)
827 return std::move(*Err);
828 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000829 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000830 }
831};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000832} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000833
834ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
835 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000836 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000837 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000838 return llvm::make_unique<InProcessThinBackend>(
839 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000840 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000841 };
842}
843
Teresa Johnson3f212b82016-09-21 19:12:05 +0000844// Given the original \p Path to an output file, replace any path
845// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
846// resulting directory if it does not yet exist.
847std::string lto::getThinLTOOutputFile(const std::string &Path,
848 const std::string &OldPrefix,
849 const std::string &NewPrefix) {
850 if (OldPrefix.empty() && NewPrefix.empty())
851 return Path;
852 SmallString<128> NewPath(Path);
853 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
854 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
855 if (!ParentPath.empty()) {
856 // Make sure the new directory exists, creating it if necessary.
857 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
858 llvm::errs() << "warning: could not create directory '" << ParentPath
859 << "': " << EC.message() << '\n';
860 }
861 return NewPath.str();
862}
863
Benjamin Kramerffd37152016-11-19 20:44:26 +0000864namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000865class WriteIndexesThinBackend : public ThinBackendProc {
866 std::string OldPrefix, NewPrefix;
867 bool ShouldEmitImportsFiles;
868
869 std::string LinkedObjectsFileName;
870 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
871
872public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000873 WriteIndexesThinBackend(
874 Config &Conf, ModuleSummaryIndex &CombinedIndex,
875 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
876 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
877 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000878 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000879 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
880 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
881 LinkedObjectsFileName(LinkedObjectsFileName) {}
882
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000883 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000884 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000885 const FunctionImporter::ImportMapTy &ImportList,
886 const FunctionImporter::ExportSetTy &ExportList,
887 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000888 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
889 StringRef ModulePath = BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000890 std::string NewModulePath =
891 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
892
893 std::error_code EC;
894 if (!LinkedObjectsFileName.empty()) {
895 if (!LinkedObjectsFile) {
896 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
897 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
898 if (EC)
899 return errorCodeToError(EC);
900 }
901 *LinkedObjectsFile << NewModulePath << '\n';
902 }
903
904 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
905 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000906 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000907
908 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
909 sys::fs::OpenFlags::F_None);
910 if (EC)
911 return errorCodeToError(EC);
912 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
913
914 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000915 return errorCodeToError(
916 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000917 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000918 }
919
Mehdi Amini41af4302016-11-11 04:28:40 +0000920 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000921};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000922} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000923
924ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
925 std::string NewPrefix,
926 bool ShouldEmitImportsFiles,
927 std::string LinkedObjectsFile) {
928 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000929 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000930 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000931 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000932 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
933 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000934 };
935}
936
Peter Collingbourne80186a52016-09-23 21:33:43 +0000937Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
938 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000939 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000940 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000941
942 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000943 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000944
945 // Collect for each module the list of function it defines (GUID ->
946 // Summary).
947 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
948 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
949 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
950 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000951 // Create entries for any modules that didn't have any GV summaries
952 // (either they didn't have any GVs to start with, or we suppressed
953 // generation of the summaries because they e.g. had inline assembly
954 // uses that couldn't be promoted/renamed on export). This is so
955 // InProcessThinBackend::start can still launch a backend thread, which
956 // is passed the map of summaries for the module, without any special
957 // handling for this case.
958 for (auto &Mod : ThinLTO.ModuleMap)
959 if (!ModuleToDefinedGVSummaries.count(Mod.first))
960 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000961
962 StringMap<FunctionImporter::ImportMapTy> ImportLists(
963 ThinLTO.ModuleMap.size());
964 StringMap<FunctionImporter::ExportSetTy> ExportLists(
965 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000966 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000967
Teresa Johnson002af9b2016-10-31 22:12:21 +0000968 if (Conf.OptLevel > 0) {
Mehdi Aminif39ce992017-01-20 23:34:12 +0000969 // Compute "dead" symbols, we don't want to import/export these!
970 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
971 for (auto &Res : GlobalResolutions) {
972 if (Res.second.VisibleOutsideThinLTO &&
973 // IRName will be defined if we have seen the prevailing copy of
974 // this value. If not, no need to preserve any ThinLTO copies.
975 !Res.second.IRName.empty())
Bob Haarmand6aea712017-03-31 21:56:30 +0000976 GUIDPreservedSymbols.insert(GlobalValue::getGUID(
977 GlobalValue::getRealLinkageName(Res.second.IRName)));
Mehdi Aminif39ce992017-01-20 23:34:12 +0000978 }
979
980 auto DeadSymbols =
981 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
982
Teresa Johnson002af9b2016-10-31 22:12:21 +0000983 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000984 ImportLists, ExportLists, &DeadSymbols);
Teresa Johnson002af9b2016-10-31 22:12:21 +0000985
986 std::set<GlobalValue::GUID> ExportedGUIDs;
987 for (auto &Res : GlobalResolutions) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000988 // First check if the symbol was flagged as having external references.
989 if (Res.second.Partition != GlobalResolution::External)
990 continue;
991 // IRName will be defined if we have seen the prevailing copy of
992 // this value. If not, no need to mark as exported from a ThinLTO
993 // partition (and we can't get the GUID).
994 if (Res.second.IRName.empty())
995 continue;
Bob Haarmand6aea712017-03-31 21:56:30 +0000996 auto GUID = GlobalValue::getGUID(
997 GlobalValue::getRealLinkageName(Res.second.IRName));
Teresa Johnson6c475a72017-01-05 21:34:18 +0000998 // Mark exported unless index-based analysis determined it to be dead.
999 if (!DeadSymbols.count(GUID))
Bob Haarmand6aea712017-03-31 21:56:30 +00001000 ExportedGUIDs.insert(GUID);
Teresa Johnson002af9b2016-10-31 22:12:21 +00001001 }
1002
1003 auto isPrevailing = [&](GlobalValue::GUID GUID,
1004 const GlobalValueSummary *S) {
1005 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1006 };
Mehdi Amini1380edf2017-02-03 07:41:43 +00001007 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson002af9b2016-10-31 22:12:21 +00001008 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +00001009 return (ExportList != ExportLists.end() &&
1010 ExportList->second.count(GUID)) ||
1011 ExportedGUIDs.count(GUID);
Teresa Johnson002af9b2016-10-31 22:12:21 +00001012 };
1013 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
1014
1015 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1016 GlobalValue::GUID GUID,
1017 GlobalValue::LinkageTypes NewLinkage) {
1018 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1019 };
1020
1021 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
1022 recordNewLinkage);
1023 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001024
Peter Collingbourne80186a52016-09-23 21:33:43 +00001025 std::unique_ptr<ThinBackendProc> BackendProc =
1026 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1027 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001028
Davide Italiano63098952017-01-04 20:37:57 +00001029 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
1030 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
1031 // are reserved for parallel code generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +00001032 unsigned Task =
1033 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001034 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +00001035 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +00001036 ExportLists[Mod.first],
1037 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001038 return E;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001039 ++Task;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001040 }
1041
1042 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001043}
Davide Italiano690ed9d2017-02-10 23:49:38 +00001044
1045Expected<std::unique_ptr<tool_output_file>>
1046lto::setupOptimizationRemarks(LLVMContext &Context,
1047 StringRef LTORemarksFilename,
1048 bool LTOPassRemarksWithHotness, int Count) {
1049 if (LTORemarksFilename.empty())
1050 return nullptr;
1051
1052 std::string Filename = LTORemarksFilename;
1053 if (Count != -1)
1054 Filename += ".thin." + llvm::utostr(Count) + ".yaml";
1055
1056 std::error_code EC;
1057 auto DiagnosticFile =
1058 llvm::make_unique<tool_output_file>(Filename, EC, sys::fs::F_None);
1059 if (EC)
1060 return errorCodeToError(EC);
1061 Context.setDiagnosticsOutputFile(
1062 llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1063 if (LTOPassRemarksWithHotness)
1064 Context.setDiagnosticHotnessRequested(true);
1065 DiagnosticFile->keep();
1066 return std::move(DiagnosticFile);
1067}