27#include "llvm/Config/llvm-config.h"
56#include "llvm/Support/VCSRevision.h"
72#define DEBUG_TYPE "lto"
74Error LTO::setupOptimizationRemarks() {
81 return DiagFileOrErr.takeError();
83 DiagnosticOutputFile = std::move(*DiagFileOrErr);
90 if (!LinkerRemarkFunction) {
91 DummyModule = std::make_unique<Module>(
"remark_dummy", RegularLTO.Ctx);
109 cl::desc(
"Dump the SCCs in the ThinLTO index's callgraph"));
120 cl::desc(
"Enable global value internalization in LTO"));
124 cl::desc(
"Keep copies of symbols in LTO indexing"));
141 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
152 Hasher.
update(LLVM_VERSION_STRING);
154 Hasher.
update(LLVM_REVISION);
162 auto AddUnsigned = [&](
unsigned I) {
172 auto AddUint8 = [&](
const uint8_t I) {
196 AddUnsigned(
static_cast<int>(Conf.
CGOptLevel));
197 AddUnsigned(
static_cast<int>(Conf.
CGFileType));
205 AddUint8(Conf.
Dtlto);
208 auto ModHash = Index.getModuleHash(ModuleID);
213 std::vector<uint64_t> ExportsGUID;
214 ExportsGUID.reserve(ExportList.
size());
215 for (
const auto &VI : ExportList)
216 ExportsGUID.push_back(VI.getGUID());
220 for (
auto GUID : ExportsGUID)
225 auto Comp = [&](
const std::pair<StringRef, GlobalValue::GUID> &L,
226 const std::pair<StringRef, GlobalValue::GUID> &R) {
227 return std::make_pair(Index.getModule(L.first)->second, L.second) <
228 std::make_pair(Index.getModule(R.first)->second, R.second);
234 for (
const auto &[FromModule, GUID,
Type] : SortedImportList)
235 ++ModuleToNumImports[FromModule];
237 std::optional<StringRef> LastModule;
238 for (
const auto &[FromModule, GUID,
Type] : SortedImportList) {
239 if (LastModule != FromModule) {
243 LastModule = FromModule;
244 auto ModHash = Index.getModule(FromModule)->second;
246 AddUint64(ModuleToNumImports[FromModule]);
253 for (
auto &Entry : ResolvedODR) {
262 std::set<GlobalValue::GUID> UsedCfiDefs;
263 std::set<GlobalValue::GUID> UsedCfiDecls;
266 std::set<GlobalValue::GUID> UsedTypeIds;
269 if (CfiFunctionDefs.
contains(ValueGUID))
270 UsedCfiDefs.insert(ValueGUID);
271 if (CfiFunctionDecls.
contains(ValueGUID))
272 UsedCfiDecls.insert(ValueGUID);
277 AddUnsigned(GS->getVisibility());
278 AddUnsigned(GS->isLive());
279 AddUnsigned(GS->canAutoHide());
281 AddUnsigned(VI.isDSOLocal(Index.withDSOLocalPropagation()));
282 AddUsedCfiGlobal(VI.getGUID());
285 AddUnsigned(GVS->maybeReadOnly());
286 AddUnsigned(GVS->maybeWriteOnly());
289 for (
auto &TT : FS->type_tests())
290 UsedTypeIds.insert(TT);
291 for (
auto &TT : FS->type_test_assume_vcalls())
292 UsedTypeIds.insert(TT.GUID);
293 for (
auto &TT : FS->type_checked_load_vcalls())
294 UsedTypeIds.insert(TT.GUID);
295 for (
auto &TT : FS->type_test_assume_const_vcalls())
296 UsedTypeIds.insert(TT.VFunc.GUID);
297 for (
auto &TT : FS->type_checked_load_const_vcalls())
298 UsedTypeIds.insert(TT.VFunc.GUID);
299 for (
auto &ET : FS->calls()) {
300 AddUnsigned(ET.first.isDSOLocal(Index.withDSOLocalPropagation()));
301 AddUsedCfiGlobal(ET.first.getGUID());
308 for (
auto &GS : DefinedGlobals) {
312 AddUsedCfiGlobal(GS.first);
313 AddUsedThings(GS.second);
318 for (
const auto &[FromModule, GUID,
Type] : SortedImportList) {
324 AddUsedThings(AS->getBaseObject());
330 AddUnsigned(S.TTRes.TheKind);
331 AddUnsigned(S.TTRes.SizeM1BitWidth);
333 AddUint64(S.TTRes.AlignLog2);
334 AddUint64(S.TTRes.SizeM1);
335 AddUint64(S.TTRes.BitMask);
336 AddUint64(S.TTRes.InlineBits);
338 AddUint64(S.WPDRes.size());
339 for (
auto &WPD : S.WPDRes) {
340 AddUnsigned(WPD.first);
341 AddUnsigned(WPD.second.TheKind);
342 AddString(WPD.second.SingleImplName);
344 AddUint64(WPD.second.ResByArg.size());
345 for (
auto &ByArg : WPD.second.ResByArg) {
346 AddUint64(ByArg.first.size());
349 AddUnsigned(ByArg.second.TheKind);
350 AddUint64(ByArg.second.Info);
351 AddUnsigned(ByArg.second.Byte);
352 AddUnsigned(ByArg.second.Bit);
359 auto TidIter = Index.typeIds().equal_range(TId);
361 AddTypeIdSummary(
I.second.first,
I.second.second);
364 AddUnsigned(UsedCfiDefs.size());
365 for (
auto &V : UsedCfiDefs)
368 AddUnsigned(UsedCfiDecls.size());
369 for (
auto &V : UsedCfiDecls)
375 Hasher.
update(FileOrErr.get()->getBuffer());
380 Hasher.
update(FileOrErr.get()->getBuffer());
411 C.VisibilityScheme ==
Config::ELF ? VI.getELFVisibility()
413 for (
auto &S : VI.getSummaryList()) {
428 if (isPrevailing(VI.getGUID(), S.get())) {
429 assert(!S->wasPromoted() &&
430 "promoted symbols used to be internal linkage and shouldn't have "
431 "a prevailing variant");
444 S->setCanAutoHide(VI.canAutoHide() &&
445 !GUIDPreservedSymbols.
count(VI.getGUID()));
448 Visibility = S->getVisibility();
465 S->setVisibility(Visibility);
467 if (S->linkage() != OriginalLinkage)
468 recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
472 for (
auto &S : VI.getSummaryList()) {
477 S->setVisibility(Visibility);
499 for (
auto &
I : Index)
500 for (
auto &S :
I.second.getSummaryList())
502 GlobalInvolvedWithAlias.
insert(&AS->getAliasee());
504 for (
auto &
I : Index)
506 GlobalInvolvedWithAlias, isPrevailing,
507 recordNewLinkage, GUIDPreservedSymbols);
519 const bool SingleExternallyVisibleCopy =
520 VI.getSummaryList().size() == 1 &&
523 bool NameRecorded =
false;
524 for (
auto &S : VI.getSummaryList()) {
527 if (isExported(S->modulePath(), VI)) {
533 if (ExternallyVisibleSymbolNamesPtr && !NameRecorded) {
535 if (ExternallyVisibleSymbolNamesPtr->
insert(VI.name()).second)
536 S->setNoRenameOnPromotion(
true);
599 if (SingleExternallyVisibleCopy && isPrevailing(VI.getGUID(), S.get()))
612 assert(!Index.withInternalizeAndPromote());
614 for (
auto &
I : Index)
617 ExternallyVisibleSymbolNamesPtr);
618 Index.setWithInternalizeAndPromote();
625 std::unique_ptr<InputFile> File(
new InputFile);
631 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
632 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
633 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
634 File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
635 File->ComdatTable = FOrErr->TheReader.getComdatTable();
639 for (
unsigned I = 0;
I != FOrErr->Mods.size(); ++
I) {
640 size_t Begin = File->Symbols.size();
642 FOrErr->TheReader.module_symbols(
I))
645 if (Sym.isGlobal() && !Sym.isFormatSpecific())
646 File->Symbols.push_back(Sym);
647 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
650 File->Mods = FOrErr->Mods;
651 File->Strtab = std::move(FOrErr->Strtab);
652 return std::move(File);
665 return Mods[0].getModuleIdentifier();
669 assert(Mods.size() == 1 &&
"Expect only one bitcode module");
675LTO::RegularLTOState::RegularLTOState(
unsigned ParallelCodeGenParallelismLevel,
677 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
678 Ctx(Conf), CombinedModule(
std::make_unique<
Module>(
"ld-temp.o", Ctx)),
679 Mover(
std::make_unique<
IRMover>(*CombinedModule)) {}
681LTO::ThinLTOState::ThinLTOState(
ThinBackend BackendParam)
682 : Backend(
std::
move(BackendParam)), CombinedIndex(
false) {
683 if (!Backend.isValid())
689 unsigned ParallelCodeGenParallelismLevel,
LTOKind LTOMode)
691 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
697 Alloc = std::make_unique<BumpPtrAllocator>();
698 GlobalResolutionSymbolSaver = std::make_unique<llvm::StringSaver>(*Alloc);
707 LinkerRemarkFunction =
nullptr;
715 unsigned Partition,
bool InSummary,
718 auto *ResI = Res.
begin();
719 auto *ResE = Res.
end();
730 if (GlobalResolutionSymbolSaver && !GlobalResolutions->contains(SymbolName))
731 SymbolName = GlobalResolutionSymbolSaver->save(SymbolName);
733 auto &GlobalRes = (*GlobalResolutions)[SymbolName];
734 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
736 assert(!GlobalRes.Prevailing &&
737 "Multiple prevailing defs are not allowed");
738 GlobalRes.Prevailing =
true;
739 GlobalRes.IRName = std::string(Sym.getIRName());
740 }
else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
747 GlobalRes.IRName = std::string(Sym.getIRName());
761 if (GlobalRes.IRName != Sym.getIRName()) {
762 GlobalRes.Partition = GlobalResolution::External;
763 GlobalRes.VisibleOutsideSummary =
true;
766 bool IsLibcall = Sym.isLibcall(TLI, Libcalls);
774 (GlobalRes.Partition != GlobalResolution::Unknown &&
775 GlobalRes.Partition != Partition)) {
776 GlobalRes.Partition = GlobalResolution::External;
779 GlobalRes.Partition = Partition;
783 GlobalRes.VisibleOutsideSummary |=
790void LTO::releaseGlobalResolutionsMemory() {
792 GlobalResolutions.reset();
794 GlobalResolutionSymbolSaver.reset();
802 auto ResI = Res.
begin();
807 OS <<
"-r=" << Path <<
',' << Sym.getName() <<
',';
825 assert(!CalledGetMaxTasks);
831 InputFile *
Input = (*InputOrErr).get();
833 if (Conf.ResolutionFile)
836 if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
838 RegularLTO.CombinedModule->setTargetTriple(InputTriple);
844 for (
unsigned I = 0;
I !=
Input->Mods.size(); ++
I) {
845 if (
auto Err = addModule(*
Input, InputRes,
I, Res).moveInto(Res))
855 "bitcode libfuncs were set twice; maybe accidentally clobbered?");
856 this->BitcodeLibFuncs.append(BitcodeLibFuncs.begin(), BitcodeLibFuncs.end());
867 if (EnableSplitLTOUnit) {
871 if (*EnableSplitLTOUnit != LTOInfo->EnableSplitLTOUnit)
874 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
879 !LTOInfo->UnifiedLTO)
881 "unified LTO compilation must use "
882 "compatible bitcode modules (use -funified-lto)",
892 Input.IsThinLTO |= IsThinLTO;
894 auto ModSyms =
Input.module_symbols(ModI);
895 addModuleToGlobalRes(ModSyms, Res,
896 IsThinLTO ? ThinLTO.ModuleMap.
size() + 1 : 0,
897 LTOInfo->HasSummary,
Triple(
Input.getTargetTriple()));
900 return addThinLTO(BM, ModSyms, Res);
902 RegularLTO.EmptyCombinedModule =
false;
903 auto ModOrErr = addRegularLTO(
Input, InputRes, BM, ModSyms, Res);
905 return ModOrErr.takeError();
906 Res = ModOrErr->second;
908 if (!LTOInfo->HasSummary) {
909 if (
Error Err = linkRegularLTO(std::move(ModOrErr->first),
919 RegularLTO.ModsWithSummaries.push_back(std::move(ModOrErr->first));
935 std::set<const Comdat *> &NonPrevailingComdats) {
940 if (!NonPrevailingComdats.count(
C))
950 GO->setComdat(
nullptr);
957 std::pair<LTO::RegularLTOState::AddedModule, ArrayRef<SymbolResolution>>>
961 llvm::TimeTraceScope timeScope(
"LTO add regular LTO");
963 Expected<std::unique_ptr<Module>> MOrErr =
969 Mod.M = std::move(*MOrErr);
971 if (
Error Err =
M.materializeMetadata())
972 return std::move(Err);
978 if (NamedMDNode *CfiFunctionsMD =
M.getNamedMetadata(
"cfi.functions"))
979 M.eraseNamedMetadata(CfiFunctionsMD);
980 }
else if (NamedMDNode *AliasesMD =
M.getNamedMetadata(
"aliases")) {
983 DenseSet<StringRef> Prevailing;
985 if (
R.Prevailing && !
I.getIRName().empty())
986 Prevailing.
insert(
I.getIRName());
987 std::vector<MDNode *> AliasGroups;
988 for (MDNode *AliasGroup : AliasesMD->operands()) {
989 std::vector<Metadata *> Aliases;
990 for (
Metadata *Alias : AliasGroup->operands()) {
993 Aliases.push_back(Alias);
995 if (Aliases.size() > 1)
996 AliasGroups.push_back(
MDTuple::get(RegularLTO.Ctx, Aliases));
998 AliasesMD->clearOperands();
999 for (MDNode *
G : AliasGroups)
1000 AliasesMD->addOperand(
G);
1005 ModuleSymbolTable SymTab;
1008 for (GlobalVariable &GV :
M.globals())
1009 if (GV.hasAppendingLinkage())
1010 Mod.Keep.push_back(&GV);
1012 DenseSet<GlobalObject *> AliasedGlobals;
1013 for (
auto &GA :
M.aliases())
1014 if (GlobalObject *GO = GA.getAliaseeObject())
1015 AliasedGlobals.
insert(GO);
1024 auto MsymI = SymTab.
symbols().begin(), MsymE = SymTab.
symbols().end();
1026 while (MsymI != MsymE) {
1036 std::set<const Comdat *> NonPrevailingComdats;
1037 SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
1038 for (
const InputFile::Symbol &Sym : Syms) {
1048 if (Sym.isUndefined())
1050 Mod.Keep.push_back(GV);
1054 if (
R.LinkerRedefined)
1062 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
1063 GV->hasAvailableExternallyLinkage()) &&
1070 Mod.Keep.push_back(GV);
1072 if (GV->hasComdat())
1073 NonPrevailingComdats.insert(GV->getComdat());
1078 if (
R.FinalDefinitionInLinkageUnit) {
1079 GV->setDSOLocal(
true);
1080 if (GV->hasDLLImportStorageClass())
1082 DefaultStorageClass);
1084 }
else if (
auto *AS =
1088 NonPrevailingAsmSymbols.
insert(AS->first);
1096 if (Sym.isCommon()) {
1099 auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
1100 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
1101 if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
1102 CommonRes.Alignment =
1103 std::max(
Align(SymAlignValue), CommonRes.Alignment);
1105 CommonRes.Prevailing |=
R.Prevailing;
1109 if (!
M.getComdatSymbolTable().empty())
1110 for (GlobalValue &GV :
M.global_values())
1115 if (!
M.getModuleInlineAsm().empty()) {
1116 std::string NewIA =
".lto_discard";
1117 if (!NonPrevailingAsmSymbols.
empty()) {
1120 M, [&](StringRef Name, StringRef Alias) {
1121 if (!NonPrevailingAsmSymbols.
count(Alias))
1122 NonPrevailingAsmSymbols.
erase(Name);
1124 NewIA +=
" " +
llvm::join(NonPrevailingAsmSymbols,
", ");
1127 M.setModuleInlineAsm(NewIA +
M.getModuleInlineAsm());
1131 return std::make_pair(std::move(
Mod), Res);
1134Error LTO::linkRegularLTO(RegularLTOState::AddedModule
Mod,
1135 bool LivenessFromIndex) {
1136 llvm::TimeTraceScope timeScope(
"LTO link regular LTO");
1137 std::vector<GlobalValue *>
Keep;
1138 for (GlobalValue *GV :
Mod.Keep) {
1139 if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->
getGUID())) {
1141 if (DiagnosticOutputFile) {
1142 if (
Error Err =
F->materialize())
1144 auto R = OptimizationRemark(
DEBUG_TYPE,
"deadfunction",
F);
1145 R <<
ore::NV(
"Function",
F) <<
" not added to the combined module ";
1159 GlobalValue *CombinedGV =
1160 RegularLTO.CombinedModule->getNamedValue(GV->
getName());
1167 return RegularLTO.Mover->move(std::move(
Mod.M),
Keep,
nullptr,
1172Expected<ArrayRef<SymbolResolution>>
1175 llvm::TimeTraceScope timeScope(
"LTO add thin LTO");
1178 for (
const InputFile::Symbol &Sym : Syms) {
1182 if (!Sym.getIRName().empty() &&
R.Prevailing) {
1186 ThinLTO.setPrevailingModuleForGUID(GUID, BMID);
1192 return ThinLTO.isPrevailingModuleForGUID(GUID, BMID);
1197 for (
const InputFile::Symbol &Sym : Syms) {
1201 if (!Sym.getIRName().empty() &&
1202 (
R.Prevailing ||
R.FinalDefinitionInLinkageUnit)) {
1207 assert(ThinLTO.isPrevailingModuleForGUID(GUID, BMID));
1213 if (
R.LinkerRedefined)
1214 if (
auto S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID))
1220 if (
R.FinalDefinitionInLinkageUnit) {
1221 if (
auto S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID)) {
1222 S->setDSOLocal(
true);
1228 if (!ThinLTO.ModuleMap.insert({BMID, BM}).second)
1230 "Expected at most one ThinLTO module per bitcode file",
1233 if (!Conf.ThinLTOModulesToCompile.empty()) {
1234 if (!ThinLTO.ModulesToCompile)
1235 ThinLTO.ModulesToCompile = ModuleMapType();
1238 for (
const std::string &Name : Conf.ThinLTOModulesToCompile) {
1239 if (BMID.contains(Name)) {
1240 ThinLTO.ModulesToCompile->insert({BMID, BM});
1241 LLVM_DEBUG(
dbgs() <<
"[ThinLTO] Selecting " << BMID <<
" to compile\n");
1251 CalledGetMaxTasks =
true;
1252 auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
1253 : ThinLTO.ModuleMap.size();
1254 return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
1259Error LTO::checkPartiallySplit() {
1263 const Module *Combined = RegularLTO.CombinedModule.get();
1269 Combined, Intrinsic::type_checked_load_relative);
1273 if ((TypeTestFunc && !TypeTestFunc->
use_empty()) ||
1274 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->
use_empty()) ||
1275 (TypeCheckedLoadRelativeFunc &&
1276 !TypeCheckedLoadRelativeFunc->
use_empty()))
1278 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1283 for (
auto &
P : ThinLTO.CombinedIndex) {
1284 for (
auto &S :
P.second.getSummaryList()) {
1288 if (!FS->type_test_assume_vcalls().empty() ||
1289 !FS->type_checked_load_vcalls().empty() ||
1290 !FS->type_test_assume_const_vcalls().empty() ||
1291 !FS->type_checked_load_const_vcalls().empty() ||
1292 !FS->type_tests().empty())
1294 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1310 for (
auto &Res : *GlobalResolutions) {
1313 if (Res.second.IRName.
empty())
1319 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1320 GUIDPreservedSymbols.
insert(GUID);
1322 if (Res.second.ExportDynamic)
1323 DynamicExportSymbols.insert(GUID);
1325 GUIDPrevailingResolutions[GUID] =
1330 auto It = GUIDPrevailingResolutions.
find(
G);
1331 if (It == GUIDPrevailingResolutions.
end())
1336 isPrevailing, Conf.OptLevel > 0);
1340 if (!StatsFileOrErr)
1341 return StatsFileOrErr.takeError();
1342 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1344 if (
Error Err = setupOptimizationRemarks())
1353 ThinLTO.CombinedIndex.setWithSupportsHotColdNew();
1355 Error Result = runRegularLTO(AddStream);
1359 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1375 for (
auto &M : RegularLTO.ModsWithSummaries)
1376 if (
Error Err = linkRegularLTO(std::move(M),
true))
1384 if (
Error Err = checkPartiallySplit())
1389 const DataLayout &
DL = RegularLTO.CombinedModule->getDataLayout();
1390 for (
auto &
I : RegularLTO.Commons) {
1391 if (!
I.second.Prevailing)
1394 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(
I.first);
1403 auto *GV =
new GlobalVariable(*RegularLTO.CombinedModule, Ty,
false,
1406 GV->setAlignment(
I.second.Alignment);
1416 bool WholeProgramVisibilityEnabledInLTO =
1417 Conf.HasWholeProgramVisibility &&
1420 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1424 auto IsVisibleToRegularObj = [&](StringRef
name) {
1425 auto It = GlobalResolutions->find(
name);
1426 return (It == GlobalResolutions->end() ||
1427 It->second.VisibleOutsideSummary || !It->second.Prevailing);
1433 *RegularLTO.CombinedModule, WholeProgramVisibilityEnabledInLTO,
1434 DynamicExportSymbols, Conf.ValidateAllVtablesHaveTypeInfos,
1435 IsVisibleToRegularObj);
1437 WholeProgramVisibilityEnabledInLTO);
1439 if (Conf.PreOptModuleHook &&
1440 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1443 if (!Conf.CodeGenOnly) {
1444 for (
const auto &R : *GlobalResolutions) {
1446 RegularLTO.CombinedModule->getNamedValue(
R.second.IRName);
1447 if (!
R.second.isPrevailingIRSymbol())
1449 if (
R.second.Partition != 0 &&
1450 R.second.Partition != GlobalResolution::External)
1478 if (Conf.PostInternalizeModuleHook &&
1479 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1483 if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1485 Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1486 *RegularLTO.CombinedModule, ThinLTO.CombinedIndex, BitcodeLibFuncs))
1503 return LibcallSymbols;
1508 auto TLII = std::make_unique<TargetLibraryInfoImpl>(TT);
1511 LibFuncSymbols.
reserve(LibFunc::NumLibFuncs);
1512 for (
unsigned I = LibFunc::Begin_LibFunc;
I != LibFunc::End_LibFunc; ++
I) {
1513 LibFunc
F =
static_cast<LibFunc
>(
I);
1517 return LibFuncSymbols;
1522 const std::string &NewModulePath)
const {
1523 return emitFiles(ImportList, ModulePath, NewModulePath,
1524 NewModulePath +
".thinlto.bc",
1530 const std::string &NewModulePath,
StringRef SummaryPath,
1531 std::optional<std::reference_wrapper<ImportsFilesContainer>> ImportsFiles)
1538 ImportList, ModuleToSummariesForIndex,
1539 DeclarationSummaries);
1546 &DeclarationSummaries);
1550 ModulePath, NewModulePath +
".imports", ModuleToSummariesForIndex);
1551 if (ImportsFilesError)
1552 return ImportsFilesError;
1558 ModulePath, ModuleToSummariesForIndex,
1559 [&](
StringRef M) { ImportsFiles->get().push_back(M.str()); });
1571 bool ShouldEmitIndexFiles;
1580 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1581 ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
1591class InProcessThinBackend :
public CGThinBackend {
1600 InProcessThinBackend(
1605 bool ShouldEmitIndexFiles,
bool ShouldEmitImportsFiles,
1607 : CGThinBackend(Conf, CombinedIndex, ModuleToDefinedGVSummaries, OnWrite,
1608 ShouldEmitIndexFiles, ShouldEmitImportsFiles,
1609 ThinLTOParallelism),
1611 BitcodeLibFuncs(BitcodeLibFuncs) {}
1613 virtual Error runThinLTOBackendThread(
1614 AddStreamFn AddStream, FileCache Cache,
unsigned Task, BitcodeModule BM,
1615 ModuleSummaryIndex &CombinedIndex,
1616 const FunctionImporter::ImportMapTy &ImportList,
1618 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1620 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1622 llvm::TimeTraceScope timeScope(
"Run ThinLTO backend thread (in-process)",
1624 auto RunThinBackend = [&](
AddStreamFn AddStream) {
1625 LTOLLVMContext BackendContext(Conf);
1626 Expected<std::unique_ptr<Module>> MOrErr = BM.
parseModule(BackendContext);
1630 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1631 ImportList, DefinedGlobals, &ModuleMap,
1634 if (ShouldEmitIndexFiles) {
1635 if (
auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
1641 [](uint32_t V) { return V == 0; }))
1644 return RunThinBackend(AddStream);
1648 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1649 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1650 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task,
Key, ModuleID);
1653 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1655 return RunThinBackend(CacheAddStream);
1661 unsigned Task, BitcodeModule BM,
1662 const FunctionImporter::ImportMapTy &ImportList,
1664 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1665 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
1667 assert(ModuleToDefinedGVSummaries.
count(ModulePath));
1669 ModuleToDefinedGVSummaries.
find(ModulePath)->second;
1670 BackendThreadPool.async(
1671 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1672 const FunctionImporter::ImportMapTy &ImportList,
1674 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1677 MapVector<StringRef, BitcodeModule> &ModuleMap) {
1681 Error E = runThinLTOBackendThread(
1682 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1683 ResolvedODR, DefinedGlobals, ModuleMap);
1685 std::unique_lock<std::mutex>
L(ErrMu);
1694 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1695 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1698 OnWrite(std::string(ModulePath));
1708class FirstRoundThinBackend :
public InProcessThinBackend {
1713 FirstRoundThinBackend(
1714 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1715 ThreadPoolStrategy ThinLTOParallelism,
1716 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1720 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1721 ModuleToDefinedGVSummaries, std::
move(CGAddStream),
1722 std::
move(CGCache), nullptr,
1724 false, BitcodeLibFuncs),
1725 IRAddStream(std::
move(IRAddStream)), IRCache(std::
move(IRCache)) {}
1727 Error runThinLTOBackendThread(
1728 AddStreamFn CGAddStream, FileCache CGCache,
unsigned Task,
1729 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1730 const FunctionImporter::ImportMapTy &ImportList,
1732 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1734 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
1736 llvm::TimeTraceScope timeScope(
"Run ThinLTO backend thread (first round)",
1738 auto RunThinBackend = [&](
AddStreamFn CGAddStream,
1740 LTOLLVMContext BackendContext(Conf);
1741 Expected<std::unique_ptr<Module>> MOrErr = BM.
parseModule(BackendContext);
1745 return thinBackend(Conf, Task, CGAddStream, **MOrErr, CombinedIndex,
1746 ImportList, DefinedGlobals, &ModuleMap,
1752 if (ShouldEmitIndexFiles) {
1753 if (
auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
1758 "Both caches for CG and IR should have matching availability");
1761 [](uint32_t V) { return V == 0; }))
1764 return RunThinBackend(CGAddStream, IRAddStream);
1768 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1769 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1770 Expected<AddStreamFn> CacheCGAddStreamOrErr =
1771 CGCache(Task, CGKey, ModuleID);
1774 AddStreamFn &CacheCGAddStream = *CacheCGAddStreamOrErr;
1778 Expected<AddStreamFn> CacheIRAddStreamOrErr =
1779 IRCache(Task, IRKey, ModuleID);
1782 AddStreamFn &CacheIRAddStream = *CacheIRAddStreamOrErr;
1788 if (CacheCGAddStream || CacheIRAddStream) {
1791 return RunThinBackend(CacheCGAddStream ? CacheCGAddStream : CGAddStream,
1792 CacheIRAddStream ? CacheIRAddStream : IRAddStream);
1804class SecondRoundThinBackend :
public InProcessThinBackend {
1805 std::unique_ptr<SmallVector<StringRef>> IRFiles;
1809 SecondRoundThinBackend(
1810 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1811 ThreadPoolStrategy ThinLTOParallelism,
1812 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1817 : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1818 ModuleToDefinedGVSummaries, std::
move(AddStream),
1822 false, BitcodeLibFuncs),
1823 IRFiles(std::
move(IRFiles)), CombinedCGDataHash(CombinedCGDataHash) {}
1825 Error runThinLTOBackendThread(
1826 AddStreamFn AddStream, FileCache Cache,
unsigned Task, BitcodeModule BM,
1827 ModuleSummaryIndex &CombinedIndex,
1828 const FunctionImporter::ImportMapTy &ImportList,
1830 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1832 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
1834 llvm::TimeTraceScope timeScope(
"Run ThinLTO backend thread (second round)",
1836 auto RunThinBackend = [&](
AddStreamFn AddStream) {
1837 LTOLLVMContext BackendContext(Conf);
1838 std::unique_ptr<Module> LoadedModule =
1841 return thinBackend(Conf, Task, AddStream, *LoadedModule, CombinedIndex,
1842 ImportList, DefinedGlobals, &ModuleMap,
1843 true, BitcodeLibFuncs);
1847 [](uint32_t V) { return V == 0; }))
1850 return RunThinBackend(AddStream);
1855 Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1856 DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1858 std::to_string(CombinedCGDataHash));
1859 Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task,
Key, ModuleID);
1862 AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1864 if (CacheAddStream) {
1867 return RunThinBackend(CacheAddStream);
1877 bool ShouldEmitIndexFiles,
1878 bool ShouldEmitImportsFiles) {
1884 return std::make_unique<InProcessThinBackend>(
1885 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
1886 AddStream, Cache, OnWrite, ShouldEmitIndexFiles,
1887 ShouldEmitImportsFiles, BitcodeLibFuncs);
1913 return std::string(Path);
1917 if (!ParentPath.
empty()) {
1920 llvm::errs() <<
"warning: could not create directory '" << ParentPath
1921 <<
"': " << EC.message() <<
'\n';
1923 return std::string(NewPath);
1928 std::string OldPrefix, NewPrefix, NativeObjectPrefix;
1932 WriteIndexesThinBackend(
1936 std::string OldPrefix, std::string NewPrefix,
1937 std::string NativeObjectPrefix,
bool ShouldEmitImportsFiles,
1940 OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1941 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1942 NativeObjectPrefix(NativeObjectPrefix),
1943 LinkedObjectsFile(LinkedObjectsFile) {}
1949 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1957 if (LinkedObjectsFile) {
1958 std::string ObjectPrefix =
1959 NativeObjectPrefix.empty() ? NewPrefix : NativeObjectPrefix;
1960 std::string LinkedObjectsFilePath =
1962 *LinkedObjectsFile << LinkedObjectsFilePath <<
'\n';
1965 BackendThreadPool.async(
1966 [
this](
const StringRef ModulePath,
1967 const FunctionImporter::ImportMapTy &ImportList,
1968 const std::string &OldPrefix,
const std::string &NewPrefix) {
1969 std::string NewModulePath =
1971 auto E = emitFiles(ImportList, ModulePath, NewModulePath);
1973 std::unique_lock<std::mutex>
L(ErrMu);
1981 ModulePath, ImportList, OldPrefix, NewPrefix);
1984 OnWrite(std::string(ModulePath));
1988 bool isSensitiveToInputOrder()
override {
1998 std::string NewPrefix, std::string NativeObjectPrefix,
2006 return std::make_unique<WriteIndexesThinBackend>(
2007 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2008 OldPrefix, NewPrefix, NativeObjectPrefix, ShouldEmitImportsFiles,
2009 LinkedObjectsFile, OnWrite);
2024 if (ThinLTO.ModuleMap.
empty())
2027 if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
2028 llvm::errs() <<
"warning: [ThinLTO] No module compiled\n";
2032 if (Conf.CombinedIndexHook &&
2033 !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
2038 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(
2039 ThinLTO.ModuleMap.size());
2040 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
2041 ModuleToDefinedGVSummaries);
2049 for (
auto &
Mod : ThinLTO.ModuleMap)
2050 if (!ModuleToDefinedGVSummaries.
count(
Mod.first))
2053 FunctionImporter::ImportListsTy ImportLists(ThinLTO.ModuleMap.size());
2054 DenseMap<StringRef, FunctionImporter::ExportSetTy> ExportLists(
2055 ThinLTO.ModuleMap.size());
2056 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
2059 ThinLTO.CombinedIndex.dumpSCCs(
outs());
2061 std::set<GlobalValue::GUID> ExportedGUIDs;
2063 bool WholeProgramVisibilityEnabledInLTO =
2064 Conf.HasWholeProgramVisibility &&
2067 (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
2069 ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
2074 DenseSet<GlobalValue::GUID> VisibleToRegularObjSymbols;
2075 if (WholeProgramVisibilityEnabledInLTO &&
2076 Conf.ValidateAllVtablesHaveTypeInfos) {
2079 auto IsVisibleToRegularObj = [&](StringRef
name) {
2080 auto It = GlobalResolutions->find(
name);
2081 return (It == GlobalResolutions->end() ||
2082 It->second.VisibleOutsideSummary || !It->second.Prevailing);
2086 VisibleToRegularObjSymbols,
2087 IsVisibleToRegularObj);
2093 ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO,
2094 DynamicExportSymbols, VisibleToRegularObjSymbols);
2099 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
2100 DenseSet<StringRef> ExternallyVisibleSymbolNames;
2106 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr =
2108 ? &ExternallyVisibleSymbolNames
2112 ExternallyVisibleSymbolNamesPtr);
2115 return ThinLTO.isPrevailingModuleForGUID(GUID, S->modulePath());
2118 MemProfContextDisambiguation ContextDisambiguation;
2119 ContextDisambiguation.
run(
2120 ThinLTO.CombinedIndex, isPrevailing, RegularLTO.Ctx,
2121 [&](StringRef
PassName, StringRef RemarkName,
const Twine &Msg) {
2122 auto R = OptimizationRemark(PassName.data(), RemarkName,
2123 LinkerRemarkFunction);
2133 for (
auto &Res : *GlobalResolutions) {
2136 if (Res.second.Partition != GlobalResolution::External ||
2137 !Res.second.isPrevailingIRSymbol())
2142 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
2143 ExportedGUIDs.insert(GUID);
2150 releaseGlobalResolutionsMemory();
2152 if (Conf.OptLevel > 0)
2154 isPrevailing, ImportLists, ExportLists);
2158 auto &Defs = ThinLTO.CombinedIndex.cfiFunctionDefs();
2159 ExportedGUIDs.insert(Defs.guid_begin(), Defs.guid_end());
2160 auto &Decls = ThinLTO.CombinedIndex.cfiFunctionDecls();
2161 ExportedGUIDs.insert(Decls.guid_begin(), Decls.guid_end());
2163 auto isExported = [&](StringRef ModuleIdentifier, ValueInfo
VI) {
2164 const auto &ExportList = ExportLists.
find(ModuleIdentifier);
2165 return (ExportList != ExportLists.end() && ExportList->second.
count(VI)) ||
2166 ExportedGUIDs.count(
VI.getGUID());
2172 LocalWPDTargetsMap, ExternallyVisibleSymbolNamesPtr);
2174 if (ExternallyVisibleSymbolNamesPtr) {
2177 for (
auto &
I : ThinLTO.CombinedIndex) {
2178 ValueInfo
VI = ThinLTO.CombinedIndex.getValueInfo(
I);
2179 for (
const auto &Summary :
VI.getSummaryList()) {
2180 const GlobalValueSummary *
Base =
Summary->getBaseObject();
2184 ExternallyVisibleSymbolNamesPtr->
insert(
VI.name());
2192 ExternallyVisibleSymbolNamesPtr);
2194 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
2197 ResolvedODR[ModuleIdentifier][
GUID] = NewLinkage;
2200 recordNewLinkage, GUIDPreservedSymbols);
2209 TimeTraceScopeExit.release();
2212 ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
2214 auto RunBackends = [&](ThinBackendProc *BackendProcess) ->
Error {
2215 auto ProcessOneModule = [&](
int I) ->
Error {
2219 return BackendProcess->start(
2220 RegularLTO.ParallelCodeGenParallelismLevel +
I,
Mod.second,
2221 ImportLists[
Mod.first], ExportLists[
Mod.first],
2222 ResolvedODR[
Mod.first], ThinLTO.ModuleMap);
2225 BackendProcess->setup(ModuleMap.
size(),
2226 RegularLTO.ParallelCodeGenParallelismLevel,
2227 RegularLTO.CombinedModule->getTargetTriple());
2229 if (BackendProcess->getThreadCount() == 1 ||
2230 BackendProcess->isSensitiveToInputOrder()) {
2236 for (
int I = 0,
E = ModuleMap.
size();
I !=
E; ++
I)
2237 if (
Error E = ProcessOneModule(
I))
2244 std::vector<BitcodeModule *> ModulesVec;
2245 ModulesVec.reserve(ModuleMap.
size());
2246 for (
auto &
Mod : ModuleMap)
2247 ModulesVec.push_back(&
Mod.second);
2249 if (
Error E = ProcessOneModule(
I))
2252 return BackendProcess->wait();
2256 std::unique_ptr<ThinBackendProc> BackendProc =
2257 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2258 AddStream, Cache, BitcodeLibFuncs);
2259 return RunBackends(BackendProc.get());
2267 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] Initializing ThinLTO two-codegen rounds\n");
2270 auto Parallelism = ThinLTO.Backend.getParallelism();
2273 cgdata::StreamCacheData CG(MaxTasks, Cache,
"CG"),
IR(MaxTasks, Cache,
"IR");
2278 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] Running the first round of codegen\n");
2279 auto FirstRoundLTO = std::make_unique<FirstRoundThinBackend>(
2280 Conf, ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2281 CG.AddStream, CG.Cache, BitcodeLibFuncs,
IR.AddStream,
IR.Cache);
2282 if (
Error E = RunBackends(FirstRoundLTO.get()))
2287 if (
Error E = CombinedHashOrErr.takeError())
2289 auto CombinedHash = *CombinedHashOrErr;
2290 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] CGData hash: " << CombinedHash <<
"\n");
2294 LLVM_DEBUG(
dbgs() <<
"[TwoRounds] Running the second round of codegen\n");
2295 auto SecondRoundLTO = std::make_unique<SecondRoundThinBackend>(
2296 Conf, ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2297 AddStream, Cache, BitcodeLibFuncs,
IR.getResult(), CombinedHash);
2298 return RunBackends(SecondRoundLTO.get());
2316 if (
Error E = ResultOrErr.takeError())
2317 return std::move(E);
2320 (*ResultOrErr)->keep();
2328 if (StatsFilename.
empty())
2339 return std::move(StatsFile);
2347 std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
2348 llvm::sort(ModulesOrdering, [&](
int LeftIndex,
int RightIndex) {
2349 auto LSize = R[LeftIndex]->getBuffer().size();
2350 auto RSize = R[RightIndex]->getBuffer().size();
2351 return LSize > RSize;
2353 return ModulesOrdering;
2363class OutOfProcessThinBackend :
public CGThinBackend {
2369 SString LinkerOutputFile;
2371 SString DistributorPath;
2374 SString RemoteCompiler;
2383 std::atomic<size_t> CachedJobs{0};
2388 StringRef NativeObjectPath;
2389 StringRef SummaryIndexPath;
2391 std::string CacheKey;
2393 bool Cached =
false;
2402 unsigned ThinLTOTaskOffset;
2405 llvm::Triple Triple;
2414 OutOfProcessThinBackend(
2415 const Config &Conf, ModuleSummaryIndex &CombinedIndex,
2416 ThreadPoolStrategy ThinLTOParallelism,
2417 const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
2419 bool ShouldEmitIndexFiles,
bool ShouldEmitImportsFiles,
2420 StringRef LinkerOutputFile, StringRef Distributor,
2425 : CGThinBackend(Conf, CombinedIndex, ModuleToDefinedGVSummaries, OnWrite,
2426 ShouldEmitIndexFiles, ShouldEmitImportsFiles,
2427 ThinLTOParallelism),
2428 LinkerOutputFile(LinkerOutputFile), DistributorPath(Distributor),
2429 DistributorArgs(DistributorArgs), RemoteCompiler(RemoteCompiler),
2430 RemoteCompilerPrependArgs(RemoteCompilerPrependArgs),
2431 RemoteCompilerArgs(RemoteCompilerArgs), SaveTemps(SaveTemps),
2432 Cache(std::
move(CacheFn)), AddBuffer(std::
move(AddBuffer)) {}
2434 void setup(
unsigned ThinLTONumTasks,
unsigned ThinLTOTaskOffset,
2435 llvm::Triple Triple)
override {
2437 Jobs.
resize((
size_t)ThinLTONumTasks);
2438 this->ThinLTOTaskOffset = ThinLTOTaskOffset;
2439 this->Triple = std::move(Triple);
2440 this->Conf.
Dtlto = 1;
2443 virtual Error runThinLTOBackendThread(
2444 Job &J,
const FunctionImporter::ImportMapTy &ImportList,
2446 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
2449 TimeTraceScope TimeScope(
"Emit individual index for DTLTO",
2450 J.SummaryIndexPath);
2451 if (
auto E = emitFiles(ImportList, J.ModuleID, J.ModuleID.str(),
2452 J.SummaryIndexPath, J.ImportsFiles))
2458 [](uint32_t V) { return V == 0; }))
2463 TimeTraceScope TimeScope(
"Check cache for DTLTO", J.SummaryIndexPath);
2465 ModuleToDefinedGVSummaries.
find(J.ModuleID)->second;
2469 ExportList, ResolvedODR, DefinedGlobals,
2470 CfiFunctionDefs, CfiFunctionDecls);
2473 auto CacheAddStreamExp = Cache(J.Task, J.CacheKey, J.ModuleID);
2474 if (
Error Err = CacheAddStreamExp.takeError())
2479 if (!CacheAddStream) {
2481 CachedJobs.fetch_add(1);
2486 J.CacheAddStream = std::move(CacheAddStream);
2492 unsigned Task, BitcodeModule BM,
2493 const FunctionImporter::ImportMapTy &ImportList,
2495 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
2496 MapVector<StringRef, BitcodeModule> &ModuleMap)
override {
2502 itostr(Task) +
"." + UID +
".native.o");
2504 Job &J = Jobs[Task - ThinLTOTaskOffset];
2507 Saver.
save(ObjFilePath.str()),
2508 Saver.
save(ObjFilePath.str() +
".thinlto.bc"),
2517 if (!ShouldEmitIndexFiles)
2521 assert(ModuleToDefinedGVSummaries.
count(ModulePath));
2525 BackendThreadPool.async(
2526 [=](Job &J,
const FunctionImporter::ImportMapTy &ImportList,
2528 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
2533 "Emit individual index and check cache for DTLTO");
2535 runThinLTOBackendThread(J, ImportList, ExportList, ResolvedODR);
2537 std::unique_lock<std::mutex>
L(ErrMu);
2546 std::ref(J), std::ref(ImportList), std::ref(ExportList),
2547 std::ref(ResolvedODR));
2561 void buildCommonRemoteCompilerOptions() {
2562 const lto::Config &
C = Conf;
2563 auto &
Ops = CodegenOptions;
2567 if (
C.Options.EmitAddrsig)
2568 Ops.push_back(
"-faddrsig");
2569 if (
C.Options.FunctionSections)
2570 Ops.push_back(
"-ffunction-sections");
2571 if (
C.Options.DataSections)
2572 Ops.push_back(
"-fdata-sections");
2577 Ops.push_back(
"-fpic");
2581 if (!
C.PGOWarnMismatch) {
2582 Ops.push_back(
"-mllvm");
2583 Ops.push_back(
"-no-pgo-warn-mismatch");
2588 if (!
C.SampleProfile.empty()) {
2590 Saver.
save(
"-fprofile-sample-use=" + Twine(
C.SampleProfile)));
2591 CommonInputs.
insert(
C.SampleProfile);
2595 Ops.push_back(
"-Wno-unused-command-line-argument");
2598 if (!RemoteCompilerArgs.
empty())
2599 for (
auto &a : RemoteCompilerArgs)
2605 bool emitDistributorJson(StringRef DistributorJson) {
2608 raw_fd_ostream OS(DistributorJson, EC);
2612 json::OStream JOS(OS);
2615 JOS.attributeObject(
"common", [&]() {
2616 JOS.attribute(
"linker_output", LinkerOutputFile);
2618 JOS.attributeArray(
"args", [&]() {
2619 JOS.value(RemoteCompiler);
2622 if (!RemoteCompilerPrependArgs.
empty())
2623 for (
auto &
A : RemoteCompilerPrependArgs)
2628 JOS.value(Saver.
save(
"--target=" + Triple.
str()));
2630 for (
const auto &
A : CodegenOptions)
2634 JOS.attribute(
"inputs",
Array(CommonInputs));
2638 JOS.attributeArray(
"jobs", [&]() {
2639 for (
const auto &J : Jobs) {
2647 SmallVector<StringRef, 1> Outputs;
2650 JOS.attributeArray(
"args", [&]() {
2651 JOS.value(J.ModuleID);
2655 Saver.
save(
"-fthinlto-index=" + Twine(J.SummaryIndexPath)));
2659 JOS.value(J.NativeObjectPath);
2667 JOS.attribute(
"inputs",
Array(Inputs));
2669 JOS.attribute(
"outputs",
Array(Outputs));
2678 void removeFile(StringRef FileName) {
2680 if (EC && EC != std::make_error_code(std::errc::no_such_file_or_directory))
2681 errs() <<
"warning: could not remove the file '" << FileName
2682 <<
"': " <<
EC.message() <<
"\n";
2685 Error wait()
override {
2688 BackendThreadPool.wait();
2690 return std::move(*Err);
2693 llvm::TimeTraceScope TimeScope(
"Remove DTLTO temporary files");
2695 for (
auto &Job : Jobs) {
2696 removeFile(Job.NativeObjectPath);
2697 if (!ShouldEmitIndexFiles)
2698 removeFile(Job.SummaryIndexPath);
2702 const StringRef BCError =
"DTLTO backend compilation: ";
2704 buildCommonRemoteCompilerOptions();
2708 llvm::TimeTraceScope TimeScope(
"Emit DTLTO JSON");
2710 UID +
".dist-file.json");
2714 if (!emitDistributorJson(JsonFile))
2716 BCError +
"failed to generate distributor JSON script: " + JsonFile,
2721 removeFile(JsonFile);
2725 llvm::TimeTraceScope TimeScope(
"Execute DTLTO distributor",
2728 if (CachedJobs.load() < Jobs.size()) {
2731 Args.push_back(JsonFile);
2738 BCError +
"distributor execution failed" +
2739 (!ErrMsg.empty() ?
": " + ErrMsg + Twine(
".") : Twine(
".")),
2746 llvm::TimeTraceScope FilesScope(
"Add DTLTO files to the link");
2747 for (
auto &Job : Jobs) {
2748 if (!Job.CacheKey.empty() && Job.Cached) {
2754 auto ObjFileMbOrErr =
2757 if (std::error_code EC = ObjFileMbOrErr.getError())
2759 BCError +
"cannot open native object file: " +
2760 Job.NativeObjectPath +
": " +
EC.message(),
2766 assert(Job.CacheAddStream);
2767 MemoryBufferRef ObjFileMbRef =
2768 ObjFileMbOrErr->get()->getMemBufferRef();
2770 auto CachedFileStreamOrErr =
2771 Job.CacheAddStream(Job.Task, Job.ModuleID);
2772 if (!CachedFileStreamOrErr)
2774 CachedFileStreamOrErr.takeError(),
2776 "Cannot get a cache file stream: %s",
2777 Job.NativeObjectPath.data()));
2779 auto &CacheStream = *(CachedFileStreamOrErr->get());
2780 *(CacheStream.OS) << ObjFileMbRef.
getBuffer();
2781 if (
Error Err = CacheStream.commit())
2784 AddBuffer(Job.Task, Job.ModuleID, std::move(*ObjFileMbOrErr));
2795 bool ShouldEmitIndexFiles,
bool ShouldEmitImportsFiles,
2805 return std::make_unique<OutOfProcessThinBackend>(
2806 Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries, Cache,
2807 OnWrite, ShouldEmitIndexFiles, ShouldEmitImportsFiles,
2808 LinkerOutputFile, Distributor, DistributorArgs, RemoteCompiler,
2809 RemoteCompilerPrependArgs, 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 void thinLTOInternalizeAndPromoteGUID(ValueInfo VI, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr)
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"))
Legalize the Machine IR a function s Machine IR
Machine Check Debug Module
static constexpr StringLiteral Filename
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...
static const char PassName[]
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.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
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
static bool isLinkOnceODRLinkage(LinkageTypes Linkage)
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
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)
Implementation of the target library information.
Provides information about what library functions are available for the current target.
bool has(LibFunc F) const
Tests whether a library function is available.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
StringRef getName(LibFunc F) const
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 Type * getVoidTy(LLVMContext &C)
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...
virtual Expected< std::shared_ptr< lto::InputFile > > addInput(std::unique_ptr< lto::InputFile > InputPtr)
LLVM_ABI void setBitcodeLibFuncs(ArrayRef< StringRef > BitcodeLibFuncs)
Set the list of functions implemented in bitcode that were not extracted from an archive.
virtual Error serializeInputsForDistribution()
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.
void emitRemark(OptimizationRemark &Remark)
Helper to emit an optimization remark during the LTO link when outside of the standard optimization p...
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.
static LLVM_ABI SmallVector< StringRef > getLibFuncSymbols(const Triple &TT, llvm::StringSaver &Saver)
Static method that returns a list of library function symbols that can be generated by LTO but might ...
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 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, AddBufferFn AddBuffer)
This ThinBackend generates the index shards and then runs the individual backend jobs via an external...
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, ArrayRef< StringRef > BitcodeLibFuncs, AddStreamFn IRAddStream=nullptr, const std::vector< uint8_t > &CmdArgs=std::vector< uint8_t >())
Runs a ThinLTO backend.
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 Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &M, ModuleSummaryIndex &CombinedIndex, ArrayRef< StringRef > BitcodeLibFuncs)
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::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 bool RemoveFileOnSignal(StringRef Filename, std::string *ErrMsg=nullptr)
This function registers signal handlers to ensure that if a signal gets delivered that the named file...
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"))
LLVM_ABI void runWholeProgramDevirtOnIndex(ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Perform index-based whole program devirtualization on the Summary index.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
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.
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.
scope_exit(Callable) -> scope_exit< Callable >
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 updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
std::function< void(unsigned Task, const Twine &ModuleName, std::unique_ptr< MemoryBuffer > MB)> AddBufferFn
This type defines the callback to add a pre-existing file (e.g.
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.
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.
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.
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.
cl::opt< bool > AlwaysRenamePromotedLocals
FIXME: The current optimization that avoids unnecessary renaming of promoted locals is incompatible w...
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.
void consumeError(Error Err)
Consume a Error without doing anything.
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 thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
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
LLVM_ABI RTLIB::LibcallImpl getSupportedLibcallImpl(StringRef FuncName) const
Check if this is valid libcall for the current module, otherwise RTLIB::Unsupported.
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.