LLVM 22.0.0git
ThinLTOCodeGenerator.cpp
Go to the documentation of this file.
1//===-ThinLTOCodeGenerator.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 the Thin Link Time Optimization library. This library is
10// intended to be used by linker to optimize code at link time.
11//
12//===----------------------------------------------------------------------===//
13
16
17#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/Statistic.h"
26#include "llvm/Config/llvm-config.h"
27#include "llvm/IR/DebugInfo.h"
29#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/Mangler.h"
34#include "llvm/IR/Verifier.h"
36#include "llvm/LTO/LTO.h"
43#include "llvm/Support/Debug.h"
44#include "llvm/Support/Error.h"
47#include "llvm/Support/Path.h"
48#include "llvm/Support/SHA1.h"
61
62#if !defined(_MSC_VER) && !defined(__MINGW32__)
63#include <unistd.h>
64#else
65#include <io.h>
66#endif
67
68using namespace llvm;
69using namespace ThinLTOCodeGeneratorImpl;
70
71#define DEBUG_TYPE "thinlto"
72
73namespace llvm {
74// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
82}
83
84// Default to using all available threads in the system, but using only one
85// thred per core, as indicated by the usage of
86// heavyweight_hardware_concurrency() below.
87static cl::opt<int> ThreadCount("threads", cl::init(0));
88
89// Simple helper to save temporary files for debug.
90static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
91 unsigned count, StringRef Suffix) {
92 if (TempDir.empty())
93 return;
94 // User asked to save temps, let dump the bitcode file after import.
95 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
96 std::error_code EC;
97 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
98 if (EC)
99 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
100 " to save optimized bitcode\n");
101 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
102}
103
104static const GlobalValueSummary *
106 // If there is any strong definition anywhere, get it.
107 auto StrongDefForLinker = llvm::find_if(
108 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
109 auto Linkage = Summary->linkage();
112 });
113 if (StrongDefForLinker != GVSummaryList.end())
114 return StrongDefForLinker->get();
115 // Get the first *linker visible* definition for this global in the summary
116 // list.
117 auto FirstDefForLinker = llvm::find_if(
118 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
119 auto Linkage = Summary->linkage();
121 });
122 // Extern templates can be emitted as available_externally.
123 if (FirstDefForLinker == GVSummaryList.end())
124 return nullptr;
125 return FirstDefForLinker->get();
126}
127
128// Populate map of GUID to the prevailing copy for any multiply defined
129// symbols. Currently assume first copy is prevailing, or any strong
130// definition. Can be refined with Linker information in the future.
132 const ModuleSummaryIndex &Index,
134 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
135 return GVSummaryList.size() > 1;
136 };
137
138 for (auto &I : Index) {
139 if (HasMultipleCopies(I.second.SummaryList))
140 PrevailingCopy[I.first] =
141 getFirstDefinitionForLinker(I.second.SummaryList);
142 }
143}
144
146generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) {
148 for (auto &M : Modules) {
149 LLVM_DEBUG(dbgs() << "Adding module " << M->getName() << " to ModuleMap\n");
150 assert(!ModuleMap.contains(M->getName()) &&
151 "Expect unique Buffer Identifier");
152 ModuleMap[M->getName()] = M.get();
153 }
154 return ModuleMap;
155}
156
157static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index,
158 bool ClearDSOLocalOnDeclarations) {
159 renameModuleForThinLTO(TheModule, Index, ClearDSOLocalOnDeclarations);
160}
161
162namespace {
163class ThinLTODiagnosticInfo : public DiagnosticInfo {
164 const Twine &Msg;
165public:
166 ThinLTODiagnosticInfo(const Twine &DiagMsg LLVM_LIFETIME_BOUND,
167 DiagnosticSeverity Severity = DS_Error)
168 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
169 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
170};
171}
172
173/// Verify the module and strip broken debug info.
174static void verifyLoadedModule(Module &TheModule) {
175 bool BrokenDebugInfo = false;
176 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
177 report_fatal_error("Broken module found, compilation aborted!");
178 if (BrokenDebugInfo) {
179 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
180 "Invalid debug info found, debug info will be stripped", DS_Warning));
181 StripDebugInfo(TheModule);
182 }
183}
184
185static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile *Input,
186 LLVMContext &Context,
187 bool Lazy,
188 bool IsImporting) {
189 auto &Mod = Input->getSingleBitcodeModule();
190 SMDiagnostic Err;
192 Lazy ? Mod.getLazyModule(Context,
193 /* ShouldLazyLoadMetadata */ true, IsImporting)
194 : Mod.parseModule(Context);
195 if (!ModuleOrErr) {
196 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
197 SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(),
198 SourceMgr::DK_Error, EIB.message());
199 Err.print("ThinLTO", errs());
200 });
201 report_fatal_error("Can't load module, abort.");
202 }
203 if (!Lazy)
204 verifyLoadedModule(*ModuleOrErr.get());
205 return std::move(*ModuleOrErr);
206}
207
208static void
211 const FunctionImporter::ImportMapTy &ImportList,
212 bool ClearDSOLocalOnDeclarations) {
213 auto Loader = [&](StringRef Identifier) {
214 auto &Input = ModuleMap[Identifier];
215 return loadModuleFromInput(Input, TheModule.getContext(),
216 /*Lazy=*/true, /*IsImporting*/ true);
217 };
218
219 FunctionImporter Importer(Index, Loader, ClearDSOLocalOnDeclarations);
220 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
221 if (!Result) {
222 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
223 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
224 SourceMgr::DK_Error, EIB.message());
225 Err.print("ThinLTO", errs());
226 });
227 report_fatal_error("importFunctions failed");
228 }
229 // Verify again after cross-importing.
230 verifyLoadedModule(TheModule);
231}
232
233static void optimizeModule(Module &TheModule, TargetMachine &TM,
234 unsigned OptLevel, bool Freestanding,
235 bool DebugPassManager, ModuleSummaryIndex *Index) {
236 std::optional<PGOOptions> PGOOpt;
241
243 StandardInstrumentations SI(TheModule.getContext(), DebugPassManager);
244 SI.registerCallbacks(PIC, &MAM);
246 PTO.LoopVectorization = true;
247 PTO.SLPVectorization = true;
248 PassBuilder PB(&TM, PTO, PGOOpt, &PIC);
249
250 std::unique_ptr<TargetLibraryInfoImpl> TLII(
251 new TargetLibraryInfoImpl(TM.getTargetTriple()));
252 if (Freestanding)
253 TLII->disableAllFunctions();
254 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
255
256 // Register all the basic analyses with the managers.
262
264
266
267 switch (OptLevel) {
268 default:
269 llvm_unreachable("Invalid optimization level");
270 case 0:
272 break;
273 case 1:
275 break;
276 case 2:
278 break;
279 case 3:
281 break;
282 }
283
284 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, Index));
285
286 MPM.run(TheModule, MAM);
287}
288
289static void
291 DenseSet<GlobalValue::GUID> &PreservedGUID) {
292 for (const auto &Sym : File.symbols()) {
293 if (Sym.isUsed())
294 PreservedGUID.insert(
296 }
297}
298
299// Convert the PreservedSymbols map from "Name" based to "GUID" based.
301 const StringSet<> &PreservedSymbols,
302 const Triple &TheTriple,
304 // Iterate the symbols in the input file and if the input has preserved symbol
305 // compute the GUID for the symbol.
306 for (const auto &Sym : File.symbols()) {
307 if (PreservedSymbols.count(Sym.getName()) && !Sym.getIRName().empty())
309 GlobalValue::getGlobalIdentifier(Sym.getIRName(),
311 }
312}
313
316 const StringSet<> &PreservedSymbols,
317 const Triple &TheTriple) {
318 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
319 computeGUIDPreservedSymbols(File, PreservedSymbols, TheTriple,
320 GUIDPreservedSymbols);
321 return GUIDPreservedSymbols;
322}
323
324static std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
325 TargetMachine &TM) {
327
328 // CodeGen
329 {
332
333 // Setup the codegen now.
334 if (TM.addPassesToEmitFile(PM, OS, nullptr, CodeGenFileType::ObjectFile,
335 /* DisableVerify */ true))
336 report_fatal_error("Failed to setup codegen");
337
338 // Run codegen now. resulting binary is in OutputBuffer.
339 PM.run(TheModule);
340 }
341 return std::make_unique<SmallVectorMemoryBuffer>(
342 std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
343}
344
345namespace {
346/// Manage caching for a single Module.
347class ModuleCacheEntry {
348 SmallString<128> EntryPath;
349
350public:
351 // Create a cache entry. This compute a unique hash for the Module considering
352 // the current list of export/import, and offer an interface to query to
353 // access the content in the cache.
354 ModuleCacheEntry(
355 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
356 const FunctionImporter::ImportMapTy &ImportList,
357 const FunctionImporter::ExportSetTy &ExportList,
358 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
359 const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel,
360 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
361 if (CachePath.empty())
362 return;
363
364 if (!Index.modulePaths().count(ModuleID))
365 // The module does not have an entry, it can't have a hash at all
366 return;
367
368 if (all_of(Index.getModuleHash(ModuleID),
369 [](uint32_t V) { return V == 0; }))
370 // No hash entry, no caching!
371 return;
372
374 Conf.OptLevel = OptLevel;
375 Conf.Options = TMBuilder.Options;
376 Conf.CPU = TMBuilder.MCpu;
377 Conf.MAttrs.push_back(TMBuilder.MAttr);
378 Conf.RelocModel = TMBuilder.RelocModel;
379 Conf.CGOptLevel = TMBuilder.CGOptLevel;
380 Conf.Freestanding = Freestanding;
381 std::string Key =
382 computeLTOCacheKey(Conf, Index, ModuleID, ImportList, ExportList,
383 ResolvedODR, DefinedGVSummaries);
384
385 // This choice of file name allows the cache to be pruned (see pruneCache()
386 // in include/llvm/Support/CachePruning.h).
387 sys::path::append(EntryPath, CachePath, Twine("llvmcache-", Key));
388 }
389
390 // Access the path to this entry in the cache.
391 StringRef getEntryPath() { return EntryPath; }
392
393 // Try loading the buffer for this cache entry.
394 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
395 if (EntryPath.empty())
396 return std::error_code();
397 SmallString<64> ResultPath;
399 Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
400 if (!FDOrErr)
401 return errorToErrorCode(FDOrErr.takeError());
403 *FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
404 sys::fs::closeFile(*FDOrErr);
405 return MBOrErr;
406 }
407
408 // Cache the Produced object file
409 void write(const MemoryBuffer &OutputBuffer) {
410 if (EntryPath.empty())
411 return;
412
413 if (auto Err = llvm::writeToOutput(
414 EntryPath, [&OutputBuffer](llvm::raw_ostream &OS) -> llvm::Error {
416 return llvm::Error::success();
417 }))
418 report_fatal_error(llvm::formatv("ThinLTO: Can't write file {0}: {1}",
419 EntryPath,
420 toString(std::move(Err)).c_str()));
421 }
422};
423} // end anonymous namespace
424
425static std::unique_ptr<MemoryBuffer>
428 const FunctionImporter::ImportMapTy &ImportList,
429 const FunctionImporter::ExportSetTy &ExportList,
430 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
431 const GVSummaryMapTy &DefinedGlobals,
432 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
433 bool DisableCodeGen, StringRef SaveTempsDir,
434 bool Freestanding, unsigned OptLevel, unsigned count,
435 bool DebugPassManager) {
436 // "Benchmark"-like optimization: single-source case
437 bool SingleModule = (ModuleMap.size() == 1);
438
439 // When linking an ELF shared object, dso_local should be dropped. We
440 // conservatively do this for -fpic.
441 bool ClearDSOLocalOnDeclarations =
442 TM.getTargetTriple().isOSBinFormatELF() &&
443 TM.getRelocationModel() != Reloc::Static &&
444 TheModule.getPIELevel() == PIELevel::Default;
445
446 if (!SingleModule) {
447 promoteModule(TheModule, Index, ClearDSOLocalOnDeclarations);
448
449 // Apply summary-based prevailing-symbol resolution decisions.
450 thinLTOFinalizeInModule(TheModule, DefinedGlobals, /*PropagateAttrs=*/true);
451
452 // Save temps: after promotion.
453 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
454 }
455
456 // Be friendly and don't nuke totally the module when the client didn't
457 // supply anything to preserve.
458 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
459 // Apply summary-based internalization decisions.
460 thinLTOInternalizeModule(TheModule, DefinedGlobals);
461 }
462
463 // Save internalized bitcode
464 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
465
466 if (!SingleModule)
467 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
468 ClearDSOLocalOnDeclarations);
469
470 // Do this after any importing so that imported code is updated.
471 // See comment at call to updateVCallVisibilityInIndex() for why
472 // WholeProgramVisibilityEnabledInLTO is false.
474 /* WholeProgramVisibilityEnabledInLTO */ false);
475
476 // Save temps: after cross-module import.
477 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
478
479 optimizeModule(TheModule, TM, OptLevel, Freestanding, DebugPassManager,
480 &Index);
481
482 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
483
484 if (DisableCodeGen) {
485 // Configured to stop before CodeGen, serialize the bitcode and return.
487 {
489 ProfileSummaryInfo PSI(TheModule);
490 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
491 WriteBitcodeToFile(TheModule, OS, true, &Index);
492 }
493 return std::make_unique<SmallVectorMemoryBuffer>(
494 std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
495 }
496
497 return codegenModule(TheModule, TM);
498}
499
500/// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
501/// for caching, and in the \p Index for application during the ThinLTO
502/// backends. This is needed for correctness for exported symbols (ensure
503/// at least one copy kept) and a compile-time optimization (to drop duplicate
504/// copies when possible).
506 ModuleSummaryIndex &Index,
507 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
508 &ResolvedODR,
509 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
511 &PrevailingCopy) {
512
513 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
514 const auto &Prevailing = PrevailingCopy.find(GUID);
515 // Not in map means that there was only one copy, which must be prevailing.
516 if (Prevailing == PrevailingCopy.end())
517 return true;
518 return Prevailing->second == S;
519 };
520
521 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
523 GlobalValue::LinkageTypes NewLinkage) {
524 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
525 };
526
527 // TODO Conf.VisibilityScheme can be lto::Config::ELF for ELF.
528 lto::Config Conf;
529 thinLTOResolvePrevailingInIndex(Conf, Index, isPrevailing, recordNewLinkage,
530 GUIDPreservedSymbols);
531}
532
533// Initialize the TargetMachine builder for a given Triple
534static void initTMBuilder(TargetMachineBuilder &TMBuilder,
535 const Triple &TheTriple) {
536 if (TMBuilder.MCpu.empty())
537 TMBuilder.MCpu = lto::getThinLTODefaultCPU(TheTriple);
538 TMBuilder.TheTriple = std::move(TheTriple);
539}
540
542 MemoryBufferRef Buffer(Data, Identifier);
543
544 auto InputOrError = lto::InputFile::create(Buffer);
545 if (!InputOrError)
546 report_fatal_error(Twine("ThinLTO cannot create input file: ") +
547 toString(InputOrError.takeError()));
548
549 auto TripleStr = (*InputOrError)->getTargetTriple();
550 Triple TheTriple(TripleStr);
551
552 if (Modules.empty())
553 initTMBuilder(TMBuilder, Triple(TheTriple));
554 else if (TMBuilder.TheTriple != TheTriple) {
555 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
556 report_fatal_error("ThinLTO modules with incompatible triples not "
557 "supported");
558 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
559 }
560
561 Modules.emplace_back(std::move(*InputOrError));
562}
563
565 PreservedSymbols.insert(Name);
566}
567
569 // FIXME: At the moment, we don't take advantage of this extra information,
570 // we're conservatively considering cross-references as preserved.
571 // CrossReferencedSymbols.insert(Name);
572 PreservedSymbols.insert(Name);
573}
574
575// TargetMachine factory
576std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
577 std::string ErrMsg;
578 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple, ErrMsg);
579 if (!TheTarget) {
580 report_fatal_error(Twine("Can't load target for this Triple: ") + ErrMsg);
581 }
582
583 // Use MAttr as the default set of features.
584 SubtargetFeatures Features(MAttr);
585 Features.getDefaultSubtargetFeatures(TheTriple);
586 std::string FeatureStr = Features.getString();
587
588 std::unique_ptr<TargetMachine> TM(
589 TheTarget->createTargetMachine(TheTriple, MCpu, FeatureStr, Options,
590 RelocModel, std::nullopt, CGOptLevel));
591 assert(TM && "Cannot create target machine");
592
593 return TM;
594}
595
596/**
597 * Produce the combined summary index from all the bitcode files:
598 * "thin-link".
599 */
600std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
601 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
602 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
603 for (auto &Mod : Modules) {
604 auto &M = Mod->getSingleBitcodeModule();
605 if (Error Err = M.readSummary(*CombinedIndex, Mod->getName())) {
606 // FIXME diagnose
608 std::move(Err), errs(),
609 "error: can't create module summary index for buffer: ");
610 return nullptr;
611 }
612 }
613 return CombinedIndex;
614}
615
616namespace {
617struct IsExported {
619 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols;
620
621 IsExported(
623 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)
624 : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {}
625
626 bool operator()(StringRef ModuleIdentifier, ValueInfo VI) const {
627 const auto &ExportList = ExportLists.find(ModuleIdentifier);
628 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
629 GUIDPreservedSymbols.count(VI.getGUID());
630 }
631};
632
633struct IsPrevailing {
636 &PrevailingCopy)
637 : PrevailingCopy(PrevailingCopy) {}
638
639 bool operator()(GlobalValue::GUID GUID, const GlobalValueSummary *S) const {
640 const auto &Prevailing = PrevailingCopy.find(GUID);
641 // Not in map means that there was only one copy, which must be prevailing.
642 if (Prevailing == PrevailingCopy.end())
643 return true;
644 return Prevailing->second == S;
645 };
646};
647} // namespace
648
650 ModuleSummaryIndex &Index,
651 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
652 // We have no symbols resolution available. And can't do any better now in the
653 // case where the prevailing symbol is in a native object. It can be refined
654 // with linker information in the future.
655 auto isPrevailing = [&](GlobalValue::GUID G) {
657 };
658 computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
659 /* ImportEnabled = */ true);
660}
661
662/**
663 * Perform promotion and renaming of exported internal functions.
664 * Index is updated to reflect linkage changes from weak resolution.
665 */
667 const lto::InputFile &File) {
668 auto ModuleCount = Index.modulePaths().size();
669 auto ModuleIdentifier = TheModule.getModuleIdentifier();
670
671 // Collect for each module the list of function it defines (GUID -> Summary).
672 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries;
673 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
674
675 // Convert the preserved symbols set from string to GUID
676 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
677 File, PreservedSymbols, TheModule.getTargetTriple());
678
679 // Add used symbol to the preserved symbols.
680 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
681
682 // Compute "dead" symbols, we don't want to import/export these!
683 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
684
685 // Compute prevailing symbols
687 computePrevailingCopies(Index, PrevailingCopy);
688
689 // Generate import/export list
690 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
692 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
693 IsPrevailing(PrevailingCopy), ImportLists,
694 ExportLists);
695
696 // Resolve prevailing symbols
698 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
699 PrevailingCopy);
700
701 thinLTOFinalizeInModule(TheModule,
702 ModuleToDefinedGVSummaries[ModuleIdentifier],
703 /*PropagateAttrs=*/false);
704
705 // Promote the exported values in the index, so that they are promoted
706 // in the module.
708 Index, IsExported(ExportLists, GUIDPreservedSymbols),
709 IsPrevailing(PrevailingCopy));
710
711 // FIXME Set ClearDSOLocalOnDeclarations.
712 promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
713}
714
715/**
716 * Perform cross-module importing for the module identified by ModuleIdentifier.
717 */
719 ModuleSummaryIndex &Index,
720 const lto::InputFile &File) {
721 auto ModuleMap = generateModuleMap(Modules);
722 auto ModuleCount = Index.modulePaths().size();
723
724 // Collect for each module the list of function it defines (GUID -> Summary).
725 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
726 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
727
728 // Convert the preserved symbols set from string to GUID
729 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
730 File, PreservedSymbols, TheModule.getTargetTriple());
731
732 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
733
734 // Compute "dead" symbols, we don't want to import/export these!
735 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
736
737 // Compute prevailing symbols
739 computePrevailingCopies(Index, PrevailingCopy);
740
741 // Generate import/export list
742 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
744 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
745 IsPrevailing(PrevailingCopy), ImportLists,
746 ExportLists);
747 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
748
749 // FIXME Set ClearDSOLocalOnDeclarations.
750 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
751 /*ClearDSOLocalOnDeclarations=*/false);
752}
753
754/**
755 * Compute the list of summaries needed for importing into module.
756 */
758 Module &TheModule, ModuleSummaryIndex &Index,
759 ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
760 GVSummaryPtrSet &DecSummaries, const lto::InputFile &File) {
761 auto ModuleCount = Index.modulePaths().size();
762 auto ModuleIdentifier = TheModule.getModuleIdentifier();
763
764 // Collect for each module the list of function it defines (GUID -> Summary).
765 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
766 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
767
768 // Convert the preserved symbols set from string to GUID
769 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
770 File, PreservedSymbols, TheModule.getTargetTriple());
771
772 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
773
774 // Compute "dead" symbols, we don't want to import/export these!
775 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
776
777 // Compute prevailing symbols
779 computePrevailingCopies(Index, PrevailingCopy);
780
781 // Generate import/export list
782 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
784 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
785 IsPrevailing(PrevailingCopy), ImportLists,
786 ExportLists);
787
789 ModuleIdentifier, ModuleToDefinedGVSummaries,
790 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex, DecSummaries);
791}
792
793/**
794 * Emit the list of files needed for importing into module.
795 */
797 ModuleSummaryIndex &Index,
798 const lto::InputFile &File) {
799 auto ModuleCount = Index.modulePaths().size();
800 auto ModuleIdentifier = TheModule.getModuleIdentifier();
801
802 // Collect for each module the list of function it defines (GUID -> Summary).
803 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
804 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
805
806 // Convert the preserved symbols set from string to GUID
807 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
808 File, PreservedSymbols, TheModule.getTargetTriple());
809
810 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
811
812 // Compute "dead" symbols, we don't want to import/export these!
813 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
814
815 // Compute prevailing symbols
817 computePrevailingCopies(Index, PrevailingCopy);
818
819 // Generate import/export list
820 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
822 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
823 IsPrevailing(PrevailingCopy), ImportLists,
824 ExportLists);
825
826 // 'EmitImportsFiles' emits the list of modules from which to import from, and
827 // the set of keys in `ModuleToSummariesForIndex` should be a superset of keys
828 // in `DecSummaries`, so no need to use `DecSummaries` in `EmitImportsFiles`.
829 GVSummaryPtrSet DecSummaries;
830 ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
832 ModuleIdentifier, ModuleToDefinedGVSummaries,
833 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex, DecSummaries);
834
835 if (Error EC = EmitImportsFiles(ModuleIdentifier, OutputName,
836 ModuleToSummariesForIndex))
837 report_fatal_error(Twine("Failed to open ") + OutputName +
838 " to save imports lists\n");
839}
840
841/**
842 * Perform internalization. Runs promote and internalization together.
843 * Index is updated to reflect linkage changes.
844 */
846 ModuleSummaryIndex &Index,
847 const lto::InputFile &File) {
848 initTMBuilder(TMBuilder, TheModule.getTargetTriple());
849 auto ModuleCount = Index.modulePaths().size();
850 auto ModuleIdentifier = TheModule.getModuleIdentifier();
851
852 // Convert the preserved symbols set from string to GUID
853 auto GUIDPreservedSymbols =
854 computeGUIDPreservedSymbols(File, PreservedSymbols, TMBuilder.TheTriple);
855
856 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
857
858 // Collect for each module the list of function it defines (GUID -> Summary).
859 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
860 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
861
862 // Compute "dead" symbols, we don't want to import/export these!
863 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
864
865 // Compute prevailing symbols
867 computePrevailingCopies(Index, PrevailingCopy);
868
869 // Generate import/export list
870 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
872 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
873 IsPrevailing(PrevailingCopy), ImportLists,
874 ExportLists);
875 auto &ExportList = ExportLists[ModuleIdentifier];
876
877 // Be friendly and don't nuke totally the module when the client didn't
878 // supply anything to preserve.
879 if (ExportList.empty() && GUIDPreservedSymbols.empty())
880 return;
881
882 // Resolve prevailing symbols
884 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
885 PrevailingCopy);
886
887 // Promote the exported values in the index, so that they are promoted
888 // in the module.
890 Index, IsExported(ExportLists, GUIDPreservedSymbols),
891 IsPrevailing(PrevailingCopy));
892
893 // FIXME Set ClearDSOLocalOnDeclarations.
894 promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
895
896 // Internalization
897 thinLTOFinalizeInModule(TheModule,
898 ModuleToDefinedGVSummaries[ModuleIdentifier],
899 /*PropagateAttrs=*/false);
900
901 thinLTOInternalizeModule(TheModule,
902 ModuleToDefinedGVSummaries[ModuleIdentifier]);
903}
904
905/**
906 * Perform post-importing ThinLTO optimizations.
907 */
909 initTMBuilder(TMBuilder, TheModule.getTargetTriple());
910
911 // Optimize now
912 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
913 DebugPassManager, nullptr);
914}
915
916/// Write out the generated object file, either from CacheEntryPath or from
917/// OutputBuffer, preferring hard-link when possible.
918/// Returns the path to the generated file in SavedObjectsDirectoryPath.
919std::string
921 const MemoryBuffer &OutputBuffer) {
922 auto ArchName = TMBuilder.TheTriple.getArchName();
923 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
924 llvm::sys::path::append(OutputPath,
925 Twine(count) + "." + ArchName + ".thinlto.o");
926 OutputPath.c_str(); // Ensure the string is null terminated.
927 if (sys::fs::exists(OutputPath))
928 sys::fs::remove(OutputPath);
929
930 // We don't return a memory buffer to the linker, just a list of files.
931 if (!CacheEntryPath.empty()) {
932 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
933 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
934 if (!Err)
935 return std::string(OutputPath);
936 // Hard linking failed, try to copy.
937 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
938 if (!Err)
939 return std::string(OutputPath);
940 // Copy failed (could be because the CacheEntry was removed from the cache
941 // in the meantime by another process), fall back and try to write down the
942 // buffer to the output.
943 errs() << "remark: can't link or copy from cached entry '" << CacheEntryPath
944 << "' to '" << OutputPath << "'\n";
945 }
946 // No cache entry, just write out the buffer.
947 std::error_code Err;
948 raw_fd_ostream OS(OutputPath, Err, sys::fs::OF_None);
949 if (Err)
950 report_fatal_error(Twine("Can't open output '") + OutputPath + "'\n");
951 OS << OutputBuffer.getBuffer();
952 return std::string(OutputPath);
953}
954
955// Main entry point for the ThinLTO processing
957 timeTraceProfilerBegin("ThinLink", StringRef(""));
958 auto TimeTraceScopeExit = llvm::make_scope_exit([]() {
961 });
962 // Prepare the resulting object vector
963 assert(ProducedBinaries.empty() && "The generator should not be reused");
964 if (SavedObjectsDirectoryPath.empty())
965 ProducedBinaries.resize(Modules.size());
966 else {
967 sys::fs::create_directories(SavedObjectsDirectoryPath);
968 bool IsDir;
969 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
970 if (!IsDir)
971 report_fatal_error(Twine("Unexistent dir: '") + SavedObjectsDirectoryPath + "'");
972 ProducedBinaryFiles.resize(Modules.size());
973 }
974
975 if (CodeGenOnly) {
976 // Perform only parallel codegen and return.
978 int count = 0;
979 for (auto &Mod : Modules) {
980 Pool.async([&](int count) {
982 Context.setDiscardValueNames(LTODiscardValueNames);
983
984 // Parse module now
985 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
986 /*IsImporting*/ false);
987
988 // CodeGen
989 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
990 if (SavedObjectsDirectoryPath.empty())
991 ProducedBinaries[count] = std::move(OutputBuffer);
992 else
993 ProducedBinaryFiles[count] =
994 writeGeneratedObject(count, "", *OutputBuffer);
995 }, count++);
996 }
997
998 return;
999 }
1000
1001 // Sequential linking phase
1002 auto Index = linkCombinedIndex();
1003
1004 // Save temps: index.
1005 if (!SaveTempsDir.empty()) {
1006 auto SaveTempPath = SaveTempsDir + "index.bc";
1007 std::error_code EC;
1008 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
1009 if (EC)
1010 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
1011 " to save optimized bitcode\n");
1012 writeIndexToFile(*Index, OS);
1013 }
1014
1015
1016 // Prepare the module map.
1017 auto ModuleMap = generateModuleMap(Modules);
1018 auto ModuleCount = Modules.size();
1019
1020 // Collect for each module the list of function it defines (GUID -> Summary).
1021 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
1022 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1023
1024 // Convert the preserved symbols set from string to GUID, this is needed for
1025 // computing the caching hash and the internalization.
1026 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1027 for (const auto &M : Modules)
1028 computeGUIDPreservedSymbols(*M, PreservedSymbols, TMBuilder.TheTriple,
1029 GUIDPreservedSymbols);
1030
1031 // Add used symbol from inputs to the preserved symbols.
1032 for (const auto &M : Modules)
1033 addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
1034
1035 // Compute "dead" symbols, we don't want to import/export these!
1036 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
1037
1038 // Currently there is no support for enabling whole program visibility via a
1039 // linker option in the old LTO API, but this call allows it to be specified
1040 // via the internal option. Must be done before WPD below.
1041 if (hasWholeProgramVisibility(/* WholeProgramVisibilityEnabledInLTO */ false))
1042 Index->setWithWholeProgramVisibility();
1043
1044 // FIXME: This needs linker information via a TBD new interface
1046 /*WholeProgramVisibilityEnabledInLTO=*/false,
1047 // FIXME: These need linker information via a
1048 // TBD new interface.
1049 /*DynamicExportSymbols=*/{},
1050 /*VisibleToRegularObjSymbols=*/{});
1051
1052 // Perform index-based WPD. This will return immediately if there are
1053 // no index entries in the typeIdMetadata map (e.g. if we are instead
1054 // performing IR-based WPD in hybrid regular/thin LTO mode).
1055 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1056 std::set<GlobalValue::GUID> ExportedGUIDs;
1057 runWholeProgramDevirtOnIndex(*Index, ExportedGUIDs, LocalWPDTargetsMap);
1058 GUIDPreservedSymbols.insert_range(ExportedGUIDs);
1059
1060 // Compute prevailing symbols
1062 computePrevailingCopies(*Index, PrevailingCopy);
1063
1064 // Collect the import/export lists for all modules from the call-graph in the
1065 // combined index.
1066 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
1068 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries,
1069 IsPrevailing(PrevailingCopy), ImportLists,
1070 ExportLists);
1071
1072 // We use a std::map here to be able to have a defined ordering when
1073 // producing a hash for the cache entry.
1074 // FIXME: we should be able to compute the caching hash for the entry based
1075 // on the index, and nuke this map.
1077
1078 // Resolve prevailing symbols, this has to be computed early because it
1079 // impacts the caching.
1080 resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols,
1081 PrevailingCopy);
1082
1083 // Use global summary-based analysis to identify symbols that can be
1084 // internalized (because they aren't exported or preserved as per callback).
1085 // Changes are made in the index, consumed in the ThinLTO backends.
1087 IsExported(ExportLists, GUIDPreservedSymbols),
1088 LocalWPDTargetsMap);
1090 *Index, IsExported(ExportLists, GUIDPreservedSymbols),
1091 IsPrevailing(PrevailingCopy));
1092
1093 thinLTOPropagateFunctionAttrs(*Index, IsPrevailing(PrevailingCopy));
1094
1095 // Make sure that every module has an entry in the ExportLists, ImportList,
1096 // GVSummary and ResolvedODR maps to enable threaded access to these maps
1097 // below.
1098 for (auto &Module : Modules) {
1099 auto ModuleIdentifier = Module->getName();
1100 ExportLists[ModuleIdentifier];
1101 ImportLists[ModuleIdentifier];
1102 ResolvedODR[ModuleIdentifier];
1103 ModuleToDefinedGVSummaries[ModuleIdentifier];
1104 }
1105
1106 std::vector<BitcodeModule *> ModulesVec;
1107 ModulesVec.reserve(Modules.size());
1108 for (auto &Mod : Modules)
1109 ModulesVec.push_back(&Mod->getSingleBitcodeModule());
1110 std::vector<int> ModulesOrdering = lto::generateModulesOrdering(ModulesVec);
1111
1114
1115 TimeTraceScopeExit.release();
1116
1117 // Parallel optimizer + codegen
1118 {
1120 for (auto IndexCount : ModulesOrdering) {
1121 auto &Mod = Modules[IndexCount];
1122 Pool.async([&](int count) {
1123 auto ModuleIdentifier = Mod->getName();
1124 auto &ExportList = ExportLists[ModuleIdentifier];
1125
1126 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
1127
1128 // The module may be cached, this helps handling it.
1129 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
1130 ImportLists[ModuleIdentifier], ExportList,
1131 ResolvedODR[ModuleIdentifier],
1132 DefinedGVSummaries, OptLevel, Freestanding,
1133 TMBuilder);
1134 auto CacheEntryPath = CacheEntry.getEntryPath();
1135
1136 {
1137 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1138 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1139 << " '" << CacheEntryPath << "' for buffer "
1140 << count << " " << ModuleIdentifier << "\n");
1141
1142 if (ErrOrBuffer) {
1143 // Cache Hit!
1144 if (SavedObjectsDirectoryPath.empty())
1145 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1146 else
1147 ProducedBinaryFiles[count] = writeGeneratedObject(
1148 count, CacheEntryPath, *ErrOrBuffer.get());
1149 return;
1150 }
1151 }
1152
1154 Context.setDiscardValueNames(LTODiscardValueNames);
1155 Context.enableDebugTypeODRUniquing();
1156 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1159 if (!DiagFileOrErr) {
1160 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1161 report_fatal_error("ThinLTO: Can't get an output file for the "
1162 "remarks");
1163 }
1164
1165 // Parse module now
1166 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1167 /*IsImporting*/ false);
1168
1169 // Save temps: original file.
1170 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1171
1172 auto &ImportList = ImportLists[ModuleIdentifier];
1173 // Run the main process now, and generates a binary
1174 auto OutputBuffer = ProcessThinLTOModule(
1175 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1176 ExportList, GUIDPreservedSymbols,
1177 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1178 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count,
1179 DebugPassManager);
1180
1181 // Commit to the cache (if enabled)
1182 CacheEntry.write(*OutputBuffer);
1183
1184 if (SavedObjectsDirectoryPath.empty()) {
1185 // We need to generated a memory buffer for the linker.
1186 if (!CacheEntryPath.empty()) {
1187 // When cache is enabled, reload from the cache if possible.
1188 // Releasing the buffer from the heap and reloading it from the
1189 // cache file with mmap helps us to lower memory pressure.
1190 // The freed memory can be used for the next input file.
1191 // The final binary link will read from the VFS cache (hopefully!)
1192 // or from disk (if the memory pressure was too high).
1193 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1194 if (auto EC = ReloadedBufferOrErr.getError()) {
1195 // On error, keep the preexisting buffer and print a diagnostic.
1196 errs() << "remark: can't reload cached file '" << CacheEntryPath
1197 << "': " << EC.message() << "\n";
1198 } else {
1199 OutputBuffer = std::move(*ReloadedBufferOrErr);
1200 }
1201 }
1202 ProducedBinaries[count] = std::move(OutputBuffer);
1203 return;
1204 }
1205 ProducedBinaryFiles[count] = writeGeneratedObject(
1206 count, CacheEntryPath, *OutputBuffer);
1207 }, IndexCount);
1208 }
1209 }
1210
1211 pruneCache(CacheOptions.Path, CacheOptions.Policy, ProducedBinaries);
1212
1213 // If statistics were requested, print them out now.
1217}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file provides a bitcode writing pass.
#define LLVM_LIFETIME_BOUND
Definition: Compiler.h:435
std::string Name
Symbol * Sym
Definition: ELF_riscv.cpp:479
Provides passes for computing function attributes based on interprocedural analyses.
This file implements a simple parser to decode commandline option for remarks hotness threshold that ...
static LVOptions Options
Definition: LVOptions.cpp:25
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
This is the interface to build a ModuleSummaryIndex for a module.
CGSCCAnalysisManager CGAM
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
This header defines classes/functions to handle pass execution timing information with interfaces for...
raw_pwrite_stream & OS
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This header defines a class that provides bookkeeping for all standard (i.e in-tree) pass instrumenta...
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
static void crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index, StringMap< lto::InputFile * > &ModuleMap, const FunctionImporter::ImportMapTy &ImportList, bool ClearDSOLocalOnDeclarations)
static void computeDeadSymbolsInIndex(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
static StringMap< lto::InputFile * > generateModuleMap(std::vector< std::unique_ptr< lto::InputFile > > &Modules)
static void initTMBuilder(TargetMachineBuilder &TMBuilder, const Triple &TheTriple)
static void resolvePrevailingInIndex(ModuleSummaryIndex &Index, StringMap< std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > > &ResolvedODR, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, const DenseMap< GlobalValue::GUID, const GlobalValueSummary * > &PrevailingCopy)
Resolve prevailing symbols.
static void computePrevailingCopies(const ModuleSummaryIndex &Index, DenseMap< GlobalValue::GUID, const GlobalValueSummary * > &PrevailingCopy)
static void saveTempBitcode(const Module &TheModule, StringRef TempDir, unsigned count, StringRef Suffix)
static void verifyLoadedModule(Module &TheModule)
Verify the module and strip broken debug info.
static void addUsedSymbolToPreservedGUID(const lto::InputFile &File, DenseSet< GlobalValue::GUID > &PreservedGUID)
static std::unique_ptr< MemoryBuffer > ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index, StringMap< lto::InputFile * > &ModuleMap, TargetMachine &TM, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, const GVSummaryMapTy &DefinedGlobals, const ThinLTOCodeGenerator::CachingOptions &CacheOptions, bool DisableCodeGen, StringRef SaveTempsDir, bool Freestanding, unsigned OptLevel, unsigned count, bool DebugPassManager)
static cl::opt< int > ThreadCount("threads", cl::init(0))
static std::unique_ptr< MemoryBuffer > codegenModule(Module &TheModule, TargetMachine &TM)
static void optimizeModule(Module &TheModule, TargetMachine &TM, unsigned OptLevel, bool Freestanding, bool DebugPassManager, ModuleSummaryIndex *Index)
static void computeGUIDPreservedSymbols(const lto::InputFile &File, const StringSet<> &PreservedSymbols, const Triple &TheTriple, DenseSet< GlobalValue::GUID > &GUIDs)
static std::unique_ptr< Module > loadModuleFromInput(lto::InputFile *Input, LLVMContext &Context, bool Lazy, bool IsImporting)
static const GlobalValueSummary * getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList)
static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations)
char * getBuffer()
Definition: Utility.h:206
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:473
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:177
iterator end()
Definition: DenseMap.h:87
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition: DenseMap.h:124
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
This is the base abstract class for diagnostic reporting in the backend.
virtual void print(DiagnosticPrinter &DP) const =0
Print using the given DP a user-friendly message.
Interface for custom diagnostic printing.
Base class for error info classes.
Definition: Error.h:44
Represents either an error or a value T.
Definition: ErrorOr.h:56
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
static ErrorSuccess success()
Create a success value.
Definition: Error.h:336
Tagged union holding either a T or a Error.
Definition: Error.h:485
Error takeError()
Take ownership of the stored error.
Definition: Error.h:612
reference get()
Returns a reference to the stored T value.
Definition: Error.h:582
The map maintains the list of imports.
The function importer is automatically importing function from other modules based on the provided su...
LLVM_ABI Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
Function and variable summary information to aid decisions and implementation of importing.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition: Globals.cpp:77
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:381
bool isWeakForLinker() const
Definition: GlobalValue.h:554
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:52
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:53
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:52
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Given an already-open file descriptor, read the file and return a MemoryBuffer.
StringRef getBuffer() const
Definition: MemoryBuffer.h:71
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:281
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:285
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:269
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:252
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition: Module.cpp:631
static LLVM_ABI const OptimizationLevel O3
Optimize for fast execution as much as possible.
static LLVM_ABI const OptimizationLevel O0
Disable as many optimizations as possible.
static LLVM_ABI const OptimizationLevel O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
static LLVM_ABI const OptimizationLevel O1
Optimize quickly without destroying debuggability.
This class provides access to building LLVM's passes.
Definition: PassBuilder.h:110
LLVM_ABI void registerLoopAnalyses(LoopAnalysisManager &LAM)
Registers all available loop analysis passes.
LLVM_ABI void crossRegisterProxies(LoopAnalysisManager &LAM, FunctionAnalysisManager &FAM, CGSCCAnalysisManager &CGAM, ModuleAnalysisManager &MAM, MachineFunctionAnalysisManager *MFAM=nullptr)
Cross register the analysis managers through their proxies.
LLVM_ABI ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary)
Build a ThinLTO default optimization pipeline to a pass manager.
LLVM_ABI void registerModuleAnalyses(ModuleAnalysisManager &MAM)
Registers all available module analysis passes.
LLVM_ABI void registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM)
Registers all available CGSCC analysis passes.
LLVM_ABI void registerFunctionAnalyses(FunctionAnalysisManager &FAM)
Registers all available function analysis passes.
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
Definition: PassManager.h:196
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
Tunable parameters for passes in the default pipelines.
Definition: PassBuilder.h:44
bool SLPVectorization
Tuning option to enable/disable slp loop vectorization, set based on opt level.
Definition: PassBuilder.h:59
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition: PassBuilder.h:55
Analysis providing profile information.
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:282
A non-threaded implementation.
Definition: ThreadPool.h:215
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
const char * c_str()
Definition: SmallString.h:259
bool empty() const
Definition: SmallVector.h:82
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
This class provides an interface to register all the standard pass instrumentations and manages their...
unsigned size() const
Definition: StringMap.h:109
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:133
bool contains(StringRef Key) const
contains - Return true if the element is in the map, false otherwise.
Definition: StringMap.h:277
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:280
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:25
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition: StringSet.h:39
Manages the enabling and disabling of subtarget specific features.
LLVM_ABI void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
LLVM_ABI std::string getString() const
Returns features as a string.
Analysis pass providing the TargetLibraryInfo.
Implementation of the target library information.
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:83
Target - Wrapper for Target specific information.
TargetMachine * createTargetMachine(const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
LLVM_ABI void preserveSymbol(StringRef Name)
Adds to a list of all global symbols that must exist in the final generated code.
LLVM_ABI void run()
Process all the modules that were added to the code generator in parallel.
LLVM_ABI void crossReferenceSymbol(StringRef Name)
Adds to a list of all global symbols that are cross-referenced between ThinLTO files.
LLVM_ABI void addModule(StringRef Identifier, StringRef Data)
Add given module to the code generator.
auto async(Function &&F, Args &&...ArgList)
Asynchronous submission of a task to the pool.
Definition: ThreadPool.h:79
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:47
LLVM_ABI std::string merge(const Triple &Other) const
Merge target triples.
Definition: Triple.cpp:2149
LLVM_ABI StringRef getArchName() const
Get the architecture (first) component of the triple.
Definition: Triple.cpp:1376
LLVM_ABI bool isCompatibleWith(const Triple &Other) const
Test whether target triples are compatible.
Definition: Triple.cpp:2114
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:194
void insert_range(Range &&R)
Definition: DenseSet.h:222
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:174
PassManager manages ModulePassManagers.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
An input file.
Definition: LTO.h:118
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition: LTO.cpp:561
LLVM_ABI BitcodeModule & getSingleBitcodeModule()
Definition: LTO.cpp:594
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:461
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:692
LLVM_ABI void optimize(Module &Module)
Perform post-importing ThinLTO optimizations.
LLVM_ABI std::unique_ptr< ModuleSummaryIndex > linkCombinedIndex()
Produce the combined summary index from all the bitcode files: "thin-link".
LLVM_ABI void crossModuleImport(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform cross-module importing for the module identified by ModuleIdentifier.
LLVM_ABI void emitImports(Module &Module, StringRef OutputName, ModuleSummaryIndex &Index, const lto::InputFile &File)
Compute and emit the imported files for module at ModulePath.
LLVM_ABI void internalize(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform internalization.
LLVM_ABI void gatherImportedSummariesForModule(Module &Module, ModuleSummaryIndex &Index, ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, GVSummaryPtrSet &DecSummaries, const lto::InputFile &File)
Compute the list of summaries and the subset of declaration summaries needed for importing into modul...
LLVM_ABI void promote(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform promotion and renaming of exported internal functions, and additionally resolve weak and link...
LLVM_ABI std::string writeGeneratedObject(int count, StringRef CacheEntryPath, const MemoryBuffer &OutputBuffer)
Write temporary object file to SavedObjectDirectoryPath, write symlink to Cache directory if needed.
Interfaces for registering analysis passes, producing common pass manager configurations,...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Key
PAL metadata keys.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition: LTO.cpp:1795
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition: LTO.cpp:2211
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > 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:2167
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
LLVM_ABI std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
LLVM_ABI bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1077
@ OF_UpdateAtime
Force files Atime to be updated on access.
Definition: FileSystem.h:786
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
LLVM_ABI Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition: Path.cpp:967
LLVM_ABI std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition: Path.cpp:1016
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition: Path.cpp:1092
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:456
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
ThreadPoolStrategy heavyweight_hardware_concurrency(unsigned ThreadCount=0)
Returns a thread strategy for tasks requiring significant memory or other resources.
Definition: Threading.h:162
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition: Error.cpp:65
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1744
cl::opt< bool > LTODiscardValueNames("lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), cl::init(false), cl::Hidden)
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
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"))
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:990
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
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 void renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations, SetVector< GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
LLVM_ABI ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI, std::function< const StackSafetyInfo *(const Function &F)> GetSSICallback=[](const Function &F) -> const StackSafetyInfo *{ return nullptr;})
Direct function to compute a ModuleSummaryIndex from a given module.
LLVM_ABI void reportAndResetTimings(raw_ostream *OutStream=nullptr)
If -time-passes has been specified, report the timings immediately and then reset the timers to zero.
@ DK_Linker
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.
LLVM_ABI void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition: LTO.cpp:548
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
LLVM_ABI Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue)
Definition: DWP.cpp:622
bool timeTraceProfilerEnabled()
Is the time trace profiler enabled, i.e. initialized?
Definition: TimeProfiler.h:130
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition: Error.cpp:167
LLVM_ABI Error writeToOutput(StringRef OutputFileName, std::function< Error(raw_ostream &)> Write)
This helper creates an output stream and then passes it to Write.
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
Definition: Statistic.cpp:139
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"))
LLVM_ABI void updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
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:447
std::vector< std::unique_ptr< GlobalValueSummary > > GlobalValueSummaryList
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:565
@ Mod
The access may modify the value stored in memory.
LLVM_ABI void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
Definition: Statistic.cpp:229
LLVM_ABI void runWholeProgramDevirtOnIndex(ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap)
Perform index-based whole program devirtualization on the Summary index.
LLVM_ABI bool pruneCache(StringRef Path, CachePruningPolicy Policy, const std::vector< std::unique_ptr< MemoryBuffer > > &Files={})
Peform pruning using the supplied policy, returns true if pruning occurred, i.e.
LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
std::unordered_set< GlobalValueSummary * > GVSummaryPtrSet
A set of global value summary pointers.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1973
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.
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
@ DS_Warning
@ DS_Error
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)
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1777
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:103
const char * toString(DWARFSectionKind Kind)
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition: Error.cpp:117
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.
LLVM_ABI bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
Definition: Verifier.cpp:7513
LLVM_ABI TimeTraceProfilerEntry * timeTraceProfilerBegin(StringRef Name, StringRef Detail)
Manually begin a time section, with the given Name and Detail.
LLVM_ABI void updateVCallVisibilityInIndex(ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, const DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
LLVM_ABI void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)
Based on the information recorded in the summaries during global summary-based analysis:
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
static const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Helper to gather options relevant to the target machine creation.
LLVM_ABI std::unique_ptr< TargetMachine > create() const
Struct that holds a reference to a particular GUID in a global value summary.
LTO configuration.
Definition: Config.h:42
std::vector< std::string > MAttrs
Definition: Config.h:51
CodeGenOptLevel CGOptLevel
Definition: Config.h:58
std::string CPU
Definition: Config.h:49
TargetOptions Options
Definition: Config.h:50
unsigned OptLevel
Definition: Config.h:60
std::optional< Reloc::Model > RelocModel
Definition: Config.h:56
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition: Config.h:66