blob: f3d258e6c259bd16710a8bf06fd27af88c9fbb84 [file] [log] [blame]
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001//===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements functions and classes used to support LTO.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000015#include "llvm/Analysis/TargetLibraryInfo.h"
16#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000017#include "llvm/Bitcode/BitcodeReader.h"
18#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000019#include "llvm/CodeGen/Analysis.h"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000020#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000021#include "llvm/IR/AutoUpgrade.h"
22#include "llvm/IR/DiagnosticPrinter.h"
23#include "llvm/IR/LegacyPassManager.h"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000024#include "llvm/IR/Mangler.h"
25#include "llvm/IR/Metadata.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000026#include "llvm/LTO/LTOBackend.h"
27#include "llvm/Linker/IRMover.h"
Peter Collingbourne192d8522017-03-28 23:35:34 +000028#include "llvm/Object/IRObjectFile.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000029#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000030#include "llvm/Support/Error.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000032#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000033#include "llvm/Support/Path.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000034#include "llvm/Support/SHA1.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000035#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000036#include "llvm/Support/TargetRegistry.h"
37#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000038#include "llvm/Support/Threading.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000039#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000040#include "llvm/Target/TargetMachine.h"
41#include "llvm/Target/TargetOptions.h"
42#include "llvm/Transforms/IPO.h"
43#include "llvm/Transforms/IPO/PassManagerBuilder.h"
44#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000045
Teresa Johnson9ba95f92016-08-11 14:58:12 +000046#include <set>
47
48using namespace llvm;
49using namespace lto;
50using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000051
Mehdi Aminiadc0e262016-08-23 21:30:12 +000052#define DEBUG_TYPE "lto"
53
Peter Collingbourne780a4dd2017-03-10 21:35:17 +000054// The values are (type identifier, summary) pairs.
55typedef DenseMap<
56 GlobalValue::GUID,
57 TinyPtrVector<const std::pair<const std::string, TypeIdSummary> *>>
58 TypeIdSummariesByGuidTy;
59
Mehdi Aminiadc0e262016-08-23 21:30:12 +000060// Returns a unique hash for the Module considering the current list of
61// export/import and other global analysis results.
62// The hash is produced in \p Key.
63static void computeCacheKey(
Peter Collingbournef4257522016-12-08 05:28:30 +000064 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
65 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +000066 const FunctionImporter::ExportSetTy &ExportList,
67 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +000068 const GVSummaryMapTy &DefinedGlobals,
69 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +000070 // Compute the unique hash for this entry.
71 // This is based on the current compiler version, the module itself, the
72 // export list, the hash for every single module in the import list, the
73 // list of ResolvedODR for the module, and the list of preserved symbols.
74 SHA1 Hasher;
75
76 // Start with the compiler revision
77 Hasher.update(LLVM_VERSION_STRING);
78#ifdef HAVE_LLVM_REVISION
79 Hasher.update(LLVM_REVISION);
80#endif
81
Peter Collingbournef4257522016-12-08 05:28:30 +000082 // Include the parts of the LTO configuration that affect code generation.
83 auto AddString = [&](StringRef Str) {
84 Hasher.update(Str);
85 Hasher.update(ArrayRef<uint8_t>{0});
86 };
87 auto AddUnsigned = [&](unsigned I) {
88 uint8_t Data[4];
89 Data[0] = I;
90 Data[1] = I >> 8;
91 Data[2] = I >> 16;
92 Data[3] = I >> 24;
93 Hasher.update(ArrayRef<uint8_t>{Data, 4});
94 };
Peter Collingbourne54a52b72017-03-03 20:25:30 +000095 auto AddUint64 = [&](uint64_t I) {
96 uint8_t Data[8];
97 Data[0] = I;
98 Data[1] = I >> 8;
99 Data[2] = I >> 16;
100 Data[3] = I >> 24;
101 Data[4] = I >> 32;
102 Data[5] = I >> 40;
103 Data[6] = I >> 48;
104 Data[7] = I >> 56;
105 Hasher.update(ArrayRef<uint8_t>{Data, 8});
106 };
Peter Collingbournef4257522016-12-08 05:28:30 +0000107 AddString(Conf.CPU);
108 // FIXME: Hash more of Options. For now all clients initialize Options from
109 // command-line flags (which is unsupported in production), but may set
110 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
111 // DataSections and DebuggerTuning via command line flags.
112 AddUnsigned(Conf.Options.RelaxELFRelocations);
113 AddUnsigned(Conf.Options.FunctionSections);
114 AddUnsigned(Conf.Options.DataSections);
115 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
116 for (auto &A : Conf.MAttrs)
117 AddString(A);
118 AddUnsigned(Conf.RelocModel);
119 AddUnsigned(Conf.CodeModel);
120 AddUnsigned(Conf.CGOptLevel);
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000121 AddUnsigned(Conf.CGFileType);
Peter Collingbournef4257522016-12-08 05:28:30 +0000122 AddUnsigned(Conf.OptLevel);
123 AddString(Conf.OptPipeline);
124 AddString(Conf.AAPipeline);
125 AddString(Conf.OverrideTriple);
126 AddString(Conf.DefaultTriple);
127
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000128 // Include the hash for the current module
129 auto ModHash = Index.getModuleHash(ModuleID);
130 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
131 for (auto F : ExportList)
132 // The export list can impact the internalization, be conservative here
133 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
134
Peter Collingbourne54a52b72017-03-03 20:25:30 +0000135 // Include the hash for every module we import functions from. The set of
136 // imported symbols for each module may affect code generation and is
137 // sensitive to link order, so include that as well.
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000138 for (auto &Entry : ImportList) {
139 auto ModHash = Index.getModuleHash(Entry.first());
140 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
Peter Collingbourne54a52b72017-03-03 20:25:30 +0000141
142 AddUint64(Entry.second.size());
143 for (auto &Fn : Entry.second)
144 AddUint64(Fn.first);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000145 }
146
147 // Include the hash for the resolved ODR.
148 for (auto &Entry : ResolvedODR) {
149 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
150 sizeof(GlobalValue::GUID)));
151 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
152 sizeof(GlobalValue::LinkageTypes)));
153 }
154
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000155 std::set<GlobalValue::GUID> UsedTypeIds;
156
157 auto AddUsedTypeIds = [&](GlobalValueSummary *GS) {
158 auto *FS = dyn_cast_or_null<FunctionSummary>(GS);
159 if (!FS)
160 return;
161 for (auto &TT : FS->type_tests())
162 UsedTypeIds.insert(TT);
163 for (auto &TT : FS->type_test_assume_vcalls())
164 UsedTypeIds.insert(TT.GUID);
165 for (auto &TT : FS->type_checked_load_vcalls())
166 UsedTypeIds.insert(TT.GUID);
167 for (auto &TT : FS->type_test_assume_const_vcalls())
168 UsedTypeIds.insert(TT.VFunc.GUID);
169 for (auto &TT : FS->type_checked_load_const_vcalls())
170 UsedTypeIds.insert(TT.VFunc.GUID);
171 };
172
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000173 // Include the hash for the linkage type to reflect internalization and weak
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000174 // resolution, and collect any used type identifier resolutions.
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000175 for (auto &GS : DefinedGlobals) {
176 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
177 Hasher.update(
178 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000179 AddUsedTypeIds(GS.second);
180 }
181
182 // Imported functions may introduce new uses of type identifier resolutions,
183 // so we need to collect their used resolutions as well.
184 for (auto &ImpM : ImportList)
185 for (auto &ImpF : ImpM.second)
186 AddUsedTypeIds(Index.findSummaryInModule(ImpF.first, ImpM.first()));
187
188 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
189 AddString(TId);
190
191 AddUnsigned(S.TTRes.TheKind);
192 AddUnsigned(S.TTRes.SizeM1BitWidth);
Peter Collingbourne711284b2017-03-10 21:37:10 +0000193
194 AddUint64(S.WPDRes.size());
195 for (auto &WPD : S.WPDRes) {
196 AddUnsigned(WPD.first);
197 AddUnsigned(WPD.second.TheKind);
198 AddString(WPD.second.SingleImplName);
199
200 AddUint64(WPD.second.ResByArg.size());
201 for (auto &ByArg : WPD.second.ResByArg) {
202 AddUint64(ByArg.first.size());
203 for (uint64_t Arg : ByArg.first)
204 AddUint64(Arg);
205 AddUnsigned(ByArg.second.TheKind);
206 AddUint64(ByArg.second.Info);
207 }
208 }
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000209 };
210
211 // Include the hash for all type identifiers used by this module.
212 for (GlobalValue::GUID TId : UsedTypeIds) {
213 auto SummariesI = TypeIdSummariesByGuid.find(TId);
214 if (SummariesI != TypeIdSummariesByGuid.end())
215 for (auto *Summary : SummariesI->second)
216 AddTypeIdSummary(Summary->first, Summary->second);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000217 }
218
Dehao Chen27978002016-12-16 16:48:46 +0000219 if (!Conf.SampleProfile.empty()) {
220 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
221 if (FileOrErr)
222 Hasher.update(FileOrErr.get()->getBuffer());
223 }
224
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000225 Key = toHex(Hasher.result());
226}
227
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000228static void thinLTOResolveWeakForLinkerGUID(
229 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
230 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000231 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000232 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000233 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000234 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000235 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000236 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
237 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
238 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000239 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000240 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000241 // This is both a compile-time optimization and a correctness
242 // transformation. This is necessary for correctness when we have exported
243 // a reference - we need to convert the linkonce to weak to
244 // ensure a copy is kept to satisfy the exported reference.
245 // FIXME: We may want to split the compile time and correctness
246 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000247 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000248 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
249 S->setLinkage(GlobalValue::getWeakLinkage(
250 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000251 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000252 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000253 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000254 !GlobalInvolvedWithAlias.count(S.get()))
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000255 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
256 if (S->linkage() != OriginalLinkage)
257 recordNewLinkage(S->modulePath(), GUID, S->linkage());
258 }
259}
260
261// Resolve Weak and LinkOnce values in the \p Index.
262//
263// We'd like to drop these functions if they are no longer referenced in the
264// current module. However there is a chance that another module is still
265// referencing them because of the import. We make sure we always emit at least
266// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000267void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000268 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000269 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000270 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000271 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000272 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000273 // We won't optimize the globals that are referenced by an alias for now
274 // Ideally we should turn the alias into a global and duplicate the definition
275 // when needed.
276 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
277 for (auto &I : Index)
278 for (auto &S : I.second)
279 if (auto AS = dyn_cast<AliasSummary>(S.get()))
280 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
281
282 for (auto &I : Index)
283 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000284 isPrevailing, 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)
305 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
306}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000307
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000308struct InputFile::InputModule {
309 BitcodeModule BM;
310 std::unique_ptr<Module> Mod;
311
312 // The range of ModuleSymbolTable entries for this input module.
313 size_t SymBegin, SymEnd;
314};
315
316// Requires a destructor for std::vector<InputModule>.
317InputFile::~InputFile() = default;
318
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000319Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
320 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000321
Peter Collingbournead903692016-12-13 19:43:49 +0000322 ErrorOr<MemoryBufferRef> BCOrErr =
323 IRObjectFile::findBitcodeInMemBuffer(Object);
324 if (!BCOrErr)
325 return errorCodeToError(BCOrErr.getError());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000326
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000327 Expected<std::vector<BitcodeModule>> BMsOrErr =
328 getBitcodeModuleList(*BCOrErr);
329 if (!BMsOrErr)
330 return BMsOrErr.takeError();
Peter Collingbournead903692016-12-13 19:43:49 +0000331
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000332 if (BMsOrErr->empty())
333 return make_error<StringError>("Bitcode file does not contain any modules",
334 inconvertibleErrorCode());
Peter Collingbournead903692016-12-13 19:43:49 +0000335
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000336 // Create an InputModule for each module in the InputFile, and add it to the
337 // ModuleSymbolTable.
338 for (auto BM : *BMsOrErr) {
339 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000340 BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true,
341 /*IsImporting*/ false);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000342 if (!MOrErr)
343 return MOrErr.takeError();
344
345 size_t SymBegin = File->SymTab.symbols().size();
346 File->SymTab.addModule(MOrErr->get());
347 size_t SymEnd = File->SymTab.symbols().size();
348
349 for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
350 auto P = File->ComdatMap.insert(
351 std::make_pair(&C.second, File->Comdats.size()));
352 assert(P.second);
353 (void)P;
354 File->Comdats.push_back(C.first());
355 }
356
357 File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
Rafael Espindola79121102016-10-25 12:02:03 +0000358 }
359
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000360 return std::move(File);
361}
362
Rafael Espindola79121102016-10-25 12:02:03 +0000363Expected<int> InputFile::Symbol::getComdatIndex() const {
Peter Collingbournead903692016-12-13 19:43:49 +0000364 if (!isGV())
Rafael Espindola79121102016-10-25 12:02:03 +0000365 return -1;
Peter Collingbournead903692016-12-13 19:43:49 +0000366 const GlobalObject *GO = getGV()->getBaseObject();
367 if (!GO)
368 return make_error<StringError>("Unable to determine comdat of alias!",
369 inconvertibleErrorCode());
Rafael Espindola79121102016-10-25 12:02:03 +0000370 if (const Comdat *C = GO->getComdat()) {
371 auto I = File->ComdatMap.find(C);
372 assert(I != File->ComdatMap.end());
373 return I->second;
374 }
375 return -1;
376}
377
Bob Haarmandd4ebc12017-02-02 23:00:49 +0000378Expected<std::string> InputFile::getLinkerOpts() {
379 std::string LinkerOpts;
380 raw_string_ostream LOS(LinkerOpts);
381 // Extract linker options from module metadata.
382 for (InputModule &Mod : Mods) {
383 std::unique_ptr<Module> &M = Mod.Mod;
384 if (auto E = M->materializeMetadata())
385 return std::move(E);
386 if (Metadata *Val = M->getModuleFlag("Linker Options")) {
387 MDNode *LinkerOptions = cast<MDNode>(Val);
388 for (const MDOperand &MDOptions : LinkerOptions->operands())
389 for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
390 LOS << " " << cast<MDString>(MDOption)->getString();
391 }
392 }
393
394 // Synthesize export flags for symbols with dllexport storage.
395 const Triple TT(Mods[0].Mod->getTargetTriple());
396 Mangler M;
397 for (const ModuleSymbolTable::Symbol &Sym : SymTab.symbols())
398 if (auto *GV = Sym.dyn_cast<GlobalValue*>())
399 emitLinkerFlagsForGlobalCOFF(LOS, GV, TT, M);
400 LOS.flush();
401 return LinkerOpts;
402}
403
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000404StringRef InputFile::getName() const {
405 return Mods[0].BM.getModuleIdentifier();
406}
407
408StringRef InputFile::getSourceFileName() const {
409 return Mods[0].Mod->getSourceFileName();
410}
411
412iterator_range<InputFile::symbol_iterator>
413InputFile::module_symbols(InputModule &IM) {
414 return llvm::make_range(
415 symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
416 symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
417}
418
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000419LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
420 Config &Conf)
421 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000422 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000423
424LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
425 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000426 this->Backend =
427 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000428}
429
430LTO::LTO(Config Conf, ThinBackend Backend,
431 unsigned ParallelCodeGenParallelismLevel)
432 : Conf(std::move(Conf)),
433 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000434 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000435
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000436// Requires a destructor for MapVector<BitcodeModule>.
437LTO::~LTO() = default;
438
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000439// Add the given symbol to the GlobalResolutions map, and resolve its partition.
Peter Collingbournead903692016-12-13 19:43:49 +0000440void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000441 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000442 SymbolResolution Res, unsigned Partition) {
Peter Collingbournead903692016-12-13 19:43:49 +0000443 GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000444
445 auto &GlobalRes = GlobalResolutions[Sym.getName()];
446 if (GV) {
447 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
448 if (Res.Prevailing)
449 GlobalRes.IRName = GV->getName();
450 }
Teresa Johnson6c475a72017-01-05 21:34:18 +0000451 // Set the partition to external if we know it is used elsewhere, e.g.
452 // it is visible to a regular object, is referenced from llvm.compiler_used,
453 // or was already recorded as being referenced from a different partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000454 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
455 (GlobalRes.Partition != GlobalResolution::Unknown &&
Teresa Johnson6c475a72017-01-05 21:34:18 +0000456 GlobalRes.Partition != Partition)) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000457 GlobalRes.Partition = GlobalResolution::External;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000458 } else
459 // First recorded reference, save the current partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000460 GlobalRes.Partition = Partition;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000461
462 // Flag as visible outside of ThinLTO if visible from a regular object or
463 // if this is a reference in the regular LTO partition.
464 GlobalRes.VisibleOutsideThinLTO |=
465 (Res.VisibleToRegularObj || (Partition == GlobalResolution::RegularLTO));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000466}
467
Rafael Espindola7775c332016-08-26 20:19:35 +0000468static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
469 ArrayRef<SymbolResolution> Res) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000470 StringRef Path = Input->getName();
Rafael Espindola7775c332016-08-26 20:19:35 +0000471 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000472 auto ResI = Res.begin();
473 for (const InputFile::Symbol &Sym : Input->symbols()) {
474 assert(ResI != Res.end());
475 SymbolResolution Res = *ResI++;
476
Rafael Espindola7775c332016-08-26 20:19:35 +0000477 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000478 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000479 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000480 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000481 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000482 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000483 OS << 'x';
484 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000485 }
Peter Collingbourne58ffcfb2017-01-19 23:10:14 +0000486 OS.flush();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000487 assert(ResI == Res.end());
488}
489
490Error LTO::add(std::unique_ptr<InputFile> Input,
491 ArrayRef<SymbolResolution> Res) {
492 assert(!CalledGetMaxTasks);
493
494 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000495 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000496
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000497 const SymbolResolution *ResI = Res.begin();
498 for (InputFile::InputModule &IM : Input->Mods)
499 if (Error Err = addModule(*Input, IM, ResI, Res.end()))
500 return Err;
501
502 assert(ResI == Res.end());
503 return Error::success();
504}
505
506Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
507 const SymbolResolution *&ResI,
508 const SymbolResolution *ResE) {
Mehdi Amini9989f802016-08-19 15:35:44 +0000509 // FIXME: move to backend
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000510 Module &M = *IM.Mod;
Davide Italiano2ceb6282016-12-14 21:57:04 +0000511
512 if (M.getDataLayoutStr().empty())
513 return make_error<StringError>("input module has no datalayout",
514 inconvertibleErrorCode());
515
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000516 if (!Conf.OverrideTriple.empty())
517 M.setTargetTriple(Conf.OverrideTriple);
518 else if (M.getTargetTriple().empty())
519 M.setTargetTriple(Conf.DefaultTriple);
520
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000521 Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000522 if (!HasThinLTOSummary)
523 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000524
Peter Collingbournecd513a42016-11-11 19:50:24 +0000525 if (*HasThinLTOSummary)
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000526 return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000527 else
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000528 return addRegularLTO(IM.BM, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000529}
530
531// Add a regular LTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000532Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
533 const SymbolResolution *ResE) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000534 if (!RegularLTO.CombinedModule) {
535 RegularLTO.CombinedModule =
536 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
537 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
538 }
Peter Collingbournead903692016-12-13 19:43:49 +0000539 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000540 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
541 /*IsImporting*/ false);
Peter Collingbournead903692016-12-13 19:43:49 +0000542 if (!MOrErr)
543 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000544
Peter Collingbournead903692016-12-13 19:43:49 +0000545 Module &M = **MOrErr;
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000546 if (Error Err = M.materializeMetadata())
547 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000548 UpgradeDebugInfo(M);
549
Peter Collingbournead903692016-12-13 19:43:49 +0000550 ModuleSymbolTable SymTab;
551 SymTab.addModule(&M);
552
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000553 SmallPtrSet<GlobalValue *, 8> Used;
554 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
555
556 std::vector<GlobalValue *> Keep;
557
558 for (GlobalVariable &GV : M.globals())
559 if (GV.hasAppendingLinkage())
560 Keep.push_back(&GV);
561
Peter Collingbourne46136262017-02-02 05:22:42 +0000562 DenseSet<GlobalObject *> AliasedGlobals;
563 for (auto &GA : M.aliases())
564 if (GlobalObject *GO = GA.getBaseObject())
565 AliasedGlobals.insert(GO);
566
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000567 for (const InputFile::Symbol &Sym :
Peter Collingbournead903692016-12-13 19:43:49 +0000568 make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
569 nullptr),
570 InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
571 nullptr))) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000572 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000573 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000574 addSymbolToGlobalRes(Used, Sym, Res, 0);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000575
Peter Collingbournec387e702017-02-02 05:12:15 +0000576 if (Sym.isGV()) {
Peter Collingbournead903692016-12-13 19:43:49 +0000577 GlobalValue *GV = Sym.getGV();
Peter Collingbournec387e702017-02-02 05:12:15 +0000578 if (Res.Prevailing) {
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000579 if (Sym.isUndefined())
Peter Collingbournec387e702017-02-02 05:12:15 +0000580 continue;
581 Keep.push_back(GV);
582 switch (GV->getLinkage()) {
583 default:
584 break;
585 case GlobalValue::LinkOnceAnyLinkage:
586 GV->setLinkage(GlobalValue::WeakAnyLinkage);
587 break;
588 case GlobalValue::LinkOnceODRLinkage:
589 GV->setLinkage(GlobalValue::WeakODRLinkage);
590 break;
591 }
Peter Collingbourne46136262017-02-02 05:22:42 +0000592 } else if (isa<GlobalObject>(GV) &&
593 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
594 GV->hasAvailableExternallyLinkage()) &&
595 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
596 // Either of the above three types of linkage indicates that the
597 // chosen prevailing symbol will have the same semantics as this copy of
598 // the symbol, so we can link it with available_externally linkage. We
599 // only need to do this if the symbol is undefined.
Peter Collingbournec387e702017-02-02 05:12:15 +0000600 GlobalValue *CombinedGV =
601 RegularLTO.CombinedModule->getNamedValue(GV->getName());
Peter Collingbourne46136262017-02-02 05:22:42 +0000602 if (!CombinedGV || CombinedGV->isDeclaration()) {
Peter Collingbournec387e702017-02-02 05:12:15 +0000603 Keep.push_back(GV);
Peter Collingbourne46136262017-02-02 05:22:42 +0000604 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
605 cast<GlobalObject>(GV)->setComdat(nullptr);
606 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000607 }
608 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000609 // Common resolution: collect the maximum size/alignment over all commons.
610 // We also record if we see an instance of a common as prevailing, so that
611 // if none is prevailing we can ignore it later.
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000612 if (Sym.isCommon()) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000613 // FIXME: We should figure out what to do about commons defined by asm.
614 // For now they aren't reported correctly by ModuleSymbolTable.
Peter Collingbournead903692016-12-13 19:43:49 +0000615 auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000616 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
617 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000618 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000619 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000620
621 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
622 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000623
Peter Collingbournead903692016-12-13 19:43:49 +0000624 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000625 [](GlobalValue &, IRMover::ValueAdder) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000626 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000627}
628
629// Add a ThinLTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000630// FIXME: This function should not need to take as many parameters once we have
631// a bitcode symbol table.
632Error LTO::addThinLTO(BitcodeModule BM, Module &M,
633 iterator_range<InputFile::symbol_iterator> Syms,
634 const SymbolResolution *&ResI,
635 const SymbolResolution *ResE) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000636 SmallPtrSet<GlobalValue *, 8> Used;
637 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
638
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000639 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
640 if (!SummaryOrErr)
641 return SummaryOrErr.takeError();
642 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000643 ThinLTO.ModuleMap.size());
644
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000645 for (const InputFile::Symbol &Sym : Syms) {
646 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000647 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000648 addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000649
Peter Collingbournead903692016-12-13 19:43:49 +0000650 if (Res.Prevailing && Sym.isGV())
651 ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000652 BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000653 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000654
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000655 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
656 return make_error<StringError>(
657 "Expected at most one ThinLTO module per bitcode file",
658 inconvertibleErrorCode());
659
Mehdi Amini41af4302016-11-11 04:28:40 +0000660 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000661}
662
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000663unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000664 CalledGetMaxTasks = true;
665 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
666}
667
Peter Collingbourne80186a52016-09-23 21:33:43 +0000668Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000669 // Save the status of having a regularLTO combined module, as
670 // this is needed for generating the ThinLTO Task ID, and
671 // the CombinedModule will be moved at the end of runRegularLTO.
672 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000673 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000674 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000675 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000676 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000677 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000678}
679
Peter Collingbourne80186a52016-09-23 21:33:43 +0000680Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000681 // Make sure commons have the right size/alignment: we kept the largest from
682 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000683 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000684 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000685 if (!I.second.Prevailing)
686 // Don't do anything if no instance of this common was prevailing.
687 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000688 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000689 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000690 // Don't create a new global if the type is already correct, just make
691 // sure the alignment is correct.
692 OldGV->setAlignment(I.second.Align);
693 continue;
694 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000695 ArrayType *Ty =
696 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000697 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
698 GlobalValue::CommonLinkage,
699 ConstantAggregateZero::get(Ty), "");
700 GV->setAlignment(I.second.Align);
701 if (OldGV) {
702 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
703 GV->takeName(OldGV);
704 OldGV->eraseFromParent();
705 } else {
706 GV->setName(I.first);
707 }
708 }
709
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000710 if (Conf.PreOptModuleHook &&
711 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000712 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000713
Mehdi Aminid310b472016-08-22 06:25:41 +0000714 if (!Conf.CodeGenOnly) {
715 for (const auto &R : GlobalResolutions) {
716 if (R.second.IRName.empty())
717 continue;
718 if (R.second.Partition != 0 &&
719 R.second.Partition != GlobalResolution::External)
720 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000721
Mehdi Aminid310b472016-08-22 06:25:41 +0000722 GlobalValue *GV =
723 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
724 // Ignore symbols defined in other partitions.
725 if (!GV || GV->hasLocalLinkage())
726 continue;
727 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
728 : GlobalValue::UnnamedAddr::None);
729 if (R.second.Partition == 0)
730 GV->setLinkage(GlobalValue::InternalLinkage);
731 }
732
733 if (Conf.PostInternalizeModuleHook &&
734 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000735 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000736 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000737 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000738 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000739}
740
741/// This class defines the interface to the ThinLTO backend.
742class lto::ThinBackendProc {
743protected:
744 Config &Conf;
745 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000746 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000747
748public:
749 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000750 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000751 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000752 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
753
754 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000755 virtual Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000756 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000757 const FunctionImporter::ImportMapTy &ImportList,
758 const FunctionImporter::ExportSetTy &ExportList,
759 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000760 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000761 virtual Error wait() = 0;
762};
763
Benjamin Kramerffd37152016-11-19 20:44:26 +0000764namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000765class InProcessThinBackend : public ThinBackendProc {
766 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000767 AddStreamFn AddStream;
768 NativeObjectCache Cache;
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000769 TypeIdSummariesByGuidTy TypeIdSummariesByGuid;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000770
771 Optional<Error> Err;
772 std::mutex ErrMu;
773
774public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000775 InProcessThinBackend(
776 Config &Conf, ModuleSummaryIndex &CombinedIndex,
777 unsigned ThinLTOParallelismLevel,
778 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000779 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000780 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
781 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000782 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
783 // Create a mapping from type identifier GUIDs to type identifier summaries.
784 // This allows backends to use the type identifier GUIDs stored in the
785 // function summaries to determine which type identifier summaries affect
786 // each function without needing to compute GUIDs in each backend.
787 for (auto &TId : CombinedIndex.typeIds())
788 TypeIdSummariesByGuid[GlobalValue::getGUID(TId.first)].push_back(&TId);
789 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000790
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000791 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000792 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000793 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000794 const FunctionImporter::ImportMapTy &ImportList,
795 const FunctionImporter::ExportSetTy &ExportList,
796 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
797 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000798 MapVector<StringRef, BitcodeModule> &ModuleMap,
799 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000800 auto RunThinBackend = [&](AddStreamFn AddStream) {
801 LTOLLVMContext BackendContext(Conf);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000802 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000803 if (!MOrErr)
804 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000805
Peter Collingbourne80186a52016-09-23 21:33:43 +0000806 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
807 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000808 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000809
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000810 auto ModuleID = BM.getModuleIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000811
812 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
813 all_of(CombinedIndex.getModuleHash(ModuleID),
814 [](uint32_t V) { return V == 0; }))
815 // Cache disabled or no entry for this module in the combined index or
816 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000817 return RunThinBackend(AddStream);
818
819 SmallString<40> Key;
820 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000821 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000822 ResolvedODR, DefinedGlobals, TypeIdSummariesByGuid);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000823 if (AddStreamFn CacheAddStream = Cache(Task, Key))
824 return RunThinBackend(CacheAddStream);
825
Mehdi Amini41af4302016-11-11 04:28:40 +0000826 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000827 }
828
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000829 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000830 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000831 const FunctionImporter::ImportMapTy &ImportList,
832 const FunctionImporter::ExportSetTy &ExportList,
833 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000834 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
835 StringRef ModulePath = BM.getModuleIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000836 assert(ModuleToDefinedGVSummaries.count(ModulePath));
837 const GVSummaryMapTy &DefinedGlobals =
838 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000839 BackendThreadPool.async(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000840 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000841 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000842 const FunctionImporter::ExportSetTy &ExportList,
843 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
844 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000845 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000846 MapVector<StringRef, BitcodeModule> &ModuleMap,
847 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000848 Error E = runThinLTOBackendThread(
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000849 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
850 ResolvedODR, DefinedGlobals, ModuleMap, TypeIdSummariesByGuid);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000851 if (E) {
852 std::unique_lock<std::mutex> L(ErrMu);
853 if (Err)
854 Err = joinErrors(std::move(*Err), std::move(E));
855 else
856 Err = std::move(E);
857 }
858 },
Peter Collingbourne780a4dd2017-03-10 21:35:17 +0000859 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
860 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap),
861 std::ref(TypeIdSummariesByGuid));
Mehdi Amini41af4302016-11-11 04:28:40 +0000862 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000863 }
864
865 Error wait() override {
866 BackendThreadPool.wait();
867 if (Err)
868 return std::move(*Err);
869 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000870 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000871 }
872};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000873} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000874
875ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
876 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000877 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000878 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000879 return llvm::make_unique<InProcessThinBackend>(
880 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000881 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000882 };
883}
884
Teresa Johnson3f212b82016-09-21 19:12:05 +0000885// Given the original \p Path to an output file, replace any path
886// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
887// resulting directory if it does not yet exist.
888std::string lto::getThinLTOOutputFile(const std::string &Path,
889 const std::string &OldPrefix,
890 const std::string &NewPrefix) {
891 if (OldPrefix.empty() && NewPrefix.empty())
892 return Path;
893 SmallString<128> NewPath(Path);
894 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
895 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
896 if (!ParentPath.empty()) {
897 // Make sure the new directory exists, creating it if necessary.
898 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
899 llvm::errs() << "warning: could not create directory '" << ParentPath
900 << "': " << EC.message() << '\n';
901 }
902 return NewPath.str();
903}
904
Benjamin Kramerffd37152016-11-19 20:44:26 +0000905namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000906class WriteIndexesThinBackend : public ThinBackendProc {
907 std::string OldPrefix, NewPrefix;
908 bool ShouldEmitImportsFiles;
909
910 std::string LinkedObjectsFileName;
911 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
912
913public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000914 WriteIndexesThinBackend(
915 Config &Conf, ModuleSummaryIndex &CombinedIndex,
916 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
917 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
918 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000919 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000920 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
921 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
922 LinkedObjectsFileName(LinkedObjectsFileName) {}
923
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000924 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000925 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000926 const FunctionImporter::ImportMapTy &ImportList,
927 const FunctionImporter::ExportSetTy &ExportList,
928 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000929 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
930 StringRef ModulePath = BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000931 std::string NewModulePath =
932 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
933
934 std::error_code EC;
935 if (!LinkedObjectsFileName.empty()) {
936 if (!LinkedObjectsFile) {
937 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
938 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
939 if (EC)
940 return errorCodeToError(EC);
941 }
942 *LinkedObjectsFile << NewModulePath << '\n';
943 }
944
945 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
946 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000947 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000948
949 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
950 sys::fs::OpenFlags::F_None);
951 if (EC)
952 return errorCodeToError(EC);
953 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
954
955 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000956 return errorCodeToError(
957 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000958 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000959 }
960
Mehdi Amini41af4302016-11-11 04:28:40 +0000961 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000962};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000963} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000964
965ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
966 std::string NewPrefix,
967 bool ShouldEmitImportsFiles,
968 std::string LinkedObjectsFile) {
969 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000970 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000971 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000972 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000973 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
974 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000975 };
976}
977
Peter Collingbourne80186a52016-09-23 21:33:43 +0000978Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
979 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000980 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000981 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000982
983 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000984 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000985
986 // Collect for each module the list of function it defines (GUID ->
987 // Summary).
988 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
989 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
990 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
991 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000992 // Create entries for any modules that didn't have any GV summaries
993 // (either they didn't have any GVs to start with, or we suppressed
994 // generation of the summaries because they e.g. had inline assembly
995 // uses that couldn't be promoted/renamed on export). This is so
996 // InProcessThinBackend::start can still launch a backend thread, which
997 // is passed the map of summaries for the module, without any special
998 // handling for this case.
999 for (auto &Mod : ThinLTO.ModuleMap)
1000 if (!ModuleToDefinedGVSummaries.count(Mod.first))
1001 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001002
1003 StringMap<FunctionImporter::ImportMapTy> ImportLists(
1004 ThinLTO.ModuleMap.size());
1005 StringMap<FunctionImporter::ExportSetTy> ExportLists(
1006 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +00001007 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +00001008
Teresa Johnson002af9b2016-10-31 22:12:21 +00001009 if (Conf.OptLevel > 0) {
Mehdi Aminif39ce992017-01-20 23:34:12 +00001010 // Compute "dead" symbols, we don't want to import/export these!
1011 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1012 for (auto &Res : GlobalResolutions) {
1013 if (Res.second.VisibleOutsideThinLTO &&
1014 // IRName will be defined if we have seen the prevailing copy of
1015 // this value. If not, no need to preserve any ThinLTO copies.
1016 !Res.second.IRName.empty())
1017 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Res.second.IRName));
1018 }
1019
1020 auto DeadSymbols =
1021 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
1022
Teresa Johnson002af9b2016-10-31 22:12:21 +00001023 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
Teresa Johnson6c475a72017-01-05 21:34:18 +00001024 ImportLists, ExportLists, &DeadSymbols);
Teresa Johnson002af9b2016-10-31 22:12:21 +00001025
1026 std::set<GlobalValue::GUID> ExportedGUIDs;
1027 for (auto &Res : GlobalResolutions) {
Teresa Johnson6c475a72017-01-05 21:34:18 +00001028 // First check if the symbol was flagged as having external references.
1029 if (Res.second.Partition != GlobalResolution::External)
1030 continue;
1031 // IRName will be defined if we have seen the prevailing copy of
1032 // this value. If not, no need to mark as exported from a ThinLTO
1033 // partition (and we can't get the GUID).
1034 if (Res.second.IRName.empty())
1035 continue;
1036 auto GUID = GlobalValue::getGUID(Res.second.IRName);
1037 // Mark exported unless index-based analysis determined it to be dead.
1038 if (!DeadSymbols.count(GUID))
Teresa Johnson002af9b2016-10-31 22:12:21 +00001039 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
1040 }
1041
1042 auto isPrevailing = [&](GlobalValue::GUID GUID,
1043 const GlobalValueSummary *S) {
1044 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1045 };
Mehdi Amini1380edf2017-02-03 07:41:43 +00001046 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson002af9b2016-10-31 22:12:21 +00001047 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +00001048 return (ExportList != ExportLists.end() &&
1049 ExportList->second.count(GUID)) ||
1050 ExportedGUIDs.count(GUID);
Teresa Johnson002af9b2016-10-31 22:12:21 +00001051 };
1052 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
1053
1054 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1055 GlobalValue::GUID GUID,
1056 GlobalValue::LinkageTypes NewLinkage) {
1057 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1058 };
1059
1060 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
1061 recordNewLinkage);
1062 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001063
Peter Collingbourne80186a52016-09-23 21:33:43 +00001064 std::unique_ptr<ThinBackendProc> BackendProc =
1065 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1066 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001067
Davide Italiano63098952017-01-04 20:37:57 +00001068 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
1069 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
1070 // are reserved for parallel code generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +00001071 unsigned Task =
1072 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001073 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +00001074 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +00001075 ExportLists[Mod.first],
1076 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001077 return E;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001078 ++Task;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001079 }
1080
1081 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001082}
Davide Italiano690ed9d2017-02-10 23:49:38 +00001083
1084Expected<std::unique_ptr<tool_output_file>>
1085lto::setupOptimizationRemarks(LLVMContext &Context,
1086 StringRef LTORemarksFilename,
1087 bool LTOPassRemarksWithHotness, int Count) {
1088 if (LTORemarksFilename.empty())
1089 return nullptr;
1090
1091 std::string Filename = LTORemarksFilename;
1092 if (Count != -1)
1093 Filename += ".thin." + llvm::utostr(Count) + ".yaml";
1094
1095 std::error_code EC;
1096 auto DiagnosticFile =
1097 llvm::make_unique<tool_output_file>(Filename, EC, sys::fs::F_None);
1098 if (EC)
1099 return errorCodeToError(EC);
1100 Context.setDiagnosticsOutputFile(
1101 llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1102 if (LTOPassRemarksWithHotness)
1103 Context.setDiagnosticHotnessRequested(true);
1104 DiagnosticFile->keep();
1105 return std::move(DiagnosticFile);
1106}