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