LLVM 23.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
85}
86
87// Default to using all available threads in the system, but using only one
88// thred per core, as indicated by the usage of
89// heavyweight_hardware_concurrency() below.
90static cl::opt<int> ThreadCount("threads", cl::init(0));
91
92// Simple helper to save temporary files for debug.
93static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
94 unsigned count, StringRef Suffix) {
95 if (TempDir.empty())
96 return;
97 // User asked to save temps, let dump the bitcode file after import.
98 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
99 std::error_code EC;
100 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
101 if (EC)
102 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
103 " to save optimized bitcode\n");
104 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
105}
106
108 ArrayRef<std::unique_ptr<GlobalValueSummary>> GVSummaryList) {
109 // If there is any strong definition anywhere, get it.
110 auto StrongDefForLinker = llvm::find_if(
111 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
112 auto Linkage = Summary->linkage();
115 });
116 if (StrongDefForLinker != GVSummaryList.end())
117 return StrongDefForLinker->get();
118 // Get the first *linker visible* definition for this global in the summary
119 // list.
120 auto FirstDefForLinker = llvm::find_if(
121 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
122 auto Linkage = Summary->linkage();
124 });
125 // Extern templates can be emitted as available_externally.
126 if (FirstDefForLinker == GVSummaryList.end())
127 return nullptr;
128 return FirstDefForLinker->get();
129}
130
131// Populate map of GUID to the prevailing copy for any multiply defined
132// symbols. Currently assume first copy is prevailing, or any strong
133// definition. Can be refined with Linker information in the future.
135 const ModuleSummaryIndex &Index,
137 auto HasMultipleCopies =
139 return GVSummaryList.size() > 1;
140 };
141
142 for (auto &I : Index) {
143 if (HasMultipleCopies(I.second.getSummaryList()))
144 PrevailingCopy[I.first] =
145 getFirstDefinitionForLinker(I.second.getSummaryList());
146 }
147}
148
150generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) {
152 for (auto &M : Modules) {
153 LLVM_DEBUG(dbgs() << "Adding module " << M->getName() << " to ModuleMap\n");
154 assert(!ModuleMap.contains(M->getName()) &&
155 "Expect unique Buffer Identifier");
156 ModuleMap[M->getName()] = M.get();
157 }
158 return ModuleMap;
159}
160
161static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index,
162 bool ClearDSOLocalOnDeclarations) {
163 renameModuleForThinLTO(TheModule, Index, ClearDSOLocalOnDeclarations);
164}
165
166namespace {
167class ThinLTODiagnosticInfo : public DiagnosticInfo {
168 const Twine &Msg;
169public:
170 ThinLTODiagnosticInfo(const Twine &DiagMsg LLVM_LIFETIME_BOUND,
171 DiagnosticSeverity Severity = DS_Error)
172 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
173 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
174};
175}
176
177/// Verify the module and strip broken debug info.
178static void verifyLoadedModule(Module &TheModule) {
179 bool BrokenDebugInfo = false;
180 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
181 report_fatal_error("Broken module found, compilation aborted!");
182 if (BrokenDebugInfo) {
183 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
184 "Invalid debug info found, debug info will be stripped", DS_Warning));
185 StripDebugInfo(TheModule);
186 }
187}
188
189static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile *Input,
190 LLVMContext &Context,
191 bool Lazy,
192 bool IsImporting) {
193 auto &Mod = Input->getSingleBitcodeModule();
194 SMDiagnostic Err;
196 Lazy ? Mod.getLazyModule(Context,
197 /* ShouldLazyLoadMetadata */ true, IsImporting)
198 : Mod.parseModule(Context);
199 if (!ModuleOrErr) {
200 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
201 SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(),
202 SourceMgr::DK_Error, EIB.message());
203 Err.print("ThinLTO", errs());
204 });
205 report_fatal_error("Can't load module, abort.");
206 }
207 if (!Lazy)
208 verifyLoadedModule(*ModuleOrErr.get());
209 return std::move(*ModuleOrErr);
210}
211
212static void
215 const FunctionImporter::ImportMapTy &ImportList,
216 bool ClearDSOLocalOnDeclarations) {
217 auto Loader = [&](StringRef Identifier) {
218 auto &Input = ModuleMap[Identifier];
219 return loadModuleFromInput(Input, TheModule.getContext(),
220 /*Lazy=*/true, /*IsImporting*/ true);
221 };
222
223 FunctionImporter Importer(Index, Loader, ClearDSOLocalOnDeclarations);
224 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
225 if (!Result) {
226 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
227 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
228 SourceMgr::DK_Error, EIB.message());
229 Err.print("ThinLTO", errs());
230 });
231 report_fatal_error("importFunctions failed");
232 }
233 // Verify again after cross-importing.
234 verifyLoadedModule(TheModule);
235}
236
237static void optimizeModule(Module &TheModule, TargetMachine &TM,
238 unsigned OptLevel, bool Freestanding,
239 bool DebugPassManager, ModuleSummaryIndex *Index) {
240 std::optional<PGOOptions> PGOOpt;
241 if (LTORunCSIRInstr) {
242 PGOOpt =
244 /*MemoryProfile=*/"", PGOOptions::IRUse,
246 } else if (!LTOCSIRProfile.empty()) {
247 PGOOpt = PGOOptions(LTOCSIRProfile, "", "",
248 /*MemoryProfile=*/"", PGOOptions::IRUse,
250 } else if (!SampleProfileFile.empty()) {
251 PGOOpt =
253 /*MemoryProfile=*/"", PGOOptions::SampleUse,
255 }
260
262 StandardInstrumentations SI(TheModule.getContext(), DebugPassManager);
263 SI.registerCallbacks(PIC, &MAM);
265 PTO.LoopVectorization = true;
266 PTO.SLPVectorization = true;
267 PassBuilder PB(&TM, PTO, PGOOpt, &PIC);
268
269 std::unique_ptr<TargetLibraryInfoImpl> TLII(
271 if (Freestanding)
272 TLII->disableAllFunctions();
273 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
274
275 // Register all the basic analyses with the managers.
276 PB.registerModuleAnalyses(MAM);
277 PB.registerCGSCCAnalyses(CGAM);
278 PB.registerFunctionAnalyses(FAM);
279 PB.registerLoopAnalyses(LAM);
280 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
281
283
285
286 switch (OptLevel) {
287 default:
288 llvm_unreachable("Invalid optimization level");
289 case 0:
291 break;
292 case 1:
294 break;
295 case 2:
297 break;
298 case 3:
300 break;
301 }
302
303 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, Index));
304
305 MPM.run(TheModule, MAM);
306}
307
308static void
310 DenseSet<GlobalValue::GUID> &PreservedGUID) {
311 Triple TT(File.getTargetTriple());
312 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
313 TargetLibraryInfoImpl TLII(TT);
314 TargetLibraryInfo TLI(TLII);
315 for (const auto &Sym : File.symbols())
316 if (Sym.isUsed() || Sym.isLibcall(TLI, Libcalls))
317 PreservedGUID.insert(
319}
320
321// Convert the PreservedSymbols map from "Name" based to "GUID" based.
323 const StringSet<> &PreservedSymbols,
324 const Triple &TheTriple,
326 // Iterate the symbols in the input file and if the input has preserved symbol
327 // compute the GUID for the symbol.
328 for (const auto &Sym : File.symbols()) {
329 if (PreservedSymbols.count(Sym.getName()) && !Sym.getIRName().empty())
331 GlobalValue::getGlobalIdentifier(Sym.getIRName(),
333 }
334}
335
338 const StringSet<> &PreservedSymbols,
339 const Triple &TheTriple) {
340 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
341 computeGUIDPreservedSymbols(File, PreservedSymbols, TheTriple,
342 GUIDPreservedSymbols);
343 return GUIDPreservedSymbols;
344}
345
346static std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
347 TargetMachine &TM) {
349
350 // CodeGen
351 {
354
355 // Setup the codegen now.
356 if (TM.addPassesToEmitFile(PM, OS, nullptr, CodeGenFileType::ObjectFile,
357 /* DisableVerify */ true))
358 report_fatal_error("Failed to setup codegen");
359
360 // Run codegen now. resulting binary is in OutputBuffer.
361 PM.run(TheModule);
362 }
363 return std::make_unique<SmallVectorMemoryBuffer>(
364 std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
365}
366
367namespace {
368/// Manage caching for a single Module.
369class ModuleCacheEntry {
370 SmallString<128> EntryPath;
371
372public:
373 // Create a cache entry. This compute a unique hash for the Module considering
374 // the current list of export/import, and offer an interface to query to
375 // access the content in the cache.
376 ModuleCacheEntry(
377 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
378 const FunctionImporter::ImportMapTy &ImportList,
379 const FunctionImporter::ExportSetTy &ExportList,
380 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
381 const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel,
382 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
383 if (CachePath.empty())
384 return;
385
386 if (!Index.modulePaths().count(ModuleID))
387 // The module does not have an entry, it can't have a hash at all
388 return;
389
390 if (all_of(Index.getModuleHash(ModuleID),
391 [](uint32_t V) { return V == 0; }))
392 // No hash entry, no caching!
393 return;
394
395 llvm::lto::Config Conf;
396 Conf.OptLevel = OptLevel;
397 Conf.Options = TMBuilder.Options;
398 Conf.CPU = TMBuilder.MCpu;
399 Conf.MAttrs.push_back(TMBuilder.MAttr);
400 Conf.RelocModel = TMBuilder.RelocModel;
401 Conf.CGOptLevel = TMBuilder.CGOptLevel;
402 Conf.Freestanding = Freestanding;
403 std::string Key =
404 computeLTOCacheKey(Conf, Index, ModuleID, ImportList, ExportList,
405 ResolvedODR, DefinedGVSummaries);
406
407 // This choice of file name allows the cache to be pruned (see pruneCache()
408 // in include/llvm/Support/CachePruning.h).
409 sys::path::append(EntryPath, CachePath, Twine("llvmcache-", Key));
410 }
411
412 // Access the path to this entry in the cache.
413 StringRef getEntryPath() { return EntryPath; }
414
415 // Try loading the buffer for this cache entry.
416 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
417 if (EntryPath.empty())
418 return std::error_code();
419 SmallString<64> ResultPath;
420 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
421 Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
422 if (!FDOrErr)
423 return errorToErrorCode(FDOrErr.takeError());
424 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getOpenFile(
425 *FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
426 sys::fs::closeFile(*FDOrErr);
427 return MBOrErr;
428 }
429
430 // Cache the Produced object file
431 void write(const MemoryBuffer &OutputBuffer) {
432 if (EntryPath.empty())
433 return;
434
435 if (auto Err = llvm::writeToOutput(
436 EntryPath, [&OutputBuffer](llvm::raw_ostream &OS) -> llvm::Error {
437 OS << OutputBuffer.getBuffer();
438 return llvm::Error::success();
439 }))
440 report_fatal_error(llvm::formatv("ThinLTO: Can't write file {0}: {1}",
441 EntryPath,
442 toString(std::move(Err)).c_str()));
443 }
444};
445} // end anonymous namespace
446
447static std::unique_ptr<MemoryBuffer>
450 const FunctionImporter::ImportMapTy &ImportList,
451 const FunctionImporter::ExportSetTy &ExportList,
452 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
453 const GVSummaryMapTy &DefinedGlobals,
454 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
455 bool DisableCodeGen, StringRef SaveTempsDir,
456 bool Freestanding, unsigned OptLevel, unsigned count,
457 bool DebugPassManager) {
458 // "Benchmark"-like optimization: single-source case
459 bool SingleModule = (ModuleMap.size() == 1);
460
461 // When linking an ELF shared object, dso_local should be dropped. We
462 // conservatively do this for -fpic.
463 bool ClearDSOLocalOnDeclarations =
466 TheModule.getPIELevel() == PIELevel::Default;
467
468 if (!SingleModule) {
469 promoteModule(TheModule, Index, ClearDSOLocalOnDeclarations);
470
471 // Apply summary-based prevailing-symbol resolution decisions.
472 thinLTOFinalizeInModule(TheModule, DefinedGlobals, /*PropagateAttrs=*/true);
473
474 // Save temps: after promotion.
475 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
476 }
477
478 // Be friendly and don't nuke totally the module when the client didn't
479 // supply anything to preserve.
480 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
481 // Apply summary-based internalization decisions.
482 thinLTOInternalizeModule(TheModule, DefinedGlobals);
483 }
484
485 // Save internalized bitcode
486 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
487
488 if (!SingleModule)
489 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
490 ClearDSOLocalOnDeclarations);
491
492 // Do this after any importing so that imported code is updated.
493 // See comment at call to updateVCallVisibilityInIndex() for why
494 // WholeProgramVisibilityEnabledInLTO is false.
496 /* WholeProgramVisibilityEnabledInLTO */ false);
497
498 // Save temps: after cross-module import.
499 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
500
501 optimizeModule(TheModule, TM, OptLevel, Freestanding, DebugPassManager,
502 &Index);
503
504 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
505
506 if (DisableCodeGen) {
507 // Configured to stop before CodeGen, serialize the bitcode and return.
509 {
511 ProfileSummaryInfo PSI(TheModule);
512 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
513 WriteBitcodeToFile(TheModule, OS, true, &Index);
514 }
515 return std::make_unique<SmallVectorMemoryBuffer>(
516 std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
517 }
518
519 return codegenModule(TheModule, TM);
520}
521
522/// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
523/// for caching, and in the \p Index for application during the ThinLTO
524/// backends. This is needed for correctness for exported symbols (ensure
525/// at least one copy kept) and a compile-time optimization (to drop duplicate
526/// copies when possible).
528 ModuleSummaryIndex &Index,
529 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
530 &ResolvedODR,
531 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
533 &PrevailingCopy) {
534
535 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
536 const auto &Prevailing = PrevailingCopy.find(GUID);
537 // Not in map means that there was only one copy, which must be prevailing.
538 if (Prevailing == PrevailingCopy.end())
539 return true;
540 return Prevailing->second == S;
541 };
542
543 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
545 GlobalValue::LinkageTypes NewLinkage) {
546 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
547 };
548
549 // TODO Conf.VisibilityScheme can be lto::Config::ELF for ELF.
550 lto::Config Conf;
551 thinLTOResolvePrevailingInIndex(Conf, Index, isPrevailing, recordNewLinkage,
552 GUIDPreservedSymbols);
553}
554
555// Initialize the TargetMachine builder for a given Triple
556static void initTMBuilder(TargetMachineBuilder &TMBuilder,
557 const Triple &TheTriple) {
558 if (TMBuilder.MCpu.empty())
559 TMBuilder.MCpu = lto::getThinLTODefaultCPU(TheTriple);
560 TMBuilder.TheTriple = std::move(TheTriple);
561}
562
564 MemoryBufferRef Buffer(Data, Identifier);
565
566 auto InputOrError = lto::InputFile::create(Buffer);
567 if (!InputOrError)
568 report_fatal_error(Twine("ThinLTO cannot create input file: ") +
569 toString(InputOrError.takeError()));
570
571 auto TripleStr = (*InputOrError)->getTargetTriple();
572 Triple TheTriple(TripleStr);
573
574 if (Modules.empty())
575 initTMBuilder(TMBuilder, Triple(TheTriple));
576 else if (TMBuilder.TheTriple != TheTriple) {
577 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
578 report_fatal_error("ThinLTO modules with incompatible triples not "
579 "supported");
580 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
581 }
582
583 Modules.emplace_back(std::move(*InputOrError));
584}
585
587 PreservedSymbols.insert(Name);
588}
589
591 // FIXME: At the moment, we don't take advantage of this extra information,
592 // we're conservatively considering cross-references as preserved.
593 // CrossReferencedSymbols.insert(Name);
594 PreservedSymbols.insert(Name);
595}
596
597// TargetMachine factory
598std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
599 std::string ErrMsg;
600 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple, ErrMsg);
601 if (!TheTarget) {
602 report_fatal_error(Twine("Can't load target for this Triple: ") + ErrMsg);
603 }
604
605 // Use MAttr as the default set of features.
606 SubtargetFeatures Features(MAttr);
608 std::string FeatureStr = Features.getString();
609
610 std::unique_ptr<TargetMachine> TM(
611 TheTarget->createTargetMachine(TheTriple, MCpu, FeatureStr, Options,
612 RelocModel, std::nullopt, CGOptLevel));
613 assert(TM && "Cannot create target machine");
614
615 return TM;
616}
617
618/**
619 * Produce the combined summary index from all the bitcode files:
620 * "thin-link".
621 */
622std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
623 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
624 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
625 for (auto &Mod : Modules) {
626 auto &M = Mod->getSingleBitcodeModule();
627 if (Error Err = M.readSummary(*CombinedIndex, Mod->getName())) {
628 // FIXME diagnose
630 std::move(Err), errs(),
631 "error: can't create module summary index for buffer: ");
632 return nullptr;
633 }
634 }
635 return CombinedIndex;
636}
637
638namespace {
639struct IsExported {
641 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols;
642
643 IsExported(
645 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)
646 : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {}
647
648 bool operator()(StringRef ModuleIdentifier, ValueInfo VI) const {
649 const auto &ExportList = ExportLists.find(ModuleIdentifier);
650 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
651 GUIDPreservedSymbols.count(VI.getGUID());
652 }
653};
654
655struct IsPrevailing {
656 const DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy;
657 IsPrevailing(const DenseMap<GlobalValue::GUID, const GlobalValueSummary *>
658 &PrevailingCopy)
659 : PrevailingCopy(PrevailingCopy) {}
660
661 bool operator()(GlobalValue::GUID GUID, const GlobalValueSummary *S) const {
662 const auto &Prevailing = PrevailingCopy.find(GUID);
663 // Not in map means that there was only one copy, which must be prevailing.
664 if (Prevailing == PrevailingCopy.end())
665 return true;
666 return Prevailing->second == S;
667 };
668};
669} // namespace
670
672 ModuleSummaryIndex &Index,
673 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
674 // We have no symbols resolution available. And can't do any better now in the
675 // case where the prevailing symbol is in a native object. It can be refined
676 // with linker information in the future.
677 auto isPrevailing = [&](GlobalValue::GUID G) {
679 };
680 computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
681 /* ImportEnabled = */ true);
682}
683
684/**
685 * Perform promotion and renaming of exported internal functions.
686 * Index is updated to reflect linkage changes from weak resolution.
687 */
689 const lto::InputFile &File) {
690 auto ModuleCount = Index.modulePaths().size();
691 auto ModuleIdentifier = TheModule.getModuleIdentifier();
692
693 // Collect for each module the list of function it defines (GUID -> Summary).
694 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries;
695 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
696
697 // Convert the preserved symbols set from string to GUID
698 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
699 File, PreservedSymbols, TheModule.getTargetTriple());
700
701 // Add used symbol to the preserved symbols.
702 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
703
704 // Compute "dead" symbols, we don't want to import/export these!
705 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
706
707 // Compute prevailing symbols
709 computePrevailingCopies(Index, PrevailingCopy);
710
711 // Generate import/export list
712 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
714 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
715 IsPrevailing(PrevailingCopy), ImportLists,
716 ExportLists);
717
718 // Resolve prevailing symbols
720 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
721 PrevailingCopy);
722
723 thinLTOFinalizeInModule(TheModule,
724 ModuleToDefinedGVSummaries[ModuleIdentifier],
725 /*PropagateAttrs=*/false);
726
727 // Promote the exported values in the index, so that they are promoted
728 // in the module.
730 Index, IsExported(ExportLists, GUIDPreservedSymbols),
731 IsPrevailing(PrevailingCopy));
732
733 // FIXME Set ClearDSOLocalOnDeclarations.
734 promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
735}
736
737/**
738 * Perform cross-module importing for the module identified by ModuleIdentifier.
739 */
741 ModuleSummaryIndex &Index,
742 const lto::InputFile &File) {
743 auto ModuleMap = generateModuleMap(Modules);
744 auto ModuleCount = Index.modulePaths().size();
745
746 // Collect for each module the list of function it defines (GUID -> Summary).
747 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
748 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
749
750 // Convert the preserved symbols set from string to GUID
751 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
752 File, PreservedSymbols, TheModule.getTargetTriple());
753
754 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
755
756 // Compute "dead" symbols, we don't want to import/export these!
757 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
758
759 // Compute prevailing symbols
761 computePrevailingCopies(Index, PrevailingCopy);
762
763 // Generate import/export list
764 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
766 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
767 IsPrevailing(PrevailingCopy), ImportLists,
768 ExportLists);
769 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
770
771 // FIXME Set ClearDSOLocalOnDeclarations.
772 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
773 /*ClearDSOLocalOnDeclarations=*/false);
774}
775
776/**
777 * Compute the list of summaries needed for importing into module.
778 */
780 Module &TheModule, ModuleSummaryIndex &Index,
781 ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
782 GVSummaryPtrSet &DecSummaries, const lto::InputFile &File) {
783 auto ModuleCount = Index.modulePaths().size();
784 auto ModuleIdentifier = TheModule.getModuleIdentifier();
785
786 // Collect for each module the list of function it defines (GUID -> Summary).
787 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
788 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
789
790 // Convert the preserved symbols set from string to GUID
791 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
792 File, PreservedSymbols, TheModule.getTargetTriple());
793
794 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
795
796 // Compute "dead" symbols, we don't want to import/export these!
797 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
798
799 // Compute prevailing symbols
801 computePrevailingCopies(Index, PrevailingCopy);
802
803 // Generate import/export list
804 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
806 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
807 IsPrevailing(PrevailingCopy), ImportLists,
808 ExportLists);
809
811 ModuleIdentifier, ModuleToDefinedGVSummaries,
812 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex, DecSummaries);
813}
814
815/**
816 * Emit the list of files needed for importing into module.
817 */
819 ModuleSummaryIndex &Index,
820 const lto::InputFile &File) {
821 auto ModuleCount = Index.modulePaths().size();
822 auto ModuleIdentifier = TheModule.getModuleIdentifier();
823
824 // Collect for each module the list of function it defines (GUID -> Summary).
825 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
826 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
827
828 // Convert the preserved symbols set from string to GUID
829 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
830 File, PreservedSymbols, TheModule.getTargetTriple());
831
832 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
833
834 // Compute "dead" symbols, we don't want to import/export these!
835 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
836
837 // Compute prevailing symbols
839 computePrevailingCopies(Index, PrevailingCopy);
840
841 // Generate import/export list
842 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
844 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
845 IsPrevailing(PrevailingCopy), ImportLists,
846 ExportLists);
847
848 // 'EmitImportsFiles' emits the list of modules from which to import from, and
849 // the set of keys in `ModuleToSummariesForIndex` should be a superset of keys
850 // in `DecSummaries`, so no need to use `DecSummaries` in `EmitImportsFiles`.
851 GVSummaryPtrSet DecSummaries;
852 ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
854 ModuleIdentifier, ModuleToDefinedGVSummaries,
855 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex, DecSummaries);
856
857 if (Error EC = EmitImportsFiles(ModuleIdentifier, OutputName,
858 ModuleToSummariesForIndex))
859 report_fatal_error(Twine("Failed to open ") + OutputName +
860 " to save imports lists\n");
861}
862
863/**
864 * Perform internalization. Runs promote and internalization together.
865 * Index is updated to reflect linkage changes.
866 */
868 ModuleSummaryIndex &Index,
869 const lto::InputFile &File) {
870 initTMBuilder(TMBuilder, TheModule.getTargetTriple());
871 auto ModuleCount = Index.modulePaths().size();
872 auto ModuleIdentifier = TheModule.getModuleIdentifier();
873
874 // Convert the preserved symbols set from string to GUID
875 auto GUIDPreservedSymbols =
876 computeGUIDPreservedSymbols(File, PreservedSymbols, TMBuilder.TheTriple);
877
878 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
879
880 // Collect for each module the list of function it defines (GUID -> Summary).
881 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
882 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
883
884 // Compute "dead" symbols, we don't want to import/export these!
885 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
886
887 // Compute prevailing symbols
889 computePrevailingCopies(Index, PrevailingCopy);
890
891 // Generate import/export list
892 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
894 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
895 IsPrevailing(PrevailingCopy), ImportLists,
896 ExportLists);
897 auto &ExportList = ExportLists[ModuleIdentifier];
898
899 // Be friendly and don't nuke totally the module when the client didn't
900 // supply anything to preserve.
901 if (ExportList.empty() && GUIDPreservedSymbols.empty())
902 return;
903
904 // Resolve prevailing symbols
906 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
907 PrevailingCopy);
908
909 // Promote the exported values in the index, so that they are promoted
910 // in the module.
912 Index, IsExported(ExportLists, GUIDPreservedSymbols),
913 IsPrevailing(PrevailingCopy));
914
915 // FIXME Set ClearDSOLocalOnDeclarations.
916 promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
917
918 // Internalization
919 thinLTOFinalizeInModule(TheModule,
920 ModuleToDefinedGVSummaries[ModuleIdentifier],
921 /*PropagateAttrs=*/false);
922
923 thinLTOInternalizeModule(TheModule,
924 ModuleToDefinedGVSummaries[ModuleIdentifier]);
925}
926
927/**
928 * Perform post-importing ThinLTO optimizations.
929 */
931 initTMBuilder(TMBuilder, TheModule.getTargetTriple());
932
933 // Optimize now
934 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
935 DebugPassManager, nullptr);
936}
937
938/// Write out the generated object file, either from CacheEntryPath or from
939/// OutputBuffer, preferring hard-link when possible.
940/// Returns the path to the generated file in SavedObjectsDirectoryPath.
941std::string
943 const MemoryBuffer &OutputBuffer) {
944 auto ArchName = TMBuilder.TheTriple.getArchName();
945 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
946 llvm::sys::path::append(OutputPath,
947 Twine(count) + "." + ArchName + ".thinlto.o");
948 OutputPath.c_str(); // Ensure the string is null terminated.
949 if (sys::fs::exists(OutputPath))
950 sys::fs::remove(OutputPath);
951
952 // We don't return a memory buffer to the linker, just a list of files.
953 if (!CacheEntryPath.empty()) {
954 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
955 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
956 if (!Err)
957 return std::string(OutputPath);
958 // Hard linking failed, try to copy.
959 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
960 if (!Err)
961 return std::string(OutputPath);
962 // Copy failed (could be because the CacheEntry was removed from the cache
963 // in the meantime by another process), fall back and try to write down the
964 // buffer to the output.
965 errs() << "remark: can't link or copy from cached entry '" << CacheEntryPath
966 << "' to '" << OutputPath << "'\n";
967 }
968 // No cache entry, just write out the buffer.
969 std::error_code Err;
970 raw_fd_ostream OS(OutputPath, Err, sys::fs::OF_None);
971 if (Err)
972 report_fatal_error(Twine("Can't open output '") + OutputPath + "'\n");
973 OS << OutputBuffer.getBuffer();
974 return std::string(OutputPath);
975}
976
977// Main entry point for the ThinLTO processing
979 timeTraceProfilerBegin("ThinLink", StringRef(""));
980 llvm::scope_exit TimeTraceScopeExit([]() {
983 });
984 // Prepare the resulting object vector
985 assert(ProducedBinaries.empty() && "The generator should not be reused");
986 if (SavedObjectsDirectoryPath.empty())
987 ProducedBinaries.resize(Modules.size());
988 else {
989 sys::fs::create_directories(SavedObjectsDirectoryPath);
990 bool IsDir;
991 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
992 if (!IsDir)
993 report_fatal_error(Twine("Unexistent dir: '") + SavedObjectsDirectoryPath + "'");
994 ProducedBinaryFiles.resize(Modules.size());
995 }
996
997 if (CodeGenOnly) {
998 // Perform only parallel codegen and return.
1000 int count = 0;
1001 for (auto &Mod : Modules) {
1002 Pool.async([&](int count) {
1003 LLVMContext Context;
1005
1006 // Parse module now
1007 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1008 /*IsImporting*/ false);
1009
1010 // CodeGen
1011 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
1012 if (SavedObjectsDirectoryPath.empty())
1013 ProducedBinaries[count] = std::move(OutputBuffer);
1014 else
1015 ProducedBinaryFiles[count] =
1017 }, count++);
1018 }
1019
1020 return;
1021 }
1022
1023 // Sequential linking phase
1024 auto Index = linkCombinedIndex();
1025
1026 // Save temps: index.
1027 if (!SaveTempsDir.empty()) {
1028 auto SaveTempPath = SaveTempsDir + "index.bc";
1029 std::error_code EC;
1030 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
1031 if (EC)
1032 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
1033 " to save optimized bitcode\n");
1034 writeIndexToFile(*Index, OS);
1035 }
1036
1037
1038 // Prepare the module map.
1039 auto ModuleMap = generateModuleMap(Modules);
1040 auto ModuleCount = Modules.size();
1041
1042 // Collect for each module the list of function it defines (GUID -> Summary).
1043 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
1044 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1045
1046 // Convert the preserved symbols set from string to GUID, this is needed for
1047 // computing the caching hash and the internalization.
1048 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1049 for (const auto &M : Modules)
1050 computeGUIDPreservedSymbols(*M, PreservedSymbols, TMBuilder.TheTriple,
1051 GUIDPreservedSymbols);
1052
1053 // Add used symbol from inputs to the preserved symbols.
1054 for (const auto &M : Modules)
1055 addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
1056
1057 // Compute "dead" symbols, we don't want to import/export these!
1058 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
1059
1060 // Currently there is no support for enabling whole program visibility via a
1061 // linker option in the old LTO API, but this call allows it to be specified
1062 // via the internal option. Must be done before WPD below.
1063 if (hasWholeProgramVisibility(/* WholeProgramVisibilityEnabledInLTO */ false))
1064 Index->setWithWholeProgramVisibility();
1065
1066 // FIXME: This needs linker information via a TBD new interface
1068 /*WholeProgramVisibilityEnabledInLTO=*/false,
1069 // FIXME: These need linker information via a
1070 // TBD new interface.
1071 /*DynamicExportSymbols=*/{},
1072 /*VisibleToRegularObjSymbols=*/{});
1073
1074 // Perform index-based WPD. This will return immediately if there are
1075 // no index entries in the typeIdMetadata map (e.g. if we are instead
1076 // performing IR-based WPD in hybrid regular/thin LTO mode).
1077 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1078 std::set<GlobalValue::GUID> ExportedGUIDs;
1079 runWholeProgramDevirtOnIndex(*Index, ExportedGUIDs, LocalWPDTargetsMap);
1080 GUIDPreservedSymbols.insert_range(ExportedGUIDs);
1081
1082 // Compute prevailing symbols
1084 computePrevailingCopies(*Index, PrevailingCopy);
1085
1086 // Collect the import/export lists for all modules from the call-graph in the
1087 // combined index.
1088 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
1090 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries,
1091 IsPrevailing(PrevailingCopy), ImportLists,
1092 ExportLists);
1093
1094 // We use a std::map here to be able to have a defined ordering when
1095 // producing a hash for the cache entry.
1096 // FIXME: we should be able to compute the caching hash for the entry based
1097 // on the index, and nuke this map.
1099
1100 // Resolve prevailing symbols, this has to be computed early because it
1101 // impacts the caching.
1102 resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols,
1103 PrevailingCopy);
1104
1105 // Use global summary-based analysis to identify symbols that can be
1106 // internalized (because they aren't exported or preserved as per callback).
1107 // Changes are made in the index, consumed in the ThinLTO backends.
1109 IsExported(ExportLists, GUIDPreservedSymbols),
1110 LocalWPDTargetsMap);
1112 *Index, IsExported(ExportLists, GUIDPreservedSymbols),
1113 IsPrevailing(PrevailingCopy));
1114
1115 thinLTOPropagateFunctionAttrs(*Index, IsPrevailing(PrevailingCopy));
1116
1117 // Make sure that every module has an entry in the ExportLists, ImportList,
1118 // GVSummary and ResolvedODR maps to enable threaded access to these maps
1119 // below.
1120 for (auto &Module : Modules) {
1121 auto ModuleIdentifier = Module->getName();
1122 ExportLists[ModuleIdentifier];
1123 ImportLists[ModuleIdentifier];
1124 ResolvedODR[ModuleIdentifier];
1125 ModuleToDefinedGVSummaries[ModuleIdentifier];
1126 }
1127
1128 std::vector<BitcodeModule *> ModulesVec;
1129 ModulesVec.reserve(Modules.size());
1130 for (auto &Mod : Modules)
1131 ModulesVec.push_back(&Mod->getSingleBitcodeModule());
1132 std::vector<int> ModulesOrdering = lto::generateModulesOrdering(ModulesVec);
1133
1136
1137 TimeTraceScopeExit.release();
1138
1139 // Parallel optimizer + codegen
1140 {
1142 for (auto IndexCount : ModulesOrdering) {
1143 auto &Mod = Modules[IndexCount];
1144 Pool.async([&](int count) {
1145 auto ModuleIdentifier = Mod->getName();
1146 auto &ExportList = ExportLists[ModuleIdentifier];
1147
1148 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
1149
1150 // The module may be cached, this helps handling it.
1151 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
1152 ImportLists[ModuleIdentifier], ExportList,
1153 ResolvedODR[ModuleIdentifier],
1154 DefinedGVSummaries, OptLevel, Freestanding,
1155 TMBuilder);
1156 auto CacheEntryPath = CacheEntry.getEntryPath();
1157
1158 {
1159 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1160 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1161 << " '" << CacheEntryPath << "' for buffer "
1162 << count << " " << ModuleIdentifier << "\n");
1163
1164 if (ErrOrBuffer) {
1165 // Cache Hit!
1166 if (SavedObjectsDirectoryPath.empty())
1167 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1168 else
1169 ProducedBinaryFiles[count] = writeGeneratedObject(
1170 count, CacheEntryPath, *ErrOrBuffer.get());
1171 return;
1172 }
1173 }
1174
1175 LLVMContext Context;
1177 Context.enableDebugTypeODRUniquing();
1178 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1181 if (!DiagFileOrErr) {
1182 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1183 report_fatal_error("ThinLTO: Can't get an output file for the "
1184 "remarks");
1185 }
1186
1187 // Parse module now
1188 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1189 /*IsImporting*/ false);
1190
1191 // Save temps: original file.
1192 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1193
1194 auto &ImportList = ImportLists[ModuleIdentifier];
1195 // Run the main process now, and generates a binary
1197 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1198 ExportList, GUIDPreservedSymbols,
1199 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1200 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count,
1201 DebugPassManager);
1202
1203 // Commit to the cache (if enabled)
1204 CacheEntry.write(*OutputBuffer);
1205
1206 if (SavedObjectsDirectoryPath.empty()) {
1207 // We need to generated a memory buffer for the linker.
1208 if (!CacheEntryPath.empty()) {
1209 // When cache is enabled, reload from the cache if possible.
1210 // Releasing the buffer from the heap and reloading it from the
1211 // cache file with mmap helps us to lower memory pressure.
1212 // The freed memory can be used for the next input file.
1213 // The final binary link will read from the VFS cache (hopefully!)
1214 // or from disk (if the memory pressure was too high).
1215 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1216 if (auto EC = ReloadedBufferOrErr.getError()) {
1217 // On error, keep the preexisting buffer and print a diagnostic.
1218 errs() << "remark: can't reload cached file '" << CacheEntryPath
1219 << "': " << EC.message() << "\n";
1220 } else {
1221 OutputBuffer = std::move(*ReloadedBufferOrErr);
1222 }
1223 }
1224 ProducedBinaries[count] = std::move(OutputBuffer);
1225 return;
1226 }
1227 ProducedBinaryFiles[count] = writeGeneratedObject(
1228 count, CacheEntryPath, *OutputBuffer);
1229 }, IndexCount);
1230 }
1231 }
1232
1233 Expected<bool> PrunedOrErr =
1234 pruneCache(CacheOptions.Path, CacheOptions.Policy, ProducedBinaries);
1235 if (!PrunedOrErr) {
1236 errs() << "Error: " << toString(PrunedOrErr.takeError()) << "\n";
1237 report_fatal_error("ThinLTO: failure to prune cache");
1238 }
1239
1240 // If statistics were requested, print them out now.
1244}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file provides a bitcode writing pass.
#define LLVM_LIFETIME_BOUND
Definition Compiler.h:435
DXIL Finalize Linkage
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 ...
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
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...
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 const GlobalValueSummary * getFirstDefinitionForLinker(ArrayRef< std::unique_ptr< GlobalValueSummary > > GVSummaryList)
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 void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations)
The Input class is used to parse a yaml document into in-memory structs and vectors.
char * getBuffer()
Definition Utility.h:220
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
iterator end()
Definition DenseMap.h:81
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
This is the base abstract class for diagnostic reporting in the backend.
Base class for error info classes.
Definition Error.h:44
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.
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
Function and variable summary information to aid decisions and implementation of importing.
static 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
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
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:170
bool isWeakForLinker() const
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.
LLVM_ABI void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
This interface provides simple read-only access to a block of memory, and provides simple methods for...
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
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:283
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:287
StringRef getName() const
Get a short "name" for the module.
Definition Module.h:271
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition Module.h:254
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition Module.cpp:643
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.
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
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:41
bool SLPVectorization
Tuning option to enable/disable slp loop vectorization, set based on opt level.
Definition PassBuilder.h:56
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition PassBuilder.h:52
Analysis providing profile information.
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition SourceMgr.h:303
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
const char * c_str()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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:280
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition StringMap.h:285
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
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
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.
Provides information about what library functions are available for the current target.
Primary interface to the complete machine description for the target machine.
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfoWrapperPass *MMIWP=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
const Triple & getTargetTriple() const
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
TargetOptions Options
VectorLibrary VecLib
Vector math library to use.
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:80
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:782
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:202
void insert_range(Range &&R)
Definition DenseSet.h:228
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:180
PassManager manages ModulePassManagers.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
An input file.
Definition LTO.h:115
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:624
A raw_ostream that writes to a file descriptor.
A raw_ostream that writes to an SmallVector or SmallString.
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.
ThinLTOCodeGeneratorImpl - Namespace used for ThinLTOCodeGenerator implementation details.
initializer< Ty > init(const Ty &Val)
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1892
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:2301
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2345
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:1097
@ OF_UpdateAtime
Force files Atime to be updated on access.
Definition FileSystem.h:801
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:983
LLVM_ABI std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition Path.cpp:1032
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition Path.cpp:1112
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:457
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
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
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:1738
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
std::unordered_set< GlobalValueSummary * > GVSummaryPtrSet
A set of global value summary pointers.
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.
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:1013
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
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.
LLVM_ABI bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO)
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
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 ...
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
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 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...
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
cl::opt< std::string > LTOCSIRProfile("cs-profile-path", cl::desc("Context sensitive profile file path"))
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
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
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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.
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
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 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:488
cl::opt< bool > LTORunCSIRInstr("cs-profile-generate", cl::desc("Perform context sensitive PGO instrumentation"))
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
LLVM_ABI void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
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:2011
SingleThreadExecutor DefaultThreadPool
Definition ThreadPool.h:262
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::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
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:1771
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:137
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI Expected< bool > pruneCache(StringRef Path, CachePruningPolicy Policy, const std::vector< std::unique_ptr< MemoryBuffer > > &Files={})
Perform pruning using the supplied policy, returns true if pruning occurred, i.e.
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition Error.cpp:113
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 write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:721
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.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
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:606
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...
cl::opt< std::string > SampleProfileFile
LLVM_ABI void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)
Based on the information recorded in the summaries during global summary-based analysis:
A struct capturing PGO tunables.
Definition PGOOptions.h:22
A simple container for information about the supported runtime calls.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, 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:43
std::vector< std::string > MAttrs
Definition Config.h:52
CodeGenOptLevel CGOptLevel
Definition Config.h:64
std::string CPU
Definition Config.h:50
TargetOptions Options
Definition Config.h:51
unsigned OptLevel
Definition Config.h:66
std::optional< Reloc::Model > RelocModel
Definition Config.h:62
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition Config.h:72