LLVM 22.0.0git
LTO.cpp
Go to the documentation of this file.
1//===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements functions and classes used to support LTO.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/LTO/LTO.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/ScopeExit.h"
16#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/Statistic.h"
28#include "llvm/Config/llvm-config.h"
29#include "llvm/IR/AutoUpgrade.h"
31#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/Mangler.h"
35#include "llvm/IR/Metadata.h"
37#include "llvm/LTO/LTOBackend.h"
38#include "llvm/Linker/IRMover.h"
44#include "llvm/Support/Error.h"
46#include "llvm/Support/JSON.h"
48#include "llvm/Support/Path.h"
50#include "llvm/Support/SHA1.h"
56#include "llvm/Support/VCSRevision.h"
59#include "llvm/Transforms/IPO.h"
64
65#include <optional>
66#include <set>
67
68using namespace llvm;
69using namespace lto;
70using namespace object;
71
72#define DEBUG_TYPE "lto"
73
74static cl::opt<bool>
75 DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden,
76 cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
77
78namespace llvm {
81} // end namespace llvm
82
83namespace llvm {
84/// Enable global value internalization in LTO.
86 "enable-lto-internalization", cl::init(true), cl::Hidden,
87 cl::desc("Enable global value internalization in LTO"));
88
89static cl::opt<bool>
90 LTOKeepSymbolCopies("lto-keep-symbol-copies", cl::init(false), cl::Hidden,
91 cl::desc("Keep copies of symbols in LTO indexing"));
92
93/// Indicate we are linking with an allocator that supports hot/cold operator
94/// new interfaces.
96
97/// Enable MemProf context disambiguation for thin link.
99} // namespace llvm
100
101// Computes a unique hash for the Module considering the current list of
102// export/import and other global analysis results.
103// Returns the hash in its hexadecimal representation.
105 const Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID,
106 const FunctionImporter::ImportMapTy &ImportList,
107 const FunctionImporter::ExportSetTy &ExportList,
108 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
109 const GVSummaryMapTy &DefinedGlobals,
110 const DenseSet<GlobalValue::GUID> &CfiFunctionDefs,
111 const DenseSet<GlobalValue::GUID> &CfiFunctionDecls) {
112 // Compute the unique hash for this entry.
113 // This is based on the current compiler version, the module itself, the
114 // export list, the hash for every single module in the import list, the
115 // list of ResolvedODR for the module, and the list of preserved symbols.
116 SHA1 Hasher;
117
118 // Start with the compiler revision
119 Hasher.update(LLVM_VERSION_STRING);
120#ifdef LLVM_REVISION
121 Hasher.update(LLVM_REVISION);
122#endif
123
124 // Include the parts of the LTO configuration that affect code generation.
125 auto AddString = [&](StringRef Str) {
126 Hasher.update(Str);
127 Hasher.update(ArrayRef<uint8_t>{0});
128 };
129 auto AddUnsigned = [&](unsigned I) {
130 uint8_t Data[4];
132 Hasher.update(Data);
133 };
134 auto AddUint64 = [&](uint64_t I) {
135 uint8_t Data[8];
137 Hasher.update(Data);
138 };
139 auto AddUint8 = [&](const uint8_t I) {
140 Hasher.update(ArrayRef<uint8_t>(&I, 1));
141 };
142 AddString(Conf.CPU);
143 // FIXME: Hash more of Options. For now all clients initialize Options from
144 // command-line flags (which is unsupported in production), but may set
145 // X86RelaxRelocations. The clang driver can also pass FunctionSections,
146 // DataSections and DebuggerTuning via command line flags.
147 AddUnsigned(Conf.Options.MCOptions.X86RelaxRelocations);
148 AddUnsigned(Conf.Options.FunctionSections);
149 AddUnsigned(Conf.Options.DataSections);
150 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
151 for (auto &A : Conf.MAttrs)
152 AddString(A);
153 if (Conf.RelocModel)
154 AddUnsigned(*Conf.RelocModel);
155 else
156 AddUnsigned(-1);
157 if (Conf.CodeModel)
158 AddUnsigned(*Conf.CodeModel);
159 else
160 AddUnsigned(-1);
161 for (const auto &S : Conf.MllvmArgs)
162 AddString(S);
163 AddUnsigned(static_cast<int>(Conf.CGOptLevel));
164 AddUnsigned(static_cast<int>(Conf.CGFileType));
165 AddUnsigned(Conf.OptLevel);
166 AddUnsigned(Conf.Freestanding);
167 AddString(Conf.OptPipeline);
168 AddString(Conf.AAPipeline);
169 AddString(Conf.OverrideTriple);
170 AddString(Conf.DefaultTriple);
171 AddString(Conf.DwoDir);
172
173 // Include the hash for the current module
174 auto ModHash = Index.getModuleHash(ModuleID);
175 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
176
177 // TODO: `ExportList` is determined by `ImportList`. Since `ImportList` is
178 // used to compute cache key, we could omit hashing `ExportList` here.
179 std::vector<uint64_t> ExportsGUID;
180 ExportsGUID.reserve(ExportList.size());
181 for (const auto &VI : ExportList)
182 ExportsGUID.push_back(VI.getGUID());
183
184 // Sort the export list elements GUIDs.
185 llvm::sort(ExportsGUID);
186 for (auto GUID : ExportsGUID)
187 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
188
189 // Order using module hash, to be both independent of module name and
190 // module order.
191 auto Comp = [&](const std::pair<StringRef, GlobalValue::GUID> &L,
192 const std::pair<StringRef, GlobalValue::GUID> &R) {
193 return std::make_pair(Index.getModule(L.first)->second, L.second) <
194 std::make_pair(Index.getModule(R.first)->second, R.second);
195 };
196 FunctionImporter::SortedImportList SortedImportList(ImportList, Comp);
197
198 // Count the number of imports for each source module.
199 DenseMap<StringRef, unsigned> ModuleToNumImports;
200 for (const auto &[FromModule, GUID, Type] : SortedImportList)
201 ++ModuleToNumImports[FromModule];
202
203 std::optional<StringRef> LastModule;
204 for (const auto &[FromModule, GUID, Type] : SortedImportList) {
205 if (LastModule != FromModule) {
206 // Include the hash for every module we import functions from. The set of
207 // imported symbols for each module may affect code generation and is
208 // sensitive to link order, so include that as well.
209 LastModule = FromModule;
210 auto ModHash = Index.getModule(FromModule)->second;
211 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
212 AddUint64(ModuleToNumImports[FromModule]);
213 }
214 AddUint64(GUID);
215 AddUint8(Type);
216 }
217
218 // Include the hash for the resolved ODR.
219 for (auto &Entry : ResolvedODR) {
220 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
221 sizeof(GlobalValue::GUID)));
222 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
224 }
225
226 // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
227 // defined in this module.
228 std::set<GlobalValue::GUID> UsedCfiDefs;
229 std::set<GlobalValue::GUID> UsedCfiDecls;
230
231 // Typeids used in this module.
232 std::set<GlobalValue::GUID> UsedTypeIds;
233
234 auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
235 if (CfiFunctionDefs.contains(ValueGUID))
236 UsedCfiDefs.insert(ValueGUID);
237 if (CfiFunctionDecls.contains(ValueGUID))
238 UsedCfiDecls.insert(ValueGUID);
239 };
240
241 auto AddUsedThings = [&](GlobalValueSummary *GS) {
242 if (!GS) return;
243 AddUnsigned(GS->getVisibility());
244 AddUnsigned(GS->isLive());
245 AddUnsigned(GS->canAutoHide());
246 for (const ValueInfo &VI : GS->refs()) {
247 AddUnsigned(VI.isDSOLocal(Index.withDSOLocalPropagation()));
248 AddUsedCfiGlobal(VI.getGUID());
249 }
250 if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) {
251 AddUnsigned(GVS->maybeReadOnly());
252 AddUnsigned(GVS->maybeWriteOnly());
253 }
254 if (auto *FS = dyn_cast<FunctionSummary>(GS)) {
255 for (auto &TT : FS->type_tests())
256 UsedTypeIds.insert(TT);
257 for (auto &TT : FS->type_test_assume_vcalls())
258 UsedTypeIds.insert(TT.GUID);
259 for (auto &TT : FS->type_checked_load_vcalls())
260 UsedTypeIds.insert(TT.GUID);
261 for (auto &TT : FS->type_test_assume_const_vcalls())
262 UsedTypeIds.insert(TT.VFunc.GUID);
263 for (auto &TT : FS->type_checked_load_const_vcalls())
264 UsedTypeIds.insert(TT.VFunc.GUID);
265 for (auto &ET : FS->calls()) {
266 AddUnsigned(ET.first.isDSOLocal(Index.withDSOLocalPropagation()));
267 AddUsedCfiGlobal(ET.first.getGUID());
268 }
269 }
270 };
271
272 // Include the hash for the linkage type to reflect internalization and weak
273 // resolution, and collect any used type identifier resolutions.
274 for (auto &GS : DefinedGlobals) {
275 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
276 Hasher.update(
277 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
278 AddUsedCfiGlobal(GS.first);
279 AddUsedThings(GS.second);
280 }
281
282 // Imported functions may introduce new uses of type identifier resolutions,
283 // so we need to collect their used resolutions as well.
284 for (const auto &[FromModule, GUID, Type] : SortedImportList) {
285 GlobalValueSummary *S = Index.findSummaryInModule(GUID, FromModule);
286 AddUsedThings(S);
287 // If this is an alias, we also care about any types/etc. that the aliasee
288 // may reference.
289 if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
290 AddUsedThings(AS->getBaseObject());
291 }
292
293 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
294 AddString(TId);
295
296 AddUnsigned(S.TTRes.TheKind);
297 AddUnsigned(S.TTRes.SizeM1BitWidth);
298
299 AddUint64(S.TTRes.AlignLog2);
300 AddUint64(S.TTRes.SizeM1);
301 AddUint64(S.TTRes.BitMask);
302 AddUint64(S.TTRes.InlineBits);
303
304 AddUint64(S.WPDRes.size());
305 for (auto &WPD : S.WPDRes) {
306 AddUnsigned(WPD.first);
307 AddUnsigned(WPD.second.TheKind);
308 AddString(WPD.second.SingleImplName);
309
310 AddUint64(WPD.second.ResByArg.size());
311 for (auto &ByArg : WPD.second.ResByArg) {
312 AddUint64(ByArg.first.size());
313 for (uint64_t Arg : ByArg.first)
314 AddUint64(Arg);
315 AddUnsigned(ByArg.second.TheKind);
316 AddUint64(ByArg.second.Info);
317 AddUnsigned(ByArg.second.Byte);
318 AddUnsigned(ByArg.second.Bit);
319 }
320 }
321 };
322
323 // Include the hash for all type identifiers used by this module.
324 for (GlobalValue::GUID TId : UsedTypeIds) {
325 auto TidIter = Index.typeIds().equal_range(TId);
326 for (const auto &I : make_range(TidIter))
327 AddTypeIdSummary(I.second.first, I.second.second);
328 }
329
330 AddUnsigned(UsedCfiDefs.size());
331 for (auto &V : UsedCfiDefs)
332 AddUint64(V);
333
334 AddUnsigned(UsedCfiDecls.size());
335 for (auto &V : UsedCfiDecls)
336 AddUint64(V);
337
338 if (!Conf.SampleProfile.empty()) {
339 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
340 if (FileOrErr) {
341 Hasher.update(FileOrErr.get()->getBuffer());
342
343 if (!Conf.ProfileRemapping.empty()) {
344 FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping);
345 if (FileOrErr)
346 Hasher.update(FileOrErr.get()->getBuffer());
347 }
348 }
349 }
350
351 return toHex(Hasher.result());
352}
353
354std::string llvm::recomputeLTOCacheKey(const std::string &Key,
355 StringRef ExtraID) {
356 SHA1 Hasher;
357
358 auto AddString = [&](StringRef Str) {
359 Hasher.update(Str);
360 Hasher.update(ArrayRef<uint8_t>{0});
361 };
362 AddString(Key);
363 AddString(ExtraID);
364
365 return toHex(Hasher.result());
366}
367
369 const Config &C, ValueInfo VI,
370 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
372 isPrevailing,
374 recordNewLinkage,
375 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
377 C.VisibilityScheme == Config::ELF ? VI.getELFVisibility()
379 for (auto &S : VI.getSummaryList()) {
380 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
381 // Ignore local and appending linkage values since the linker
382 // doesn't resolve them.
383 if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
385 continue;
386 // We need to emit only one of these. The prevailing module will keep it,
387 // but turned into a weak, while the others will drop it when possible.
388 // This is both a compile-time optimization and a correctness
389 // transformation. This is necessary for correctness when we have exported
390 // a reference - we need to convert the linkonce to weak to
391 // ensure a copy is kept to satisfy the exported reference.
392 // FIXME: We may want to split the compile time and correctness
393 // aspects into separate routines.
394 if (isPrevailing(VI.getGUID(), S.get())) {
395 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) {
396 S->setLinkage(GlobalValue::getWeakLinkage(
397 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
398 // The kept copy is eligible for auto-hiding (hidden visibility) if all
399 // copies were (i.e. they were all linkonce_odr global unnamed addr).
400 // If any copy is not (e.g. it was originally weak_odr), then the symbol
401 // must remain externally available (e.g. a weak_odr from an explicitly
402 // instantiated template). Additionally, if it is in the
403 // GUIDPreservedSymbols set, that means that it is visibile outside
404 // the summary (e.g. in a native object or a bitcode file without
405 // summary), and in that case we cannot hide it as it isn't possible to
406 // check all copies.
407 S->setCanAutoHide(VI.canAutoHide() &&
408 !GUIDPreservedSymbols.count(VI.getGUID()));
409 }
410 if (C.VisibilityScheme == Config::FromPrevailing)
411 Visibility = S->getVisibility();
412 }
413 // Alias and aliasee can't be turned into available_externally.
414 // When force-import-all is used, it indicates that object linking is not
415 // supported by the target. In this case, we can't change the linkage as
416 // well in case the global is converted to declaration.
417 else if (!isa<AliasSummary>(S.get()) &&
418 !GlobalInvolvedWithAlias.count(S.get()) && !ForceImportAll)
420
421 // For ELF, set visibility to the computed visibility from summaries. We
422 // don't track visibility from declarations so this may be more relaxed than
423 // the most constraining one.
424 if (C.VisibilityScheme == Config::ELF)
425 S->setVisibility(Visibility);
426
427 if (S->linkage() != OriginalLinkage)
428 recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
429 }
430
431 if (C.VisibilityScheme == Config::FromPrevailing) {
432 for (auto &S : VI.getSummaryList()) {
433 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
434 if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
436 continue;
437 S->setVisibility(Visibility);
438 }
439 }
440}
441
442/// Resolve linkage for prevailing symbols in the \p Index.
443//
444// We'd like to drop these functions if they are no longer referenced in the
445// current module. However there is a chance that another module is still
446// referencing them because of the import. We make sure we always emit at least
447// one copy.
449 const Config &C, ModuleSummaryIndex &Index,
451 isPrevailing,
453 recordNewLinkage,
454 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
455 // We won't optimize the globals that are referenced by an alias for now
456 // Ideally we should turn the alias into a global and duplicate the definition
457 // when needed.
458 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
459 for (auto &I : Index)
460 for (auto &S : I.second.getSummaryList())
461 if (auto AS = dyn_cast<AliasSummary>(S.get()))
462 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
463
464 for (auto &I : Index)
465 thinLTOResolvePrevailingGUID(C, Index.getValueInfo(I),
466 GlobalInvolvedWithAlias, isPrevailing,
467 recordNewLinkage, GUIDPreservedSymbols);
468}
469
471 ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
473 isPrevailing) {
474 // Before performing index-based internalization and promotion for this GUID,
475 // the local flag should be consistent with the summary list linkage types.
476 VI.verifyLocal();
477
478 const bool SingleExternallyVisibleCopy =
479 VI.getSummaryList().size() == 1 &&
480 !GlobalValue::isLocalLinkage(VI.getSummaryList().front()->linkage());
481
482 for (auto &S : VI.getSummaryList()) {
483 // First see if we need to promote an internal value because it is not
484 // exported.
485 if (isExported(S->modulePath(), VI)) {
486 if (GlobalValue::isLocalLinkage(S->linkage()))
487 S->setLinkage(GlobalValue::ExternalLinkage);
488 continue;
489 }
490
491 // Otherwise, see if we can internalize.
493 continue;
494
495 // Non-exported values with external linkage can be internalized.
496 if (GlobalValue::isExternalLinkage(S->linkage())) {
497 S->setLinkage(GlobalValue::InternalLinkage);
498 continue;
499 }
500
501 // Non-exported function and variable definitions with a weak-for-linker
502 // linkage can be internalized in certain cases. The minimum legality
503 // requirements would be that they are not address taken to ensure that we
504 // don't break pointer equality checks, and that variables are either read-
505 // or write-only. For functions, this is the case if either all copies are
506 // [local_]unnamed_addr, or we can propagate reference edge attributes
507 // (which is how this is guaranteed for variables, when analyzing whether
508 // they are read or write-only).
509 //
510 // However, we only get to this code for weak-for-linkage values in one of
511 // two cases:
512 // 1) The prevailing copy is not in IR (it is in native code).
513 // 2) The prevailing copy in IR is not exported from its module.
514 // Additionally, at least for the new LTO API, case 2 will only happen if
515 // there is exactly one definition of the value (i.e. in exactly one
516 // module), as duplicate defs are result in the value being marked exported.
517 // Likely, users of the legacy LTO API are similar, however, currently there
518 // are llvm-lto based tests of the legacy LTO API that do not mark
519 // duplicate linkonce_odr copies as exported via the tool, so we need
520 // to handle that case below by checking the number of copies.
521 //
522 // Generally, we only want to internalize a weak-for-linker value in case
523 // 2, because in case 1 we cannot see how the value is used to know if it
524 // is read or write-only. We also don't want to bloat the binary with
525 // multiple internalized copies of non-prevailing linkonce/weak functions.
526 // Note if we don't internalize, we will convert non-prevailing copies to
527 // available_externally anyway, so that we drop them after inlining. The
528 // only reason to internalize such a function is if we indeed have a single
529 // copy, because internalizing it won't increase binary size, and enables
530 // use of inliner heuristics that are more aggressive in the face of a
531 // single call to a static (local). For variables, internalizing a read or
532 // write only variable can enable more aggressive optimization. However, we
533 // already perform this elsewhere in the ThinLTO backend handling for
534 // read or write-only variables (processGlobalForThinLTO).
535 //
536 // Therefore, only internalize linkonce/weak if there is a single copy, that
537 // is prevailing in this IR module. We can do so aggressively, without
538 // requiring the address to be insignificant, or that a variable be read or
539 // write-only.
540 if (!GlobalValue::isWeakForLinker(S->linkage()) ||
542 continue;
543
544 // We may have a single summary copy that is externally visible but not
545 // prevailing if the prevailing copy is in a native object.
546 if (SingleExternallyVisibleCopy && isPrevailing(VI.getGUID(), S.get()))
547 S->setLinkage(GlobalValue::InternalLinkage);
548 }
549}
550
551// Update the linkages in the given \p Index to mark exported values
552// as external and non-exported values as internal.
554 ModuleSummaryIndex &Index,
555 function_ref<bool(StringRef, ValueInfo)> isExported,
557 isPrevailing) {
558 assert(!Index.withInternalizeAndPromote());
559 for (auto &I : Index)
560 thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported,
561 isPrevailing);
562 Index.setWithInternalizeAndPromote();
563}
564
565// Requires a destructor for std::vector<InputModule>.
566InputFile::~InputFile() = default;
567
569 std::unique_ptr<InputFile> File(new InputFile);
570
571 Expected<IRSymtabFile> FOrErr = readIRSymtab(Object);
572 if (!FOrErr)
573 return FOrErr.takeError();
574
575 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
576 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
577 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
578 File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
579 File->ComdatTable = FOrErr->TheReader.getComdatTable();
580
581 for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
582 size_t Begin = File->Symbols.size();
583 for (const irsymtab::Reader::SymbolRef &Sym :
584 FOrErr->TheReader.module_symbols(I))
585 // Skip symbols that are irrelevant to LTO. Note that this condition needs
586 // to match the one in Skip() in LTO::addRegularLTO().
587 if (Sym.isGlobal() && !Sym.isFormatSpecific())
588 File->Symbols.push_back(Sym);
589 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
590 }
591
592 File->Mods = FOrErr->Mods;
593 File->Strtab = std::move(FOrErr->Strtab);
594 return std::move(File);
595}
596
598 return Mods[0].getModuleIdentifier();
599}
600
602 assert(Mods.size() == 1 && "Expect only one bitcode module");
603 return Mods[0];
604}
605
606LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
607 const Config &Conf)
608 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
609 Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)),
610 Mover(std::make_unique<IRMover>(*CombinedModule)) {}
611
612LTO::ThinLTOState::ThinLTOState(ThinBackend BackendParam)
613 : Backend(std::move(BackendParam)), CombinedIndex(/*HaveGVs*/ false) {
614 if (!Backend.isValid())
615 Backend =
617}
618
620 unsigned ParallelCodeGenParallelismLevel, LTOKind LTOMode)
621 : Conf(std::move(Conf)),
622 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
623 ThinLTO(std::move(Backend)),
624 GlobalResolutions(
625 std::make_unique<DenseMap<StringRef, GlobalResolution>>()),
626 LTOMode(LTOMode) {
627 if (Conf.KeepSymbolNameCopies || LTOKeepSymbolCopies) {
628 Alloc = std::make_unique<BumpPtrAllocator>();
629 GlobalResolutionSymbolSaver = std::make_unique<llvm::StringSaver>(*Alloc);
630 }
631}
632
633// Requires a destructor for MapVector<BitcodeModule>.
634LTO::~LTO() = default;
635
636// Add the symbols in the given module to the GlobalResolutions map, and resolve
637// their partitions.
638void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
640 unsigned Partition, bool InSummary) {
641 llvm::TimeTraceScope timeScope("LTO add module to global resolution");
642 auto *ResI = Res.begin();
643 auto *ResE = Res.end();
644 (void)ResE;
645 for (const InputFile::Symbol &Sym : Syms) {
646 assert(ResI != ResE);
647 SymbolResolution Res = *ResI++;
648
649 StringRef SymbolName = Sym.getName();
650 // Keep copies of symbols if the client of LTO says so.
651 if (GlobalResolutionSymbolSaver && !GlobalResolutions->contains(SymbolName))
652 SymbolName = GlobalResolutionSymbolSaver->save(SymbolName);
653
654 auto &GlobalRes = (*GlobalResolutions)[SymbolName];
655 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
656 if (Res.Prevailing) {
657 assert(!GlobalRes.Prevailing &&
658 "Multiple prevailing defs are not allowed");
659 GlobalRes.Prevailing = true;
660 GlobalRes.IRName = std::string(Sym.getIRName());
661 } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
662 // Sometimes it can be two copies of symbol in a module and prevailing
663 // symbol can have no IR name. That might happen if symbol is defined in
664 // module level inline asm block. In case we have multiple modules with
665 // the same symbol we want to use IR name of the prevailing symbol.
666 // Otherwise, if we haven't seen a prevailing symbol, set the name so that
667 // we can later use it to check if there is any prevailing copy in IR.
668 GlobalRes.IRName = std::string(Sym.getIRName());
669 }
670
671 // In rare occasion, the symbol used to initialize GlobalRes has a different
672 // IRName from the inspected Symbol. This can happen on macOS + iOS, when a
673 // symbol is referenced through its mangled name, say @"\01_symbol" while
674 // the IRName is @symbol (the prefix underscore comes from MachO mangling).
675 // In that case, we have the same actual Symbol that can get two different
676 // GUID, leading to some invalid internalization. Workaround this by marking
677 // the GlobalRes external.
678
679 // FIXME: instead of this check, it would be desirable to compute GUIDs
680 // based on mangled name, but this requires an access to the Target Triple
681 // and would be relatively invasive on the codebase.
682 if (GlobalRes.IRName != Sym.getIRName()) {
683 GlobalRes.Partition = GlobalResolution::External;
684 GlobalRes.VisibleOutsideSummary = true;
685 }
686
687 // Set the partition to external if we know it is re-defined by the linker
688 // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
689 // regular object, is referenced from llvm.compiler.used/llvm.used, or was
690 // already recorded as being referenced from a different partition.
691 if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
692 (GlobalRes.Partition != GlobalResolution::Unknown &&
693 GlobalRes.Partition != Partition)) {
694 GlobalRes.Partition = GlobalResolution::External;
695 } else
696 // First recorded reference, save the current partition.
697 GlobalRes.Partition = Partition;
698
699 // Flag as visible outside of summary if visible from a regular object or
700 // from a module that does not have a summary.
701 GlobalRes.VisibleOutsideSummary |=
702 (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
703
704 GlobalRes.ExportDynamic |= Res.ExportDynamic;
705 }
706}
707
708void LTO::releaseGlobalResolutionsMemory() {
709 // Release GlobalResolutions dense-map itself.
710 GlobalResolutions.reset();
711 // Release the string saver memory.
712 GlobalResolutionSymbolSaver.reset();
713 Alloc.reset();
714}
715
718 StringRef Path = Input->getName();
719 OS << Path << '\n';
720 auto ResI = Res.begin();
721 for (const InputFile::Symbol &Sym : Input->symbols()) {
722 assert(ResI != Res.end());
723 SymbolResolution Res = *ResI++;
724
725 OS << "-r=" << Path << ',' << Sym.getName() << ',';
726 if (Res.Prevailing)
727 OS << 'p';
729 OS << 'l';
730 if (Res.VisibleToRegularObj)
731 OS << 'x';
732 if (Res.LinkerRedefined)
733 OS << 'r';
734 OS << '\n';
735 }
736 OS.flush();
737 assert(ResI == Res.end());
738}
739
740Error LTO::add(std::unique_ptr<InputFile> Input,
742 llvm::TimeTraceScope timeScope("LTO add input", Input->getName());
743 assert(!CalledGetMaxTasks);
744
745 if (Conf.ResolutionFile)
746 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
747
748 if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
749 Triple InputTriple(Input->getTargetTriple());
750 RegularLTO.CombinedModule->setTargetTriple(InputTriple);
751 if (InputTriple.isOSBinFormatELF())
752 Conf.VisibilityScheme = Config::ELF;
753 }
754
755 ArrayRef<SymbolResolution> InputRes = Res;
756 for (unsigned I = 0; I != Input->Mods.size(); ++I) {
757 if (auto Err = addModule(*Input, InputRes, I, Res).moveInto(Res))
758 return Err;
759 }
760
761 assert(Res.empty());
762 return Error::success();
763}
764
766LTO::addModule(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
767 unsigned ModI, ArrayRef<SymbolResolution> Res) {
768 llvm::TimeTraceScope timeScope("LTO add module", Input.getName());
769 Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
770 if (!LTOInfo)
771 return LTOInfo.takeError();
772
773 if (EnableSplitLTOUnit) {
774 // If only some modules were split, flag this in the index so that
775 // we can skip or error on optimizations that need consistently split
776 // modules (whole program devirt and lower type tests).
777 if (*EnableSplitLTOUnit != LTOInfo->EnableSplitLTOUnit)
778 ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
779 } else
780 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
781
782 BitcodeModule BM = Input.Mods[ModI];
783
784 if ((LTOMode == LTOK_UnifiedRegular || LTOMode == LTOK_UnifiedThin) &&
785 !LTOInfo->UnifiedLTO)
787 "unified LTO compilation must use "
788 "compatible bitcode modules (use -funified-lto)",
790
791 if (LTOInfo->UnifiedLTO && LTOMode == LTOK_Default)
792 LTOMode = LTOK_UnifiedThin;
793
794 bool IsThinLTO = LTOInfo->IsThinLTO && (LTOMode != LTOK_UnifiedRegular);
795
796 auto ModSyms = Input.module_symbols(ModI);
797 addModuleToGlobalRes(ModSyms, Res,
798 IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
799 LTOInfo->HasSummary);
800
801 if (IsThinLTO)
802 return addThinLTO(BM, ModSyms, Res);
803
804 RegularLTO.EmptyCombinedModule = false;
805 auto ModOrErr = addRegularLTO(Input, InputRes, BM, ModSyms, Res);
806 if (!ModOrErr)
807 return ModOrErr.takeError();
808 Res = ModOrErr->second;
809
810 if (!LTOInfo->HasSummary) {
811 if (Error Err = linkRegularLTO(std::move(ModOrErr->first),
812 /*LivenessFromIndex=*/false))
813 return Err;
814 return Res;
815 }
816
817 // Regular LTO module summaries are added to a dummy module that represents
818 // the combined regular LTO module.
819 if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, ""))
820 return Err;
821 RegularLTO.ModsWithSummaries.push_back(std::move(ModOrErr->first));
822 return Res;
823}
824
825// Checks whether the given global value is in a non-prevailing comdat
826// (comdat containing values the linker indicated were not prevailing,
827// which we then dropped to available_externally), and if so, removes
828// it from the comdat. This is called for all global values to ensure the
829// comdat is empty rather than leaving an incomplete comdat. It is needed for
830// regular LTO modules, in case we are in a mixed-LTO mode (both regular
831// and thin LTO modules) compilation. Since the regular LTO module will be
832// linked first in the final native link, we want to make sure the linker
833// doesn't select any of these incomplete comdats that would be left
834// in the regular LTO module without this cleanup.
835static void
837 std::set<const Comdat *> &NonPrevailingComdats) {
838 Comdat *C = GV.getComdat();
839 if (!C)
840 return;
841
842 if (!NonPrevailingComdats.count(C))
843 return;
844
845 // Additionally need to drop all global values from the comdat to
846 // available_externally, to satisfy the COMDAT requirement that all members
847 // are discarded as a unit. The non-local linkage global values avoid
848 // duplicate definition linker errors.
850
851 if (auto GO = dyn_cast<GlobalObject>(&GV))
852 GO->setComdat(nullptr);
853}
854
855// Add a regular LTO object to the link.
856// The resulting module needs to be linked into the combined LTO module with
857// linkRegularLTO.
858Expected<
859 std::pair<LTO::RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
860LTO::addRegularLTO(InputFile &Input, ArrayRef<SymbolResolution> InputRes,
861 BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
863 llvm::TimeTraceScope timeScope("LTO add regular LTO");
865 Expected<std::unique_ptr<Module>> MOrErr =
866 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
867 /*IsImporting*/ false);
868 if (!MOrErr)
869 return MOrErr.takeError();
870 Module &M = **MOrErr;
871 Mod.M = std::move(*MOrErr);
872
873 if (Error Err = M.materializeMetadata())
874 return std::move(Err);
875
876 if (LTOMode == LTOK_UnifiedRegular) {
877 // cfi.functions metadata is intended to be used with ThinLTO and may
878 // trigger invalid IR transformations if they are present when doing regular
879 // LTO, so delete it.
880 if (NamedMDNode *CfiFunctionsMD = M.getNamedMetadata("cfi.functions"))
881 M.eraseNamedMetadata(CfiFunctionsMD);
882 } else if (NamedMDNode *AliasesMD = M.getNamedMetadata("aliases")) {
883 // Delete aliases entries for non-prevailing symbols on the ThinLTO side of
884 // this input file.
885 DenseSet<StringRef> Prevailing;
886 for (auto [I, R] : zip(Input.symbols(), InputRes))
887 if (R.Prevailing && !I.getIRName().empty())
888 Prevailing.insert(I.getIRName());
889 std::vector<MDNode *> AliasGroups;
890 for (MDNode *AliasGroup : AliasesMD->operands()) {
891 std::vector<Metadata *> Aliases;
892 for (Metadata *Alias : AliasGroup->operands()) {
893 if (isa<MDString>(Alias) &&
894 Prevailing.count(cast<MDString>(Alias)->getString()))
895 Aliases.push_back(Alias);
896 }
897 if (Aliases.size() > 1)
898 AliasGroups.push_back(MDTuple::get(RegularLTO.Ctx, Aliases));
899 }
900 AliasesMD->clearOperands();
901 for (MDNode *G : AliasGroups)
902 AliasesMD->addOperand(G);
903 }
904
906
907 ModuleSymbolTable SymTab;
908 SymTab.addModule(&M);
909
910 for (GlobalVariable &GV : M.globals())
911 if (GV.hasAppendingLinkage())
912 Mod.Keep.push_back(&GV);
913
914 DenseSet<GlobalObject *> AliasedGlobals;
915 for (auto &GA : M.aliases())
916 if (GlobalObject *GO = GA.getAliaseeObject())
917 AliasedGlobals.insert(GO);
918
919 // In this function we need IR GlobalValues matching the symbols in Syms
920 // (which is not backed by a module), so we need to enumerate them in the same
921 // order. The symbol enumeration order of a ModuleSymbolTable intentionally
922 // matches the order of an irsymtab, but when we read the irsymtab in
923 // InputFile::create we omit some symbols that are irrelevant to LTO. The
924 // Skip() function skips the same symbols from the module as InputFile does
925 // from the symbol table.
926 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
927 auto Skip = [&]() {
928 while (MsymI != MsymE) {
929 auto Flags = SymTab.getSymbolFlags(*MsymI);
930 if ((Flags & object::BasicSymbolRef::SF_Global) &&
932 return;
933 ++MsymI;
934 }
935 };
936 Skip();
937
938 std::set<const Comdat *> NonPrevailingComdats;
939 SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
940 for (const InputFile::Symbol &Sym : Syms) {
941 assert(!Res.empty());
942 const SymbolResolution &R = Res.consume_front();
943
944 assert(MsymI != MsymE);
945 ModuleSymbolTable::Symbol Msym = *MsymI++;
946 Skip();
947
948 if (GlobalValue *GV = dyn_cast_if_present<GlobalValue *>(Msym)) {
949 if (R.Prevailing) {
950 if (Sym.isUndefined())
951 continue;
952 Mod.Keep.push_back(GV);
953 // For symbols re-defined with linker -wrap and -defsym options,
954 // set the linkage to weak to inhibit IPO. The linkage will be
955 // restored by the linker.
956 if (R.LinkerRedefined)
957 GV->setLinkage(GlobalValue::WeakAnyLinkage);
958
959 GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
960 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
961 GV->setLinkage(GlobalValue::getWeakLinkage(
962 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
963 } else if (isa<GlobalObject>(GV) &&
964 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
965 GV->hasAvailableExternallyLinkage()) &&
966 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
967 // Any of the above three types of linkage indicates that the
968 // chosen prevailing symbol will have the same semantics as this copy of
969 // the symbol, so we may be able to link it with available_externally
970 // linkage. We will decide later whether to do that when we link this
971 // module (in linkRegularLTO), based on whether it is undefined.
972 Mod.Keep.push_back(GV);
974 if (GV->hasComdat())
975 NonPrevailingComdats.insert(GV->getComdat());
976 cast<GlobalObject>(GV)->setComdat(nullptr);
977 }
978
979 // Set the 'local' flag based on the linker resolution for this symbol.
980 if (R.FinalDefinitionInLinkageUnit) {
981 GV->setDSOLocal(true);
982 if (GV->hasDLLImportStorageClass())
983 GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
984 DefaultStorageClass);
985 }
986 } else if (auto *AS =
988 // Collect non-prevailing symbols.
989 if (!R.Prevailing)
990 NonPrevailingAsmSymbols.insert(AS->first);
991 } else {
992 llvm_unreachable("unknown symbol type");
993 }
994
995 // Common resolution: collect the maximum size/alignment over all commons.
996 // We also record if we see an instance of a common as prevailing, so that
997 // if none is prevailing we can ignore it later.
998 if (Sym.isCommon()) {
999 // FIXME: We should figure out what to do about commons defined by asm.
1000 // For now they aren't reported correctly by ModuleSymbolTable.
1001 auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
1002 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
1003 if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
1004 CommonRes.Alignment =
1005 std::max(Align(SymAlignValue), CommonRes.Alignment);
1006 }
1007 CommonRes.Prevailing |= R.Prevailing;
1008 }
1009 }
1010
1011 if (!M.getComdatSymbolTable().empty())
1012 for (GlobalValue &GV : M.global_values())
1013 handleNonPrevailingComdat(GV, NonPrevailingComdats);
1014
1015 // Prepend ".lto_discard <sym>, <sym>*" directive to each module inline asm
1016 // block.
1017 if (!M.getModuleInlineAsm().empty()) {
1018 std::string NewIA = ".lto_discard";
1019 if (!NonPrevailingAsmSymbols.empty()) {
1020 // Don't dicard a symbol if there is a live .symver for it.
1022 M, [&](StringRef Name, StringRef Alias) {
1023 if (!NonPrevailingAsmSymbols.count(Alias))
1024 NonPrevailingAsmSymbols.erase(Name);
1025 });
1026 NewIA += " " + llvm::join(NonPrevailingAsmSymbols, ", ");
1027 }
1028 NewIA += "\n";
1029 M.setModuleInlineAsm(NewIA + M.getModuleInlineAsm());
1030 }
1031
1032 assert(MsymI == MsymE);
1033 return std::make_pair(std::move(Mod), Res);
1034}
1035
1036Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
1037 bool LivenessFromIndex) {
1038 llvm::TimeTraceScope timeScope("LTO link regular LTO");
1039 std::vector<GlobalValue *> Keep;
1040 for (GlobalValue *GV : Mod.Keep) {
1041 if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
1042 if (Function *F = dyn_cast<Function>(GV)) {
1043 if (DiagnosticOutputFile) {
1044 if (Error Err = F->materialize())
1045 return Err;
1046 OptimizationRemarkEmitter ORE(F, nullptr);
1047 ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
1048 << ore::NV("Function", F)
1049 << " not added to the combined module ");
1050 }
1051 }
1052 continue;
1053 }
1054
1055 if (!GV->hasAvailableExternallyLinkage()) {
1056 Keep.push_back(GV);
1057 continue;
1058 }
1059
1060 // Only link available_externally definitions if we don't already have a
1061 // definition.
1062 GlobalValue *CombinedGV =
1063 RegularLTO.CombinedModule->getNamedValue(GV->getName());
1064 if (CombinedGV && !CombinedGV->isDeclaration())
1065 continue;
1066
1067 Keep.push_back(GV);
1068 }
1069
1070 return RegularLTO.Mover->move(std::move(Mod.M), Keep, nullptr,
1071 /* IsPerformingImport */ false);
1072}
1073
1074// Add a ThinLTO module to the link.
1075Expected<ArrayRef<SymbolResolution>>
1076LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
1078 llvm::TimeTraceScope timeScope("LTO add thin LTO");
1079 const auto BMID = BM.getModuleIdentifier();
1080 ArrayRef<SymbolResolution> ResTmp = Res;
1081 for (const InputFile::Symbol &Sym : Syms) {
1082 assert(!ResTmp.empty());
1083 const SymbolResolution &R = ResTmp.consume_front();
1084
1085 if (!Sym.getIRName().empty() && R.Prevailing) {
1087 GlobalValue::getGlobalIdentifier(Sym.getIRName(),
1089 ThinLTO.setPrevailingModuleForGUID(GUID, BMID);
1090 }
1091 }
1092
1093 if (Error Err = BM.readSummary(
1094 ThinLTO.CombinedIndex, BMID, [&](GlobalValue::GUID GUID) {
1095 return ThinLTO.isPrevailingModuleForGUID(GUID, BMID);
1096 }))
1097 return Err;
1098 LLVM_DEBUG(dbgs() << "Module " << BMID << "\n");
1099
1100 for (const InputFile::Symbol &Sym : Syms) {
1101 assert(!Res.empty());
1102 const SymbolResolution &R = Res.consume_front();
1103
1104 if (!Sym.getIRName().empty() &&
1105 (R.Prevailing || R.FinalDefinitionInLinkageUnit)) {
1107 GlobalValue::getGlobalIdentifier(Sym.getIRName(),
1109 if (R.Prevailing) {
1110 assert(ThinLTO.isPrevailingModuleForGUID(GUID, BMID));
1111
1112 // For linker redefined symbols (via --wrap or --defsym) we want to
1113 // switch the linkage to `weak` to prevent IPOs from happening.
1114 // Find the summary in the module for this very GV and record the new
1115 // linkage so that we can switch it when we import the GV.
1116 if (R.LinkerRedefined)
1117 if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID))
1118 S->setLinkage(GlobalValue::WeakAnyLinkage);
1119 }
1120
1121 // If the linker resolved the symbol to a local definition then mark it
1122 // as local in the summary for the module we are adding.
1123 if (R.FinalDefinitionInLinkageUnit) {
1124 if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID)) {
1125 S->setDSOLocal(true);
1126 }
1127 }
1128 }
1129 }
1130
1131 if (!ThinLTO.ModuleMap.insert({BMID, BM}).second)
1133 "Expected at most one ThinLTO module per bitcode file",
1135
1136 if (!Conf.ThinLTOModulesToCompile.empty()) {
1137 if (!ThinLTO.ModulesToCompile)
1138 ThinLTO.ModulesToCompile = ModuleMapType();
1139 // This is a fuzzy name matching where only modules with name containing the
1140 // specified switch values are going to be compiled.
1141 for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
1142 if (BMID.contains(Name)) {
1143 ThinLTO.ModulesToCompile->insert({BMID, BM});
1144 LLVM_DEBUG(dbgs() << "[ThinLTO] Selecting " << BMID << " to compile\n");
1145 break;
1146 }
1147 }
1148 }
1149
1150 return Res;
1151}
1152
1153unsigned LTO::getMaxTasks() const {
1154 CalledGetMaxTasks = true;
1155 auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
1156 : ThinLTO.ModuleMap.size();
1157 return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
1158}
1159
1160// If only some of the modules were split, we cannot correctly handle
1161// code that contains type tests or type checked loads.
1162Error LTO::checkPartiallySplit() {
1163 if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
1164 return Error::success();
1165
1166 const Module *Combined = RegularLTO.CombinedModule.get();
1167 Function *TypeTestFunc =
1168 Intrinsic::getDeclarationIfExists(Combined, Intrinsic::type_test);
1169 Function *TypeCheckedLoadFunc =
1170 Intrinsic::getDeclarationIfExists(Combined, Intrinsic::type_checked_load);
1171 Function *TypeCheckedLoadRelativeFunc = Intrinsic::getDeclarationIfExists(
1172 Combined, Intrinsic::type_checked_load_relative);
1173
1174 // First check if there are type tests / type checked loads in the
1175 // merged regular LTO module IR.
1176 if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
1177 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()) ||
1178 (TypeCheckedLoadRelativeFunc &&
1179 !TypeCheckedLoadRelativeFunc->use_empty()))
1181 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1183
1184 // Otherwise check if there are any recorded in the combined summary from the
1185 // ThinLTO modules.
1186 for (auto &P : ThinLTO.CombinedIndex) {
1187 for (auto &S : P.second.getSummaryList()) {
1188 auto *FS = dyn_cast<FunctionSummary>(S.get());
1189 if (!FS)
1190 continue;
1191 if (!FS->type_test_assume_vcalls().empty() ||
1192 !FS->type_checked_load_vcalls().empty() ||
1193 !FS->type_test_assume_const_vcalls().empty() ||
1194 !FS->type_checked_load_const_vcalls().empty() ||
1195 !FS->type_tests().empty())
1197 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1199 }
1200 }
1201 return Error::success();
1202}
1203
1205 // Compute "dead" symbols, we don't want to import/export these!
1206 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1207 DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
1208 for (auto &Res : *GlobalResolutions) {
1209 // Normally resolution have IR name of symbol. We can do nothing here
1210 // otherwise. See comments in GlobalResolution struct for more details.
1211 if (Res.second.IRName.empty())
1212 continue;
1213
1215 GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1216
1217 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1218 GUIDPreservedSymbols.insert(GUID);
1219
1220 if (Res.second.ExportDynamic)
1221 DynamicExportSymbols.insert(GUID);
1222
1223 GUIDPrevailingResolutions[GUID] =
1224 Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
1225 }
1226
1227 auto isPrevailing = [&](GlobalValue::GUID G) {
1228 auto It = GUIDPrevailingResolutions.find(G);
1229 if (It == GUIDPrevailingResolutions.end())
1231 return It->second;
1232 };
1233 computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
1234 isPrevailing, Conf.OptLevel > 0);
1235
1236 // Setup output file to emit statistics.
1237 auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
1238 if (!StatsFileOrErr)
1239 return StatsFileOrErr.takeError();
1240 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1241
1242 // TODO: Ideally this would be controlled automatically by detecting that we
1243 // are linking with an allocator that supports these interfaces, rather than
1244 // an internal option (which would still be needed for tests, however). For
1245 // example, if the library exported a symbol like __malloc_hot_cold the linker
1246 // could recognize that and set a flag in the lto::Config.
1248 ThinLTO.CombinedIndex.setWithSupportsHotColdNew();
1249
1250 Error Result = runRegularLTO(AddStream);
1251 if (!Result)
1252 // This will reset the GlobalResolutions optional once done with it to
1253 // reduce peak memory before importing.
1254 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1255
1256 if (StatsFile)
1257 PrintStatisticsJSON(StatsFile->os());
1258
1259 return Result;
1260}
1261
1262Error LTO::runRegularLTO(AddStreamFn AddStream) {
1263 llvm::TimeTraceScope timeScope("Run regular LTO");
1264 LLVMContext &CombinedCtx = RegularLTO.CombinedModule->getContext();
1265 // Setup optimization remarks.
1266 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1267 CombinedCtx, Conf.RemarksFilename, Conf.RemarksPasses, Conf.RemarksFormat,
1269 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
1270 if (!DiagFileOrErr)
1271 return DiagFileOrErr.takeError();
1272 DiagnosticOutputFile = std::move(*DiagFileOrErr);
1273
1274 // Finalize linking of regular LTO modules containing summaries now that
1275 // we have computed liveness information.
1276 {
1277 llvm::TimeTraceScope timeScope("Link regular LTO");
1278 for (auto &M : RegularLTO.ModsWithSummaries)
1279 if (Error Err = linkRegularLTO(std::move(M), /*LivenessFromIndex=*/true))
1280 return Err;
1281 }
1282
1283 // Ensure we don't have inconsistently split LTO units with type tests.
1284 // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
1285 // this path both cases but eventually this should be split into two and
1286 // do the ThinLTO checks in `runThinLTO`.
1287 if (Error Err = checkPartiallySplit())
1288 return Err;
1289
1290 // Make sure commons have the right size/alignment: we kept the largest from
1291 // all the prevailing when adding the inputs, and we apply it here.
1292 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
1293 for (auto &I : RegularLTO.Commons) {
1294 if (!I.second.Prevailing)
1295 // Don't do anything if no instance of this common was prevailing.
1296 continue;
1297 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
1298 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
1299 // Don't create a new global if the type is already correct, just make
1300 // sure the alignment is correct.
1301 OldGV->setAlignment(I.second.Alignment);
1302 continue;
1303 }
1304 ArrayType *Ty =
1305 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
1306 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
1309 GV->setAlignment(I.second.Alignment);
1310 if (OldGV) {
1311 OldGV->replaceAllUsesWith(GV);
1312 GV->takeName(OldGV);
1313 OldGV->eraseFromParent();
1314 } else {
1315 GV->setName(I.first);
1316 }
1317 }
1318
1319 bool WholeProgramVisibilityEnabledInLTO =
1320 Conf.HasWholeProgramVisibility &&
1321 // If validation is enabled, upgrade visibility only when all vtables
1322 // have typeinfos.
1323 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1324
1325 // This returns true when the name is local or not defined. Locals are
1326 // expected to be handled separately.
1327 auto IsVisibleToRegularObj = [&](StringRef name) {
1328 auto It = GlobalResolutions->find(name);
1329 return (It == GlobalResolutions->end() ||
1330 It->second.VisibleOutsideSummary || !It->second.Prevailing);
1331 };
1332
1333 // If allowed, upgrade public vcall visibility metadata to linkage unit
1334 // visibility before whole program devirtualization in the optimizer.
1336 *RegularLTO.CombinedModule, WholeProgramVisibilityEnabledInLTO,
1337 DynamicExportSymbols, Conf.ValidateAllVtablesHaveTypeInfos,
1338 IsVisibleToRegularObj);
1339 updatePublicTypeTestCalls(*RegularLTO.CombinedModule,
1340 WholeProgramVisibilityEnabledInLTO);
1341
1342 if (Conf.PreOptModuleHook &&
1343 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1344 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1345
1346 if (!Conf.CodeGenOnly) {
1347 for (const auto &R : *GlobalResolutions) {
1348 GlobalValue *GV =
1349 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
1350 if (!R.second.isPrevailingIRSymbol())
1351 continue;
1352 if (R.second.Partition != 0 &&
1353 R.second.Partition != GlobalResolution::External)
1354 continue;
1355
1356 // Ignore symbols defined in other partitions.
1357 // Also skip declarations, which are not allowed to have internal linkage.
1358 if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1359 continue;
1360
1361 // Symbols that are marked DLLImport or DLLExport should not be
1362 // internalized, as they are either externally visible or referencing
1363 // external symbols. Symbols that have AvailableExternally or Appending
1364 // linkage might be used by future passes and should be kept as is.
1365 // These linkages are seen in Unified regular LTO, because the process
1366 // of creating split LTO units introduces symbols with that linkage into
1367 // one of the created modules. Normally, only the ThinLTO backend would
1368 // compile this module, but Unified Regular LTO processes both
1369 // modules created by the splitting process as regular LTO modules.
1370 if ((LTOMode == LTOKind::LTOK_UnifiedRegular) &&
1373 continue;
1374
1375 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1377 if (EnableLTOInternalization && R.second.Partition == 0)
1379 }
1380
1381 if (Conf.PostInternalizeModuleHook &&
1382 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1383 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1384 }
1385
1386 if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1387 if (Error Err =
1388 backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1389 *RegularLTO.CombinedModule, ThinLTO.CombinedIndex))
1390 return Err;
1391 }
1392
1393 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1394}
1395
1397 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
1398 SmallVector<const char *> LibcallSymbols;
1399 LibcallSymbols.reserve(Libcalls.getNumAvailableLibcallImpls());
1400
1401 for (RTLIB::LibcallImpl Impl : RTLIB::libcall_impls()) {
1402 if (Libcalls.isAvailable(Impl))
1403 LibcallSymbols.push_back(Libcalls.getLibcallImplName(Impl).data());
1404 }
1405
1406 return LibcallSymbols;
1407}
1408
1410 const FunctionImporter::ImportMapTy &ImportList, llvm::StringRef ModulePath,
1411 const std::string &NewModulePath) const {
1412 return emitFiles(ImportList, ModulePath, NewModulePath,
1413 NewModulePath + ".thinlto.bc",
1414 /*ImportsFiles=*/std::nullopt);
1415}
1416
1418 const FunctionImporter::ImportMapTy &ImportList, llvm::StringRef ModulePath,
1419 const std::string &NewModulePath, StringRef SummaryPath,
1420 std::optional<std::reference_wrapper<ImportsFilesContainer>> ImportsFiles)
1421 const {
1422 ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
1423 GVSummaryPtrSet DeclarationSummaries;
1424
1425 std::error_code EC;
1427 ImportList, ModuleToSummariesForIndex,
1428 DeclarationSummaries);
1429
1430 raw_fd_ostream OS(SummaryPath, EC, sys::fs::OpenFlags::OF_None);
1431 if (EC)
1432 return createFileError("cannot open " + Twine(SummaryPath), EC);
1433
1434 writeIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex,
1435 &DeclarationSummaries);
1436
1438 Error ImportsFilesError = EmitImportsFiles(
1439 ModulePath, NewModulePath + ".imports", ModuleToSummariesForIndex);
1440 if (ImportsFilesError)
1441 return ImportsFilesError;
1442 }
1443
1444 // Optionally, store the imports files.
1445 if (ImportsFiles)
1447 ModulePath, ModuleToSummariesForIndex,
1448 [&](StringRef M) { ImportsFiles->get().push_back(M.str()); });
1449
1450 return Error::success();
1451}
1452
1453namespace {
1454/// Base class for ThinLTO backends that perform code generation and insert the
1455/// generated files back into the link.
1456class CGThinBackend : public ThinBackendProc {
1457protected:
1458 AddStreamFn AddStream;
1459 DenseSet<GlobalValue::GUID> CfiFunctionDefs;
1460 DenseSet<GlobalValue::GUID> CfiFunctionDecls;
1461 bool ShouldEmitIndexFiles;
1462
1463public:
1464 CGThinBackend(
1465 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1466 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1467 AddStreamFn AddStream, lto::IndexWriteCallback OnWrite,
1468 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
1469 ThreadPoolStrategy ThinLTOParallelism)
1470 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1471 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1472 AddStream(std::move(AddStream)),
1473 ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
1474 auto &Defs = CombinedIndex.cfiFunctionDefs();
1475 CfiFunctionDefs.insert_range(Defs.guids());
1476 auto &Decls = CombinedIndex.cfiFunctionDecls();
1477 CfiFunctionDecls.insert_range(Decls.guids());
1478 }
1479};
1480
1481/// This backend performs code generation by scheduling a job to run on
1482/// an in-process thread when invoked for each task.
1483class InProcessThinBackend : public CGThinBackend {
1484protected:
1485 FileCache Cache;
1486
1487public:
1488 InProcessThinBackend(
1489 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1490 ThreadPoolStrategy ThinLTOParallelism,
1491 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1492 AddStreamFn AddStream, FileCache Cache, lto::IndexWriteCallback OnWrite,
1493 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles)
1494 : CGThinBackend(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1495 AddStream, OnWrite, ShouldEmitIndexFiles,
1496 ShouldEmitImportsFiles, ThinLTOParallelism),
1497 Cache(std::move(Cache)) {}
1498
1499 virtual Error runThinLTOBackendThread(
1500 AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1501 ModuleSummaryIndex &CombinedIndex,
1502 const FunctionImporter::ImportMapTy &ImportList,
1503 const FunctionImporter::ExportSetTy &ExportList,
1504 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1505 const GVSummaryMapTy &DefinedGlobals,
1506 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1507 auto ModuleID = BM.getModuleIdentifier();
1508 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (in-process)",
1509 ModuleID);
1510 auto RunThinBackend = [&](AddStreamFn AddStream) {
1511 LTOLLVMContext BackendContext(Conf);
1512 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1513 if (!MOrErr)
1514 return MOrErr.takeError();
1515
1516 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1517 ImportList, DefinedGlobals, &ModuleMap,
1518 Conf.CodeGenOnly);
1519 };
1520 if (ShouldEmitIndexFiles) {
1521 if (auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
1522 return E;
1523 }
1524
1525 if (!Cache.isValid() || !CombinedIndex.modulePaths().count(ModuleID) ||
1526 all_of(CombinedIndex.getModuleHash(ModuleID),
1527 [](uint32_t V) { return V == 0; }))
1528 // Cache disabled or no entry for this module in the combined index or
1529 // no module hash.
1530 return RunThinBackend(AddStream);
1531
1532 // The module may be cached, this helps handling it.
1533 std::string Key = computeLTOCacheKey(
1534 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1535 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1536 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1537 if (Error Err = CacheAddStreamOrErr.takeError())
1538 return Err;
1539 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1540 if (CacheAddStream)
1541 return RunThinBackend(CacheAddStream);
1542
1543 return Error::success();
1544 }
1545
1546 Error start(
1547 unsigned Task, BitcodeModule BM,
1548 const FunctionImporter::ImportMapTy &ImportList,
1549 const FunctionImporter::ExportSetTy &ExportList,
1550 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1551 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1552 StringRef ModulePath = BM.getModuleIdentifier();
1553 assert(ModuleToDefinedGVSummaries.count(ModulePath));
1554 const GVSummaryMapTy &DefinedGlobals =
1555 ModuleToDefinedGVSummaries.find(ModulePath)->second;
1556 BackendThreadPool.async(
1557 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1558 const FunctionImporter::ImportMapTy &ImportList,
1559 const FunctionImporter::ExportSetTy &ExportList,
1560 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1561 &ResolvedODR,
1562 const GVSummaryMapTy &DefinedGlobals,
1563 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1564 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1566 "thin backend");
1567 Error E = runThinLTOBackendThread(
1568 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1569 ResolvedODR, DefinedGlobals, ModuleMap);
1570 if (E) {
1571 std::unique_lock<std::mutex> L(ErrMu);
1572 if (Err)
1573 Err = joinErrors(std::move(*Err), std::move(E));
1574 else
1575 Err = std::move(E);
1576 }
1577 if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1579 },
1580 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1581 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1582
1583 if (OnWrite)
1584 OnWrite(std::string(ModulePath));
1585 return Error::success();
1586 }
1587};
1588
1589/// This backend is utilized in the first round of a two-codegen round process.
1590/// It first saves optimized bitcode files to disk before the codegen process
1591/// begins. After codegen, it stores the resulting object files in a scratch
1592/// buffer. Note the codegen data stored in the scratch buffer will be extracted
1593/// and merged in the subsequent step.
1594class FirstRoundThinBackend : public InProcessThinBackend {
1595 AddStreamFn IRAddStream;
1596 FileCache IRCache;
1597
1598public:
1599 FirstRoundThinBackend(
1600 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1601 ThreadPoolStrategy ThinLTOParallelism,
1602 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1603 AddStreamFn CGAddStream, FileCache CGCache, AddStreamFn IRAddStream,
1604 FileCache IRCache)
1605 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1606 ModuleToDefinedGVSummaries, std::move(CGAddStream),
1607 std::move(CGCache), /*OnWrite=*/nullptr,
1608 /*ShouldEmitIndexFiles=*/false,
1609 /*ShouldEmitImportsFiles=*/false),
1610 IRAddStream(std::move(IRAddStream)), IRCache(std::move(IRCache)) {}
1611
1612 Error runThinLTOBackendThread(
1613 AddStreamFn CGAddStream, FileCache CGCache, unsigned Task,
1614 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1615 const FunctionImporter::ImportMapTy &ImportList,
1616 const FunctionImporter::ExportSetTy &ExportList,
1617 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1618 const GVSummaryMapTy &DefinedGlobals,
1619 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1620 auto ModuleID = BM.getModuleIdentifier();
1621 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (first round)",
1622 ModuleID);
1623 auto RunThinBackend = [&](AddStreamFn CGAddStream,
1624 AddStreamFn IRAddStream) {
1625 LTOLLVMContext BackendContext(Conf);
1626 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1627 if (!MOrErr)
1628 return MOrErr.takeError();
1629
1630 return thinBackend(Conf, Task, CGAddStream, **MOrErr, CombinedIndex,
1631 ImportList, DefinedGlobals, &ModuleMap,
1632 Conf.CodeGenOnly, IRAddStream);
1633 };
1634 // Like InProcessThinBackend, we produce index files as needed for
1635 // FirstRoundThinBackend. However, these files are not generated for
1636 // SecondRoundThinBackend.
1637 if (ShouldEmitIndexFiles) {
1638 if (auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
1639 return E;
1640 }
1641
1642 assert((CGCache.isValid() == IRCache.isValid()) &&
1643 "Both caches for CG and IR should have matching availability");
1644 if (!CGCache.isValid() || !CombinedIndex.modulePaths().count(ModuleID) ||
1645 all_of(CombinedIndex.getModuleHash(ModuleID),
1646 [](uint32_t V) { return V == 0; }))
1647 // Cache disabled or no entry for this module in the combined index or
1648 // no module hash.
1649 return RunThinBackend(CGAddStream, IRAddStream);
1650
1651 // Get CGKey for caching object in CGCache.
1652 std::string CGKey = computeLTOCacheKey(
1653 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1654 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1655 Expected<AddStreamFn> CacheCGAddStreamOrErr =
1656 CGCache(Task, CGKey, ModuleID);
1657 if (Error Err = CacheCGAddStreamOrErr.takeError())
1658 return Err;
1659 AddStreamFn &CacheCGAddStream = *CacheCGAddStreamOrErr;
1660
1661 // Get IRKey for caching (optimized) IR in IRCache with an extra ID.
1662 std::string IRKey = recomputeLTOCacheKey(CGKey, /*ExtraID=*/"IR");
1663 Expected<AddStreamFn> CacheIRAddStreamOrErr =
1664 IRCache(Task, IRKey, ModuleID);
1665 if (Error Err = CacheIRAddStreamOrErr.takeError())
1666 return Err;
1667 AddStreamFn &CacheIRAddStream = *CacheIRAddStreamOrErr;
1668
1669 // Ideally, both CG and IR caching should be synchronized. However, in
1670 // practice, their availability may differ due to different expiration
1671 // times. Therefore, if either cache is missing, the backend process is
1672 // triggered.
1673 if (CacheCGAddStream || CacheIRAddStream) {
1674 LLVM_DEBUG(dbgs() << "[FirstRound] Cache Miss for "
1675 << BM.getModuleIdentifier() << "\n");
1676 return RunThinBackend(CacheCGAddStream ? CacheCGAddStream : CGAddStream,
1677 CacheIRAddStream ? CacheIRAddStream : IRAddStream);
1678 }
1679
1680 return Error::success();
1681 }
1682};
1683
1684/// This backend operates in the second round of a two-codegen round process.
1685/// It starts by reading the optimized bitcode files that were saved during the
1686/// first round. The backend then executes the codegen only to further optimize
1687/// the code, utilizing the codegen data merged from the first round. Finally,
1688/// it writes the resulting object files as usual.
1689class SecondRoundThinBackend : public InProcessThinBackend {
1690 std::unique_ptr<SmallVector<StringRef>> IRFiles;
1691 stable_hash CombinedCGDataHash;
1692
1693public:
1694 SecondRoundThinBackend(
1695 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1696 ThreadPoolStrategy ThinLTOParallelism,
1697 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1698 AddStreamFn AddStream, FileCache Cache,
1699 std::unique_ptr<SmallVector<StringRef>> IRFiles,
1700 stable_hash CombinedCGDataHash)
1701 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1702 ModuleToDefinedGVSummaries, std::move(AddStream),
1703 std::move(Cache),
1704 /*OnWrite=*/nullptr,
1705 /*ShouldEmitIndexFiles=*/false,
1706 /*ShouldEmitImportsFiles=*/false),
1707 IRFiles(std::move(IRFiles)), CombinedCGDataHash(CombinedCGDataHash) {}
1708
1709 Error runThinLTOBackendThread(
1710 AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1711 ModuleSummaryIndex &CombinedIndex,
1712 const FunctionImporter::ImportMapTy &ImportList,
1713 const FunctionImporter::ExportSetTy &ExportList,
1714 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1715 const GVSummaryMapTy &DefinedGlobals,
1716 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1717 auto ModuleID = BM.getModuleIdentifier();
1718 llvm::TimeTraceScope timeScope("Run ThinLTO backend thread (second round)",
1719 ModuleID);
1720 auto RunThinBackend = [&](AddStreamFn AddStream) {
1721 LTOLLVMContext BackendContext(Conf);
1722 std::unique_ptr<Module> LoadedModule =
1723 cgdata::loadModuleForTwoRounds(BM, Task, BackendContext, *IRFiles);
1724
1725 return thinBackend(Conf, Task, AddStream, *LoadedModule, CombinedIndex,
1726 ImportList, DefinedGlobals, &ModuleMap,
1727 /*CodeGenOnly=*/true);
1728 };
1729 if (!Cache.isValid() || !CombinedIndex.modulePaths().count(ModuleID) ||
1730 all_of(CombinedIndex.getModuleHash(ModuleID),
1731 [](uint32_t V) { return V == 0; }))
1732 // Cache disabled or no entry for this module in the combined index or
1733 // no module hash.
1734 return RunThinBackend(AddStream);
1735
1736 // Get Key for caching the final object file in Cache with the combined
1737 // CGData hash.
1738 std::string Key = computeLTOCacheKey(
1739 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1740 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1742 /*ExtraID=*/std::to_string(CombinedCGDataHash));
1743 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1744 if (Error Err = CacheAddStreamOrErr.takeError())
1745 return Err;
1746 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1747
1748 if (CacheAddStream) {
1749 LLVM_DEBUG(dbgs() << "[SecondRound] Cache Miss for "
1750 << BM.getModuleIdentifier() << "\n");
1751 return RunThinBackend(CacheAddStream);
1752 }
1753
1754 return Error::success();
1755 }
1756};
1757} // end anonymous namespace
1758
1761 bool ShouldEmitIndexFiles,
1762 bool ShouldEmitImportsFiles) {
1763 auto Func =
1764 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1765 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1766 AddStreamFn AddStream, FileCache Cache) {
1767 return std::make_unique<InProcessThinBackend>(
1768 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
1769 AddStream, Cache, OnWrite, ShouldEmitIndexFiles,
1770 ShouldEmitImportsFiles);
1771 };
1772 return ThinBackend(Func, Parallelism);
1773}
1774
1776 if (!TheTriple.isOSDarwin())
1777 return "";
1778 if (TheTriple.getArch() == Triple::x86_64)
1779 return "core2";
1780 if (TheTriple.getArch() == Triple::x86)
1781 return "yonah";
1782 if (TheTriple.isArm64e())
1783 return "apple-a12";
1784 if (TheTriple.getArch() == Triple::aarch64 ||
1785 TheTriple.getArch() == Triple::aarch64_32)
1786 return "cyclone";
1787 return "";
1788}
1789
1790// Given the original \p Path to an output file, replace any path
1791// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1792// resulting directory if it does not yet exist.
1794 StringRef NewPrefix) {
1795 if (OldPrefix.empty() && NewPrefix.empty())
1796 return std::string(Path);
1797 SmallString<128> NewPath(Path);
1798 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
1799 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
1800 if (!ParentPath.empty()) {
1801 // Make sure the new directory exists, creating it if necessary.
1802 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
1803 llvm::errs() << "warning: could not create directory '" << ParentPath
1804 << "': " << EC.message() << '\n';
1805 }
1806 return std::string(NewPath);
1807}
1808
1809namespace {
1810class WriteIndexesThinBackend : public ThinBackendProc {
1811 std::string OldPrefix, NewPrefix, NativeObjectPrefix;
1812 raw_fd_ostream *LinkedObjectsFile;
1813
1814public:
1815 WriteIndexesThinBackend(
1816 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1817 ThreadPoolStrategy ThinLTOParallelism,
1818 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1819 std::string OldPrefix, std::string NewPrefix,
1820 std::string NativeObjectPrefix, bool ShouldEmitImportsFiles,
1821 raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
1822 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1823 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1824 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1825 NativeObjectPrefix(NativeObjectPrefix),
1826 LinkedObjectsFile(LinkedObjectsFile) {}
1827
1828 Error start(
1829 unsigned Task, BitcodeModule BM,
1830 const FunctionImporter::ImportMapTy &ImportList,
1831 const FunctionImporter::ExportSetTy &ExportList,
1832 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1833 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1834 StringRef ModulePath = BM.getModuleIdentifier();
1835
1836 // The contents of this file may be used as input to a native link, and must
1837 // therefore contain the processed modules in a determinstic order that
1838 // match the order they are provided on the command line. For that reason,
1839 // we cannot include this in the asynchronously executed lambda below.
1840 if (LinkedObjectsFile) {
1841 std::string ObjectPrefix =
1842 NativeObjectPrefix.empty() ? NewPrefix : NativeObjectPrefix;
1843 std::string LinkedObjectsFilePath =
1844 getThinLTOOutputFile(ModulePath, OldPrefix, ObjectPrefix);
1845 *LinkedObjectsFile << LinkedObjectsFilePath << '\n';
1846 }
1847
1848 BackendThreadPool.async(
1849 [this](const StringRef ModulePath,
1850 const FunctionImporter::ImportMapTy &ImportList,
1851 const std::string &OldPrefix, const std::string &NewPrefix) {
1852 std::string NewModulePath =
1853 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
1854 auto E = emitFiles(ImportList, ModulePath, NewModulePath);
1855 if (E) {
1856 std::unique_lock<std::mutex> L(ErrMu);
1857 if (Err)
1858 Err = joinErrors(std::move(*Err), std::move(E));
1859 else
1860 Err = std::move(E);
1861 return;
1862 }
1863 },
1864 ModulePath, ImportList, OldPrefix, NewPrefix);
1865
1866 if (OnWrite)
1867 OnWrite(std::string(ModulePath));
1868 return Error::success();
1869 }
1870
1871 bool isSensitiveToInputOrder() override {
1872 // The order which modules are written to LinkedObjectsFile should be
1873 // deterministic and match the order they are passed on the command line.
1874 return true;
1875 }
1876};
1877} // end anonymous namespace
1878
1880 ThreadPoolStrategy Parallelism, std::string OldPrefix,
1881 std::string NewPrefix, std::string NativeObjectPrefix,
1882 bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
1883 IndexWriteCallback OnWrite) {
1884 auto Func =
1885 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1886 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1887 AddStreamFn AddStream, FileCache Cache) {
1888 return std::make_unique<WriteIndexesThinBackend>(
1889 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
1890 OldPrefix, NewPrefix, NativeObjectPrefix, ShouldEmitImportsFiles,
1891 LinkedObjectsFile, OnWrite);
1892 };
1893 return ThinBackend(Func, Parallelism);
1894}
1895
1896Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache,
1897 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
1898 llvm::TimeTraceScope timeScope("Run ThinLTO");
1899 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
1900 ThinLTO.CombinedIndex.releaseTemporaryMemory();
1901 timeTraceProfilerBegin("ThinLink", StringRef(""));
1902 auto TimeTraceScopeExit = llvm::make_scope_exit([]() {
1905 });
1906 if (ThinLTO.ModuleMap.empty())
1907 return Error::success();
1908
1909 if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
1910 llvm::errs() << "warning: [ThinLTO] No module compiled\n";
1911 return Error::success();
1912 }
1913
1914 if (Conf.CombinedIndexHook &&
1915 !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
1916 return Error::success();
1917
1918 // Collect for each module the list of function it defines (GUID ->
1919 // Summary).
1920 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(
1921 ThinLTO.ModuleMap.size());
1922 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1923 ModuleToDefinedGVSummaries);
1924 // Create entries for any modules that didn't have any GV summaries
1925 // (either they didn't have any GVs to start with, or we suppressed
1926 // generation of the summaries because they e.g. had inline assembly
1927 // uses that couldn't be promoted/renamed on export). This is so
1928 // InProcessThinBackend::start can still launch a backend thread, which
1929 // is passed the map of summaries for the module, without any special
1930 // handling for this case.
1931 for (auto &Mod : ThinLTO.ModuleMap)
1932 if (!ModuleToDefinedGVSummaries.count(Mod.first))
1933 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
1934
1935 FunctionImporter::ImportListsTy ImportLists(ThinLTO.ModuleMap.size());
1936 DenseMap<StringRef, FunctionImporter::ExportSetTy> ExportLists(
1937 ThinLTO.ModuleMap.size());
1938 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1939
1940 if (DumpThinCGSCCs)
1941 ThinLTO.CombinedIndex.dumpSCCs(outs());
1942
1943 std::set<GlobalValue::GUID> ExportedGUIDs;
1944
1945 bool WholeProgramVisibilityEnabledInLTO =
1946 Conf.HasWholeProgramVisibility &&
1947 // If validation is enabled, upgrade visibility only when all vtables
1948 // have typeinfos.
1949 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1950 if (hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
1951 ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
1952
1953 // If we're validating, get the vtable symbols that should not be
1954 // upgraded because they correspond to typeIDs outside of index-based
1955 // WPD info.
1956 DenseSet<GlobalValue::GUID> VisibleToRegularObjSymbols;
1957 if (WholeProgramVisibilityEnabledInLTO &&
1958 Conf.ValidateAllVtablesHaveTypeInfos) {
1959 // This returns true when the name is local or not defined. Locals are
1960 // expected to be handled separately.
1961 auto IsVisibleToRegularObj = [&](StringRef name) {
1962 auto It = GlobalResolutions->find(name);
1963 return (It == GlobalResolutions->end() ||
1964 It->second.VisibleOutsideSummary || !It->second.Prevailing);
1965 };
1966
1967 getVisibleToRegularObjVtableGUIDs(ThinLTO.CombinedIndex,
1968 VisibleToRegularObjSymbols,
1969 IsVisibleToRegularObj);
1970 }
1971
1972 // If allowed, upgrade public vcall visibility to linkage unit visibility in
1973 // the summaries before whole program devirtualization below.
1975 ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO,
1976 DynamicExportSymbols, VisibleToRegularObjSymbols);
1977
1978 // Perform index-based WPD. This will return immediately if there are
1979 // no index entries in the typeIdMetadata map (e.g. if we are instead
1980 // performing IR-based WPD in hybrid regular/thin LTO mode).
1981 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1982 runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
1983 LocalWPDTargetsMap);
1984
1985 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
1986 return ThinLTO.isPrevailingModuleForGUID(GUID, S->modulePath());
1987 };
1989 MemProfContextDisambiguation ContextDisambiguation;
1990 ContextDisambiguation.run(ThinLTO.CombinedIndex, isPrevailing);
1991 }
1992
1993 // Figure out which symbols need to be internalized. This also needs to happen
1994 // at -O0 because summary-based DCE is implemented using internalization, and
1995 // we must apply DCE consistently with the full LTO module in order to avoid
1996 // undefined references during the final link.
1997 for (auto &Res : *GlobalResolutions) {
1998 // If the symbol does not have external references or it is not prevailing,
1999 // then not need to mark it as exported from a ThinLTO partition.
2000 if (Res.second.Partition != GlobalResolution::External ||
2001 !Res.second.isPrevailingIRSymbol())
2002 continue;
2004 GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
2005 // Mark exported unless index-based analysis determined it to be dead.
2006 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
2007 ExportedGUIDs.insert(GUID);
2008 }
2009
2010 // Reset the GlobalResolutions to deallocate the associated memory, as there
2011 // are no further accesses. We specifically want to do this before computing
2012 // cross module importing, which adds to peak memory via the computed import
2013 // and export lists.
2014 releaseGlobalResolutionsMemory();
2015
2016 if (Conf.OptLevel > 0)
2017 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2018 isPrevailing, ImportLists, ExportLists);
2019
2020 // Any functions referenced by the jump table in the regular LTO object must
2021 // be exported.
2022 auto &Defs = ThinLTO.CombinedIndex.cfiFunctionDefs();
2023 ExportedGUIDs.insert(Defs.guid_begin(), Defs.guid_end());
2024 auto &Decls = ThinLTO.CombinedIndex.cfiFunctionDecls();
2025 ExportedGUIDs.insert(Decls.guid_begin(), Decls.guid_end());
2026
2027 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
2028 const auto &ExportList = ExportLists.find(ModuleIdentifier);
2029 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
2030 ExportedGUIDs.count(VI.getGUID());
2031 };
2032
2033 // Update local devirtualized targets that were exported by cross-module
2034 // importing or by other devirtualizations marked in the ExportedGUIDs set.
2035 updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
2036 LocalWPDTargetsMap);
2037
2038 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
2039 isPrevailing);
2040
2041 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
2043 GlobalValue::LinkageTypes NewLinkage) {
2044 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
2045 };
2046 thinLTOResolvePrevailingInIndex(Conf, ThinLTO.CombinedIndex, isPrevailing,
2047 recordNewLinkage, GUIDPreservedSymbols);
2048
2049 thinLTOPropagateFunctionAttrs(ThinLTO.CombinedIndex, isPrevailing);
2050
2051 generateParamAccessSummary(ThinLTO.CombinedIndex);
2052
2055
2056 TimeTraceScopeExit.release();
2057
2058 auto &ModuleMap =
2059 ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
2060
2061 auto RunBackends = [&](ThinBackendProc *BackendProcess) -> Error {
2062 auto ProcessOneModule = [&](int I) -> Error {
2063 auto &Mod = *(ModuleMap.begin() + I);
2064 // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
2065 // combined module and parallel code generation partitions.
2066 return BackendProcess->start(
2067 RegularLTO.ParallelCodeGenParallelismLevel + I, Mod.second,
2068 ImportLists[Mod.first], ExportLists[Mod.first],
2069 ResolvedODR[Mod.first], ThinLTO.ModuleMap);
2070 };
2071
2072 BackendProcess->setup(ModuleMap.size(),
2073 RegularLTO.ParallelCodeGenParallelismLevel,
2074 RegularLTO.CombinedModule->getTargetTriple());
2075
2076 if (BackendProcess->getThreadCount() == 1 ||
2077 BackendProcess->isSensitiveToInputOrder()) {
2078 // Process the modules in the order they were provided on the
2079 // command-line. It is important for this codepath to be used for
2080 // WriteIndexesThinBackend, to ensure the emitted LinkedObjectsFile lists
2081 // ThinLTO objects in the same order as the inputs, which otherwise would
2082 // affect the final link order.
2083 for (int I = 0, E = ModuleMap.size(); I != E; ++I)
2084 if (Error E = ProcessOneModule(I))
2085 return E;
2086 } else {
2087 // When executing in parallel, process largest bitsize modules first to
2088 // improve parallelism, and avoid starving the thread pool near the end.
2089 // This saves about 15 sec on a 36-core machine while link `clang.exe`
2090 // (out of 100 sec).
2091 std::vector<BitcodeModule *> ModulesVec;
2092 ModulesVec.reserve(ModuleMap.size());
2093 for (auto &Mod : ModuleMap)
2094 ModulesVec.push_back(&Mod.second);
2095 for (int I : generateModulesOrdering(ModulesVec))
2096 if (Error E = ProcessOneModule(I))
2097 return E;
2098 }
2099 return BackendProcess->wait();
2100 };
2101
2103 std::unique_ptr<ThinBackendProc> BackendProc =
2104 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2105 AddStream, Cache);
2106 return RunBackends(BackendProc.get());
2107 }
2108
2109 // Perform two rounds of code generation for ThinLTO:
2110 // 1. First round: Perform optimization and code generation, outputting to
2111 // temporary scratch objects.
2112 // 2. Merge code generation data extracted from the temporary scratch objects.
2113 // 3. Second round: Execute code generation again using the merged data.
2114 LLVM_DEBUG(dbgs() << "[TwoRounds] Initializing ThinLTO two-codegen rounds\n");
2115
2116 unsigned MaxTasks = getMaxTasks();
2117 auto Parallelism = ThinLTO.Backend.getParallelism();
2118 // Set up two additional streams and caches for storing temporary scratch
2119 // objects and optimized IRs, using the same cache directory as the original.
2120 cgdata::StreamCacheData CG(MaxTasks, Cache, "CG"), IR(MaxTasks, Cache, "IR");
2121
2122 // First round: Execute optimization and code generation, outputting to
2123 // temporary scratch objects. Serialize the optimized IRs before initiating
2124 // code generation.
2125 LLVM_DEBUG(dbgs() << "[TwoRounds] Running the first round of codegen\n");
2126 auto FirstRoundLTO = std::make_unique<FirstRoundThinBackend>(
2127 Conf, ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2128 CG.AddStream, CG.Cache, IR.AddStream, IR.Cache);
2129 if (Error E = RunBackends(FirstRoundLTO.get()))
2130 return E;
2131
2132 LLVM_DEBUG(dbgs() << "[TwoRounds] Merging codegen data\n");
2133 auto CombinedHashOrErr = cgdata::mergeCodeGenData(*CG.getResult());
2134 if (Error E = CombinedHashOrErr.takeError())
2135 return E;
2136 auto CombinedHash = *CombinedHashOrErr;
2137 LLVM_DEBUG(dbgs() << "[TwoRounds] CGData hash: " << CombinedHash << "\n");
2138
2139 // Second round: Read the optimized IRs and execute code generation using the
2140 // merged data.
2141 LLVM_DEBUG(dbgs() << "[TwoRounds] Running the second round of codegen\n");
2142 auto SecondRoundLTO = std::make_unique<SecondRoundThinBackend>(
2143 Conf, ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2144 AddStream, Cache, IR.getResult(), CombinedHash);
2145 return RunBackends(SecondRoundLTO.get());
2146}
2147
2151 std::optional<uint64_t> RemarksHotnessThreshold, int Count) {
2152 std::string Filename = std::string(RemarksFilename);
2153 // For ThinLTO, file.opt.<format> becomes
2154 // file.opt.<format>.thin.<num>.<format>.
2155 if (!Filename.empty() && Count != -1)
2156 Filename =
2157 (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
2158 .str();
2159
2160 auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
2161 Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness,
2163 if (Error E = ResultOrErr.takeError())
2164 return std::move(E);
2165
2166 if (*ResultOrErr)
2167 (*ResultOrErr)->keep();
2168
2169 return ResultOrErr;
2170}
2171
2174 // Setup output file to emit statistics.
2175 if (StatsFilename.empty())
2176 return nullptr;
2177
2179 std::error_code EC;
2180 auto StatsFile =
2181 std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
2182 if (EC)
2183 return errorCodeToError(EC);
2184
2185 StatsFile->keep();
2186 return std::move(StatsFile);
2187}
2188
2189// Compute the ordering we will process the inputs: the rough heuristic here
2190// is to sort them per size so that the largest module get schedule as soon as
2191// possible. This is purely a compile-time optimization.
2193 auto Seq = llvm::seq<int>(0, R.size());
2194 std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
2195 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
2196 auto LSize = R[LeftIndex]->getBuffer().size();
2197 auto RSize = R[RightIndex]->getBuffer().size();
2198 return LSize > RSize;
2199 });
2200 return ModulesOrdering;
2201}
2202
2203namespace {
2204/// This out-of-process backend does not perform code generation when invoked
2205/// for each task. Instead, it generates the necessary information (e.g., the
2206/// summary index shard, import list, etc.) to enable code generation to be
2207/// performed externally, similar to WriteIndexesThinBackend. The backend's
2208/// `wait` function then invokes an external distributor process to carry out
2209/// the backend compilations.
2210class OutOfProcessThinBackend : public CGThinBackend {
2211 using SString = SmallString<128>;
2212
2214 StringSaver Saver{Alloc};
2215
2216 SString LinkerOutputFile;
2217
2218 SString DistributorPath;
2219 ArrayRef<StringRef> DistributorArgs;
2220
2221 SString RemoteCompiler;
2222 ArrayRef<StringRef> RemoteCompilerPrependArgs;
2223 ArrayRef<StringRef> RemoteCompilerArgs;
2224
2225 bool SaveTemps;
2226
2227 SmallVector<StringRef, 0> CodegenOptions;
2228 DenseSet<StringRef> CommonInputs;
2229
2230 // Information specific to individual backend compilation job.
2231 struct Job {
2232 unsigned Task;
2233 StringRef ModuleID;
2234 StringRef NativeObjectPath;
2235 StringRef SummaryIndexPath;
2236 ImportsFilesContainer ImportsFiles;
2237 };
2238 // The set of backend compilations jobs.
2239 SmallVector<Job> Jobs;
2240
2241 // A unique string to identify the current link.
2242 SmallString<8> UID;
2243
2244 // The offset to the first ThinLTO task.
2245 unsigned ThinLTOTaskOffset;
2246
2247 // The target triple to supply for backend compilations.
2248 llvm::Triple Triple;
2249
2250public:
2251 OutOfProcessThinBackend(
2252 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
2253 ThreadPoolStrategy ThinLTOParallelism,
2254 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
2255 AddStreamFn AddStream, lto::IndexWriteCallback OnWrite,
2256 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
2257 StringRef LinkerOutputFile, StringRef Distributor,
2258 ArrayRef<StringRef> DistributorArgs, StringRef RemoteCompiler,
2259 ArrayRef<StringRef> RemoteCompilerPrependArgs,
2260 ArrayRef<StringRef> RemoteCompilerArgs, bool SaveTemps)
2261 : CGThinBackend(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
2262 AddStream, OnWrite, ShouldEmitIndexFiles,
2263 ShouldEmitImportsFiles, ThinLTOParallelism),
2264 LinkerOutputFile(LinkerOutputFile), DistributorPath(Distributor),
2265 DistributorArgs(DistributorArgs), RemoteCompiler(RemoteCompiler),
2266 RemoteCompilerPrependArgs(RemoteCompilerPrependArgs),
2267 RemoteCompilerArgs(RemoteCompilerArgs), SaveTemps(SaveTemps) {}
2268
2269 void setup(unsigned ThinLTONumTasks, unsigned ThinLTOTaskOffset,
2270 llvm::Triple Triple) override {
2272 Jobs.resize((size_t)ThinLTONumTasks);
2273 this->ThinLTOTaskOffset = ThinLTOTaskOffset;
2274 this->Triple = Triple;
2275 }
2276
2277 Error start(
2278 unsigned Task, BitcodeModule BM,
2279 const FunctionImporter::ImportMapTy &ImportList,
2280 const FunctionImporter::ExportSetTy &ExportList,
2281 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
2282 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
2283
2284 StringRef ModulePath = BM.getModuleIdentifier();
2285
2286 SString ObjFilePath = sys::path::parent_path(LinkerOutputFile);
2287 sys::path::append(ObjFilePath, sys::path::stem(ModulePath) + "." +
2288 itostr(Task) + "." + UID + ".native.o");
2289
2290 Job &J = Jobs[Task - ThinLTOTaskOffset];
2291 J = {
2292 Task,
2293 ModulePath,
2294 Saver.save(ObjFilePath.str()),
2295 Saver.save(ObjFilePath.str() + ".thinlto.bc"),
2296 {} // Filled in by emitFiles below.
2297 };
2298
2299 assert(ModuleToDefinedGVSummaries.count(ModulePath));
2300
2301 // The BackendThreadPool is only used here to write the sharded index files
2302 // (similar to WriteIndexesThinBackend).
2303 BackendThreadPool.async(
2304 [=](Job &J, const FunctionImporter::ImportMapTy &ImportList) {
2305 if (auto E = emitFiles(ImportList, J.ModuleID, J.ModuleID.str(),
2306 J.SummaryIndexPath, J.ImportsFiles)) {
2307 std::unique_lock<std::mutex> L(ErrMu);
2308 if (Err)
2309 Err = joinErrors(std::move(*Err), std::move(E));
2310 else
2311 Err = std::move(E);
2312 }
2313 },
2314 std::ref(J), std::ref(ImportList));
2315
2316 return Error::success();
2317 }
2318
2319 // Derive a set of Clang options that will be shared/common for all DTLTO
2320 // backend compilations. We are intentionally minimal here as these options
2321 // must remain synchronized with the behavior of Clang. DTLTO does not support
2322 // all the features available with in-process LTO. More features are expected
2323 // to be added over time. Users can specify Clang options directly if a
2324 // feature is not supported. Note that explicitly specified options that imply
2325 // additional input or output file dependencies must be communicated to the
2326 // distribution system, potentially by setting extra options on the
2327 // distributor program.
2328 void buildCommonRemoteCompilerOptions() {
2329 const lto::Config &C = Conf;
2330 auto &Ops = CodegenOptions;
2331
2332 Ops.push_back(Saver.save("-O" + Twine(C.OptLevel)));
2333
2334 if (C.Options.EmitAddrsig)
2335 Ops.push_back("-faddrsig");
2336 if (C.Options.FunctionSections)
2337 Ops.push_back("-ffunction-sections");
2338 if (C.Options.DataSections)
2339 Ops.push_back("-fdata-sections");
2340
2341 if (C.RelocModel == Reloc::PIC_)
2342 // Clang doesn't have -fpic for all triples.
2343 if (!Triple.isOSBinFormatCOFF())
2344 Ops.push_back("-fpic");
2345
2346 // Turn on/off warnings about profile cfg mismatch (default on)
2347 // --lto-pgo-warn-mismatch.
2348 if (!C.PGOWarnMismatch) {
2349 Ops.push_back("-mllvm");
2350 Ops.push_back("-no-pgo-warn-mismatch");
2351 }
2352
2353 // Enable sample-based profile guided optimizations.
2354 // Sample profile file path --lto-sample-profile=<value>.
2355 if (!C.SampleProfile.empty()) {
2356 Ops.push_back(
2357 Saver.save("-fprofile-sample-use=" + Twine(C.SampleProfile)));
2358 CommonInputs.insert(C.SampleProfile);
2359 }
2360
2361 // We don't know which of options will be used by Clang.
2362 Ops.push_back("-Wno-unused-command-line-argument");
2363
2364 // Forward any supplied options.
2365 if (!RemoteCompilerArgs.empty())
2366 for (auto &a : RemoteCompilerArgs)
2367 Ops.push_back(a);
2368 }
2369
2370 // Generates a JSON file describing the backend compilations, for the
2371 // distributor.
2372 bool emitDistributorJson(StringRef DistributorJson) {
2373 using json::Array;
2374 std::error_code EC;
2375 raw_fd_ostream OS(DistributorJson, EC);
2376 if (EC)
2377 return false;
2378
2379 json::OStream JOS(OS);
2380 JOS.object([&]() {
2381 // Information common to all jobs.
2382 JOS.attributeObject("common", [&]() {
2383 JOS.attribute("linker_output", LinkerOutputFile);
2384
2385 JOS.attributeArray("args", [&]() {
2386 JOS.value(RemoteCompiler);
2387
2388 // Forward any supplied prepend options.
2389 if (!RemoteCompilerPrependArgs.empty())
2390 for (auto &A : RemoteCompilerPrependArgs)
2391 JOS.value(A);
2392
2393 JOS.value("-c");
2394
2395 JOS.value(Saver.save("--target=" + Triple.str()));
2396
2397 for (const auto &A : CodegenOptions)
2398 JOS.value(A);
2399 });
2400
2401 JOS.attribute("inputs", Array(CommonInputs));
2402 });
2403
2404 // Per-compilation-job information.
2405 JOS.attributeArray("jobs", [&]() {
2406 for (const auto &J : Jobs) {
2407 assert(J.Task != 0);
2408
2410 SmallVector<StringRef, 1> Outputs;
2411
2412 JOS.object([&]() {
2413 JOS.attributeArray("args", [&]() {
2414 JOS.value(J.ModuleID);
2415 Inputs.push_back(J.ModuleID);
2416
2417 JOS.value(
2418 Saver.save("-fthinlto-index=" + Twine(J.SummaryIndexPath)));
2419 Inputs.push_back(J.SummaryIndexPath);
2420
2421 JOS.value("-o");
2422 JOS.value(J.NativeObjectPath);
2423 Outputs.push_back(J.NativeObjectPath);
2424 });
2425
2426 // Add the bitcode files from which imports will be made. These do
2427 // not explicitly appear on the backend compilation command lines
2428 // but are recorded in the summary index shards.
2429 llvm::append_range(Inputs, J.ImportsFiles);
2430 JOS.attribute("inputs", Array(Inputs));
2431
2432 JOS.attribute("outputs", Array(Outputs));
2433 });
2434 }
2435 });
2436 });
2437
2438 return true;
2439 }
2440
2441 void removeFile(StringRef FileName) {
2442 std::error_code EC = sys::fs::remove(FileName, true);
2443 if (EC && EC != std::make_error_code(std::errc::no_such_file_or_directory))
2444 errs() << "warning: could not remove the file '" << FileName
2445 << "': " << EC.message() << "\n";
2446 }
2447
2448 Error wait() override {
2449 // Wait for the information on the required backend compilations to be
2450 // gathered.
2451 BackendThreadPool.wait();
2452 if (Err)
2453 return std::move(*Err);
2454
2455 auto CleanPerJobFiles = llvm::make_scope_exit([&] {
2456 if (!SaveTemps)
2457 for (auto &Job : Jobs) {
2458 removeFile(Job.NativeObjectPath);
2459 if (!ShouldEmitIndexFiles)
2460 removeFile(Job.SummaryIndexPath);
2461 }
2462 });
2463
2464 const StringRef BCError = "DTLTO backend compilation: ";
2465
2466 buildCommonRemoteCompilerOptions();
2467
2468 SString JsonFile = sys::path::parent_path(LinkerOutputFile);
2469 sys::path::append(JsonFile, sys::path::stem(LinkerOutputFile) + "." + UID +
2470 ".dist-file.json");
2471 if (!emitDistributorJson(JsonFile))
2473 BCError + "failed to generate distributor JSON script: " + JsonFile,
2475 auto CleanJson = llvm::make_scope_exit([&] {
2476 if (!SaveTemps)
2477 removeFile(JsonFile);
2478 });
2479
2480 SmallVector<StringRef, 3> Args = {DistributorPath};
2481 llvm::append_range(Args, DistributorArgs);
2482 Args.push_back(JsonFile);
2483 std::string ErrMsg;
2484 if (sys::ExecuteAndWait(Args[0], Args,
2485 /*Env=*/std::nullopt, /*Redirects=*/{},
2486 /*SecondsToWait=*/0, /*MemoryLimit=*/0, &ErrMsg)) {
2488 BCError + "distributor execution failed" +
2489 (!ErrMsg.empty() ? ": " + ErrMsg + Twine(".") : Twine(".")),
2491 }
2492
2493 for (auto &Job : Jobs) {
2494 // Load the native object from a file into a memory buffer
2495 // and store its contents in the output buffer.
2496 auto ObjFileMbOrErr =
2497 MemoryBuffer::getFile(Job.NativeObjectPath, /*IsText=*/false,
2498 /*RequiresNullTerminator=*/false);
2499 if (std::error_code EC = ObjFileMbOrErr.getError())
2501 BCError + "cannot open native object file: " +
2502 Job.NativeObjectPath + ": " + EC.message(),
2504 auto StreamOrErr = AddStream(Job.Task, Job.ModuleID);
2505 if (Error Err = StreamOrErr.takeError())
2506 report_fatal_error(std::move(Err));
2507 auto &Stream = *StreamOrErr->get();
2508 *Stream.OS << ObjFileMbOrErr->get()->getMemBufferRef().getBuffer();
2509 if (Error Err = Stream.commit())
2510 report_fatal_error(std::move(Err));
2511 }
2512
2513 return Error::success();
2514 }
2515};
2516} // end anonymous namespace
2517
2519 ThreadPoolStrategy Parallelism, lto::IndexWriteCallback OnWrite,
2520 bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles,
2521 StringRef LinkerOutputFile, StringRef Distributor,
2522 ArrayRef<StringRef> DistributorArgs, StringRef RemoteCompiler,
2523 ArrayRef<StringRef> RemoteCompilerPrependArgs,
2524 ArrayRef<StringRef> RemoteCompilerArgs, bool SaveTemps) {
2525 auto Func =
2526 [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
2527 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
2528 AddStreamFn AddStream, FileCache /*Cache*/) {
2529 return std::make_unique<OutOfProcessThinBackend>(
2530 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2531 AddStream, OnWrite, ShouldEmitIndexFiles, ShouldEmitImportsFiles,
2532 LinkerOutputFile, Distributor, DistributorArgs, RemoteCompiler,
2533 RemoteCompilerPrependArgs, RemoteCompilerArgs, SaveTemps);
2534 };
2535 return ThinBackend(Func, Parallelism);
2536}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
dxil translate DXIL Translate Metadata
#define DEBUG_TYPE
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file supports working with JSON data.
static void writeToResolutionFile(raw_ostream &OS, InputFile *Input, ArrayRef< SymbolResolution > Res)
Definition LTO.cpp:716
static void thinLTOResolvePrevailingGUID(const Config &C, ValueInfo VI, DenseSet< GlobalValueSummary * > &GlobalInvolvedWithAlias, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Definition LTO.cpp:368
static void handleNonPrevailingComdat(GlobalValue &GV, std::set< const Comdat * > &NonPrevailingComdats)
Definition LTO.cpp:836
static cl::opt< bool > DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden, cl::desc("Dump the SCCs in the ThinLTO index's callgraph"))
static void thinLTOInternalizeAndPromoteGUID(ValueInfo VI, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Definition LTO.cpp:470
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:80
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
#define G(x, y, z)
Definition MD5.cpp:56
Machine Check Debug Module
This file contains the declarations for metadata subclasses.
#define P(N)
Provides a library for accessing information about this process and other processes on the operating ...
static const char * name
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:114
This pass exposes codegen information to IR-level passes.
The Input class is used to parse a yaml document into in-memory structs and vectors.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
iterator end() const
Definition ArrayRef.h:132
iterator begin() const
Definition ArrayRef.h:131
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:138
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
Definition ArrayRef.h:158
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Represents a module in a bitcode file.
StringRef getModuleIdentifier() const
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(GlobalValue::GUID)> IsPrevailing=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:248
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:174
iterator end()
Definition DenseMap.h:81
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
The map maintains the list of imports.
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
Function and variable summary information to aid decisions and implementation of importing.
static bool isAppendingLinkage(LinkageTypes Linkage)
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:77
static bool isExternalWeakLinkage(LinkageTypes Linkage)
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:328
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
LLVM_ABI const Comdat * getComdat() const
Definition Globals.cpp:201
static bool isLinkOnceLinkage(LinkageTypes Linkage)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
static bool isExternalLinkage(LinkageTypes Linkage)
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:161
static LinkageTypes getWeakLinkage(bool ODR)
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
DLLStorageClassTypes getDLLStorageClass() const
Type * getValueType() const
static bool isLinkOnceODRLinkage(LinkageTypes Linkage)
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:520
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1526
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
bool empty() const
Definition MapVector.h:77
iterator begin()
Definition MapVector.h:65
size_type size() const
Definition MapVector.h:56
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
CfiFunctionIndex & cfiFunctionDecls()
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
const StringMap< ModuleHash > & modulePaths() const
Table of modules, containing module hash and id.
CfiFunctionIndex & cfiFunctionDefs()
LLVM_ABI void addModule(Module *M)
static LLVM_ABI void CollectAsmSymvers(const Module &M, function_ref< void(StringRef, StringRef)> AsmSymver)
Parse inline ASM and collect the symvers directives that are defined in the current module.
PointerUnion< GlobalValue *, AsmSymbol * > Symbol
LLVM_ABI uint32_t getSymbolFlags(Symbol S) const
ArrayRef< Symbol > symbols() const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A class that wrap the SHA1 algorithm.
Definition SHA1.h:27
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
Definition SHA1.cpp:208
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
Definition SHA1.cpp:288
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:175
bool empty() const
Definition SmallSet.h:168
bool erase(const T &V)
Definition SmallSet.h:199
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:183
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
void reserve(size_type N)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:854
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition StringMap.h:285
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:140
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:22
StringRef save(const char *S)
Definition StringSaver.h:31
MCTargetOptions MCOptions
Machine level options.
DebuggerKind DebuggerTuning
Which debugger to tune for.
unsigned FunctionSections
Emit functions into separate sections.
unsigned DataSections
Emit data into separate sections.
This tells how a thread pool will be used.
Definition Threading.h:115
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
bool isArm64e() const
Tests whether the target is the Apple "arm64e" AArch64 subarch.
Definition Triple.h:1138
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition Triple.h:413
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition Triple.h:776
const std::string & str() const
Definition Triple.h:480
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:613
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:771
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:295
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
iterator find(const_arg_type_t< ValueT > V)
Definition DenseSet.h:167
void insert_range(Range &&R)
Definition DenseSet.h:228
size_type size() const
Definition DenseSet.h:87
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:180
An efficient, type-erasing, non-owning reference to a callable.
Ephemeral symbols produced by Reader::symbols() and Reader::module_symbols().
Definition IRSymtab.h:316
An input file.
Definition LTO.h:113
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:568
ArrayRef< Symbol > symbols() const
A range over the symbols in this InputFile.
Definition LTO.h:167
LLVM_ABI StringRef getName() const
Returns the path to the InputFile.
Definition LTO.cpp:597
LLVM_ABI BitcodeModule & getSingleBitcodeModule()
Definition LTO.cpp:601
LLVM_ABI LTO(Config Conf, ThinBackend Backend={}, unsigned ParallelCodeGenParallelismLevel=1, LTOKind LTOMode=LTOK_Default)
Create an LTO object.
Definition LTO.cpp:619
LLVM_ABI Error add(std::unique_ptr< InputFile > Obj, ArrayRef< SymbolResolution > Res)
Add an input file to the LTO link, using the provided symbol resolutions.
Definition LTO.cpp:740
static LLVM_ABI SmallVector< const char * > getRuntimeLibcallSymbols(const Triple &TT)
Static method that returns a list of libcall symbols that can be generated by LTO but might not be vi...
Definition LTO.cpp:1396
LTOKind
Unified LTO modes.
Definition LTO.h:376
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
Definition LTO.h:381
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
Definition LTO.h:378
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
Definition LTO.h:384
LLVM_ABI ~LTO()
LLVM_ABI unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
Definition LTO.cpp:1153
LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
Definition LTO.cpp:1204
This class defines the interface to the ThinLTO backend.
Definition LTO.h:204
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
Definition LTO.h:208
LLVM_ABI Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath, const std::string &NewModulePath) const
Definition LTO.cpp:1409
ModuleSummaryIndex & CombinedIndex
Definition LTO.h:207
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
static LLVM_ABI Pid getProcessId()
Get the process's identifier.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
static auto libcall_impls()
LLVM_ABI Expected< stable_hash > mergeCodeGenData(ArrayRef< StringRef > ObjectFiles)
Merge the codegen data from the scratch objects ObjectFiles from the first codegen round.
LLVM_ABI std::unique_ptr< Module > loadModuleForTwoRounds(BitcodeModule &OrigModule, unsigned Task, LLVMContext &Context, ArrayRef< StringRef > IRFiles)
Load the optimized bitcode module for the second codegen round.
initializer< Ty > init(const Ty &Val)
LLVM_ABI ThinBackend createInProcessThinBackend(ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite=nullptr, bool ShouldEmitIndexFiles=false, bool ShouldEmitImportsFiles=false)
This ThinBackend runs the individual backend jobs in-process.
Definition LTO.cpp:1759
LLVM_ABI std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix, StringRef NewPrefix)
Given the original Path to an output file, replace any path prefix matching OldPrefix with NewPrefix.
Definition LTO.cpp:1793
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1775
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
Definition LTO.cpp:2173
LLVM_ABI ThinBackend createOutOfProcessThinBackend(ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite, bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles, StringRef LinkerOutputFile, StringRef Distributor, ArrayRef< StringRef > DistributorArgs, StringRef RemoteCompiler, ArrayRef< StringRef > RemoteCompilerPrependArgs, ArrayRef< StringRef > RemoteCompilerArgs, bool SaveTemps)
This ThinBackend generates the index shards and then runs the individual backend jobs via an external...
Definition LTO.cpp:2518
LLVM_ABI Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
std::function< void(const std::string &)> IndexWriteCallback
Definition LTO.h:199
LLVM_ABI Error finalizeOptimizationRemarks(LLVMRemarkFileHandle DiagOutputFile)
LLVM_ABI ThinBackend createWriteIndexesThinBackend(ThreadPoolStrategy Parallelism, std::string OldPrefix, std::string NewPrefix, std::string NativeObjectPrefix, bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite)
This ThinBackend writes individual module indexes to files, instead of running the individual backend...
Definition LTO.cpp:1879
LLVM_ABI Expected< LLVMRemarkFileHandle > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, std::optional< uint64_t > RemarksHotnessThreshold=0, int Count=-1)
Setup optimization remarks.
Definition LTO.cpp:2148
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2192
LLVM_ABI Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > *ModuleMap, bool CodeGenOnly, AddStreamFn IRAddStream=nullptr, const std::vector< uint8_t > &CmdArgs=std::vector< uint8_t >())
Runs a ThinLTO backend.
llvm::SmallVector< std::string > ImportsFilesContainer
Definition LTO.h:201
LLVM_ABI Expected< IRSymtabFile > readIRSymtab(MemoryBufferRef MBRef)
Reads a bitcode file, creating its irsymtab if necessary.
DiagnosticInfoOptimizationBase::Argument NV
void write64le(void *P, uint64_t V)
Definition Endian.h:478
void write32le(void *P, uint32_t V)
Definition Endian.h:475
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
LLVM_ABI std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition Path.cpp:967
LLVM_ABI StringRef stem(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get stem.
Definition Path.cpp:579
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
Definition Path.cpp:467
LLVM_ABI bool replace_path_prefix(SmallVectorImpl< char > &Path, StringRef OldPrefix, StringRef NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
Definition Path.cpp:518
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:456
LLVM_ABI int ExecuteAndWait(StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env=std::nullopt, ArrayRef< std::optional< StringRef > > Redirects={}, unsigned SecondsToWait=0, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr, std::optional< ProcessStatistics > *ProcStat=nullptr, BitVector *AffinityMask=nullptr)
This function executes the program using the arguments provided.
Definition Program.cpp:32
This is an optimization pass for GlobalISel generic memory operations.
ThreadPoolStrategy heavyweight_hardware_concurrency(unsigned ThreadCount=0)
Returns a thread strategy for tasks requiring significant memory or other resources.
Definition Threading.h:167
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:829
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1725
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1399
std::unordered_set< GlobalValueSummary * > GVSummaryPtrSet
A set of global value summary pointers.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition ScopeExit.h:59
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void generateParamAccessSummary(ModuleSummaryIndex &Index)
cl::opt< bool > CodeGenDataThinLTOTwoRounds("codegen-data-thinlto-two-rounds", cl::init(false), cl::Hidden, cl::desc("Enable two-round ThinLTO code generation. The first round " "emits codegen data, while the second round uses the emitted " "codegen data for further optimizations."))
Definition LTO.cpp:79
LLVM_ABI Expected< LLVMRemarkFileHandle > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, std::optional< uint64_t > RemarksHotnessThreshold=0)
Set up optimization remarks that output to a file.
cl::opt< std::string > RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex"))
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:98
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2136
uint64_t stable_hash
An opaque object representing a stable hash code.
std::string utostr(uint64_t X, bool isNeg=false)
LLVM_ABI bool thinLTOPropagateFunctionAttrs(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Propagate function attributes for function summaries along the index's callgraph during thinlink.
LLVM_ABI bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO)
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI void EnableStatistics(bool DoPrintOnExit=true)
Enable the collection and printing of statistics.
LLVM_ABI void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition LTO.cpp:553
LLVM_ABI void timeTraceProfilerInitialize(unsigned TimeTraceGranularity, StringRef ProcName, bool TimeTraceVerbose=false)
Initialize the time trace profiler.
LLVM_ABI void timeTraceProfilerFinishThread()
Finish a time trace profiler running on a worker thread.
LLVM_ABI std::string recomputeLTOCacheKey(const std::string &Key, StringRef ExtraID)
Recomputes the LTO cache key for a given key with an extra identifier.
Definition LTO.cpp:354
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
LLVM_ABI void getVisibleToRegularObjVtableGUIDs(ModuleSummaryIndex &Index, DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols, function_ref< bool(StringRef)> IsVisibleToRegularObj)
Based on typeID string, get all associated vtable GUIDS that are visible to regular objects.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1622
bool timeTraceProfilerEnabled()
Is the time trace profiler enabled, i.e. initialized?
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
LLVM_ABI cl::opt< bool > EnableLTOInternalization
Enable global value internalization in LTO.
cl::opt< bool > RemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
LLVM_ABI void timeTraceProfilerEnd()
Manually end the last time section.
cl::opt< std::string > RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
cl::opt< bool > SupportsHotColdNew
Indicate we are linking with an allocator that supports hot/cold operator new interfaces.
LLVM_ABI void updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI void thinLTOResolvePrevailingInIndex(const lto::Config &C, ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Resolve linkage for prevailing symbols in the Index.
Definition LTO.cpp:448
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
LLVM_ABI void runWholeProgramDevirtOnIndex(ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap)
Perform index-based whole program devirtualization on the Summary index.
cl::opt< bool > ForceImportAll
LLVM_ABI void gatherImportedSummariesForModule(StringRef ModulePath, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, GVSummaryPtrSet &DecSummaries)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
ArrayRef(const T &OneElt) -> ArrayRef< T >
void toHex(ArrayRef< uint8_t > Input, bool LowerCase, SmallVectorImpl< char > &Output)
Convert buffer Input to its hexadecimal representation. The returned string is double the size of Inp...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1867
LLVM_ABI void processImportsFiles(StringRef ModulePath, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, function_ref< void(const std::string &)> F)
Call F passing each of the files module ModulePath will import from.
cl::opt< std::optional< uint64_t >, false, remarks::HotnessThresholdParser > RemarksHotnessThreshold("lto-pass-remarks-hotness-threshold", cl::desc("Minimum profile count required for an " "optimization remark to be output." " Use 'auto' to apply the threshold from profile summary."), cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::string computeLTOCacheKey(const lto::Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > &ResolvedODR, const GVSummaryMapTy &DefinedGlobals, const DenseSet< GlobalValue::GUID > &CfiFunctionDefs={}, const DenseSet< GlobalValue::GUID > &CfiFunctionDecls={})
Computes a unique hash for the Module considering the current list of export/import and other global ...
Definition LTO.cpp:104
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:111
static cl::opt< bool > LTOKeepSymbolCopies("lto-keep-symbol-copies", cl::init(false), cl::Hidden, cl::desc("Keep copies of symbols in LTO indexing"))
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition Caching.h:58
LLVM_ABI void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
LLVM_ABI void computeDeadSymbolsWithConstProp(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing, bool ImportEnabled)
Compute dead symbols and run constant propagation in combined index after that.
LLVM_ABI Error EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
@ Keep
No function return thunk.
Definition CodeGen.h:156
std::string itostr(int64_t X)
LLVM_ABI void updateVCallVisibilityInModule(Module &M, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, bool ValidateAllVtablesHaveTypeInfos, function_ref< bool(StringRef)> IsVisibleToRegularObj)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
LLVM_ABI TimeTraceProfilerEntry * timeTraceProfilerBegin(StringRef Name, StringRef Detail)
Manually begin a time section, with the given Name and Detail.
LLVM_ABI void updateVCallVisibilityInIndex(ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, const DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
This type represents a file cache system that manages caching of files.
Definition Caching.h:84
bool isValid() const
Definition Caching.h:97
A simple container for information about the supported runtime calls.
unsigned getNumAvailableLibcallImpls() const
bool isAvailable(RTLIB::LibcallImpl Impl) const
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
Struct that holds a reference to a particular GUID in a global value summary.
LTO configuration.
Definition Config.h:42
std::optional< uint64_t > RemarksHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
Definition Config.h:166
std::optional< CodeModel::Model > CodeModel
Definition Config.h:57
std::string AAPipeline
Definition Config.h:111
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Definition Config.h:69
std::vector< std::string > MAttrs
Definition Config.h:51
std::vector< std::string > MllvmArgs
Definition Config.h:52
CodeGenOptLevel CGOptLevel
Definition Config.h:58
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple.
Definition Config.h:119
std::string CPU
Definition Config.h:49
std::string DwoDir
The directory to store .dwo files.
Definition Config.h:131
std::string RemarksFilename
Optimization remarks file path.
Definition Config.h:145
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Definition Config.h:115
std::string ProfileRemapping
Name remapping file for profile data.
Definition Config.h:128
TargetOptions Options
Definition Config.h:50
bool TimeTraceEnabled
Time trace enabled.
Definition Config.h:181
std::string RemarksPasses
Optimization remarks pass filter.
Definition Config.h:148
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
Definition Config.h:106
unsigned TimeTraceGranularity
Time trace granularity.
Definition Config.h:184
unsigned OptLevel
Definition Config.h:60
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition Config.h:151
std::optional< Reloc::Model > RelocModel
Definition Config.h:56
CodeGenFileType CGFileType
Definition Config.h:59
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition Config.h:66
std::string SampleProfile
Sample PGO profile path.
Definition Config.h:125
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition Config.h:169
The purpose of this struct is to only expose the symbol information that an LTO client should need in...
Definition LTO.h:142
The resolution for a symbol.
Definition LTO.h:598
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
Definition LTO.h:608
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
Definition LTO.h:615
unsigned Prevailing
The linker has chosen this definition of the symbol.
Definition LTO.h:604
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
Definition LTO.h:619
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
Definition LTO.h:611
This type defines the behavior following the thin-link phase during ThinLTO.
Definition LTO.h:274