28#include "llvm/Config/llvm-config.h"
56#include "llvm/Support/VCSRevision.h"
72#define DEBUG_TYPE "lto"
76 cl::desc(
"Dump the SCCs in the ThinLTO index's callgraph"));
87 cl::desc(
"Enable global value internalization in LTO"));
91 cl::desc(
"Keep copies of symbols in LTO indexing"));
108 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
119 Hasher.
update(LLVM_VERSION_STRING);
121 Hasher.
update(LLVM_REVISION);
129 auto AddUnsigned = [&](
unsigned I) {
139 auto AddUint8 = [&](
const uint8_t I) {
163 AddUnsigned(
static_cast<int>(Conf.
CGOptLevel));
164 AddUnsigned(
static_cast<int>(Conf.
CGFileType));
172 AddUint8(Conf.
Dtlto);
175 auto ModHash = Index.getModuleHash(ModuleID);
180 std::vector<uint64_t> ExportsGUID;
181 ExportsGUID.reserve(ExportList.
size());
182 for (
const auto &VI : ExportList)
183 ExportsGUID.push_back(VI.getGUID());
187 for (
auto GUID : ExportsGUID)
192 auto Comp = [&](
const std::pair<StringRef, GlobalValue::GUID> &L,
193 const std::pair<StringRef, GlobalValue::GUID> &R) {
194 return std::make_pair(Index.getModule(L.first)->second, L.second) <
195 std::make_pair(Index.getModule(R.first)->second, R.second);
201 for (
const auto &[FromModule, GUID,
Type] : SortedImportList)
202 ++ModuleToNumImports[FromModule];
204 std::optional<StringRef> LastModule;
205 for (
const auto &[FromModule, GUID,
Type] : SortedImportList) {
206 if (LastModule != FromModule) {
210 LastModule = FromModule;
211 auto ModHash = Index.getModule(FromModule)->second;
213 AddUint64(ModuleToNumImports[FromModule]);
220 for (
auto &Entry : ResolvedODR) {
229 std::set<GlobalValue::GUID> UsedCfiDefs;
230 std::set<GlobalValue::GUID> UsedCfiDecls;
233 std::set<GlobalValue::GUID> UsedTypeIds;
236 if (CfiFunctionDefs.
contains(ValueGUID))
237 UsedCfiDefs.insert(ValueGUID);
238 if (CfiFunctionDecls.
contains(ValueGUID))
239 UsedCfiDecls.insert(ValueGUID);
244 AddUnsigned(GS->getVisibility());
245 AddUnsigned(GS->isLive());
246 AddUnsigned(GS->canAutoHide());
248 AddUnsigned(VI.isDSOLocal(Index.withDSOLocalPropagation()));
249 AddUsedCfiGlobal(VI.getGUID());
252 AddUnsigned(GVS->maybeReadOnly());
253 AddUnsigned(GVS->maybeWriteOnly());
256 for (
auto &TT : FS->type_tests())
257 UsedTypeIds.insert(TT);
258 for (
auto &TT : FS->type_test_assume_vcalls())
259 UsedTypeIds.insert(TT.GUID);
260 for (
auto &TT : FS->type_checked_load_vcalls())
261 UsedTypeIds.insert(TT.GUID);
262 for (
auto &TT : FS->type_test_assume_const_vcalls())
263 UsedTypeIds.insert(TT.VFunc.GUID);
264 for (
auto &TT : FS->type_checked_load_const_vcalls())
265 UsedTypeIds.insert(TT.VFunc.GUID);
266 for (
auto &ET : FS->calls()) {
267 AddUnsigned(ET.first.isDSOLocal(Index.withDSOLocalPropagation()));
268 AddUsedCfiGlobal(ET.first.getGUID());
275 for (
auto &GS : DefinedGlobals) {
279 AddUsedCfiGlobal(GS.first);
280 AddUsedThings(GS.second);
285 for (
const auto &[FromModule, GUID,
Type] : SortedImportList) {
291 AddUsedThings(AS->getBaseObject());
297 AddUnsigned(S.TTRes.TheKind);
298 AddUnsigned(S.TTRes.SizeM1BitWidth);
300 AddUint64(S.TTRes.AlignLog2);
301 AddUint64(S.TTRes.SizeM1);
302 AddUint64(S.TTRes.BitMask);
303 AddUint64(S.TTRes.InlineBits);
305 AddUint64(S.WPDRes.size());
306 for (
auto &WPD : S.WPDRes) {
307 AddUnsigned(WPD.first);
308 AddUnsigned(WPD.second.TheKind);
309 AddString(WPD.second.SingleImplName);
311 AddUint64(WPD.second.ResByArg.size());
312 for (
auto &ByArg : WPD.second.ResByArg) {
313 AddUint64(ByArg.first.size());
316 AddUnsigned(ByArg.second.TheKind);
317 AddUint64(ByArg.second.Info);
318 AddUnsigned(ByArg.second.Byte);
319 AddUnsigned(ByArg.second.Bit);
326 auto TidIter = Index.typeIds().equal_range(TId);
328 AddTypeIdSummary(
I.second.first,
I.second.second);
331 AddUnsigned(UsedCfiDefs.size());
332 for (
auto &V : UsedCfiDefs)
335 AddUnsigned(UsedCfiDecls.size());
336 for (
auto &V : UsedCfiDecls)
342 Hasher.
update(FileOrErr.get()->getBuffer());
347 Hasher.
update(FileOrErr.get()->getBuffer());
378 C.VisibilityScheme ==
Config::ELF ? VI.getELFVisibility()
380 for (
auto &S : VI.getSummaryList()) {
395 if (isPrevailing(VI.getGUID(), S.get())) {
408 S->setCanAutoHide(VI.canAutoHide() &&
409 !GUIDPreservedSymbols.
count(VI.getGUID()));
412 Visibility = S->getVisibility();
426 S->setVisibility(Visibility);
428 if (S->linkage() != OriginalLinkage)
429 recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
433 for (
auto &S : VI.getSummaryList()) {
438 S->setVisibility(Visibility);
460 for (
auto &
I : Index)
461 for (
auto &S :
I.second.getSummaryList())
463 GlobalInvolvedWithAlias.
insert(&AS->getAliasee());
465 for (
auto &
I : Index)
467 GlobalInvolvedWithAlias, isPrevailing,
468 recordNewLinkage, GUIDPreservedSymbols);
479 const bool SingleExternallyVisibleCopy =
480 VI.getSummaryList().size() == 1 &&
483 for (
auto &S : VI.getSummaryList()) {
486 if (isExported(S->modulePath(), VI)) {
547 if (SingleExternallyVisibleCopy && isPrevailing(VI.getGUID(), S.get()))
559 assert(!Index.withInternalizeAndPromote());
560 for (
auto &
I : Index)
563 Index.setWithInternalizeAndPromote();
570 std::unique_ptr<InputFile> File(
new InputFile);
576 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
577 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
578 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
579 File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
580 File->ComdatTable = FOrErr->TheReader.getComdatTable();
582 for (
unsigned I = 0;
I != FOrErr->Mods.size(); ++
I) {
583 size_t Begin = File->Symbols.size();
585 FOrErr->TheReader.module_symbols(
I))
588 if (Sym.isGlobal() && !Sym.isFormatSpecific())
589 File->Symbols.push_back(Sym);
590 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
593 File->Mods = FOrErr->Mods;
594 File->Strtab = std::move(FOrErr->Strtab);
595 return std::move(File);
599 return Mods[0].getModuleIdentifier();
603 assert(Mods.size() == 1 &&
"Expect only one bitcode module");
607LTO::RegularLTOState::RegularLTOState(
unsigned ParallelCodeGenParallelismLevel,
609 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
610 Ctx(Conf), CombinedModule(
std::make_unique<
Module>(
"ld-temp.o", Ctx)),
611 Mover(
std::make_unique<
IRMover>(*CombinedModule)) {}
613LTO::ThinLTOState::ThinLTOState(
ThinBackend BackendParam)
614 : Backend(
std::
move(BackendParam)), CombinedIndex(
false) {
615 if (!Backend.isValid())
621 unsigned ParallelCodeGenParallelismLevel,
LTOKind LTOMode)
623 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
629 Alloc = std::make_unique<BumpPtrAllocator>();
630 GlobalResolutionSymbolSaver = std::make_unique<llvm::StringSaver>(*Alloc);
641 unsigned Partition,
bool InSummary) {
643 auto *ResI = Res.
begin();
644 auto *ResE = Res.
end();
652 if (GlobalResolutionSymbolSaver && !GlobalResolutions->contains(SymbolName))
653 SymbolName = GlobalResolutionSymbolSaver->save(SymbolName);
655 auto &GlobalRes = (*GlobalResolutions)[SymbolName];
656 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
658 assert(!GlobalRes.Prevailing &&
659 "Multiple prevailing defs are not allowed");
660 GlobalRes.Prevailing =
true;
661 GlobalRes.IRName = std::string(Sym.getIRName());
662 }
else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
669 GlobalRes.IRName = std::string(Sym.getIRName());
683 if (GlobalRes.IRName != Sym.getIRName()) {
684 GlobalRes.Partition = GlobalResolution::External;
685 GlobalRes.VisibleOutsideSummary =
true;
693 (GlobalRes.Partition != GlobalResolution::Unknown &&
694 GlobalRes.Partition != Partition)) {
695 GlobalRes.Partition = GlobalResolution::External;
698 GlobalRes.Partition = Partition;
702 GlobalRes.VisibleOutsideSummary |=
709void LTO::releaseGlobalResolutionsMemory() {
711 GlobalResolutions.reset();
713 GlobalResolutionSymbolSaver.reset();
721 auto ResI = Res.
begin();
726 OS <<
"-r=" << Path <<
',' << Sym.getName() <<
',';
744 assert(!CalledGetMaxTasks);
746 if (Conf.ResolutionFile)
749 if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
751 RegularLTO.CombinedModule->setTargetTriple(InputTriple);
757 for (
unsigned I = 0;
I !=
Input->Mods.size(); ++
I) {
758 if (
auto Err = addModule(*
Input, InputRes,
I, Res).moveInto(Res))
774 if (EnableSplitLTOUnit) {
778 if (*EnableSplitLTOUnit != LTOInfo->EnableSplitLTOUnit)
781 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
786 !LTOInfo->UnifiedLTO)
788 "unified LTO compilation must use "
789 "compatible bitcode modules (use -funified-lto)",
797 auto ModSyms =
Input.module_symbols(ModI);
798 addModuleToGlobalRes(ModSyms, Res,
799 IsThinLTO ? ThinLTO.ModuleMap.
size() + 1 : 0,
800 LTOInfo->HasSummary);
803 return addThinLTO(BM, ModSyms, Res);
805 RegularLTO.EmptyCombinedModule =
false;
806 auto ModOrErr = addRegularLTO(
Input, InputRes, BM, ModSyms, Res);
808 return ModOrErr.takeError();
809 Res = ModOrErr->second;
811 if (!LTOInfo->HasSummary) {
812 if (
Error Err = linkRegularLTO(std::move(ModOrErr->first),
822 RegularLTO.ModsWithSummaries.push_back(std::move(ModOrErr->first));
838 std::set<const Comdat *> &NonPrevailingComdats) {
843 if (!NonPrevailingComdats.count(
C))
853 GO->setComdat(
nullptr);
860 std::pair<LTO::RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
864 llvm::TimeTraceScope timeScope(
"LTO add regular LTO");
866 Expected<std::unique_ptr<Module>> MOrErr =
872 Mod.M = std::move(*MOrErr);
874 if (
Error Err =
M.materializeMetadata())
875 return std::move(Err);
881 if (NamedMDNode *CfiFunctionsMD =
M.getNamedMetadata(
"cfi.functions"))
882 M.eraseNamedMetadata(CfiFunctionsMD);
883 }
else if (NamedMDNode *AliasesMD =
M.getNamedMetadata(
"aliases")) {
886 DenseSet<StringRef> Prevailing;
888 if (
R.Prevailing && !
I.getIRName().empty())
889 Prevailing.
insert(
I.getIRName());
890 std::vector<MDNode *> AliasGroups;
891 for (MDNode *AliasGroup : AliasesMD->operands()) {
892 std::vector<Metadata *> Aliases;
893 for (
Metadata *Alias : AliasGroup->operands()) {
896 Aliases.push_back(Alias);
898 if (Aliases.size() > 1)
899 AliasGroups.push_back(
MDTuple::get(RegularLTO.Ctx, Aliases));
901 AliasesMD->clearOperands();
902 for (MDNode *
G : AliasGroups)
903 AliasesMD->addOperand(
G);
908 ModuleSymbolTable SymTab;
911 for (GlobalVariable &GV :
M.globals())
912 if (GV.hasAppendingLinkage())
913 Mod.Keep.push_back(&GV);
915 DenseSet<GlobalObject *> AliasedGlobals;
916 for (
auto &GA :
M.aliases())
917 if (GlobalObject *GO = GA.getAliaseeObject())
918 AliasedGlobals.
insert(GO);
927 auto MsymI = SymTab.
symbols().begin(), MsymE = SymTab.
symbols().end();
929 while (MsymI != MsymE) {
939 std::set<const Comdat *> NonPrevailingComdats;
940 SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
941 for (
const InputFile::Symbol &Sym : Syms) {
951 if (Sym.isUndefined())
953 Mod.Keep.push_back(GV);
957 if (
R.LinkerRedefined)
965 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
966 GV->hasAvailableExternallyLinkage()) &&
973 Mod.Keep.push_back(GV);
976 NonPrevailingComdats.insert(GV->getComdat());
981 if (
R.FinalDefinitionInLinkageUnit) {
982 GV->setDSOLocal(
true);
983 if (GV->hasDLLImportStorageClass())
985 DefaultStorageClass);
987 }
else if (
auto *AS =
991 NonPrevailingAsmSymbols.
insert(AS->first);
999 if (Sym.isCommon()) {
1002 auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
1003 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
1004 if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
1005 CommonRes.Alignment =
1006 std::max(
Align(SymAlignValue), CommonRes.Alignment);
1008 CommonRes.Prevailing |=
R.Prevailing;
1012 if (!
M.getComdatSymbolTable().empty())
1013 for (GlobalValue &GV :
M.global_values())
1018 if (!
M.getModuleInlineAsm().empty()) {
1019 std::string NewIA =
".lto_discard";
1020 if (!NonPrevailingAsmSymbols.
empty()) {
1023 M, [&](StringRef Name, StringRef Alias) {
1024 if (!NonPrevailingAsmSymbols.
count(Alias))
1025 NonPrevailingAsmSymbols.
erase(Name);
1027 NewIA +=
" " +
llvm::join(NonPrevailingAsmSymbols,
", ");
1030 M.setModuleInlineAsm(NewIA +
M.getModuleInlineAsm());
1034 return std::make_pair(std::move(
Mod), Res);
1037Error LTO::linkRegularLTO(RegularLTOState::AddedModule
Mod,
1038 bool LivenessFromIndex) {
1039 llvm::TimeTraceScope timeScope(
"LTO link regular LTO");
1040 std::vector<GlobalValue *>
Keep;
1041 for (GlobalValue *GV :
Mod.Keep) {
1042 if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->
getGUID())) {
1044 if (DiagnosticOutputFile) {
1045 if (
Error Err =
F->materialize())
1047 OptimizationRemarkEmitter ORE(
F,
nullptr);
1048 ORE.emit(OptimizationRemark(
DEBUG_TYPE,
"deadfunction",
F)
1050 <<
" not added to the combined module ");
1063 GlobalValue *CombinedGV =
1064 RegularLTO.CombinedModule->getNamedValue(GV->
getName());
1071 return RegularLTO.Mover->move(std::move(
Mod.M),
Keep,
nullptr,
1076Expected<ArrayRef<SymbolResolution>>
1079 llvm::TimeTraceScope timeScope(
"LTO add thin LTO");
1082 for (
const InputFile::Symbol &Sym : Syms) {
1086 if (!Sym.getIRName().empty() &&
R.Prevailing) {
1090 ThinLTO.setPrevailingModuleForGUID(GUID, BMID);
1096 return ThinLTO.isPrevailingModuleForGUID(GUID, BMID);
1101 for (
const InputFile::Symbol &Sym : Syms) {
1105 if (!Sym.getIRName().empty() &&
1106 (
R.Prevailing ||
R.FinalDefinitionInLinkageUnit)) {
1111 assert(ThinLTO.isPrevailingModuleForGUID(GUID, BMID));
1117 if (
R.LinkerRedefined)
1118 if (
auto S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID))
1124 if (
R.FinalDefinitionInLinkageUnit) {
1125 if (
auto S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID)) {
1126 S->setDSOLocal(
true);
1132 if (!ThinLTO.ModuleMap.insert({BMID, BM}).second)
1134 "Expected at most one ThinLTO module per bitcode file",
1137 if (!Conf.ThinLTOModulesToCompile.empty()) {
1138 if (!ThinLTO.ModulesToCompile)
1139 ThinLTO.ModulesToCompile = ModuleMapType();
1142 for (
const std::string &Name : Conf.ThinLTOModulesToCompile) {
1143 if (BMID.contains(Name)) {
1144 ThinLTO.ModulesToCompile->insert({BMID, BM});
1145 LLVM_DEBUG(
dbgs() <<
"[ThinLTO] Selecting " << BMID <<
" to compile\n");
1155 CalledGetMaxTasks =
true;
1156 auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
1157 : ThinLTO.ModuleMap.size();
1158 return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
1163Error LTO::checkPartiallySplit() {
1167 const Module *Combined = RegularLTO.CombinedModule.get();
1173 Combined, Intrinsic::type_checked_load_relative);
1177 if ((TypeTestFunc && !TypeTestFunc->
use_empty()) ||
1178 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->
use_empty()) ||
1179 (TypeCheckedLoadRelativeFunc &&
1180 !TypeCheckedLoadRelativeFunc->
use_empty()))
1182 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1187 for (
auto &
P : ThinLTO.CombinedIndex) {
1188 for (
auto &S :
P.second.getSummaryList()) {
1192 if (!FS->type_test_assume_vcalls().empty() ||
1193 !FS->type_checked_load_vcalls().empty() ||
1194 !FS->type_test_assume_const_vcalls().empty() ||
1195 !FS->type_checked_load_const_vcalls().empty() ||
1196 !FS->type_tests().empty())
1198 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1209 for (
auto &Res : *GlobalResolutions) {
1212 if (Res.second.IRName.
empty())
1218 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1219 GUIDPreservedSymbols.
insert(GUID);
1221 if (Res.second.ExportDynamic)
1222 DynamicExportSymbols.insert(GUID);
1224 GUIDPrevailingResolutions[GUID] =
1229 auto It = GUIDPrevailingResolutions.
find(
G);
1230 if (It == GUIDPrevailingResolutions.
end())
1235 isPrevailing, Conf.OptLevel > 0);
1239 if (!StatsFileOrErr)
1240 return StatsFileOrErr.takeError();
1241 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1249 ThinLTO.CombinedIndex.setWithSupportsHotColdNew();
1251 Error Result = runRegularLTO(AddStream);
1255 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1265 LLVMContext &CombinedCtx = RegularLTO.CombinedModule->getContext();
1272 return DiagFileOrErr.takeError();
1273 DiagnosticOutputFile = std::move(*DiagFileOrErr);
1279 for (
auto &M : RegularLTO.ModsWithSummaries)
1280 if (
Error Err = linkRegularLTO(std::move(M),
true))
1288 if (
Error Err = checkPartiallySplit())
1293 const DataLayout &
DL = RegularLTO.CombinedModule->getDataLayout();
1294 for (
auto &
I : RegularLTO.Commons) {
1295 if (!
I.second.Prevailing)
1298 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(
I.first);
1299 if (OldGV &&
DL.getTypeAllocSize(OldGV->
getValueType()) ==
I.second.Size) {
1307 auto *GV =
new GlobalVariable(*RegularLTO.CombinedModule, Ty,
false,
1310 GV->setAlignment(
I.second.Alignment);
1320 bool WholeProgramVisibilityEnabledInLTO =
1321 Conf.HasWholeProgramVisibility &&
1324 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1328 auto IsVisibleToRegularObj = [&](StringRef
name) {
1329 auto It = GlobalResolutions->find(
name);
1330 return (It == GlobalResolutions->end() ||
1331 It->second.VisibleOutsideSummary || !It->second.Prevailing);
1337 *RegularLTO.CombinedModule, WholeProgramVisibilityEnabledInLTO,
1338 DynamicExportSymbols, Conf.ValidateAllVtablesHaveTypeInfos,
1339 IsVisibleToRegularObj);
1341 WholeProgramVisibilityEnabledInLTO);
1343 if (Conf.PreOptModuleHook &&
1344 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1347 if (!Conf.CodeGenOnly) {
1348 for (
const auto &R : *GlobalResolutions) {
1350 RegularLTO.CombinedModule->getNamedValue(
R.second.IRName);
1351 if (!
R.second.isPrevailingIRSymbol())
1353 if (
R.second.Partition != 0 &&
1354 R.second.Partition != GlobalResolution::External)
1382 if (Conf.PostInternalizeModuleHook &&
1383 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1387 if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1389 backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1390 *RegularLTO.CombinedModule, ThinLTO.CombinedIndex))
1407 return LibcallSymbols;
1412 const std::string &NewModulePath)
const {
1413 return emitFiles(ImportList, ModulePath, NewModulePath,
1414 NewModulePath +
".thinlto.bc",
1420 const std::string &NewModulePath,
StringRef SummaryPath,
1421 std::optional<std::reference_wrapper<ImportsFilesContainer>> ImportsFiles)
1428 ImportList, ModuleToSummariesForIndex,
1429 DeclarationSummaries);
1436 &DeclarationSummaries);
1440 ModulePath, NewModulePath +
".imports", ModuleToSummariesForIndex);
1441 if (ImportsFilesError)
1442 return ImportsFilesError;
1448 ModulePath, ModuleToSummariesForIndex,
1449 [&](
StringRef M) { ImportsFiles->get().push_back(M.str()); });
1462 bool ShouldEmitIndexFiles;
1469 bool ShouldEmitIndexFiles,
bool ShouldEmitImportsFiles,
1472 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1473 AddStream(
std::
move(AddStream)),
1474 ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
1484class InProcessThinBackend :
public CGThinBackend {
1489 InProcessThinBackend(
1494 bool ShouldEmitIndexFiles,
bool ShouldEmitImportsFiles)
1495 : CGThinBackend(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1496 AddStream, OnWrite, ShouldEmitIndexFiles,
1497 ShouldEmitImportsFiles, ThinLTOParallelism),
1500 virtual Error runThinLTOBackendThread(
1501 AddStreamFn AddStream, FileCache Cache,
unsigned Task, BitcodeModule BM,
1502 ModuleSummaryIndex &CombinedIndex,
1503 const FunctionImporter::ImportMapTy &ImportList,
1505 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1507 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1509 llvm::TimeTraceScope timeScope(
"Run ThinLTO backend thread (in-process)",
1511 auto RunThinBackend = [&](
AddStreamFn AddStream) {
1512 LTOLLVMContext BackendContext(Conf);
1513 Expected<std::unique_ptr<Module>> MOrErr = BM.
parseModule(BackendContext);
1517 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1518 ImportList, DefinedGlobals, &ModuleMap,
1521 if (ShouldEmitIndexFiles) {
1522 if (
auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
1528 [](uint32_t V) { return V == 0; }))
1531 return RunThinBackend(AddStream);
1535 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1536 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1537 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task,
Key, ModuleID);
1540 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1542 return RunThinBackend(CacheAddStream);
1548 unsigned Task, BitcodeModule BM,
1549 const FunctionImporter::ImportMapTy &ImportList,
1551 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1552 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
1554 assert(ModuleToDefinedGVSummaries.
count(ModulePath));
1556 ModuleToDefinedGVSummaries.
find(ModulePath)->second;
1557 BackendThreadPool.async(
1558 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1559 const FunctionImporter::ImportMapTy &ImportList,
1561 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1564 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1568 Error E = runThinLTOBackendThread(
1569 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1570 ResolvedODR, DefinedGlobals, ModuleMap);
1572 std::unique_lock<std::mutex>
L(ErrMu);
1581 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1582 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1585 OnWrite(std::string(ModulePath));
1595class FirstRoundThinBackend :
public InProcessThinBackend {
1600 FirstRoundThinBackend(
1601 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1602 ThreadPoolStrategy ThinLTOParallelism,
1603 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1606 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1607 ModuleToDefinedGVSummaries, std::
move(CGAddStream),
1608 std::
move(CGCache), nullptr,
1611 IRAddStream(std::
move(IRAddStream)), IRCache(std::
move(IRCache)) {}
1613 Error runThinLTOBackendThread(
1614 AddStreamFn CGAddStream, FileCache CGCache,
unsigned Task,
1615 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1616 const FunctionImporter::ImportMapTy &ImportList,
1618 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1620 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
1622 llvm::TimeTraceScope timeScope(
"Run ThinLTO backend thread (first round)",
1624 auto RunThinBackend = [&](
AddStreamFn CGAddStream,
1626 LTOLLVMContext BackendContext(Conf);
1627 Expected<std::unique_ptr<Module>> MOrErr = BM.
parseModule(BackendContext);
1631 return thinBackend(Conf, Task, CGAddStream, **MOrErr, CombinedIndex,
1632 ImportList, DefinedGlobals, &ModuleMap,
1638 if (ShouldEmitIndexFiles) {
1639 if (
auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
1644 "Both caches for CG and IR should have matching availability");
1647 [](uint32_t V) { return V == 0; }))
1650 return RunThinBackend(CGAddStream, IRAddStream);
1654 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1655 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1656 Expected<AddStreamFn> CacheCGAddStreamOrErr =
1657 CGCache(Task, CGKey, ModuleID);
1660 AddStreamFn &CacheCGAddStream = *CacheCGAddStreamOrErr;
1664 Expected<AddStreamFn> CacheIRAddStreamOrErr =
1665 IRCache(Task, IRKey, ModuleID);
1668 AddStreamFn &CacheIRAddStream = *CacheIRAddStreamOrErr;
1674 if (CacheCGAddStream || CacheIRAddStream) {
1677 return RunThinBackend(CacheCGAddStream ? CacheCGAddStream : CGAddStream,
1678 CacheIRAddStream ? CacheIRAddStream : IRAddStream);
1690class SecondRoundThinBackend :
public InProcessThinBackend {
1691 std::unique_ptr<SmallVector<StringRef>> IRFiles;
1695 SecondRoundThinBackend(
1696 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1697 ThreadPoolStrategy ThinLTOParallelism,
1698 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1702 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1703 ModuleToDefinedGVSummaries, std::
move(AddStream),
1708 IRFiles(std::
move(IRFiles)), CombinedCGDataHash(CombinedCGDataHash) {}
1710 Error runThinLTOBackendThread(
1711 AddStreamFn AddStream, FileCache Cache,
unsigned Task, BitcodeModule BM,
1712 ModuleSummaryIndex &CombinedIndex,
1713 const FunctionImporter::ImportMapTy &ImportList,
1715 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1717 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
1719 llvm::TimeTraceScope timeScope(
"Run ThinLTO backend thread (second round)",
1721 auto RunThinBackend = [&](
AddStreamFn AddStream) {
1722 LTOLLVMContext BackendContext(Conf);
1723 std::unique_ptr<Module> LoadedModule =
1726 return thinBackend(Conf, Task, AddStream, *LoadedModule, CombinedIndex,
1727 ImportList, DefinedGlobals, &ModuleMap,
1732 [](uint32_t V) { return V == 0; }))
1735 return RunThinBackend(AddStream);
1740 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1741 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1743 std::to_string(CombinedCGDataHash));
1744 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task,
Key, ModuleID);
1747 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1749 if (CacheAddStream) {
1752 return RunThinBackend(CacheAddStream);
1762 bool ShouldEmitIndexFiles,
1763 bool ShouldEmitImportsFiles) {
1768 return std::make_unique<InProcessThinBackend>(
1769 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
1770 AddStream, Cache, OnWrite, ShouldEmitIndexFiles,
1771 ShouldEmitImportsFiles);
1797 return std::string(Path);
1801 if (!ParentPath.
empty()) {
1804 llvm::errs() <<
"warning: could not create directory '" << ParentPath
1805 <<
"': " << EC.message() <<
'\n';
1807 return std::string(NewPath);
1812 std::string OldPrefix, NewPrefix, NativeObjectPrefix;
1816 WriteIndexesThinBackend(
1820 std::string OldPrefix, std::string NewPrefix,
1821 std::string NativeObjectPrefix,
bool ShouldEmitImportsFiles,
1824 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1825 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1826 NativeObjectPrefix(NativeObjectPrefix),
1827 LinkedObjectsFile(LinkedObjectsFile) {}
1833 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1841 if (LinkedObjectsFile) {
1842 std::string ObjectPrefix =
1843 NativeObjectPrefix.empty() ? NewPrefix : NativeObjectPrefix;
1844 std::string LinkedObjectsFilePath =
1846 *LinkedObjectsFile << LinkedObjectsFilePath <<
'\n';
1849 BackendThreadPool.async(
1850 [
this](
const StringRef ModulePath,
1851 const FunctionImporter::ImportMapTy &ImportList,
1852 const std::string &OldPrefix,
const std::string &NewPrefix) {
1853 std::string NewModulePath =
1855 auto E = emitFiles(ImportList, ModulePath, NewModulePath);
1857 std::unique_lock<std::mutex>
L(ErrMu);
1865 ModulePath, ImportList, OldPrefix, NewPrefix);
1868 OnWrite(std::string(ModulePath));
1872 bool isSensitiveToInputOrder()
override {
1882 std::string NewPrefix, std::string NativeObjectPrefix,
1889 return std::make_unique<WriteIndexesThinBackend>(
1890 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
1891 OldPrefix, NewPrefix, NativeObjectPrefix, ShouldEmitImportsFiles,
1892 LinkedObjectsFile, OnWrite);
1907 if (ThinLTO.ModuleMap.
empty())
1910 if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
1911 llvm::errs() <<
"warning: [ThinLTO] No module compiled\n";
1915 if (Conf.CombinedIndexHook &&
1916 !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
1921 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(
1922 ThinLTO.ModuleMap.size());
1923 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1924 ModuleToDefinedGVSummaries);
1932 for (
auto &
Mod : ThinLTO.ModuleMap)
1933 if (!ModuleToDefinedGVSummaries.
count(
Mod.first))
1936 FunctionImporter::ImportListsTy ImportLists(ThinLTO.ModuleMap.size());
1937 DenseMap<StringRef, FunctionImporter::ExportSetTy> ExportLists(
1938 ThinLTO.ModuleMap.size());
1939 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1942 ThinLTO.CombinedIndex.dumpSCCs(
outs());
1944 std::set<GlobalValue::GUID> ExportedGUIDs;
1946 bool WholeProgramVisibilityEnabledInLTO =
1947 Conf.HasWholeProgramVisibility &&
1950 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1952 ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
1957 DenseSet<GlobalValue::GUID> VisibleToRegularObjSymbols;
1958 if (WholeProgramVisibilityEnabledInLTO &&
1959 Conf.ValidateAllVtablesHaveTypeInfos) {
1962 auto IsVisibleToRegularObj = [&](StringRef
name) {
1963 auto It = GlobalResolutions->find(
name);
1964 return (It == GlobalResolutions->end() ||
1965 It->second.VisibleOutsideSummary || !It->second.Prevailing);
1969 VisibleToRegularObjSymbols,
1970 IsVisibleToRegularObj);
1976 ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO,
1977 DynamicExportSymbols, VisibleToRegularObjSymbols);
1982 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1984 LocalWPDTargetsMap);
1987 return ThinLTO.isPrevailingModuleForGUID(GUID, S->modulePath());
1990 MemProfContextDisambiguation ContextDisambiguation;
1991 ContextDisambiguation.
run(ThinLTO.CombinedIndex, isPrevailing);
1998 for (
auto &Res : *GlobalResolutions) {
2001 if (Res.second.Partition != GlobalResolution::External ||
2002 !Res.second.isPrevailingIRSymbol())
2007 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
2008 ExportedGUIDs.insert(GUID);
2015 releaseGlobalResolutionsMemory();
2017 if (Conf.OptLevel > 0)
2019 isPrevailing, ImportLists, ExportLists);
2023 auto &Defs = ThinLTO.CombinedIndex.cfiFunctionDefs();
2024 ExportedGUIDs.insert(Defs.guid_begin(), Defs.guid_end());
2025 auto &Decls = ThinLTO.CombinedIndex.cfiFunctionDecls();
2026 ExportedGUIDs.insert(Decls.guid_begin(), Decls.guid_end());
2028 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo
VI) {
2029 const auto &ExportList = ExportLists.
find(ModuleIdentifier);
2030 return (ExportList != ExportLists.end() && ExportList->second.
count(VI)) ||
2031 ExportedGUIDs.count(
VI.getGUID());
2037 LocalWPDTargetsMap);
2042 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
2045 ResolvedODR[ModuleIdentifier][
GUID] = NewLinkage;
2048 recordNewLinkage, GUIDPreservedSymbols);
2057 TimeTraceScopeExit.release();
2060 ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
2062 auto RunBackends = [&](ThinBackendProc *BackendProcess) ->
Error {
2063 auto ProcessOneModule = [&](
int I) ->
Error {
2067 return BackendProcess->start(
2068 RegularLTO.ParallelCodeGenParallelismLevel +
I,
Mod.second,
2069 ImportLists[
Mod.first], ExportLists[
Mod.first],
2070 ResolvedODR[
Mod.first], ThinLTO.ModuleMap);
2073 BackendProcess->setup(ModuleMap.
size(),
2074 RegularLTO.ParallelCodeGenParallelismLevel,
2075 RegularLTO.CombinedModule->getTargetTriple());
2077 if (BackendProcess->getThreadCount() == 1 ||
2078 BackendProcess->isSensitiveToInputOrder()) {
2084 for (
int I = 0,
E = ModuleMap.
size();
I !=
E; ++
I)
2085 if (
Error E = ProcessOneModule(
I))
2092 std::vector<BitcodeModule *> ModulesVec;
2093 ModulesVec.reserve(ModuleMap.
size());
2094 for (
auto &
Mod : ModuleMap)
2095 ModulesVec.push_back(&
Mod.second);
2097 if (
Error E = ProcessOneModule(
I))
2100 return BackendProcess->wait();
2104 std::unique_ptr<ThinBackendProc> BackendProc =
2105 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2107 return RunBackends(BackendProc.get());
2115 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] Initializing ThinLTO two-codegen rounds\n");
2118 auto Parallelism = ThinLTO.Backend.getParallelism();
2121 cgdata::StreamCacheData CG(MaxTasks, Cache,
"CG"),
IR(MaxTasks, Cache,
"IR");
2126 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] Running the first round of codegen\n");
2127 auto FirstRoundLTO = std::make_unique<FirstRoundThinBackend>(
2128 Conf, ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2129 CG.AddStream, CG.Cache,
IR.AddStream,
IR.Cache);
2130 if (
Error E = RunBackends(FirstRoundLTO.get()))
2135 if (
Error E = CombinedHashOrErr.takeError())
2137 auto CombinedHash = *CombinedHashOrErr;
2138 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] CGData hash: " << CombinedHash <<
"\n");
2142 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] Running the second round of codegen\n");
2143 auto SecondRoundLTO = std::make_unique<SecondRoundThinBackend>(
2144 Conf, ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2145 AddStream, Cache,
IR.getResult(), CombinedHash);
2146 return RunBackends(SecondRoundLTO.get());
2156 if (!Filename.empty() &&
Count != -1)
2164 if (
Error E = ResultOrErr.takeError())
2165 return std::move(E);
2168 (*ResultOrErr)->keep();
2176 if (StatsFilename.
empty())
2187 return std::move(StatsFile);
2195 std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
2196 llvm::sort(ModulesOrdering, [&](
int LeftIndex,
int RightIndex) {
2197 auto LSize = R[LeftIndex]->getBuffer().size();
2198 auto RSize = R[RightIndex]->getBuffer().size();
2199 return LSize > RSize;
2201 return ModulesOrdering;
2211class OutOfProcessThinBackend :
public CGThinBackend {
2217 SString LinkerOutputFile;
2219 SString DistributorPath;
2222 SString RemoteCompiler;
2231 std::atomic<size_t> CachedJobs{0};
2236 StringRef NativeObjectPath;
2237 StringRef SummaryIndexPath;
2239 std::string CacheKey;
2241 bool Cached =
false;
2250 unsigned ThinLTOTaskOffset;
2253 llvm::Triple Triple;
2259 OutOfProcessThinBackend(
2260 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
2261 ThreadPoolStrategy ThinLTOParallelism,
2262 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
2264 bool ShouldEmitIndexFiles,
bool ShouldEmitImportsFiles,
2265 StringRef LinkerOutputFile, StringRef Distributor,
2269 : CGThinBackend(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
2270 AddStream, OnWrite, ShouldEmitIndexFiles,
2271 ShouldEmitImportsFiles, ThinLTOParallelism),
2272 LinkerOutputFile(LinkerOutputFile), DistributorPath(Distributor),
2273 DistributorArgs(DistributorArgs), RemoteCompiler(RemoteCompiler),
2274 RemoteCompilerPrependArgs(RemoteCompilerPrependArgs),
2275 RemoteCompilerArgs(RemoteCompilerArgs), SaveTemps(SaveTemps),
2276 Cache(std::
move(CacheFn)) {}
2278 void setup(
unsigned ThinLTONumTasks,
unsigned ThinLTOTaskOffset,
2279 llvm::Triple Triple)
override {
2281 Jobs.
resize((
size_t)ThinLTONumTasks);
2282 this->ThinLTOTaskOffset = ThinLTOTaskOffset;
2283 this->Triple = Triple;
2284 this->Conf.
Dtlto = 1;
2287 virtual Error runThinLTOBackendThread(
2288 Job &J,
const FunctionImporter::ImportMapTy &ImportList,
2290 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
2293 llvm::TimeTraceScope timeScope(
2294 "Run ThinLTO backend thread (out-of-process)", J.ModuleID);
2296 if (
auto E = emitFiles(ImportList, J.ModuleID, J.ModuleID.str(),
2297 J.SummaryIndexPath, J.ImportsFiles))
2302 [](uint32_t V) { return V == 0; }))
2308 ModuleToDefinedGVSummaries.
find(J.ModuleID)->second;
2312 ExportList, ResolvedODR, DefinedGlobals,
2313 CfiFunctionDefs, CfiFunctionDecls);
2316 auto CacheAddStreamExp = Cache(J.Task, J.CacheKey, J.ModuleID);
2317 if (
Error Err = CacheAddStreamExp.takeError())
2322 if (!CacheAddStream) {
2324 CachedJobs.fetch_add(1);
2329 J.CacheAddStream = std::move(CacheAddStream);
2335 unsigned Task, BitcodeModule BM,
2336 const FunctionImporter::ImportMapTy &ImportList,
2338 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
2339 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
2345 itostr(Task) +
"." + UID +
".native.o");
2347 Job &J = Jobs[Task - ThinLTOTaskOffset];
2350 Saver.
save(ObjFilePath.str()),
2351 Saver.
save(ObjFilePath.str() +
".thinlto.bc"),
2357 assert(ModuleToDefinedGVSummaries.
count(ModulePath));
2361 BackendThreadPool.async(
2362 [=](Job &J,
const FunctionImporter::ImportMapTy &ImportList,
2364 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
2367 runThinLTOBackendThread(J, ImportList, ExportList, ResolvedODR);
2369 std::unique_lock<std::mutex>
L(ErrMu);
2376 std::ref(J), std::ref(ImportList), std::ref(ExportList),
2377 std::ref(ResolvedODR));
2391 void buildCommonRemoteCompilerOptions() {
2392 const lto::Config &
C = Conf;
2393 auto &
Ops = CodegenOptions;
2397 if (
C.Options.EmitAddrsig)
2398 Ops.push_back(
"-faddrsig");
2399 if (
C.Options.FunctionSections)
2400 Ops.push_back(
"-ffunction-sections");
2401 if (
C.Options.DataSections)
2402 Ops.push_back(
"-fdata-sections");
2407 Ops.push_back(
"-fpic");
2411 if (!
C.PGOWarnMismatch) {
2412 Ops.push_back(
"-mllvm");
2413 Ops.push_back(
"-no-pgo-warn-mismatch");
2418 if (!
C.SampleProfile.empty()) {
2420 Saver.
save(
"-fprofile-sample-use=" + Twine(
C.SampleProfile)));
2421 CommonInputs.
insert(
C.SampleProfile);
2425 Ops.push_back(
"-Wno-unused-command-line-argument");
2428 if (!RemoteCompilerArgs.
empty())
2429 for (
auto &a : RemoteCompilerArgs)
2435 bool emitDistributorJson(StringRef DistributorJson) {
2438 raw_fd_ostream OS(DistributorJson, EC);
2442 json::OStream JOS(OS);
2445 JOS.attributeObject(
"common", [&]() {
2446 JOS.attribute(
"linker_output", LinkerOutputFile);
2448 JOS.attributeArray(
"args", [&]() {
2449 JOS.value(RemoteCompiler);
2452 if (!RemoteCompilerPrependArgs.
empty())
2453 for (
auto &
A : RemoteCompilerPrependArgs)
2458 JOS.value(Saver.
save(
"--target=" + Triple.
str()));
2460 for (
const auto &
A : CodegenOptions)
2464 JOS.attribute(
"inputs",
Array(CommonInputs));
2468 JOS.attributeArray(
"jobs", [&]() {
2469 for (
const auto &J : Jobs) {
2477 SmallVector<StringRef, 1> Outputs;
2480 JOS.attributeArray(
"args", [&]() {
2481 JOS.value(J.ModuleID);
2485 Saver.
save(
"-fthinlto-index=" + Twine(J.SummaryIndexPath)));
2489 JOS.value(J.NativeObjectPath);
2497 JOS.attribute(
"inputs",
Array(Inputs));
2499 JOS.attribute(
"outputs",
Array(Outputs));
2508 void removeFile(StringRef FileName) {
2510 if (EC && EC != std::make_error_code(std::errc::no_such_file_or_directory))
2511 errs() <<
"warning: could not remove the file '" << FileName
2512 <<
"': " <<
EC.message() <<
"\n";
2515 Error wait()
override {
2518 BackendThreadPool.wait();
2520 return std::move(*Err);
2524 for (
auto &Job : Jobs) {
2525 removeFile(Job.NativeObjectPath);
2526 if (!ShouldEmitIndexFiles)
2527 removeFile(Job.SummaryIndexPath);
2531 const StringRef BCError =
"DTLTO backend compilation: ";
2533 buildCommonRemoteCompilerOptions();
2538 if (!emitDistributorJson(JsonFile))
2540 BCError +
"failed to generate distributor JSON script: " + JsonFile,
2544 removeFile(JsonFile);
2548 if (CachedJobs.load() < Jobs.size()) {
2551 Args.push_back(JsonFile);
2558 BCError +
"distributor execution failed" +
2559 (!ErrMsg.empty() ?
": " + ErrMsg + Twine(
".") : Twine(
".")),
2564 for (
auto &Job : Jobs) {
2565 if (!Job.CacheKey.empty() && Job.Cached) {
2571 auto ObjFileMbOrErr =
2574 if (std::error_code EC = ObjFileMbOrErr.getError())
2576 BCError +
"cannot open native object file: " +
2577 Job.NativeObjectPath +
": " +
EC.message(),
2580 MemoryBufferRef ObjFileMbRef = ObjFileMbOrErr->get()->getMemBufferRef();
2584 assert(Job.CacheAddStream);
2586 auto CachedFileStreamOrErr = Job.CacheAddStream(Job.Task, Job.ModuleID);
2587 if (!CachedFileStreamOrErr)
2589 CachedFileStreamOrErr.takeError(),
2591 "Cannot get a cache file stream: %s",
2592 Job.NativeObjectPath.data()));
2594 auto &CacheStream = *(CachedFileStreamOrErr->get());
2595 *(CacheStream.OS) << ObjFileMbRef.
getBuffer();
2596 if (
Error Err = CacheStream.commit())
2599 auto StreamOrErr = AddStream(Job.Task, Job.ModuleID);
2600 if (
Error Err = StreamOrErr.takeError())
2602 auto &Stream = *StreamOrErr->get();
2604 if (
Error Err = Stream.commit())
2615 bool ShouldEmitIndexFiles,
bool ShouldEmitImportsFiles,
2624 return std::make_unique<OutOfProcessThinBackend>(
2625 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2626 AddStream, Cache, OnWrite, ShouldEmitIndexFiles,
2627 ShouldEmitImportsFiles, LinkerOutputFile, Distributor,
2628 DistributorArgs, RemoteCompiler, RemoteCompilerPrependArgs,
2629 RemoteCompilerArgs, SaveTemps);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file supports working with JSON data.
static void writeToResolutionFile(raw_ostream &OS, InputFile *Input, ArrayRef< SymbolResolution > Res)
static void thinLTOResolvePrevailingGUID(const Config &C, ValueInfo VI, DenseSet< GlobalValueSummary * > &GlobalInvolvedWithAlias, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
static void handleNonPrevailingComdat(GlobalValue &GV, std::set< const Comdat * > &NonPrevailingComdats)
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"))
static void thinLTOInternalizeAndPromoteGUID(ValueInfo VI, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Legalize the Machine IR a function s Machine IR
Machine Check Debug Module
Provides a library for accessing information about this process and other processes on the operating ...
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
empty - Check if the array is empty.
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Represents a module in a bitcode file.
StringRef getModuleIdentifier() const
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(GlobalValue::GUID)> IsPrevailing=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
The map maintains the list of imports.
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 bool isAppendingLinkage(LinkageTypes Linkage)
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isExternalWeakLinkage(LinkageTypes Linkage)
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
LLVM_ABI const Comdat * getComdat() const
static bool isLinkOnceLinkage(LinkageTypes Linkage)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
static bool isExternalLinkage(LinkageTypes Linkage)
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
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....
static LinkageTypes getWeakLinkage(bool ODR)
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AvailableExternallyLinkage
Available for inspection, not emission.
DLLStorageClassTypes getDLLStorageClass() const
Type * getValueType() const
static bool isLinkOnceODRLinkage(LinkageTypes Linkage)
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This is an important class for using LLVM in a threaded context.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
This class implements a map that also provides access to all stored values in a deterministic order.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
StringRef getBuffer() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
CfiFunctionIndex & cfiFunctionDecls()
void setPartiallySplitLTOUnits()
void releaseTemporaryMemory()
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
bool partiallySplitLTOUnits() const
const StringMap< ModuleHash > & modulePaths() const
Table of modules, containing module hash and id.
CfiFunctionIndex & cfiFunctionDefs()
LLVM_ABI void addModule(Module *M)
static LLVM_ABI void CollectAsmSymvers(const Module &M, function_ref< void(StringRef, StringRef)> AsmSymver)
Parse inline ASM and collect the symvers directives that are defined in the current module.
PointerUnion< GlobalValue *, AsmSymbol * > Symbol
LLVM_ABI uint32_t getSymbolFlags(Symbol S) const
ArrayRef< Symbol > symbols() const
A Module instance is used to store all the information related to an LLVM module.
A class that wrap the SHA1 algorithm.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
StringRef str() const
Explicit conversion to StringRef.
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
StringRef save(const char *S)
MCTargetOptions MCOptions
Machine level options.
DebuggerKind DebuggerTuning
Which debugger to tune for.
unsigned FunctionSections
Emit functions into separate sections.
unsigned DataSections
Emit data into separate sections.
This tells how a thread pool will be used.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Triple - Helper class for working with autoconf configuration names.
bool isArm64e() const
Tests whether the target is the Apple "arm64e" AArch64 subarch.
ArchType getArch() const
Get the parsed architecture type of this triple.
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
const std::string & str() const
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
iterator find(const_arg_type_t< ValueT > V)
void insert_range(Range &&R)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
An efficient, type-erasing, non-owning reference to a callable.
Ephemeral symbols produced by Reader::symbols() and Reader::module_symbols().
LLVM_ABI LTO(Config Conf, ThinBackend Backend={}, unsigned ParallelCodeGenParallelismLevel=1, LTOKind LTOMode=LTOK_Default)
Create an LTO object.
LLVM_ABI Error add(std::unique_ptr< InputFile > Obj, ArrayRef< SymbolResolution > Res)
Add an input file to the LTO link, using the provided symbol resolutions.
static LLVM_ABI SmallVector< const char * > getRuntimeLibcallSymbols(const Triple &TT)
Static method that returns a list of libcall symbols that can be generated by LTO but might not be vi...
LTOKind
Unified LTO modes.
@ LTOK_UnifiedRegular
Regular LTO, with Unified LTO enabled.
@ LTOK_Default
Any LTO mode without Unified LTO. The default mode.
@ LTOK_UnifiedThin
ThinLTO, with Unified LTO enabled.
LLVM_ABI unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
LLVM_ABI Error run(AddStreamFn AddStream, FileCache Cache={})
Runs the LTO pipeline.
This class defines the interface to the ThinLTO backend.
bool ShouldEmitImportsFiles
const DenseMap< StringRef, GVSummaryMapTy > & ModuleToDefinedGVSummaries
LLVM_ABI Error emitFiles(const FunctionImporter::ImportMapTy &ImportList, StringRef ModulePath, const std::string &NewModulePath) const
ModuleSummaryIndex & CombinedIndex
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
static LLVM_ABI Pid getProcessId()
Get the process's identifier.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ C
The default llvm calling convention, compatible with C.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
static auto libcall_impls()
LLVM_ABI Expected< stable_hash > mergeCodeGenData(ArrayRef< StringRef > ObjectFiles)
Merge the codegen data from the scratch objects ObjectFiles from the first codegen round.
LLVM_ABI std::unique_ptr< Module > loadModuleForTwoRounds(BitcodeModule &OrigModule, unsigned Task, LLVMContext &Context, ArrayRef< StringRef > IRFiles)
Load the optimized bitcode module for the second codegen round.
initializer< Ty > init(const Ty &Val)
LLVM_ABI ThinBackend createInProcessThinBackend(ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite=nullptr, bool ShouldEmitIndexFiles=false, bool ShouldEmitImportsFiles=false)
This ThinBackend runs the individual backend jobs in-process.
LLVM_ABI std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix, StringRef NewPrefix)
Given the original Path to an output file, replace any path prefix matching OldPrefix with NewPrefix.
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
LLVM_ABI Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
LLVM_ABI ThinBackend createOutOfProcessThinBackend(ThreadPoolStrategy Parallelism, IndexWriteCallback OnWrite, bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles, StringRef LinkerOutputFile, StringRef Distributor, ArrayRef< StringRef > DistributorArgs, StringRef RemoteCompiler, ArrayRef< StringRef > RemoteCompilerPrependArgs, ArrayRef< StringRef > RemoteCompilerArgs, bool SaveTemps)
This ThinBackend generates the index shards and then runs the individual backend jobs via an external...
LLVM_ABI Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
std::function< void(const std::string &)> IndexWriteCallback
LLVM_ABI Error finalizeOptimizationRemarks(LLVMRemarkFileHandle DiagOutputFile)
LLVM_ABI ThinBackend createWriteIndexesThinBackend(ThreadPoolStrategy Parallelism, std::string OldPrefix, std::string NewPrefix, std::string NativeObjectPrefix, bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite)
This ThinBackend writes individual module indexes to files, instead of running the individual backend...
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.
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
LLVM_ABI Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > *ModuleMap, bool CodeGenOnly, AddStreamFn IRAddStream=nullptr, const std::vector< uint8_t > &CmdArgs=std::vector< uint8_t >())
Runs a ThinLTO backend.
llvm::SmallVector< std::string > ImportsFilesContainer
LLVM_ABI Expected< IRSymtabFile > readIRSymtab(MemoryBufferRef MBRef)
Reads a bitcode file, creating its irsymtab if necessary.
DiagnosticInfoOptimizationBase::Argument NV
void write64le(void *P, uint64_t V)
void write32le(void *P, uint32_t V)
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
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.
LLVM_ABI StringRef stem(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get stem.
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
LLVM_ABI bool replace_path_prefix(SmallVectorImpl< char > &Path, StringRef OldPrefix, StringRef NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
LLVM_ABI int ExecuteAndWait(StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env=std::nullopt, ArrayRef< std::optional< StringRef > > Redirects={}, unsigned SecondsToWait=0, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr, std::optional< ProcessStatistics > *ProcStat=nullptr, BitVector *AffinityMask=nullptr)
This function executes the program using the arguments provided.
This is an optimization pass for GlobalISel generic memory operations.
ThreadPoolStrategy heavyweight_hardware_concurrency(unsigned ThreadCount=0)
Returns a thread strategy for tasks requiring significant memory or other resources.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
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.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
std::unordered_set< GlobalValueSummary * > GVSummaryPtrSet
A set of global value summary pointers.
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
void generateParamAccessSummary(ModuleSummaryIndex &Index)
cl::opt< bool > CodeGenDataThinLTOTwoRounds("codegen-data-thinlto-two-rounds", cl::init(false), cl::Hidden, cl::desc("Enable two-round ThinLTO code generation. The first round " "emits codegen data, while the second round uses the emitted " "codegen data for further optimizations."))
LLVM_ABI Expected< LLVMRemarkFileHandle > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, std::optional< uint64_t > RemarksHotnessThreshold=0)
Set up optimization remarks that output to a file.
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"))
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
uint64_t stable_hash
An opaque object representing a stable hash code.
std::string utostr(uint64_t X, bool isNeg=false)
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.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
LLVM_ABI bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO)
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI void EnableStatistics(bool DoPrintOnExit=true)
Enable the collection and printing of statistics.
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...
LLVM_ABI void timeTraceProfilerInitialize(unsigned TimeTraceGranularity, StringRef ProcName, bool TimeTraceVerbose=false)
Initialize the time trace profiler.
LLVM_ABI void timeTraceProfilerFinishThread()
Finish a time trace profiler running on a worker thread.
LLVM_ABI std::string recomputeLTOCacheKey(const std::string &Key, StringRef ExtraID)
Recomputes the LTO cache key for a given key with an extra identifier.
Error joinErrors(Error E1, Error E2)
Concatenate errors.
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
LLVM_ABI void getVisibleToRegularObjVtableGUIDs(ModuleSummaryIndex &Index, DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols, function_ref< bool(StringRef)> IsVisibleToRegularObj)
Based on typeID string, get all associated vtable GUIDS that are visible to regular objects.
void sort(IteratorTy Start, IteratorTy End)
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.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
FunctionAddr VTableAddr Count
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
LLVM_ABI cl::opt< bool > EnableLTOInternalization
Enable global value internalization in LTO.
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"))
cl::opt< bool > SupportsHotColdNew
Indicate we are linking with an allocator that supports hot/cold operator new interfaces.
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...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mod
The access may modify the value stored in memory.
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
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.
cl::opt< bool > ForceImportAll
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.
ArrayRef(const T &OneElt) -> ArrayRef< T >
void toHex(ArrayRef< uint8_t > Input, bool LowerCase, SmallVectorImpl< char > &Output)
Convert buffer Input to its hexadecimal representation. The returned string is double the size of Inp...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void processImportsFiles(StringRef ModulePath, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, function_ref< void(const std::string &)> F)
Call F passing each of the files module ModulePath will import from.
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)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
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 ...
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
static cl::opt< bool > LTOKeepSymbolCopies("lto-keep-symbol-copies", cl::init(false), cl::Hidden, cl::desc("Keep copies of symbols in LTO indexing"))
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
LLVM_ABI void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
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.
@ Keep
No function return thunk.
std::string itostr(int64_t X)
LLVM_ABI void updateVCallVisibilityInModule(Module &M, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, bool ValidateAllVtablesHaveTypeInfos, function_ref< bool(StringRef)> IsVisibleToRegularObj)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
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...
Implement std::hash so that hash_code can be used in STL containers.
This type represents a file cache system that manages caching of files.
const std::string & getCacheDirectoryPath() const
A simple container for information about the supported runtime calls.
unsigned getNumAvailableLibcallImpls() const
bool isAvailable(RTLIB::LibcallImpl Impl) const
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
Struct that holds a reference to a particular GUID in a global value summary.
std::optional< uint64_t > RemarksHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
std::optional< CodeModel::Model > CodeModel
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
std::vector< std::string > MAttrs
std::vector< std::string > MllvmArgs
CodeGenOptLevel CGOptLevel
bool Dtlto
This flag is used as one of parameters to calculate cache entries and to ensure that in-process cache...
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple.
std::string DwoDir
The directory to store .dwo files.
std::string RemarksFilename
Optimization remarks file path.
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
std::string ProfileRemapping
Name remapping file for profile data.
bool TimeTraceEnabled
Time trace enabled.
std::string RemarksPasses
Optimization remarks pass filter.
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
unsigned TimeTraceGranularity
Time trace granularity.
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
std::optional< Reloc::Model > RelocModel
CodeGenFileType CGFileType
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
std::string SampleProfile
Sample PGO profile path.
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
The resolution for a symbol.
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit.
unsigned ExportDynamic
The symbol was exported dynamically, and therefore could be referenced by a shared library not visibl...
unsigned Prevailing
The linker has chosen this definition of the symbol.
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
This type defines the behavior following the thin-link phase during ThinLTO.