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