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
82}
83
84// Default to using all available threads in the system, but using only one
85// thred per core, as indicated by the usage of
86// heavyweight_hardware_concurrency() below.
87static cl::opt<int> ThreadCount("threads", cl::init(0));
88
89// Simple helper to save temporary files for debug.
90static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
91 unsigned count, StringRef Suffix) {
92 if (TempDir.empty())
93 return;
94 // User asked to save temps, let dump the bitcode file after import.
95 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
96 std::error_code EC;
97 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
98 if (EC)
99 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
100 " to save optimized bitcode\n");
101 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
102}
103
105 ArrayRef<std::unique_ptr<GlobalValueSummary>> GVSummaryList) {
106 // If there is any strong definition anywhere, get it.
107 auto StrongDefForLinker = llvm::find_if(
108 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
109 auto Linkage = Summary->linkage();
112 });
113 if (StrongDefForLinker != GVSummaryList.end())
114 return StrongDefForLinker->get();
115 // Get the first *linker visible* definition for this global in the summary
116 // list.
117 auto FirstDefForLinker = llvm::find_if(
118 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
119 auto Linkage = Summary->linkage();
121 });
122 // Extern templates can be emitted as available_externally.
123 if (FirstDefForLinker == GVSummaryList.end())
124 return nullptr;
125 return FirstDefForLinker->get();
126}
127
128// Populate map of GUID to the prevailing copy for any multiply defined
129// symbols. Currently assume first copy is prevailing, or any strong
130// definition. Can be refined with Linker information in the future.
132 const ModuleSummaryIndex &Index,
134 auto HasMultipleCopies =
136 return GVSummaryList.size() > 1;
137 };
138
139 for (auto &I : Index) {
140 if (HasMultipleCopies(I.second.getSummaryList()))
141 PrevailingCopy[I.first] =
142 getFirstDefinitionForLinker(I.second.getSummaryList());
143 }
144}
145
147generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) {
149 for (auto &M : Modules) {
150 LLVM_DEBUG(dbgs() << "Adding module " << M->getName() << " to ModuleMap\n");
151 assert(!ModuleMap.contains(M->getName()) &&
152 "Expect unique Buffer Identifier");
153 ModuleMap[M->getName()] = M.get();
154 }
155 return ModuleMap;
156}
157
158static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index,
159 bool ClearDSOLocalOnDeclarations) {
160 renameModuleForThinLTO(TheModule, Index, ClearDSOLocalOnDeclarations);
161}
162
163namespace {
164class ThinLTODiagnosticInfo : public DiagnosticInfo {
165 const Twine &Msg;
166public:
167 ThinLTODiagnosticInfo(const Twine &DiagMsg LLVM_LIFETIME_BOUND,
168 DiagnosticSeverity Severity = DS_Error)
169 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
170 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
171};
172}
173
174/// Verify the module and strip broken debug info.
175static void verifyLoadedModule(Module &TheModule) {
176 bool BrokenDebugInfo = false;
177 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
178 report_fatal_error("Broken module found, compilation aborted!");
179 if (BrokenDebugInfo) {
180 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
181 "Invalid debug info found, debug info will be stripped", DS_Warning));
182 StripDebugInfo(TheModule);
183 }
184}
185
186static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile *Input,
187 LLVMContext &Context,
188 bool Lazy,
189 bool IsImporting) {
190 auto &Mod = Input->getSingleBitcodeModule();
191 SMDiagnostic Err;
193 Lazy ? Mod.getLazyModule(Context,
194 /* ShouldLazyLoadMetadata */ true, IsImporting)
195 : Mod.parseModule(Context);
196 if (!ModuleOrErr) {
197 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
198 SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(),
199 SourceMgr::DK_Error, EIB.message());
200 Err.print("ThinLTO", errs());
201 });
202 report_fatal_error("Can't load module, abort.");
203 }
204 if (!Lazy)
205 verifyLoadedModule(*ModuleOrErr.get());
206 return std::move(*ModuleOrErr);
207}
208
209static void
212 const FunctionImporter::ImportMapTy &ImportList,
213 bool ClearDSOLocalOnDeclarations) {
214 auto Loader = [&](StringRef Identifier) {
215 auto &Input = ModuleMap[Identifier];
216 return loadModuleFromInput(Input, TheModule.getContext(),
217 /*Lazy=*/true, /*IsImporting*/ true);
218 };
219
220 FunctionImporter Importer(Index, Loader, ClearDSOLocalOnDeclarations);
221 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
222 if (!Result) {
223 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
224 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
225 SourceMgr::DK_Error, EIB.message());
226 Err.print("ThinLTO", errs());
227 });
228 report_fatal_error("importFunctions failed");
229 }
230 // Verify again after cross-importing.
231 verifyLoadedModule(TheModule);
232}
233
234static void optimizeModule(Module &TheModule, TargetMachine &TM,
235 unsigned OptLevel, bool Freestanding,
236 bool DebugPassManager, ModuleSummaryIndex *Index) {
237 std::optional<PGOOptions> PGOOpt;
242
244 StandardInstrumentations SI(TheModule.getContext(), DebugPassManager);
245 SI.registerCallbacks(PIC, &MAM);
247 PTO.LoopVectorization = true;
248 PTO.SLPVectorization = true;
249 PassBuilder PB(&TM, PTO, PGOOpt, &PIC);
250
251 std::unique_ptr<TargetLibraryInfoImpl> TLII(
253 if (Freestanding)
254 TLII->disableAllFunctions();
255 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
256
257 // Register all the basic analyses with the managers.
258 PB.registerModuleAnalyses(MAM);
259 PB.registerCGSCCAnalyses(CGAM);
260 PB.registerFunctionAnalyses(FAM);
261 PB.registerLoopAnalyses(LAM);
262 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
263
265
267
268 switch (OptLevel) {
269 default:
270 llvm_unreachable("Invalid optimization level");
271 case 0:
273 break;
274 case 1:
276 break;
277 case 2:
279 break;
280 case 3:
282 break;
283 }
284
285 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, Index));
286
287 MPM.run(TheModule, MAM);
288}
289
290static void
292 DenseSet<GlobalValue::GUID> &PreservedGUID) {
293 Triple TT(File.getTargetTriple());
294 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
295 for (const auto &Sym : File.symbols())
296 if (Sym.isUsed() || Sym.isLibcall(Libcalls))
297 PreservedGUID.insert(
299}
300
301// Convert the PreservedSymbols map from "Name" based to "GUID" based.
303 const StringSet<> &PreservedSymbols,
304 const Triple &TheTriple,
306 // Iterate the symbols in the input file and if the input has preserved symbol
307 // compute the GUID for the symbol.
308 for (const auto &Sym : File.symbols()) {
309 if (PreservedSymbols.count(Sym.getName()) && !Sym.getIRName().empty())
311 GlobalValue::getGlobalIdentifier(Sym.getIRName(),
313 }
314}
315
318 const StringSet<> &PreservedSymbols,
319 const Triple &TheTriple) {
320 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
321 computeGUIDPreservedSymbols(File, PreservedSymbols, TheTriple,
322 GUIDPreservedSymbols);
323 return GUIDPreservedSymbols;
324}
325
326static std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
327 TargetMachine &TM) {
329
330 // CodeGen
331 {
334
335 // Setup the codegen now.
336 if (TM.addPassesToEmitFile(PM, OS, nullptr, CodeGenFileType::ObjectFile,
337 /* DisableVerify */ true))
338 report_fatal_error("Failed to setup codegen");
339
340 // Run codegen now. resulting binary is in OutputBuffer.
341 PM.run(TheModule);
342 }
343 return std::make_unique<SmallVectorMemoryBuffer>(
344 std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
345}
346
347namespace {
348/// Manage caching for a single Module.
349class ModuleCacheEntry {
350 SmallString<128> EntryPath;
351
352public:
353 // Create a cache entry. This compute a unique hash for the Module considering
354 // the current list of export/import, and offer an interface to query to
355 // access the content in the cache.
356 ModuleCacheEntry(
357 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
358 const FunctionImporter::ImportMapTy &ImportList,
359 const FunctionImporter::ExportSetTy &ExportList,
360 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
361 const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel,
362 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
363 if (CachePath.empty())
364 return;
365
366 if (!Index.modulePaths().count(ModuleID))
367 // The module does not have an entry, it can't have a hash at all
368 return;
369
370 if (all_of(Index.getModuleHash(ModuleID),
371 [](uint32_t V) { return V == 0; }))
372 // No hash entry, no caching!
373 return;
374
375 llvm::lto::Config Conf;
376 Conf.OptLevel = OptLevel;
377 Conf.Options = TMBuilder.Options;
378 Conf.CPU = TMBuilder.MCpu;
379 Conf.MAttrs.push_back(TMBuilder.MAttr);
380 Conf.RelocModel = TMBuilder.RelocModel;
381 Conf.CGOptLevel = TMBuilder.CGOptLevel;
382 Conf.Freestanding = Freestanding;
383 std::string Key =
384 computeLTOCacheKey(Conf, Index, ModuleID, ImportList, ExportList,
385 ResolvedODR, DefinedGVSummaries);
386
387 // This choice of file name allows the cache to be pruned (see pruneCache()
388 // in include/llvm/Support/CachePruning.h).
389 sys::path::append(EntryPath, CachePath, Twine("llvmcache-", Key));
390 }
391
392 // Access the path to this entry in the cache.
393 StringRef getEntryPath() { return EntryPath; }
394
395 // Try loading the buffer for this cache entry.
396 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
397 if (EntryPath.empty())
398 return std::error_code();
399 SmallString<64> ResultPath;
400 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
401 Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
402 if (!FDOrErr)
403 return errorToErrorCode(FDOrErr.takeError());
404 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getOpenFile(
405 *FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
406 sys::fs::closeFile(*FDOrErr);
407 return MBOrErr;
408 }
409
410 // Cache the Produced object file
411 void write(const MemoryBuffer &OutputBuffer) {
412 if (EntryPath.empty())
413 return;
414
415 if (auto Err = llvm::writeToOutput(
416 EntryPath, [&OutputBuffer](llvm::raw_ostream &OS) -> llvm::Error {
417 OS << OutputBuffer.getBuffer();
418 return llvm::Error::success();
419 }))
420 report_fatal_error(llvm::formatv("ThinLTO: Can't write file {0}: {1}",
421 EntryPath,
422 toString(std::move(Err)).c_str()));
423 }
424};
425} // end anonymous namespace
426
427static std::unique_ptr<MemoryBuffer>
430 const FunctionImporter::ImportMapTy &ImportList,
431 const FunctionImporter::ExportSetTy &ExportList,
432 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
433 const GVSummaryMapTy &DefinedGlobals,
434 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
435 bool DisableCodeGen, StringRef SaveTempsDir,
436 bool Freestanding, unsigned OptLevel, unsigned count,
437 bool DebugPassManager) {
438 // "Benchmark"-like optimization: single-source case
439 bool SingleModule = (ModuleMap.size() == 1);
440
441 // When linking an ELF shared object, dso_local should be dropped. We
442 // conservatively do this for -fpic.
443 bool ClearDSOLocalOnDeclarations =
446 TheModule.getPIELevel() == PIELevel::Default;
447
448 if (!SingleModule) {
449 promoteModule(TheModule, Index, ClearDSOLocalOnDeclarations);
450
451 // Apply summary-based prevailing-symbol resolution decisions.
452 thinLTOFinalizeInModule(TheModule, DefinedGlobals, /*PropagateAttrs=*/true);
453
454 // Save temps: after promotion.
455 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
456 }
457
458 // Be friendly and don't nuke totally the module when the client didn't
459 // supply anything to preserve.
460 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
461 // Apply summary-based internalization decisions.
462 thinLTOInternalizeModule(TheModule, DefinedGlobals);
463 }
464
465 // Save internalized bitcode
466 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
467
468 if (!SingleModule)
469 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
470 ClearDSOLocalOnDeclarations);
471
472 // Do this after any importing so that imported code is updated.
473 // See comment at call to updateVCallVisibilityInIndex() for why
474 // WholeProgramVisibilityEnabledInLTO is false.
476 /* WholeProgramVisibilityEnabledInLTO */ false);
477
478 // Save temps: after cross-module import.
479 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
480
481 optimizeModule(TheModule, TM, OptLevel, Freestanding, DebugPassManager,
482 &Index);
483
484 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
485
486 if (DisableCodeGen) {
487 // Configured to stop before CodeGen, serialize the bitcode and return.
489 {
491 ProfileSummaryInfo PSI(TheModule);
492 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
493 WriteBitcodeToFile(TheModule, OS, true, &Index);
494 }
495 return std::make_unique<SmallVectorMemoryBuffer>(
496 std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
497 }
498
499 return codegenModule(TheModule, TM);
500}
501
502/// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
503/// for caching, and in the \p Index for application during the ThinLTO
504/// backends. This is needed for correctness for exported symbols (ensure
505/// at least one copy kept) and a compile-time optimization (to drop duplicate
506/// copies when possible).
508 ModuleSummaryIndex &Index,
509 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
510 &ResolvedODR,
511 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
513 &PrevailingCopy) {
514
515 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
516 const auto &Prevailing = PrevailingCopy.find(GUID);
517 // Not in map means that there was only one copy, which must be prevailing.
518 if (Prevailing == PrevailingCopy.end())
519 return true;
520 return Prevailing->second == S;
521 };
522
523 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
525 GlobalValue::LinkageTypes NewLinkage) {
526 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
527 };
528
529 // TODO Conf.VisibilityScheme can be lto::Config::ELF for ELF.
530 lto::Config Conf;
531 thinLTOResolvePrevailingInIndex(Conf, Index, isPrevailing, recordNewLinkage,
532 GUIDPreservedSymbols);
533}
534
535// Initialize the TargetMachine builder for a given Triple
536static void initTMBuilder(TargetMachineBuilder &TMBuilder,
537 const Triple &TheTriple) {
538 if (TMBuilder.MCpu.empty())
539 TMBuilder.MCpu = lto::getThinLTODefaultCPU(TheTriple);
540 TMBuilder.TheTriple = std::move(TheTriple);
541}
542
544 MemoryBufferRef Buffer(Data, Identifier);
545
546 auto InputOrError = lto::InputFile::create(Buffer);
547 if (!InputOrError)
548 report_fatal_error(Twine("ThinLTO cannot create input file: ") +
549 toString(InputOrError.takeError()));
550
551 auto TripleStr = (*InputOrError)->getTargetTriple();
552 Triple TheTriple(TripleStr);
553
554 if (Modules.empty())
555 initTMBuilder(TMBuilder, Triple(TheTriple));
556 else if (TMBuilder.TheTriple != TheTriple) {
557 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
558 report_fatal_error("ThinLTO modules with incompatible triples not "
559 "supported");
560 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
561 }
562
563 Modules.emplace_back(std::move(*InputOrError));
564}
565
567 PreservedSymbols.insert(Name);
568}
569
571 // FIXME: At the moment, we don't take advantage of this extra information,
572 // we're conservatively considering cross-references as preserved.
573 // CrossReferencedSymbols.insert(Name);
574 PreservedSymbols.insert(Name);
575}
576
577// TargetMachine factory
578std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
579 std::string ErrMsg;
580 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple, ErrMsg);
581 if (!TheTarget) {
582 report_fatal_error(Twine("Can't load target for this Triple: ") + ErrMsg);
583 }
584
585 // Use MAttr as the default set of features.
586 SubtargetFeatures Features(MAttr);
588 std::string FeatureStr = Features.getString();
589
590 std::unique_ptr<TargetMachine> TM(
591 TheTarget->createTargetMachine(TheTriple, MCpu, FeatureStr, Options,
592 RelocModel, std::nullopt, CGOptLevel));
593 assert(TM && "Cannot create target machine");
594
595 return TM;
596}
597
598/**
599 * Produce the combined summary index from all the bitcode files:
600 * "thin-link".
601 */
602std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
603 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
604 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
605 for (auto &Mod : Modules) {
606 auto &M = Mod->getSingleBitcodeModule();
607 if (Error Err = M.readSummary(*CombinedIndex, Mod->getName())) {
608 // FIXME diagnose
610 std::move(Err), errs(),
611 "error: can't create module summary index for buffer: ");
612 return nullptr;
613 }
614 }
615 return CombinedIndex;
616}
617
618namespace {
619struct IsExported {
621 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols;
622
623 IsExported(
625 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)
626 : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {}
627
628 bool operator()(StringRef ModuleIdentifier, ValueInfo VI) const {
629 const auto &ExportList = ExportLists.find(ModuleIdentifier);
630 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
631 GUIDPreservedSymbols.count(VI.getGUID());
632 }
633};
634
635struct IsPrevailing {
636 const DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy;
637 IsPrevailing(const DenseMap<GlobalValue::GUID, const GlobalValueSummary *>
638 &PrevailingCopy)
639 : PrevailingCopy(PrevailingCopy) {}
640
641 bool operator()(GlobalValue::GUID GUID, const GlobalValueSummary *S) const {
642 const auto &Prevailing = PrevailingCopy.find(GUID);
643 // Not in map means that there was only one copy, which must be prevailing.
644 if (Prevailing == PrevailingCopy.end())
645 return true;
646 return Prevailing->second == S;
647 };
648};
649} // namespace
650
652 ModuleSummaryIndex &Index,
653 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
654 // We have no symbols resolution available. And can't do any better now in the
655 // case where the prevailing symbol is in a native object. It can be refined
656 // with linker information in the future.
657 auto isPrevailing = [&](GlobalValue::GUID G) {
659 };
660 computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
661 /* ImportEnabled = */ true);
662}
663
664/**
665 * Perform promotion and renaming of exported internal functions.
666 * Index is updated to reflect linkage changes from weak resolution.
667 */
669 const lto::InputFile &File) {
670 auto ModuleCount = Index.modulePaths().size();
671 auto ModuleIdentifier = TheModule.getModuleIdentifier();
672
673 // Collect for each module the list of function it defines (GUID -> Summary).
674 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries;
675 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
676
677 // Convert the preserved symbols set from string to GUID
678 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
679 File, PreservedSymbols, TheModule.getTargetTriple());
680
681 // Add used symbol to the preserved symbols.
682 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
683
684 // Compute "dead" symbols, we don't want to import/export these!
685 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
686
687 // Compute prevailing symbols
689 computePrevailingCopies(Index, PrevailingCopy);
690
691 // Generate import/export list
692 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
694 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
695 IsPrevailing(PrevailingCopy), ImportLists,
696 ExportLists);
697
698 // Resolve prevailing symbols
700 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
701 PrevailingCopy);
702
703 thinLTOFinalizeInModule(TheModule,
704 ModuleToDefinedGVSummaries[ModuleIdentifier],
705 /*PropagateAttrs=*/false);
706
707 // Promote the exported values in the index, so that they are promoted
708 // in the module.
710 Index, IsExported(ExportLists, GUIDPreservedSymbols),
711 IsPrevailing(PrevailingCopy));
712
713 // FIXME Set ClearDSOLocalOnDeclarations.
714 promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
715}
716
717/**
718 * Perform cross-module importing for the module identified by ModuleIdentifier.
719 */
721 ModuleSummaryIndex &Index,
722 const lto::InputFile &File) {
723 auto ModuleMap = generateModuleMap(Modules);
724 auto ModuleCount = Index.modulePaths().size();
725
726 // Collect for each module the list of function it defines (GUID -> Summary).
727 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
728 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
729
730 // Convert the preserved symbols set from string to GUID
731 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
732 File, PreservedSymbols, TheModule.getTargetTriple());
733
734 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
735
736 // Compute "dead" symbols, we don't want to import/export these!
737 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
738
739 // Compute prevailing symbols
741 computePrevailingCopies(Index, PrevailingCopy);
742
743 // Generate import/export list
744 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
746 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
747 IsPrevailing(PrevailingCopy), ImportLists,
748 ExportLists);
749 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
750
751 // FIXME Set ClearDSOLocalOnDeclarations.
752 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
753 /*ClearDSOLocalOnDeclarations=*/false);
754}
755
756/**
757 * Compute the list of summaries needed for importing into module.
758 */
760 Module &TheModule, ModuleSummaryIndex &Index,
761 ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
762 GVSummaryPtrSet &DecSummaries, const lto::InputFile &File) {
763 auto ModuleCount = Index.modulePaths().size();
764 auto ModuleIdentifier = TheModule.getModuleIdentifier();
765
766 // Collect for each module the list of function it defines (GUID -> Summary).
767 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
768 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
769
770 // Convert the preserved symbols set from string to GUID
771 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
772 File, PreservedSymbols, TheModule.getTargetTriple());
773
774 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
775
776 // Compute "dead" symbols, we don't want to import/export these!
777 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
778
779 // Compute prevailing symbols
781 computePrevailingCopies(Index, PrevailingCopy);
782
783 // Generate import/export list
784 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
786 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
787 IsPrevailing(PrevailingCopy), ImportLists,
788 ExportLists);
789
791 ModuleIdentifier, ModuleToDefinedGVSummaries,
792 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex, DecSummaries);
793}
794
795/**
796 * Emit the list of files needed for importing into module.
797 */
799 ModuleSummaryIndex &Index,
800 const lto::InputFile &File) {
801 auto ModuleCount = Index.modulePaths().size();
802 auto ModuleIdentifier = TheModule.getModuleIdentifier();
803
804 // Collect for each module the list of function it defines (GUID -> Summary).
805 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
806 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
807
808 // Convert the preserved symbols set from string to GUID
809 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
810 File, PreservedSymbols, TheModule.getTargetTriple());
811
812 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
813
814 // Compute "dead" symbols, we don't want to import/export these!
815 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
816
817 // Compute prevailing symbols
819 computePrevailingCopies(Index, PrevailingCopy);
820
821 // Generate import/export list
822 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
824 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
825 IsPrevailing(PrevailingCopy), ImportLists,
826 ExportLists);
827
828 // 'EmitImportsFiles' emits the list of modules from which to import from, and
829 // the set of keys in `ModuleToSummariesForIndex` should be a superset of keys
830 // in `DecSummaries`, so no need to use `DecSummaries` in `EmitImportsFiles`.
831 GVSummaryPtrSet DecSummaries;
832 ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
834 ModuleIdentifier, ModuleToDefinedGVSummaries,
835 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex, DecSummaries);
836
837 if (Error EC = EmitImportsFiles(ModuleIdentifier, OutputName,
838 ModuleToSummariesForIndex))
839 report_fatal_error(Twine("Failed to open ") + OutputName +
840 " to save imports lists\n");
841}
842
843/**
844 * Perform internalization. Runs promote and internalization together.
845 * Index is updated to reflect linkage changes.
846 */
848 ModuleSummaryIndex &Index,
849 const lto::InputFile &File) {
850 initTMBuilder(TMBuilder, TheModule.getTargetTriple());
851 auto ModuleCount = Index.modulePaths().size();
852 auto ModuleIdentifier = TheModule.getModuleIdentifier();
853
854 // Convert the preserved symbols set from string to GUID
855 auto GUIDPreservedSymbols =
856 computeGUIDPreservedSymbols(File, PreservedSymbols, TMBuilder.TheTriple);
857
858 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
859
860 // Collect for each module the list of function it defines (GUID -> Summary).
861 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
862 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
863
864 // Compute "dead" symbols, we don't want to import/export these!
865 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
866
867 // Compute prevailing symbols
869 computePrevailingCopies(Index, PrevailingCopy);
870
871 // Generate import/export list
872 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
874 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
875 IsPrevailing(PrevailingCopy), ImportLists,
876 ExportLists);
877 auto &ExportList = ExportLists[ModuleIdentifier];
878
879 // Be friendly and don't nuke totally the module when the client didn't
880 // supply anything to preserve.
881 if (ExportList.empty() && GUIDPreservedSymbols.empty())
882 return;
883
884 // Resolve prevailing symbols
886 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
887 PrevailingCopy);
888
889 // Promote the exported values in the index, so that they are promoted
890 // in the module.
892 Index, IsExported(ExportLists, GUIDPreservedSymbols),
893 IsPrevailing(PrevailingCopy));
894
895 // FIXME Set ClearDSOLocalOnDeclarations.
896 promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
897
898 // Internalization
899 thinLTOFinalizeInModule(TheModule,
900 ModuleToDefinedGVSummaries[ModuleIdentifier],
901 /*PropagateAttrs=*/false);
902
903 thinLTOInternalizeModule(TheModule,
904 ModuleToDefinedGVSummaries[ModuleIdentifier]);
905}
906
907/**
908 * Perform post-importing ThinLTO optimizations.
909 */
911 initTMBuilder(TMBuilder, TheModule.getTargetTriple());
912
913 // Optimize now
914 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
915 DebugPassManager, nullptr);
916}
917
918/// Write out the generated object file, either from CacheEntryPath or from
919/// OutputBuffer, preferring hard-link when possible.
920/// Returns the path to the generated file in SavedObjectsDirectoryPath.
921std::string
923 const MemoryBuffer &OutputBuffer) {
924 auto ArchName = TMBuilder.TheTriple.getArchName();
925 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
926 llvm::sys::path::append(OutputPath,
927 Twine(count) + "." + ArchName + ".thinlto.o");
928 OutputPath.c_str(); // Ensure the string is null terminated.
929 if (sys::fs::exists(OutputPath))
930 sys::fs::remove(OutputPath);
931
932 // We don't return a memory buffer to the linker, just a list of files.
933 if (!CacheEntryPath.empty()) {
934 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
935 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
936 if (!Err)
937 return std::string(OutputPath);
938 // Hard linking failed, try to copy.
939 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
940 if (!Err)
941 return std::string(OutputPath);
942 // Copy failed (could be because the CacheEntry was removed from the cache
943 // in the meantime by another process), fall back and try to write down the
944 // buffer to the output.
945 errs() << "remark: can't link or copy from cached entry '" << CacheEntryPath
946 << "' to '" << OutputPath << "'\n";
947 }
948 // No cache entry, just write out the buffer.
949 std::error_code Err;
950 raw_fd_ostream OS(OutputPath, Err, sys::fs::OF_None);
951 if (Err)
952 report_fatal_error(Twine("Can't open output '") + OutputPath + "'\n");
953 OS << OutputBuffer.getBuffer();
954 return std::string(OutputPath);
955}
956
957// Main entry point for the ThinLTO processing
959 timeTraceProfilerBegin("ThinLink", StringRef(""));
960 llvm::scope_exit TimeTraceScopeExit([]() {
963 });
964 // Prepare the resulting object vector
965 assert(ProducedBinaries.empty() && "The generator should not be reused");
966 if (SavedObjectsDirectoryPath.empty())
967 ProducedBinaries.resize(Modules.size());
968 else {
969 sys::fs::create_directories(SavedObjectsDirectoryPath);
970 bool IsDir;
971 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
972 if (!IsDir)
973 report_fatal_error(Twine("Unexistent dir: '") + SavedObjectsDirectoryPath + "'");
974 ProducedBinaryFiles.resize(Modules.size());
975 }
976
977 if (CodeGenOnly) {
978 // Perform only parallel codegen and return.
980 int count = 0;
981 for (auto &Mod : Modules) {
982 Pool.async([&](int count) {
983 LLVMContext Context;
985
986 // Parse module now
987 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
988 /*IsImporting*/ false);
989
990 // CodeGen
991 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
992 if (SavedObjectsDirectoryPath.empty())
993 ProducedBinaries[count] = std::move(OutputBuffer);
994 else
995 ProducedBinaryFiles[count] =
997 }, count++);
998 }
999
1000 return;
1001 }
1002
1003 // Sequential linking phase
1004 auto Index = linkCombinedIndex();
1005
1006 // Save temps: index.
1007 if (!SaveTempsDir.empty()) {
1008 auto SaveTempPath = SaveTempsDir + "index.bc";
1009 std::error_code EC;
1010 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
1011 if (EC)
1012 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
1013 " to save optimized bitcode\n");
1014 writeIndexToFile(*Index, OS);
1015 }
1016
1017
1018 // Prepare the module map.
1019 auto ModuleMap = generateModuleMap(Modules);
1020 auto ModuleCount = Modules.size();
1021
1022 // Collect for each module the list of function it defines (GUID -> Summary).
1023 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
1024 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1025
1026 // Convert the preserved symbols set from string to GUID, this is needed for
1027 // computing the caching hash and the internalization.
1028 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1029 for (const auto &M : Modules)
1030 computeGUIDPreservedSymbols(*M, PreservedSymbols, TMBuilder.TheTriple,
1031 GUIDPreservedSymbols);
1032
1033 // Add used symbol from inputs to the preserved symbols.
1034 for (const auto &M : Modules)
1035 addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
1036
1037 // Compute "dead" symbols, we don't want to import/export these!
1038 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
1039
1040 // Currently there is no support for enabling whole program visibility via a
1041 // linker option in the old LTO API, but this call allows it to be specified
1042 // via the internal option. Must be done before WPD below.
1043 if (hasWholeProgramVisibility(/* WholeProgramVisibilityEnabledInLTO */ false))
1044 Index->setWithWholeProgramVisibility();
1045
1046 // FIXME: This needs linker information via a TBD new interface
1048 /*WholeProgramVisibilityEnabledInLTO=*/false,
1049 // FIXME: These need linker information via a
1050 // TBD new interface.
1051 /*DynamicExportSymbols=*/{},
1052 /*VisibleToRegularObjSymbols=*/{});
1053
1054 // Perform index-based WPD. This will return immediately if there are
1055 // no index entries in the typeIdMetadata map (e.g. if we are instead
1056 // performing IR-based WPD in hybrid regular/thin LTO mode).
1057 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1058 std::set<GlobalValue::GUID> ExportedGUIDs;
1059 runWholeProgramDevirtOnIndex(*Index, ExportedGUIDs, LocalWPDTargetsMap);
1060 GUIDPreservedSymbols.insert_range(ExportedGUIDs);
1061
1062 // Compute prevailing symbols
1064 computePrevailingCopies(*Index, PrevailingCopy);
1065
1066 // Collect the import/export lists for all modules from the call-graph in the
1067 // combined index.
1068 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
1070 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries,
1071 IsPrevailing(PrevailingCopy), ImportLists,
1072 ExportLists);
1073
1074 // We use a std::map here to be able to have a defined ordering when
1075 // producing a hash for the cache entry.
1076 // FIXME: we should be able to compute the caching hash for the entry based
1077 // on the index, and nuke this map.
1079
1080 // Resolve prevailing symbols, this has to be computed early because it
1081 // impacts the caching.
1082 resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols,
1083 PrevailingCopy);
1084
1085 // Use global summary-based analysis to identify symbols that can be
1086 // internalized (because they aren't exported or preserved as per callback).
1087 // Changes are made in the index, consumed in the ThinLTO backends.
1089 IsExported(ExportLists, GUIDPreservedSymbols),
1090 LocalWPDTargetsMap);
1092 *Index, IsExported(ExportLists, GUIDPreservedSymbols),
1093 IsPrevailing(PrevailingCopy));
1094
1095 thinLTOPropagateFunctionAttrs(*Index, IsPrevailing(PrevailingCopy));
1096
1097 // Make sure that every module has an entry in the ExportLists, ImportList,
1098 // GVSummary and ResolvedODR maps to enable threaded access to these maps
1099 // below.
1100 for (auto &Module : Modules) {
1101 auto ModuleIdentifier = Module->getName();
1102 ExportLists[ModuleIdentifier];
1103 ImportLists[ModuleIdentifier];
1104 ResolvedODR[ModuleIdentifier];
1105 ModuleToDefinedGVSummaries[ModuleIdentifier];
1106 }
1107
1108 std::vector<BitcodeModule *> ModulesVec;
1109 ModulesVec.reserve(Modules.size());
1110 for (auto &Mod : Modules)
1111 ModulesVec.push_back(&Mod->getSingleBitcodeModule());
1112 std::vector<int> ModulesOrdering = lto::generateModulesOrdering(ModulesVec);
1113
1116
1117 TimeTraceScopeExit.release();
1118
1119 // Parallel optimizer + codegen
1120 {
1122 for (auto IndexCount : ModulesOrdering) {
1123 auto &Mod = Modules[IndexCount];
1124 Pool.async([&](int count) {
1125 auto ModuleIdentifier = Mod->getName();
1126 auto &ExportList = ExportLists[ModuleIdentifier];
1127
1128 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
1129
1130 // The module may be cached, this helps handling it.
1131 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
1132 ImportLists[ModuleIdentifier], ExportList,
1133 ResolvedODR[ModuleIdentifier],
1134 DefinedGVSummaries, OptLevel, Freestanding,
1135 TMBuilder);
1136 auto CacheEntryPath = CacheEntry.getEntryPath();
1137
1138 {
1139 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1140 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1141 << " '" << CacheEntryPath << "' for buffer "
1142 << count << " " << ModuleIdentifier << "\n");
1143
1144 if (ErrOrBuffer) {
1145 // Cache Hit!
1146 if (SavedObjectsDirectoryPath.empty())
1147 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1148 else
1149 ProducedBinaryFiles[count] = writeGeneratedObject(
1150 count, CacheEntryPath, *ErrOrBuffer.get());
1151 return;
1152 }
1153 }
1154
1155 LLVMContext Context;
1157 Context.enableDebugTypeODRUniquing();
1158 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1161 if (!DiagFileOrErr) {
1162 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1163 report_fatal_error("ThinLTO: Can't get an output file for the "
1164 "remarks");
1165 }
1166
1167 // Parse module now
1168 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1169 /*IsImporting*/ false);
1170
1171 // Save temps: original file.
1172 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1173
1174 auto &ImportList = ImportLists[ModuleIdentifier];
1175 // Run the main process now, and generates a binary
1177 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1178 ExportList, GUIDPreservedSymbols,
1179 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1180 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count,
1181 DebugPassManager);
1182
1183 // Commit to the cache (if enabled)
1184 CacheEntry.write(*OutputBuffer);
1185
1186 if (SavedObjectsDirectoryPath.empty()) {
1187 // We need to generated a memory buffer for the linker.
1188 if (!CacheEntryPath.empty()) {
1189 // When cache is enabled, reload from the cache if possible.
1190 // Releasing the buffer from the heap and reloading it from the
1191 // cache file with mmap helps us to lower memory pressure.
1192 // The freed memory can be used for the next input file.
1193 // The final binary link will read from the VFS cache (hopefully!)
1194 // or from disk (if the memory pressure was too high).
1195 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1196 if (auto EC = ReloadedBufferOrErr.getError()) {
1197 // On error, keep the preexisting buffer and print a diagnostic.
1198 errs() << "remark: can't reload cached file '" << CacheEntryPath
1199 << "': " << EC.message() << "\n";
1200 } else {
1201 OutputBuffer = std::move(*ReloadedBufferOrErr);
1202 }
1203 }
1204 ProducedBinaries[count] = std::move(OutputBuffer);
1205 return;
1206 }
1207 ProducedBinaryFiles[count] = writeGeneratedObject(
1208 count, CacheEntryPath, *OutputBuffer);
1209 }, IndexCount);
1210 }
1211 }
1212
1213 pruneCache(CacheOptions.Path, CacheOptions.Policy, ProducedBinaries);
1214
1215 // If statistics were requested, print them out now.
1219}
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:114
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
ArrayRef - 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:78
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:162
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:281
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:285
StringRef getName() const
Get a short "name" for the module.
Definition Module.h:269
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition Module.h:252
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition Module.cpp: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:297
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
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
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.
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:791
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:114
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:569
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:1805
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:2178
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2222
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:1090
@ OF_UpdateAtime
Force files Atime to be updated on access.
Definition FileSystem.h:779
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:976
LLVM_ABI std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition Path.cpp:1025
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition Path.cpp:1105
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.
Definition Types.h:26
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"))
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:1737
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:990
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 thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition LTO.cpp:554
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
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:207
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 updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
LLVM_ABI void thinLTOResolvePrevailingInIndex(const lto::Config &C, ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Resolve linkage for prevailing symbols in the Index.
Definition LTO.cpp:449
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:189
LLVM_ABI void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
LLVM_ABI void runWholeProgramDevirtOnIndex(ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap)
Perform index-based whole program devirtualization on the Summary index.
LLVM_ABI bool pruneCache(StringRef Path, CachePruningPolicy Policy, const std::vector< std::unique_ptr< MemoryBuffer > > &Files={})
Peform pruning using the supplied policy, returns true if pruning occurred, i.e.
LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
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:2002
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)
LLVM_ABI Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue)
Definition DWP.cpp:677
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:1770
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:104
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
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 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 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 simple container for information about the supported runtime calls.
static const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Helper to gather options relevant to the target machine creation.
LLVM_ABI std::unique_ptr< TargetMachine > create() const
Struct that holds a reference to a particular GUID in a global value summary.
LTO configuration.
Definition Config.h:42
std::vector< std::string > MAttrs
Definition Config.h:51
CodeGenOptLevel CGOptLevel
Definition Config.h:58
std::string CPU
Definition Config.h:49
TargetOptions Options
Definition Config.h:50
unsigned OptLevel
Definition Config.h:60
std::optional< Reloc::Model > RelocModel
Definition Config.h:56
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition Config.h:66