LLVM 24.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
18
19#include "llvm/ADT/ScopeExit.h"
20#include "llvm/ADT/Statistic.h"
29#include "llvm/Config/llvm-config.h"
30#include "llvm/IR/DebugInfo.h"
32#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Mangler.h"
37#include "llvm/IR/Verifier.h"
39#include "llvm/LTO/LTO.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/Error.h"
51#include "llvm/Support/Path.h"
52#include "llvm/Support/SHA1.h"
66
67#if !defined(_MSC_VER) && !defined(__MINGW32__)
68#include <unistd.h>
69#else
70#include <io.h>
71#endif
72
73using namespace llvm;
74using namespace ThinLTOCodeGeneratorImpl;
75
76#define DEBUG_TYPE "thinlto"
77
78namespace llvm {
79// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
89}
90
91// Default to using all available threads in the system, but using only one
92// thred per core, as indicated by the usage of
93// heavyweight_hardware_concurrency() below.
94static cl::opt<int> ThreadCount("threads", cl::init(0));
95
96// Simple helper to save temporary files for debug.
97static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
98 unsigned count, StringRef Suffix) {
99 if (TempDir.empty())
100 return;
101 // User asked to save temps, let dump the bitcode file after import.
102 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
103 std::error_code EC;
104 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
105 if (EC)
106 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
107 " to save optimized bitcode\n");
108 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
109}
110
112 ArrayRef<std::unique_ptr<GlobalValueSummary>> GVSummaryList) {
113 // If there is any strong definition anywhere, get it.
114 auto StrongDefForLinker = llvm::find_if(
115 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
116 auto Linkage = Summary->linkage();
119 });
120 if (StrongDefForLinker != GVSummaryList.end())
121 return StrongDefForLinker->get();
122 // Get the first *linker visible* definition for this global in the summary
123 // list.
124 auto FirstDefForLinker = llvm::find_if(
125 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
126 auto Linkage = Summary->linkage();
128 });
129 // Extern templates can be emitted as available_externally.
130 if (FirstDefForLinker == GVSummaryList.end())
131 return nullptr;
132 return FirstDefForLinker->get();
133}
134
135// Populate map of GUID to the prevailing copy for any multiply defined
136// symbols. Currently assume first copy is prevailing, or any strong
137// definition. Can be refined with Linker information in the future.
139 const ModuleSummaryIndex &Index,
141 auto HasMultipleCopies =
143 return GVSummaryList.size() > 1;
144 };
145
146 for (auto &I : Index) {
147 if (HasMultipleCopies(I.second.getSummaryList()))
148 PrevailingCopy[I.first] =
149 getFirstDefinitionForLinker(I.second.getSummaryList());
150 }
151}
152
154generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) {
156 for (auto &M : Modules) {
157 LLVM_DEBUG(dbgs() << "Adding module " << M->getName() << " to ModuleMap\n");
158 assert(!ModuleMap.contains(M->getName()) &&
159 "Expect unique Buffer Identifier");
160 ModuleMap[M->getName()] = M.get();
161 }
162 return ModuleMap;
163}
164
165static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index,
166 bool ClearDSOLocalOnDeclarations) {
167 renameModuleForThinLTO(TheModule, Index, ClearDSOLocalOnDeclarations);
168}
169
170namespace {
171class ThinLTODiagnosticInfo : public DiagnosticInfo {
172 const Twine &Msg;
173public:
174 ThinLTODiagnosticInfo(const Twine &DiagMsg LLVM_LIFETIME_BOUND,
175 DiagnosticSeverity Severity = DS_Error)
176 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
177 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
178};
179}
180
181/// Verify the module and strip broken debug info.
182static void verifyLoadedModule(Module &TheModule) {
183 bool BrokenDebugInfo = false;
184 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
185 report_fatal_error("Broken module found, compilation aborted!");
186 if (BrokenDebugInfo) {
187 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
188 "Invalid debug info found, debug info will be stripped", DS_Warning));
189 StripDebugInfo(TheModule);
190 }
191}
192
193static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile *Input,
194 LLVMContext &Context,
195 bool Lazy,
196 bool IsImporting) {
197 auto &Mod = Input->getSingleBitcodeModule();
199 Lazy ? Mod.getLazyModule(Context,
200 /* ShouldLazyLoadMetadata */ true, IsImporting)
201 : Mod.parseModule(Context);
202 if (!ModuleOrErr) {
203 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
204 SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(),
205 SourceMgr::DK_Error, EIB.message());
206 Err.print("ThinLTO", errs());
207 });
208 report_fatal_error("Can't load module, abort.");
209 }
210 if (!Lazy)
211 verifyLoadedModule(*ModuleOrErr.get());
212 return std::move(*ModuleOrErr);
213}
214
215static void
218 const FunctionImporter::ImportMapTy &ImportList,
219 bool ClearDSOLocalOnDeclarations) {
220 auto Loader = [&](StringRef Identifier) {
221 auto &Input = ModuleMap[Identifier];
222 return loadModuleFromInput(Input, TheModule.getContext(),
223 /*Lazy=*/true, /*IsImporting*/ true);
224 };
225
226 FunctionImporter Importer(Index, Loader, ClearDSOLocalOnDeclarations);
227 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
228 if (!Result) {
229 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
230 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
231 SourceMgr::DK_Error, EIB.message());
232 Err.print("ThinLTO", errs());
233 });
234 report_fatal_error("importFunctions failed");
235 }
236 // Verify again after cross-importing.
237 verifyLoadedModule(TheModule);
238}
239
240static void optimizeModule(Module &TheModule, TargetMachine &TM,
241 unsigned OptLevel, bool Freestanding,
242 bool DebugPassManager, ModuleSummaryIndex *Index) {
243 std::optional<PGOOptions> PGOOpt;
244 if (LTORunCSIRInstr) {
245 PGOOpt =
247 /*MemoryProfile=*/"", PGOOptions::IRUse,
249 } else if (!LTOCSIRProfile.empty()) {
250 PGOOpt = PGOOptions(LTOCSIRProfile, "", "",
251 /*MemoryProfile=*/"", PGOOptions::IRUse,
253 } else if (StringRef SampleProfileFile =
255 TheModule.getContext());
256 !SampleProfileFile.empty()) {
257 PGOOpt =
258 PGOOptions(SampleProfileFile.str(), "", "",
259 /*MemoryProfile=*/"", PGOOptions::SampleUse,
261 }
266
268 StandardInstrumentations SI(TheModule.getContext(), DebugPassManager);
269 SI.registerCallbacks(PIC, &MAM);
271 PTO.LoopVectorization = true;
272 PTO.SLPVectorization = true;
273 PassBuilder PB(TheModule.getContext(), &TM, PTO, PGOOpt, &PIC);
274
275 std::unique_ptr<TargetLibraryInfoImpl> TLII(
277 if (Freestanding)
278 TLII->disableAllFunctions();
279 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
280
281 // Register all the basic analyses with the managers.
282 PB.registerModuleAnalyses(MAM);
283 PB.registerCGSCCAnalyses(CGAM);
284 PB.registerFunctionAnalyses(FAM);
285 PB.registerLoopAnalyses(LAM);
286 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
287
289
291
292 switch (OptLevel) {
293 default:
294 llvm_unreachable("Invalid optimization level");
295 case 0:
297 break;
298 case 1:
300 break;
301 case 2:
303 break;
304 case 3:
306 break;
307 }
308
309 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, Index));
310
311 MPM.run(TheModule, MAM);
312}
313
314static void
316 DenseSet<GlobalValue::GUID> &PreservedGUID) {
317 Triple TT(File.getTargetTriple());
318 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
319 TargetLibraryInfoImpl TLII(TT);
321 for (const auto &Sym : File.symbols())
322 if (Sym.isUsed() || Sym.isLibcall(TLI, Libcalls))
323 PreservedGUID.insert(
325}
326
327// Convert the PreservedSymbols map from "Name" based to "GUID" based.
329 const StringSet<> &PreservedSymbols,
330 const Triple &TheTriple,
332 // Iterate the symbols in the input file and if the input has preserved symbol
333 // compute the GUID for the symbol.
334 for (const auto &Sym : File.symbols()) {
335 if (PreservedSymbols.count(Sym.getName()) && !Sym.getIRName().empty())
337 GlobalValue::getGlobalIdentifier(Sym.getIRName(),
339 }
340}
341
344 const StringSet<> &PreservedSymbols,
345 const Triple &TheTriple) {
346 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
347 computeGUIDPreservedSymbols(File, PreservedSymbols, TheTriple,
348 GUIDPreservedSymbols);
349 return GUIDPreservedSymbols;
350}
351
352static std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
353 TargetMachine &TM) {
355
356 // CodeGen
357 {
359 if (runCodeGenPipeline(TM, TheModule, OS, nullptr,
361 report_fatal_error("Failed to run codegen");
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 ArrayRef<std::string> MllvmArgs) {
384 if (CachePath.empty())
385 return;
386
387 if (!Index.modulePaths().count(ModuleID))
388 // The module does not have an entry, it can't have a hash at all
389 return;
390
391 if (all_of(Index.getModuleHash(ModuleID),
392 [](uint32_t V) { return V == 0; }))
393 // No hash entry, no caching!
394 return;
395
396 llvm::lto::Config Conf;
397 Conf.OptLevel = OptLevel;
398 Conf.Options = TMBuilder.Options;
399 Conf.CPU = TMBuilder.MCpu;
400 Conf.MAttrs.push_back(TMBuilder.MAttr);
401 Conf.RelocModel = TMBuilder.RelocModel;
402 Conf.CGOptLevel = TMBuilder.CGOptLevel;
403 Conf.Freestanding = Freestanding;
404 append_range(Conf.MllvmArgs, MllvmArgs);
405 std::string Key =
406 computeLTOCacheKey(Conf, Index, ModuleID, ImportList, ExportList,
407 ResolvedODR, DefinedGVSummaries);
408
409 // This choice of file name allows the cache to be pruned (see pruneCache()
410 // in include/llvm/Support/CachePruning.h).
411 sys::path::append(EntryPath, CachePath, Twine("llvmcache-", Key));
412 }
413
414 // Access the path to this entry in the cache.
415 StringRef getEntryPath() { return EntryPath; }
416
417 // Try loading the buffer for this cache entry.
418 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
419 if (EntryPath.empty())
420 return std::error_code();
421 SmallString<64> ResultPath;
422 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
423 Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
424 if (!FDOrErr)
425 return errorToErrorCode(FDOrErr.takeError());
426 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getOpenFile(
427 *FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
428 sys::fs::closeFile(*FDOrErr);
429 return MBOrErr;
430 }
431
432 // Cache the Produced object file
433 void write(const MemoryBuffer &OutputBuffer) {
434 if (EntryPath.empty())
435 return;
436
437 if (auto Err = llvm::writeToOutput(
438 EntryPath, [&OutputBuffer](llvm::raw_ostream &OS) -> llvm::Error {
439 OS << OutputBuffer.getBuffer();
440 return llvm::Error::success();
441 }))
442 report_fatal_error(llvm::formatv("ThinLTO: Can't write file {0}: {1}",
443 EntryPath,
444 toString(std::move(Err)).c_str()));
445 }
446};
447} // end anonymous namespace
448
449static std::unique_ptr<MemoryBuffer>
452 const FunctionImporter::ImportMapTy &ImportList,
453 const FunctionImporter::ExportSetTy &ExportList,
454 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
455 const GVSummaryMapTy &DefinedGlobals,
456 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
457 bool DisableCodeGen, StringRef SaveTempsDir,
458 bool Freestanding, unsigned OptLevel, unsigned count,
459 bool DebugPassManager) {
460 // "Benchmark"-like optimization: single-source case
461 bool SingleModule = (ModuleMap.size() == 1);
462
463 // When linking an ELF shared object, dso_local should be dropped. We
464 // conservatively do this for -fpic.
465 bool ClearDSOLocalOnDeclarations =
466 TheModule.getTargetTriple().isOSBinFormatELF() &&
468 TheModule.getPIELevel() == PIELevel::Default;
469
470 if (!SingleModule) {
471 promoteModule(TheModule, Index, ClearDSOLocalOnDeclarations);
472
473 // Apply summary-based prevailing-symbol resolution decisions.
474 thinLTOFinalizeInModule(TheModule, DefinedGlobals, /*PropagateAttrs=*/true);
475
476 // Save temps: after promotion.
477 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
478 }
479
480 // Be friendly and don't nuke totally the module when the client didn't
481 // supply anything to preserve.
482 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
483 // Apply summary-based internalization decisions.
484 thinLTOInternalizeModule(TheModule, DefinedGlobals);
485 }
486
487 // Save internalized bitcode
488 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
489
490 if (!SingleModule)
491 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
492 ClearDSOLocalOnDeclarations);
493
494 // Do this after any importing so that imported code is updated.
495 // See comment at call to updateVCallVisibilityInIndex() for why
496 // WholeProgramVisibilityEnabledInLTO is false.
498 /* WholeProgramVisibilityEnabledInLTO */ false);
499
500 // Save temps: after cross-module import.
501 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
502
503 optimizeModule(TheModule, TM, OptLevel, Freestanding, DebugPassManager,
504 &Index);
505
506 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
507
508 if (DisableCodeGen) {
509 // Configured to stop before CodeGen, serialize the bitcode and return.
511 {
513 ProfileSummaryInfo PSI(TheModule);
514 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
515 WriteBitcodeToFile(TheModule, OS, true, &Index);
516 }
517 return std::make_unique<SmallVectorMemoryBuffer>(
518 std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
519 }
520
521 return codegenModule(TheModule, TM);
522}
523
524/// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
525/// for caching, and in the \p Index for application during the ThinLTO
526/// backends. This is needed for correctness for exported symbols (ensure
527/// at least one copy kept) and a compile-time optimization (to drop duplicate
528/// copies when possible).
530 ModuleSummaryIndex &Index,
531 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
532 &ResolvedODR,
533 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
535 &PrevailingCopy) {
536
537 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
538 const auto &Prevailing = PrevailingCopy.find(GUID);
539 // Not in map means that there was only one copy, which must be prevailing.
540 if (Prevailing == PrevailingCopy.end())
541 return true;
542 return Prevailing->second == S;
543 };
544
545 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
547 GlobalValue::LinkageTypes NewLinkage) {
548 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
549 };
550
551 // TODO Conf.VisibilityScheme can be lto::Config::ELF for ELF.
552 lto::Config Conf;
553 thinLTOResolvePrevailingInIndex(Conf, Index, isPrevailing, recordNewLinkage,
554 GUIDPreservedSymbols);
555}
556
557// Initialize the TargetMachine builder for a given Triple
558static void initTMBuilder(TargetMachineBuilder &TMBuilder,
559 const Triple &TheTriple) {
560 if (TMBuilder.MCpu.empty())
561 TMBuilder.MCpu = lto::getThinLTODefaultCPU(TheTriple);
562 TMBuilder.TheTriple = std::move(TheTriple);
563 // If data-sections is not explicitly set or unset, set data-sections by
564 // default to match the behaviour of lld and gold plugin.
566 TMBuilder.Options.DataSections = true;
567}
568
570 MemoryBufferRef Buffer(Data, Identifier);
571
572 auto InputOrError = lto::InputFile::create(Buffer);
573 if (!InputOrError)
574 report_fatal_error(Twine("ThinLTO cannot create input file: ") +
575 toString(InputOrError.takeError()));
576
577 auto TripleStr = (*InputOrError)->getTargetTriple();
578 Triple TheTriple(TripleStr);
579
580 if (Modules.empty())
581 initTMBuilder(TMBuilder, Triple(TheTriple));
582 else if (TMBuilder.TheTriple != TheTriple) {
583 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
584 report_fatal_error("ThinLTO modules with incompatible triples not "
585 "supported");
586 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
587 }
588
589 Modules.emplace_back(std::move(*InputOrError));
590}
591
593 PreservedSymbols.insert(Name);
594}
595
597 // FIXME: At the moment, we don't take advantage of this extra information,
598 // we're conservatively considering cross-references as preserved.
599 // CrossReferencedSymbols.insert(Name);
600 PreservedSymbols.insert(Name);
601}
602
603// TargetMachine factory
604std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
605 std::string ErrMsg;
606 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple, ErrMsg);
607 if (!TheTarget) {
608 report_fatal_error(Twine("Can't load target for this Triple: ") + ErrMsg);
609 }
610
611 // Use MAttr as the default set of features.
612 SubtargetFeatures Features(MAttr);
614 std::string FeatureStr = Features.getString();
615
616 std::unique_ptr<TargetMachine> TM(
617 TheTarget->createTargetMachine(TheTriple, MCpu, FeatureStr, Options,
618 RelocModel, std::nullopt, CGOptLevel));
619 assert(TM && "Cannot create target machine");
620
621 return TM;
622}
623
624/**
625 * Produce the combined summary index from all the bitcode files:
626 * "thin-link".
627 */
628std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
629 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
630 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
631 for (auto &Mod : Modules) {
632 auto &M = Mod->getSingleBitcodeModule();
633 if (Error Err = M.readSummary(*CombinedIndex, Mod->getName())) {
634 // FIXME diagnose
636 std::move(Err), errs(),
637 "error: can't create module summary index for buffer: ");
638 return nullptr;
639 }
640 }
641 return CombinedIndex;
642}
643
644namespace {
645struct IsExported {
647 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols;
648
649 IsExported(
651 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)
652 : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {}
653
654 bool operator()(StringRef ModuleIdentifier, ValueInfo VI) const {
655 const auto &ExportList = ExportLists.find(ModuleIdentifier);
656 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
657 GUIDPreservedSymbols.count(VI.getGUID());
658 }
659};
660
661struct IsPrevailing {
662 const DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy;
663 IsPrevailing(const DenseMap<GlobalValue::GUID, const GlobalValueSummary *>
664 &PrevailingCopy)
665 : PrevailingCopy(PrevailingCopy) {}
666
667 bool operator()(GlobalValue::GUID GUID, const GlobalValueSummary *S) const {
668 const auto &Prevailing = PrevailingCopy.find(GUID);
669 // Not in map means that there was only one copy, which must be prevailing.
670 if (Prevailing == PrevailingCopy.end())
671 return true;
672 return Prevailing->second == S;
673 };
674};
675} // namespace
676
678 ModuleSummaryIndex &Index,
679 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
680 // We have no symbols resolution available. And can't do any better now in the
681 // case where the prevailing symbol is in a native object. It can be refined
682 // with linker information in the future.
683 auto isPrevailing = [&](GlobalValue::GUID G) {
685 };
686 computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
687 /* ImportEnabled = */ true);
688}
689
690/**
691 * Perform promotion and renaming of exported internal functions.
692 * Index is updated to reflect linkage changes from weak resolution.
693 */
695 const lto::InputFile &File) {
696 auto ModuleCount = Index.modulePaths().size();
697 auto ModuleIdentifier = TheModule.getModuleIdentifier();
698
699 // Collect for each module the list of function it defines (GUID -> Summary).
700 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries;
701 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
702
703 // Convert the preserved symbols set from string to GUID
704 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
705 File, PreservedSymbols, TheModule.getTargetTriple());
706
707 // Add used symbol to the preserved symbols.
708 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
709
710 // Compute "dead" symbols, we don't want to import/export these!
711 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
712
713 // Compute prevailing symbols
715 computePrevailingCopies(Index, PrevailingCopy);
716
717 // Generate import/export list
718 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
720 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
721 IsPrevailing(PrevailingCopy), ImportLists,
722 ExportLists);
723
724 // Resolve prevailing symbols
726 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
727 PrevailingCopy);
728
729 thinLTOFinalizeInModule(TheModule,
730 ModuleToDefinedGVSummaries[ModuleIdentifier],
731 /*PropagateAttrs=*/false);
732
733 // Promote the exported values in the index, so that they are promoted
734 // in the module.
736 Index, IsExported(ExportLists, GUIDPreservedSymbols),
737 IsPrevailing(PrevailingCopy));
738
739 // FIXME Set ClearDSOLocalOnDeclarations.
740 promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
741}
742
743/**
744 * Perform cross-module importing for the module identified by ModuleIdentifier.
745 */
747 ModuleSummaryIndex &Index,
748 const lto::InputFile &File) {
749 auto ModuleMap = generateModuleMap(Modules);
750 auto ModuleCount = Index.modulePaths().size();
751
752 // Collect for each module the list of function it defines (GUID -> Summary).
753 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
754 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
755
756 // Convert the preserved symbols set from string to GUID
757 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
758 File, PreservedSymbols, TheModule.getTargetTriple());
759
760 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
761
762 // Compute "dead" symbols, we don't want to import/export these!
763 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
764
765 // Compute prevailing symbols
767 computePrevailingCopies(Index, PrevailingCopy);
768
769 // Generate import/export list
770 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
772 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
773 IsPrevailing(PrevailingCopy), ImportLists,
774 ExportLists);
775 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
776
777 // FIXME Set ClearDSOLocalOnDeclarations.
778 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
779 /*ClearDSOLocalOnDeclarations=*/false);
780}
781
782/**
783 * Compute the list of summaries needed for importing into module.
784 */
786 Module &TheModule, ModuleSummaryIndex &Index,
787 ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
788 GVSummaryPtrSet &DecSummaries, const lto::InputFile &File) {
789 auto ModuleCount = Index.modulePaths().size();
790 auto ModuleIdentifier = TheModule.getModuleIdentifier();
791
792 // Collect for each module the list of function it defines (GUID -> Summary).
793 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
794 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
795
796 // Convert the preserved symbols set from string to GUID
797 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
798 File, PreservedSymbols, TheModule.getTargetTriple());
799
800 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
801
802 // Compute "dead" symbols, we don't want to import/export these!
803 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
804
805 // Compute prevailing symbols
807 computePrevailingCopies(Index, PrevailingCopy);
808
809 // Generate import/export list
810 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
812 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
813 IsPrevailing(PrevailingCopy), ImportLists,
814 ExportLists);
815
817 ModuleIdentifier, ModuleToDefinedGVSummaries,
818 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex, DecSummaries);
819}
820
821/**
822 * Emit the list of files needed for importing into module.
823 */
825 ModuleSummaryIndex &Index,
826 const lto::InputFile &File) {
827 auto ModuleCount = Index.modulePaths().size();
828 auto ModuleIdentifier = TheModule.getModuleIdentifier();
829
830 // Collect for each module the list of function it defines (GUID -> Summary).
831 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
832 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
833
834 // Convert the preserved symbols set from string to GUID
835 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
836 File, PreservedSymbols, TheModule.getTargetTriple());
837
838 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
839
840 // Compute "dead" symbols, we don't want to import/export these!
841 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
842
843 // Compute prevailing symbols
845 computePrevailingCopies(Index, PrevailingCopy);
846
847 // Generate import/export list
848 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
850 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
851 IsPrevailing(PrevailingCopy), ImportLists,
852 ExportLists);
853
854 // 'EmitImportsFiles' emits the list of modules from which to import from, and
855 // the set of keys in `ModuleToSummariesForIndex` should be a superset of keys
856 // in `DecSummaries`, so no need to use `DecSummaries` in `EmitImportsFiles`.
857 GVSummaryPtrSet DecSummaries;
858 ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
860 ModuleIdentifier, ModuleToDefinedGVSummaries,
861 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex, DecSummaries);
862
863 if (Error EC = EmitImportsFiles(ModuleIdentifier, OutputName,
864 ModuleToSummariesForIndex))
865 report_fatal_error(Twine("Failed to open ") + OutputName +
866 " to save imports lists\n");
867}
868
869/**
870 * Perform internalization. Runs promote and internalization together.
871 * Index is updated to reflect linkage changes.
872 */
874 ModuleSummaryIndex &Index,
875 const lto::InputFile &File) {
876 initTMBuilder(TMBuilder, TheModule.getTargetTriple());
877 auto ModuleCount = Index.modulePaths().size();
878 auto ModuleIdentifier = TheModule.getModuleIdentifier();
879
880 // Convert the preserved symbols set from string to GUID
881 auto GUIDPreservedSymbols =
882 computeGUIDPreservedSymbols(File, PreservedSymbols, TMBuilder.TheTriple);
883
884 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
885
886 // Collect for each module the list of function it defines (GUID -> Summary).
887 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
888 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
889
890 // Compute "dead" symbols, we don't want to import/export these!
891 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
892
893 // Compute prevailing symbols
895 computePrevailingCopies(Index, PrevailingCopy);
896
897 // Generate import/export list
898 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
900 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
901 IsPrevailing(PrevailingCopy), ImportLists,
902 ExportLists);
903 auto &ExportList = ExportLists[ModuleIdentifier];
904
905 // Be friendly and don't nuke totally the module when the client didn't
906 // supply anything to preserve.
907 if (ExportList.empty() && GUIDPreservedSymbols.empty())
908 return;
909
910 // Resolve prevailing symbols
912 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
913 PrevailingCopy);
914
915 // Promote the exported values in the index, so that they are promoted
916 // in the module.
918 Index, IsExported(ExportLists, GUIDPreservedSymbols),
919 IsPrevailing(PrevailingCopy));
920
921 // FIXME Set ClearDSOLocalOnDeclarations.
922 promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
923
924 // Internalization
925 thinLTOFinalizeInModule(TheModule,
926 ModuleToDefinedGVSummaries[ModuleIdentifier],
927 /*PropagateAttrs=*/false);
928
929 thinLTOInternalizeModule(TheModule,
930 ModuleToDefinedGVSummaries[ModuleIdentifier]);
931}
932
933/**
934 * Perform post-importing ThinLTO optimizations.
935 */
937 initTMBuilder(TMBuilder, TheModule.getTargetTriple());
938
939 // Optimize now
940 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
941 DebugPassManager, nullptr);
942}
943
944/// Write out the generated object file, either from CacheEntryPath or from
945/// OutputBuffer, preferring hard-link when possible.
946/// Returns the path to the generated file in SavedObjectsDirectoryPath.
947std::string
949 const MemoryBuffer &OutputBuffer) {
950 auto ArchName = TMBuilder.TheTriple.getArchName();
951 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
952 llvm::sys::path::append(OutputPath,
953 Twine(count) + "." + ArchName + ".thinlto.o");
954 OutputPath.c_str(); // Ensure the string is null terminated.
955 if (sys::fs::exists(OutputPath))
956 sys::fs::remove(OutputPath);
957
958 // We don't return a memory buffer to the linker, just a list of files.
959 if (!CacheEntryPath.empty()) {
960 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
961 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
962 if (!Err)
963 return std::string(OutputPath);
964 // Hard linking failed, try to copy.
965 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
966 if (!Err)
967 return std::string(OutputPath);
968 // Copy failed (could be because the CacheEntry was removed from the cache
969 // in the meantime by another process), fall back and try to write down the
970 // buffer to the output.
971 errs() << "remark: can't link or copy from cached entry '" << CacheEntryPath
972 << "' to '" << OutputPath << "'\n";
973 }
974 // No cache entry, just write out the buffer.
975 std::error_code Err;
976 raw_fd_ostream OS(OutputPath, Err, sys::fs::OF_None);
977 if (Err)
978 report_fatal_error(Twine("Can't open output '") + OutputPath + "'\n");
979 OS << OutputBuffer.getBuffer();
980 return std::string(OutputPath);
981}
982
983// Main entry point for the ThinLTO processing
985 timeTraceProfilerBegin("ThinLink", StringRef(""));
986 llvm::scope_exit TimeTraceScopeExit([]() {
989 });
990 // Prepare the resulting object vector
991 assert(ProducedBinaries.empty() && "The generator should not be reused");
992 if (SavedObjectsDirectoryPath.empty())
993 ProducedBinaries.resize(Modules.size());
994 else {
995 sys::fs::create_directories(SavedObjectsDirectoryPath);
996 bool IsDir;
997 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
998 if (!IsDir)
999 report_fatal_error(Twine("Unexistent dir: '") + SavedObjectsDirectoryPath + "'");
1000 ProducedBinaryFiles.resize(Modules.size());
1001 }
1002
1003 if (CodeGenOnly) {
1004 // Perform only parallel codegen and return.
1005 DefaultThreadPool Pool;
1006 int count = 0;
1007 for (auto &Mod : Modules) {
1008 Pool.async([&](int count) {
1009 LLVMContext Context;
1010 Context.getLibraryOptions().assign(LibraryOptions);
1011 Context.setDiscardValueNames(LTODiscardValueNames);
1012
1013 // Parse module now
1014 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1015 /*IsImporting*/ false);
1016
1017 // CodeGen
1018 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
1019 if (SavedObjectsDirectoryPath.empty())
1020 ProducedBinaries[count] = std::move(OutputBuffer);
1021 else
1022 ProducedBinaryFiles[count] =
1024 }, count++);
1025 }
1026
1027 return;
1028 }
1029
1030 // Sequential linking phase
1031 auto Index = linkCombinedIndex();
1032
1033 // Save temps: index.
1034 if (!SaveTempsDir.empty()) {
1035 auto SaveTempPath = SaveTempsDir + "index.bc";
1036 std::error_code EC;
1037 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
1038 if (EC)
1039 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
1040 " to save optimized bitcode\n");
1041 writeIndexToFile(*Index, OS);
1042 }
1043
1044
1045 // Prepare the module map.
1046 auto ModuleMap = generateModuleMap(Modules);
1047 auto ModuleCount = Modules.size();
1048
1049 // Collect for each module the list of function it defines (GUID -> Summary).
1050 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
1051 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1052
1053 // Convert the preserved symbols set from string to GUID, this is needed for
1054 // computing the caching hash and the internalization.
1055 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1056 for (const auto &M : Modules)
1057 computeGUIDPreservedSymbols(*M, PreservedSymbols, TMBuilder.TheTriple,
1058 GUIDPreservedSymbols);
1059
1060 // Add used symbol from inputs to the preserved symbols.
1061 for (const auto &M : Modules)
1062 addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
1063
1064 // Compute "dead" symbols, we don't want to import/export these!
1065 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
1066
1067 // Currently there is no support for enabling whole program visibility via a
1068 // linker option in the old LTO API, but this call allows it to be specified
1069 // via the internal option. Must be done before WPD below.
1070 if (hasWholeProgramVisibility(/* WholeProgramVisibilityEnabledInLTO */ false))
1071 Index->setWithWholeProgramVisibility();
1072
1073 // FIXME: This needs linker information via a TBD new interface
1075 /*WholeProgramVisibilityEnabledInLTO=*/false,
1076 // FIXME: These need linker information via a
1077 // TBD new interface.
1078 /*DynamicExportSymbols=*/{},
1079 /*VisibleToRegularObjSymbols=*/{});
1080
1081 // Perform index-based WPD. This will return immediately if there are
1082 // no index entries in the typeIdMetadata map (e.g. if we are instead
1083 // performing IR-based WPD in hybrid regular/thin LTO mode).
1084 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1085 std::set<GlobalValue::GUID> ExportedGUIDs;
1086 runWholeProgramDevirtOnIndex(*Index, ExportedGUIDs, LocalWPDTargetsMap);
1087 GUIDPreservedSymbols.insert_range(ExportedGUIDs);
1088
1089 // Compute prevailing symbols
1091 computePrevailingCopies(*Index, PrevailingCopy);
1092
1093 // Collect the import/export lists for all modules from the call-graph in the
1094 // combined index.
1095 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
1097 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries,
1098 IsPrevailing(PrevailingCopy), ImportLists,
1099 ExportLists);
1100
1101 // We use a std::map here to be able to have a defined ordering when
1102 // producing a hash for the cache entry.
1103 // FIXME: we should be able to compute the caching hash for the entry based
1104 // on the index, and nuke this map.
1106
1107 // Resolve prevailing symbols, this has to be computed early because it
1108 // impacts the caching.
1109 resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols,
1110 PrevailingCopy);
1111
1112 // Use global summary-based analysis to identify symbols that can be
1113 // internalized (because they aren't exported or preserved as per callback).
1114 // Changes are made in the index, consumed in the ThinLTO backends.
1116 IsExported(ExportLists, GUIDPreservedSymbols),
1117 LocalWPDTargetsMap);
1119 *Index, IsExported(ExportLists, GUIDPreservedSymbols),
1120 IsPrevailing(PrevailingCopy));
1121
1122 thinLTOPropagateFunctionAttrs(*Index, IsPrevailing(PrevailingCopy));
1123
1124 // Make sure that every module has an entry in the ExportLists, ImportList,
1125 // GVSummary and ResolvedODR maps to enable threaded access to these maps
1126 // below.
1127 for (auto &Module : Modules) {
1128 auto ModuleIdentifier = Module->getName();
1129 ExportLists[ModuleIdentifier];
1130 ImportLists[ModuleIdentifier];
1131 ResolvedODR[ModuleIdentifier];
1132 ModuleToDefinedGVSummaries[ModuleIdentifier];
1133 }
1134
1135 std::vector<BitcodeModule *> ModulesVec;
1136 ModulesVec.reserve(Modules.size());
1137 for (auto &Mod : Modules)
1138 ModulesVec.push_back(&Mod->getSingleBitcodeModule());
1139 std::vector<int> ModulesOrdering = lto::generateModulesOrdering(ModulesVec);
1140
1143
1144 TimeTraceScopeExit.release();
1145
1146 // Parallel optimizer + codegen
1147 {
1149 for (auto IndexCount : ModulesOrdering) {
1150 auto &Mod = Modules[IndexCount];
1151 Pool.async([&](int count) {
1152 auto ModuleIdentifier = Mod->getName();
1153 auto &ExportList = ExportLists[ModuleIdentifier];
1154
1155 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
1156
1157 // The module may be cached, this helps handling it.
1158 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
1159 ImportLists[ModuleIdentifier], ExportList,
1160 ResolvedODR[ModuleIdentifier],
1161 DefinedGVSummaries, OptLevel, Freestanding,
1162 TMBuilder, MllvmArgs);
1163 auto CacheEntryPath = CacheEntry.getEntryPath();
1164
1165 {
1166 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1167 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1168 << " '" << CacheEntryPath << "' for buffer "
1169 << count << " " << ModuleIdentifier << "\n");
1170
1171 if (ErrOrBuffer) {
1172 // Cache Hit!
1173 if (SavedObjectsDirectoryPath.empty())
1174 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1175 else
1176 ProducedBinaryFiles[count] = writeGeneratedObject(
1177 count, CacheEntryPath, *ErrOrBuffer.get());
1178 return;
1179 }
1180 }
1181
1182 LLVMContext Context;
1183 Context.getLibraryOptions().assign(LibraryOptions);
1184 Context.setDiscardValueNames(LTODiscardValueNames);
1185 Context.enableDebugTypeODRUniquing();
1186 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1189 if (!DiagFileOrErr) {
1190 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1191 report_fatal_error("ThinLTO: Can't get an output file for the "
1192 "remarks");
1193 }
1194
1195 // Parse module now
1196 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1197 /*IsImporting*/ false);
1198
1199 // Save temps: original file.
1200 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1201
1202 auto &ImportList = ImportLists[ModuleIdentifier];
1203 // Run the main process now, and generates a binary
1205 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1206 ExportList, GUIDPreservedSymbols,
1207 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1208 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count,
1209 DebugPassManager);
1210
1211 // Commit to the cache (if enabled)
1212 CacheEntry.write(*OutputBuffer);
1213
1214 if (SavedObjectsDirectoryPath.empty()) {
1215 // We need to generated a memory buffer for the linker.
1216 if (!CacheEntryPath.empty()) {
1217 // When cache is enabled, reload from the cache if possible.
1218 // Releasing the buffer from the heap and reloading it from the
1219 // cache file with mmap helps us to lower memory pressure.
1220 // The freed memory can be used for the next input file.
1221 // The final binary link will read from the VFS cache (hopefully!)
1222 // or from disk (if the memory pressure was too high).
1223 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1224 if (auto EC = ReloadedBufferOrErr.getError()) {
1225 // On error, keep the preexisting buffer and print a diagnostic.
1226 errs() << "remark: can't reload cached file '" << CacheEntryPath
1227 << "': " << EC.message() << "\n";
1228 } else {
1229 OutputBuffer = std::move(*ReloadedBufferOrErr);
1230 }
1231 }
1232 ProducedBinaries[count] = std::move(OutputBuffer);
1233 return;
1234 }
1235 ProducedBinaryFiles[count] = writeGeneratedObject(
1236 count, CacheEntryPath, *OutputBuffer);
1237 }, IndexCount);
1238 }
1239 }
1240
1241 Expected<bool> PrunedOrErr =
1242 pruneCache(CacheOptions.Path, CacheOptions.Policy, ProducedBinaries);
1243 if (!PrunedOrErr) {
1244 errs() << "Error: " << toString(PrunedOrErr.takeError()) << "\n";
1245 report_fatal_error("ThinLTO: failure to prune cache");
1246 }
1247
1248 // If statistics were requested, print them out now.
1252}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file provides a bitcode writing pass.
#define LLVM_LIFETIME_BOUND
Definition Compiler.h:464
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
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
PassInstrumentationCallbacks PIC
This header defines classes/functions to handle pass execution timing information with interfaces for...
This file provides the interface for the sampled PGO loader pass.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
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:766
iterator end()
Definition DenseMap.h:686
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
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:234
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:76
LLVM_ABI cl::LibraryOptionsContext & getLibraryOptions() const
The library options this context reads in place of their process-wide values.
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...
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:68
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
StringRef getName() const
Get a short "name" for the module.
Definition Module.h:316
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition Module.h:299
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition Module.cpp:653
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:48
bool SLPVectorization
Tuning option to enable/disable slp loop vectorization, set based on opt level.
Definition PassBuilder.h:63
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition PassBuilder.h:59
Analysis providing profile information.
static LLVM_ABI StringRef getSampleProfileFile(const LLVMContext &C)
Return -sample-profile-file.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
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:104
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
bool contains(StringRef Key) const
contains - Return true if the element is in the map, false otherwise.
Definition StringMap.h:270
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition StringMap.h:275
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:27
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.
const Triple & getTargetTriple() const
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
TargetOptions Options
VectorLibrary VecLib
Vector math library to use.
unsigned DataSections
Emit data into separate sections.
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:48
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:868
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
void assign(const LibraryOptionsContext &Other)
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
void insert_range(Range &&R)
Definition DenseSet.h:236
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
An input file.
Definition LTO.h:115
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:627
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 std::optional< bool > getExplicitDataSections()
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1921
LLVM_ABI Expected< LLVMRemarkFileHandle > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, std::optional< uint64_t > RemarksHotnessThreshold=0, int Count=-1)
Setup optimization remarks.
Definition LTO.cpp:2352
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2396
LLVM_ABI 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:1107
@ OF_UpdateAtime
Force files Atime to be updated on access.
Definition FileSystem.h:817
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:993
LLVM_ABI std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition Path.cpp:1042
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition Path.cpp:1122
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:467
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:1755
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
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,...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
@ O1
Optimize quickly without destroying debuggability.
@ O0
Disable as many optimizations as possible.
@ O3
Optimize for fast execution as much as possible.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
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 Error runCodeGenPipeline(TargetMachine &TM, Module &M, raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS, CodeGenFileType CGFT, bool DisableVerify=true, bool DisableSimplifyLibCalls=false, const ModuleSummaryIndex *MSI=nullptr, IntrusiveRefCntPtr< vfs::FileSystem > VFS=vfs::getRealFileSystem())
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:491
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
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:2028
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:1788
LLVM_ABI std::string computeLTOCacheKey(const lto::Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > &ResolvedODR, const GVSummaryMapTy &DefinedGlobals, const DenseSet< GlobalValue::GUID > &CfiFunctionDefs={}, const DenseSet< GlobalValue::GUID > &CfiFunctionDecls={})
Computes a unique hash for the Module considering the current list of export/import and other global ...
Definition LTO.cpp:136
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
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:746
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:609
LLVM_ABI void updateVCallVisibilityInIndex(ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, const DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
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:44
std::vector< std::string > MAttrs
Definition Config.h:56
std::vector< std::string > MllvmArgs
Definition Config.h:57
CodeGenOptLevel CGOptLevel
Definition Config.h:67
std::string CPU
Definition Config.h:54
TargetOptions Options
Definition Config.h:55
unsigned OptLevel
Definition Config.h:69
std::optional< Reloc::Model > RelocModel
Definition Config.h:65
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition Config.h:75