21 #include "llvm/Config/llvm-config.h" 39 #include "llvm/Support/VCSRevision.h" 53 #define DEBUG_TYPE "lto" 57 cl::desc(
"Dump the SCCs in the ThinLTO index's callgraph"));
72 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
75 const std::set<GlobalValue::GUID> &CfiFunctionDefs,
76 const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
84 Hasher.
update(LLVM_VERSION_STRING);
86 Hasher.
update(LLVM_REVISION);
94 auto AddUnsigned = [&](
unsigned I) {
102 auto AddUint64 = [&](uint64_t
I) {
123 for (
auto &A : Conf.
MAttrs)
146 for (
auto F : ExportList)
153 for (
auto &Entry : ImportList) {
157 AddUint64(Entry.second.size());
158 for (
auto &Fn : Entry.second)
163 for (
auto &Entry : ResolvedODR) {
165 sizeof(GlobalValue::GUID)));
172 std::set<GlobalValue::GUID> UsedCfiDefs;
173 std::set<GlobalValue::GUID> UsedCfiDecls;
176 std::set<GlobalValue::GUID> UsedTypeIds;
178 auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
179 if (CfiFunctionDefs.count(ValueGUID))
180 UsedCfiDefs.insert(ValueGUID);
181 if (CfiFunctionDecls.count(ValueGUID))
182 UsedCfiDecls.insert(ValueGUID);
187 AddUnsigned(GS->isLive());
189 AddUnsigned(
VI.isDSOLocal());
190 AddUsedCfiGlobal(
VI.getGUID());
192 if (
auto *FS = dyn_cast<FunctionSummary>(GS)) {
193 for (
auto &TT : FS->type_tests())
194 UsedTypeIds.insert(TT);
195 for (
auto &TT : FS->type_test_assume_vcalls())
196 UsedTypeIds.insert(TT.GUID);
197 for (
auto &TT : FS->type_checked_load_vcalls())
198 UsedTypeIds.insert(TT.GUID);
199 for (
auto &TT : FS->type_test_assume_const_vcalls())
200 UsedTypeIds.insert(TT.VFunc.GUID);
201 for (
auto &TT : FS->type_checked_load_const_vcalls())
202 UsedTypeIds.insert(TT.VFunc.GUID);
203 for (
auto &ET : FS->calls()) {
204 AddUnsigned(ET.first.isDSOLocal());
205 AddUsedCfiGlobal(ET.first.getGUID());
212 for (
auto &GS : DefinedGlobals) {
216 AddUsedCfiGlobal(GS.first);
217 AddUsedThings(GS.second);
222 for (
auto &ImpM : ImportList)
223 for (
auto &ImpF : ImpM.second)
229 AddUnsigned(S.TTRes.TheKind);
230 AddUnsigned(S.TTRes.SizeM1BitWidth);
232 AddUint64(S.TTRes.AlignLog2);
233 AddUint64(S.TTRes.SizeM1);
234 AddUint64(S.TTRes.BitMask);
235 AddUint64(S.TTRes.InlineBits);
237 AddUint64(S.WPDRes.size());
238 for (
auto &WPD : S.WPDRes) {
239 AddUnsigned(WPD.first);
240 AddUnsigned(WPD.second.TheKind);
241 AddString(WPD.second.SingleImplName);
243 AddUint64(WPD.second.ResByArg.size());
244 for (
auto &ByArg : WPD.second.ResByArg) {
245 AddUint64(ByArg.first.size());
246 for (uint64_t
Arg : ByArg.first)
248 AddUnsigned(ByArg.second.TheKind);
249 AddUint64(ByArg.second.Info);
250 AddUnsigned(ByArg.second.Byte);
251 AddUnsigned(ByArg.second.Bit);
257 for (GlobalValue::GUID TId : UsedTypeIds) {
258 auto SummariesI = TypeIdSummariesByGuid.
find(TId);
259 if (SummariesI != TypeIdSummariesByGuid.
end())
260 for (
auto *Summary : SummariesI->second)
261 AddTypeIdSummary(Summary->first, Summary->second);
264 AddUnsigned(UsedCfiDefs.size());
265 for (
auto &V : UsedCfiDefs)
268 AddUnsigned(UsedCfiDecls.size());
269 for (
auto &V : UsedCfiDecls)
275 Hasher.
update(FileOrErr.get()->getBuffer());
288 for (
auto &S : GVSummaryList) {
300 if (isPrevailing(GUID, S.get())) {
306 else if (!isa<AliasSummary>(S.get()) &&
307 !GlobalInvolvedWithAlias.
count(S.get()))
309 if (S->linkage() != OriginalLinkage)
310 recordNewLinkage(S->modulePath(), GUID, S->linkage());
330 for (
auto &
I : Index)
331 for (
auto &S :
I.second.SummaryList)
332 if (
auto AS = dyn_cast<AliasSummary>(S.get()))
333 GlobalInvolvedWithAlias.
insert(&
AS->getAliasee());
335 for (
auto &
I : Index)
337 GlobalInvolvedWithAlias, isPrevailing,
344 for (
auto &S : GVSummaryList) {
345 if (isExported(S->modulePath(), GUID)) {
358 for (
auto &
I : Index)
372 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
373 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
374 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
375 File->ComdatTable = FOrErr->TheReader.getComdatTable();
377 for (
unsigned I = 0;
I != FOrErr->Mods.size(); ++
I) {
378 size_t Begin = File->Symbols.size();
380 FOrErr->TheReader.module_symbols(
I))
383 if (Sym.isGlobal() && !Sym.isFormatSpecific())
384 File->Symbols.push_back(Sym);
385 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
388 File->Mods = FOrErr->Mods;
389 File->Strtab = std::move(FOrErr->Strtab);
390 return std::move(File);
394 return Mods[0].getModuleIdentifier();
397 LTO::RegularLTOState::RegularLTOState(
unsigned ParallelCodeGenParallelismLevel,
399 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
400 Ctx(Conf), CombinedModule(llvm::make_unique<Module>(
"ld-temp.o", Ctx)),
401 Mover(llvm::make_unique<IRMover>(*CombinedModule)) {}
403 LTO::ThinLTOState::ThinLTOState(
ThinBackend Backend)
404 : Backend(Backend), CombinedIndex(
false) {
411 unsigned ParallelCodeGenParallelismLevel)
412 : Conf(
std::move(Conf)),
413 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
414 ThinLTO(
std::move(Backend)) {}
423 unsigned Partition,
bool InSummary) {
424 auto *ResI = Res.
begin();
425 auto *ResE = Res.
end();
432 Triple TT(RegularLTO.CombinedModule->getTargetTriple());
436 if (TT.isOSBinFormatCOFF() && Name.
startswith(
"__imp_"))
437 Name = Name.
substr(strlen(
"__imp_"));
438 auto &GlobalRes = GlobalResolutions[
Name];
439 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
441 assert(!GlobalRes.Prevailing &&
442 "Multiple prevailing defs are not allowed");
443 GlobalRes.Prevailing =
true;
444 GlobalRes.IRName = Sym.getIRName();
445 }
else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
452 GlobalRes.IRName = Sym.getIRName();
461 GlobalRes.Partition != Partition)) {
462 GlobalRes.Partition = GlobalResolution::External;
465 GlobalRes.Partition = Partition;
469 GlobalRes.VisibleOutsideSummary |=
478 auto ResI = Res.
begin();
483 OS <<
"-r=" << Path <<
',' << Sym.getName() <<
',';
486 if (Res.FinalDefinitionInLinkageUnit)
488 if (Res.VisibleToRegularObj)
490 if (Res.LinkerRedefined)
500 assert(!CalledGetMaxTasks);
505 if (RegularLTO.CombinedModule->getTargetTriple().empty())
506 RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
509 for (
unsigned I = 0;
I != Input->Mods.size(); ++
I)
510 if (
Error Err = addModule(*Input,
I, ResI, Res.
end()))
525 auto ModSyms = Input.module_symbols(ModI);
526 addModuleToGlobalRes(ModSyms, {ResI, ResE},
527 LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
528 LTOInfo->HasSummary);
530 if (LTOInfo->IsThinLTO)
531 return addThinLTO(BM, ModSyms, ResI, ResE);
534 addRegularLTO(BM, ModSyms, ResI, ResE);
538 if (!LTOInfo->HasSummary)
539 return linkRegularLTO(std::move(*ModOrErr),
false);
545 RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
561 std::set<const Comdat *> &NonPrevailingComdats) {
566 if (!NonPrevailingComdats.count(C))
575 if (
auto GO = dyn_cast<GlobalObject>(&GV))
576 GO->setComdat(
nullptr);
586 RegularLTOState::AddedModule
Mod;
593 Mod.M = std::move(*MOrErr);
596 return std::move(Err);
603 if (GV.hasAppendingLinkage())
604 Mod.Keep.push_back(&GV);
609 AliasedGlobals.
insert(GO);
618 auto MsymI = SymTab.
symbols().begin(), MsymE = SymTab.
symbols().end();
620 while (MsymI != MsymE) {
630 std::set<const Comdat *> NonPrevailingComdats;
641 if (Sym.isUndefined())
643 Mod.Keep.push_back(GV);
654 }
else if (isa<GlobalObject>(GV) &&
655 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
656 GV->hasAvailableExternallyLinkage()) &&
657 !AliasedGlobals.
count(cast<GlobalObject>(GV))) {
663 Mod.Keep.push_back(GV);
666 NonPrevailingComdats.insert(GV->getComdat());
667 cast<GlobalObject>(GV)->setComdat(
nullptr);
672 GV->setDSOLocal(
true);
677 if (Sym.isCommon()) {
680 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
681 CommonRes.Size =
std::max(CommonRes.Size, Sym.getCommonSize());
682 CommonRes.Align =
std::max(CommonRes.Align, Sym.getCommonAlignment());
691 return std::move(Mod);
694 Error LTO::linkRegularLTO(RegularLTOState::AddedModule
Mod,
695 bool LivenessFromIndex) {
696 std::vector<GlobalValue *> Keep;
698 if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->
getGUID()))
709 RegularLTO.CombinedModule->getNamedValue(GV->
getName());
716 return RegularLTO.Mover->move(std::move(Mod.M), Keep,
727 ThinLTO.ModuleMap.size()))
734 if (!Sym.getIRName().empty()) {
745 if (
auto S = ThinLTO.CombinedIndex.findSummaryInModule(
753 if (
auto S = ThinLTO.CombinedIndex.findSummaryInModule(
755 S->setDSOLocal(
true);
761 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
762 return make_error<StringError>(
763 "Expected at most one ThinLTO module per bitcode file",
770 CalledGetMaxTasks =
true;
771 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
778 for (
auto &Res : GlobalResolutions) {
781 if (Res.second.IRName.
empty())
787 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
791 GUIDPrevailingResolutions[GUID] =
795 auto isPrevailing = [&](GlobalValue::GUID
G) {
796 auto It = GUIDPrevailingResolutions.
find(
G);
797 if (It == GUIDPrevailingResolutions.
end())
804 std::unique_ptr<ToolOutputFile> StatsFile =
nullptr;
817 Result = runThinLTO(AddStream, Cache);
826 for (
auto &M : RegularLTO.ModsWithSummaries)
827 if (
Error Err = linkRegularLTO(std::move(M),
833 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
834 for (
auto &
I : RegularLTO.Commons) {
835 if (!
I.second.Prevailing)
838 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(
I.first);
847 auto *GV =
new GlobalVariable(*RegularLTO.CombinedModule, Ty,
false,
850 GV->setAlignment(
I.second.Align);
856 GV->setName(
I.first);
865 for (
const auto &R : GlobalResolutions) {
866 if (!R.second.isPrevailingIRSymbol())
868 if (R.second.Partition != 0 &&
869 R.second.Partition != GlobalResolution::External)
873 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
880 if (R.second.Partition == 0)
888 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
889 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
902 : Conf(Conf), CombinedIndex(CombinedIndex),
903 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
910 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
912 virtual Error wait() = 0;
921 std::set<GlobalValue::GUID> CfiFunctionDefs;
922 std::set<GlobalValue::GUID> CfiFunctionDecls;
928 InProcessThinBackend(
930 unsigned ThinLTOParallelismLevel,
934 BackendThreadPool(ThinLTOParallelismLevel),
935 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
940 for (
auto &TId : CombinedIndex.
typeIds())
946 CfiFunctionDecls.insert(
950 Error runThinLTOBackendThread(
955 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
965 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
966 ImportList, DefinedGlobals, ModuleMap);
976 return RunThinBackend(AddStream);
980 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
981 ResolvedODR, DefinedGlobals, TypeIdSummariesByGuid,
982 CfiFunctionDefs, CfiFunctionDecls);
984 return RunThinBackend(CacheAddStream);
993 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
996 assert(ModuleToDefinedGVSummaries.
count(ModulePath));
998 ModuleToDefinedGVSummaries.
find(ModulePath)->second;
999 BackendThreadPool.
async(
1003 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1008 Error E = runThinLTOBackendThread(
1009 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1010 ResolvedODR, DefinedGlobals, ModuleMap, TypeIdSummariesByGuid);
1012 std::unique_lock<std::mutex> L(ErrMu);
1014 Err =
joinErrors(std::move(*Err), std::move(E));
1019 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1020 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap),
1021 std::ref(TypeIdSummariesByGuid));
1025 Error wait()
override {
1026 BackendThreadPool.
wait();
1028 return std::move(*Err);
1039 return llvm::make_unique<InProcessThinBackend>(
1040 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
1049 const std::string &OldPrefix,
1050 const std::string &NewPrefix) {
1051 if (OldPrefix.empty() && NewPrefix.empty())
1056 if (!ParentPath.
empty()) {
1059 llvm::errs() <<
"warning: could not create directory '" << ParentPath
1060 <<
"': " << EC.message() <<
'\n';
1062 return NewPath.
str();
1067 std::string OldPrefix, NewPrefix;
1068 bool ShouldEmitImportsFiles;
1073 WriteIndexesThinBackend(
1076 std::string OldPrefix, std::string NewPrefix,
bool ShouldEmitImportsFiles,
1079 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1080 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
1081 LinkedObjectsFile(LinkedObjectsFile), OnWrite(OnWrite) {}
1087 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1090 std::string NewModulePath =
1093 if (LinkedObjectsFile)
1094 *LinkedObjectsFile << NewModulePath <<
'\n';
1096 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
1098 ImportList, ModuleToSummariesForIndex);
1107 if (ShouldEmitImportsFiles) {
1109 ModuleToSummariesForIndex);
1115 OnWrite(ModulePath);
1124 std::string OldPrefix, std::string NewPrefix,
bool ShouldEmitImportsFiles,
1129 return llvm::make_unique<WriteIndexesThinBackend>(
1130 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
1131 ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
1136 if (ThinLTO.ModuleMap.empty())
1145 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
1146 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1147 ModuleToDefinedGVSummaries);
1155 for (
auto &Mod : ThinLTO.ModuleMap)
1156 if (!ModuleToDefinedGVSummaries.count(Mod.first))
1157 ModuleToDefinedGVSummaries.
try_emplace(Mod.first);
1160 ThinLTO.ModuleMap.size());
1162 ThinLTO.ModuleMap.size());
1166 ThinLTO.CombinedIndex.dumpSCCs(
outs());
1170 ImportLists, ExportLists);
1176 std::set<GlobalValue::GUID> ExportedGUIDs;
1177 for (
auto &Res : GlobalResolutions) {
1180 if (Res.second.Partition != GlobalResolution::External ||
1181 !Res.second.isPrevailingIRSymbol())
1186 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1187 ExportedGUIDs.insert(GUID);
1192 for (
auto &
Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1193 ExportedGUIDs.insert(
1196 auto isExported = [&](
StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
1197 const auto &ExportList = ExportLists.find(ModuleIdentifier);
1198 return (ExportList != ExportLists.end() &&
1199 ExportList->second.count(GUID)) ||
1200 ExportedGUIDs.count(GUID);
1204 auto isPrevailing = [&](GlobalValue::GUID GUID,
1206 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1208 auto recordNewLinkage = [&](
StringRef ModuleIdentifier,
1209 GlobalValue::GUID GUID,
1211 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1216 std::unique_ptr<ThinBackendProc> BackendProc =
1217 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1222 unsigned Task = RegularLTO.ParallelCodeGenParallelismLevel;
1223 for (
auto &Mod : ThinLTO.ModuleMap) {
1224 if (
Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1225 ExportLists[Mod.first],
1226 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1231 return BackendProc->wait();
1238 if (LTOPassRemarksWithHotness)
1240 if (LTORemarksFilename.
empty())
1248 auto DiagnosticFile =
1253 llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1254 DiagnosticFile->keep();
1255 return std::move(DiagnosticFile);
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.
A parsed version of the target data layout string in and methods for querying it. ...
static void thinLTOResolveWeakForLinkerGUID(GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID, DenseSet< GlobalValueSummary *> &GlobalInvolvedWithAlias, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage)
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
This class defines the interface to the ThinLTO backend.
bool hasLocalLinkage() const
uint32_t getSymbolFlags(Symbol S) const
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
void EnableStatistics(bool PrintOnExit=true)
Enable the collection and printing of statistics.
unsigned Prevailing
The linker has chosen this definition of the symbol.
CodeGenOpt::Level CGOptLevel
void replace_path_prefix(SmallVectorImpl< char > &Path, const StringRef &OldPrefix, const StringRef &NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
std::vector< std::unique_ptr< GlobalValueSummary > > GlobalValueSummaryList
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Compute iterated dominance frontiers using a linear time algorithm.
void setDiagnosticsOutputFile(std::unique_ptr< yaml::Output > F)
Set the diagnostics output file used for optimization diagnostics.
cl::opt< std::string > LTORemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
unsigned heavyweight_hardware_concurrency()
Get the amount of currency to use for tasks requiring significant memory or other resources...
A Module instance is used to store all the information related to an LLVM module. ...
GlobalValueSummary * findSummaryInModule(GlobalValue::GUID ValueGUID, StringRef ModuleId) const
Find the summary for global GUID in module ModuleId, or nullptr if not found.
Implements a dense probed hash-table based set.
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Available for inspection, not emission.
unsigned DataSections
Emit data into separate sections.
static ConstantAggregateZero * get(Type *Ty)
std::error_code EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, uint64_t ModuleId)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
bool hasAvailableExternallyLinkage() const
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
static void computeCacheKey(SmallString< 40 > &Key, const 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 TypeIdSummariesByGuidTy &TypeIdSummariesByGuid, const std::set< GlobalValue::GUID > &CfiFunctionDefs, const std::set< GlobalValue::GUID > &CfiFunctionDecls)
An efficient, type-erasing, non-owning reference to a callable.
iterator find(StringRef Key)
const StringMap< std::pair< uint64_t, ModuleHash > > & modulePaths() const
Table of modules, containing module hash and id.
Externally visible function.
The resolution for a symbol.
This class implements a map that also provides access to all stored values in a deterministic order...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
const StringMap< GVSummaryMapTy > & ModuleToDefinedGVSummaries
A class that wrap the SHA1 algorithm.
Error takeError()
Take ownership of the stored error.
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
void setAlignment(unsigned Align)
std::function< void(const std::string &)> IndexWriteCallback
This ThinBackend writes individual module indexes to files, instead of running the individual backend...
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
StringRef getModuleIdentifier() const
ThinBackend createWriteIndexesThinBackend(std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite)
static bool isLocalLinkage(LinkageTypes Linkage)
static bool isLinkOnceLinkage(LinkageTypes Linkage)
CombinedIndexHookFn CombinedIndexHook
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::function< std::unique_ptr< NativeObjectStream >unsigned Task)> AddStreamFn
This type defines the callback to add a native object that is generated on the fly.
Represents a module in a bitcode file.
std::string DwoDir
The directory to store .dwo files.
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module's symbol table for COMDATs (constant).
std::vector< std::string > MAttrs
ModuleSummaryIndex & CombinedIndex
std::unordered_set< GlobalValue::GUID > ExportSetTy
The set contains an entry for every global value the module exports.
ArrayRef< Symbol > symbols() const
Tagged union holding either a T or a Error.
StringRef result()
Return a reference to the current raw 160-bits SHA1 for the digested data since the last call to init...
void addModule(Module *M)
static bool isLinkOnceODRLinkage(LinkageTypes Linkage)
StringRef str() const
Explicit conversion to StringRef.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
const std::map< std::string, TypeIdSummary > & typeIds() const
cl::opt< bool > LTOPassRemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
void setDiagnosticsHotnessRequested(bool Requested)
Set if a code hotness metric should be included in optimization diagnostics.
Class to represent array types.
std::string SampleProfile
Sample PGO profile path.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
unsigned FunctionSections
Emit functions into separate sections.
Optional< CodeModel::Model > CodeModel
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
A ThreadPool for asynchronous parallel execution on a defined number of threads.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&... Args)
Emplace a new element for the specified key into the map if the key isn't already in the map...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
void update(ArrayRef< uint8_t > Data)
Digest more data.
iterator find(const_arg_type_t< KeyT > Val)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Ephemeral symbols produced by Reader::symbols() and Reader::module_symbols().
Error add(std::unique_ptr< InputFile > Obj, ArrayRef< SymbolResolution > Res)
Add an input file to the LTO link, using the provided symbol resolutions.
DebuggerKind DebuggerTuning
Which debugger to tune for.
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
initializer< Ty > init(const Ty &Val)
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
static cl::opt< bool > DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden, cl::desc("Dump the SCCs in the ThinLTO index's callgraph"))
std::function< AddStreamFn(unsigned Task, StringRef Key)> NativeObjectCache
This is the type of a native object cache.
void gatherImportedSummariesForModule(StringRef ModulePath, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
This is an important class for using LLVM in a threaded context.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
std::pair< iterator, bool > insert(const ValueT &V)
bool UseNewPM
Use the new pass manager.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
DenseMap< GlobalValue::GUID, TinyPtrVector< const std::pair< const std::string, TypeIdSummary > * > > TypeIdSummariesByGuidTy
bool isWeakForLinker() const
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple...
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Function and variable summary information to aid decisions and implementation of importing.
static GUID getGUID(StringRef GlobalName)
Return a 64-bit global unique ID constructed from global value name (i.e.
std::string StatsFile
Statistics output file path.
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
TargetMachine::CodeGenFileType CGFileType
Triple - Helper class for working with autoconf configuration names.
static LinkageTypes getWeakLinkage(bool ODR)
Struct that holds a reference to a particular GUID in a global value summary.
static void writeToResolutionFile(raw_ostream &OS, InputFile *Input, ArrayRef< SymbolResolution > Res)
void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
static ErrorSuccess success()
Create a success value.
std::function< std::unique_ptr< ThinBackendProc > Config &C, ModuleSummaryIndex &CombinedIndex, StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, NativeObjectCache Cache)> ThinBackend
A ThinBackend defines what happens after the thin-link phase during ThinLTO.
unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
static void thinLTOInternalizeAndPromoteGUID(GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID, function_ref< bool(StringRef, GlobalValue::GUID)> isExported)
virtual ~ThinBackendProc()
Optional< Reloc::Model > RelocModel
std::string utostr(uint64_t X, bool isNeg=false)
void setLinkage(LinkageTypes LT)
The access may modify the value stored in memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
const Comdat * getComdat() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1', drop it.
LinkageTypes
An enumeration for the kinds of linkage for global values.
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
void WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
std::string toHex(StringRef Input)
Convert buffer Input to its hexadecimal representation.
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
unsigned RelaxELFRelocations
ThinBackend createInProcessThinBackend(unsigned ParallelismLevel)
This ThinBackend runs the individual backend jobs in-process.
amdgpu Simplify well known AMD library false Value Value * Arg
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::set< std::string > & cfiFunctionDefs()
Error thinBackend(Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > &ModuleMap)
Runs a ThinLTO backend.
void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, StringMap< FunctionImporter::ImportMapTy > &ImportLists, StringMap< FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
A raw_ostream that writes to a file descriptor.
LTO(Config Conf, ThinBackend Backend=nullptr, unsigned ParallelCodeGenParallelismLevel=1)
Create an LTO object.
void setUnnamedAddr(UnnamedAddr Val)
void thinLTOResolveWeakForLinkerInIndex(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage)
Resolve Weak and LinkOnce values in the Index.
static void handleNonPrevailingComdat(GlobalValue &GV, std::set< const Comdat *> &NonPrevailingComdats)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
StringRef getName() const
Return a constant reference to the value's name.
Error run(AddStreamFn AddStream, NativeObjectCache Cache=nullptr)
Runs the LTO pipeline.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Type * getValueType() const
Keep one copy of named function when linking (weak)
Rename collisions when linking (static functions).
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
const GlobalObject * getBaseObject() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
Error backend(Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::set< std::string > & cfiFunctionDecls()
std::function< void(GlobalValue &)> ValueAdder
Lightweight error class with error context and mandatory checking.
void computeDeadSymbols(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing)
Compute all the symbols that are "dead": i.e these that can't be reached in the graph from any of the...
This class implements an extremely fast bulk output stream that can only output to a stream...
Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting)
Read the bitcode module and prepare for lazy deserialization of function bodies.
Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context)
Read the entire bitcode module and return it.
iterator_range< global_iterator > globals()
A derived class of LLVMContext that initializes itself according to a given Config object...
StringRef - Represent a constant reference to a string, i.e.
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit...
Expected< IRSymtabFile > readIRSymtab(MemoryBufferRef MBRef)
Reads a bitcode file, creating its irsymtab if necessary.
iterator_range< global_value_iterator > global_values()
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
llvm::Error materializeMetadata()
static IntegerType * getInt8Ty(LLVMContext &C)
PointerType * getType() const
Global values are always pointers.
std::string getThinLTOOutputFile(const std::string &Path, const std::string &OldPrefix, const std::string &NewPrefix)
Given the original Path to an output file, replace any path prefix matching OldPrefix with NewPrefix...
void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, GlobalValue::GUID)> isExported)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
bool empty() const
empty - Check if the array is empty.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
iterator_range< alias_iterator > aliases()