128#define DEBUG_TYPE "wholeprogramdevirt"
130STATISTIC(NumDevirtTargets,
"Number of whole program devirtualization targets");
131STATISTIC(NumSingleImpl,
"Number of single implementation devirtualizations");
133STATISTIC(NumUniformRetVal,
"Number of uniform return value optimizations");
134STATISTIC(NumUniqueRetVal,
"Number of unique return value optimizations");
136 "Number of 1 bit virtual constant propagations");
137STATISTIC(NumVirtConstProp,
"Number of virtual constant propagations");
139 "Controls how many calls should be devirtualized.");
143 std::vector<GlobPattern> Patterns;
144 template <
class T>
void init(
const T &StringList) {
145 for (
const auto &S : StringList)
147 Patterns.push_back(std::move(*Pat));
149 bool match(StringRef S) {
150 for (
const GlobPattern &
P : Patterns)
163 bool IsAfter, uint64_t
Size) {
165 uint64_t MinByte = 0;
168 MinByte = std::max(MinByte,
Target.minAfterBytes());
170 MinByte = std::max(MinByte,
Target.minBeforeBytes());
193 std::vector<ArrayRef<uint8_t>> Used;
196 :
Target.TM->Bits->Before.BytesUsed;
197 uint64_t
Offset = IsAfter ? MinByte -
Target.minAfterBytes()
198 : MinByte -
Target.minBeforeBytes();
208 for (
unsigned I = 0;; ++
I) {
210 for (
auto &&
B : Used)
213 if (BitsUsed != 0xff)
219 for (
unsigned I = 0;; ++
I) {
220 for (
auto &&
B : Used) {
222 while ((
I + Byte) <
B.size() && Byte < (
Size / 8)) {
238 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
240 OffsetByte = -(AllocBefore / 8 + 1);
242 OffsetByte = -((AllocBefore + 7) / 8 + (
BitWidth + 7) / 8);
243 OffsetBit = AllocBefore % 8;
247 Target.setBeforeBit(AllocBefore);
255 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
257 OffsetByte = AllocAfter / 8;
259 OffsetByte = (AllocAfter + 7) / 8;
260 OffsetBit = AllocAfter % 8;
264 Target.setAfterBit(AllocAfter);
293 const VTableSlot &RHS) {
294 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
305 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
326 if (!Summary->isLive())
329 if (!FS->fflags().MustBeUnreachable)
344struct VirtualCallSite {
351 unsigned *NumUnsafeUses =
nullptr;
354 emitRemark(
const StringRef OptName,
const StringRef TargetName,
355 function_ref<OptimizationRemarkEmitter &(
Function &)> OREGetter) {
361 OREGetter(*F).emit(OptimizationRemark(
DEBUG_TYPE, OptName, DLoc,
Block)
362 <<
NV(
"Optimization", OptName)
363 <<
": devirtualized a call to "
364 <<
NV(
"FunctionName", TargetName));
367 void replaceAndErase(
368 const StringRef OptName,
const StringRef TargetName,
bool RemarksEnabled,
369 function_ref<OptimizationRemarkEmitter &(
Function &)> OREGetter,
376 II->getUnwindDest()->removePredecessor(
II->getParent());
393 std::vector<VirtualCallSite> CallSites;
402 bool AllCallSitesDevirted =
true;
411 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
415 std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers;
417 bool isExported()
const {
418 return !SummaryTypeCheckedLoadUsers.empty() ||
419 !SummaryTypeTestAssumeUsers.empty();
422 void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
423 SummaryTypeCheckedLoadUsers.push_back(FS);
424 AllCallSitesDevirted =
false;
427 void addSummaryTypeTestAssumeUser(FunctionSummary *FS) {
428 SummaryTypeTestAssumeUsers.push_back(FS);
429 AllCallSitesDevirted =
false;
432 void markDevirt() { AllCallSitesDevirted =
true; }
436struct VTableSlotInfo {
443 std::map<std::vector<uint64_t>,
CallSiteInfo> ConstCSInfo;
445 void addCallSite(
Value *VTable, CallBase &CB,
unsigned *NumUnsafeUses);
451CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallBase &CB) {
452 std::vector<uint64_t>
Args;
454 if (!CBType || CBType->getBitWidth() > 64 || CB.
arg_empty())
458 if (!CI || CI->getBitWidth() > 64)
460 Args.push_back(CI->getZExtValue());
462 return ConstCSInfo[
Args];
465void VTableSlotInfo::addCallSite(
Value *VTable, CallBase &CB,
466 unsigned *NumUnsafeUses) {
467 auto &CSI = findCallSiteInfo(CB);
468 CSI.AllCallSitesDevirted =
false;
469 CSI.CallSites.push_back({
VTable, CB, NumUnsafeUses});
473 const IPOOptions &Opts;
478 ModuleSummaryIndex *
const ExportSummary;
479 const ModuleSummaryIndex *
const ImportSummary;
481 IntegerType *
const Int8Ty;
483 IntegerType *
const Int32Ty;
484 IntegerType *
const Int64Ty;
491 const bool RemarksEnabled;
492 std::function<OptimizationRemarkEmitter &(
Function &)> OREGetter;
493 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
498 SmallPtrSet<CallBase *, 8> OptimizedCalls;
512 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
513 PatternList FunctionsToSkip;
515 const bool DevirtSpeculatively;
517 ModuleSummaryIndex *ExportSummary,
518 const ModuleSummaryIndex *ImportSummary,
519 bool DevirtSpeculatively)
522 ExportSummary(ExportSummary), ImportSummary(ImportSummary),
529 RemarksEnabled(areRemarksEnabled()),
530 OREGetter([&](
Function &
F) -> OptimizationRemarkEmitter & {
534 DevirtSpeculatively ||
536 assert(!(ExportSummary && ImportSummary));
537 FunctionsToSkip.init(Opts.wholeprogramdevirt_skip);
540 bool areRemarksEnabled();
543 scanTypeTestUsers(
Function *TypeTestFunc,
544 DenseMap<
Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
545 void scanTypeCheckedLoadUsers(
Function *TypeCheckedLoadFunc);
547 void buildTypeIdentifierMap(
548 std::vector<VTableBits> &Bits,
549 DenseMap<
Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
551 bool tryFindVirtualCallTargets(
552 std::vector<VirtualCallTarget> &TargetsForSlot,
553 const std::set<TypeMemberInfo> &TypeMemberInfos,
uint64_t ByteOffset,
554 ModuleSummaryIndex *ExportSummary,
bool &HasPublicTarget);
556 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
557 bool HasPublicTarget,
bool &IsExported);
558 bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary,
560 VTableSlotInfo &SlotInfo,
561 WholeProgramDevirtResolution *Res,
562 bool HasPublicTarget);
564 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
Function &JT,
567 VTableSlotInfo &SlotInfo,
568 WholeProgramDevirtResolution *Res, VTableSlot Slot);
570 bool tryEvaluateFunctionsWithArgs(
572 ArrayRef<uint64_t> Args);
574 void applyUniformRetValOpt(
CallSiteInfo &CSInfo, StringRef FnName,
578 WholeProgramDevirtResolution::ByArg *Res);
582 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
585 bool shouldExportConstantsAsAbsoluteSymbols();
590 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
592 void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
593 uint32_t Const, uint32_t &Storage);
597 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
599 Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
600 StringRef Name, IntegerType *IntTy,
603 Constant *getMemberAddr(
const TypeMemberInfo *M);
605 void applyUniqueRetValOpt(
CallSiteInfo &CSInfo, StringRef FnName,
bool IsOne,
606 Constant *UniqueMemberAddr);
607 bool tryUniqueRetValOpt(
unsigned BitWidth,
610 WholeProgramDevirtResolution::ByArg *Res,
611 VTableSlot Slot, ArrayRef<uint64_t> Args);
613 void applyVirtualConstProp(
CallSiteInfo &CSInfo, StringRef FnName,
614 Constant *Byte, Constant *Bit);
616 VTableSlotInfo &SlotInfo,
617 WholeProgramDevirtResolution *Res, VTableSlot Slot);
619 void rebuildGlobal(VTableBits &
B);
622 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
626 void removeRedundantTypeTests();
633 static ValueInfo lookUpFunctionValueInfo(
Function *TheFn,
634 ModuleSummaryIndex *ExportSummary);
645 ModuleSummaryIndex *ExportSummary);
650 bool DevirtSpeculatively);
654 const IPOOptions &Opts;
655 ModuleSummaryIndex &ExportSummary;
658 std::set<GlobalValue::GUID> &ExportedGUIDs;
662 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap;
667 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr;
669 MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots;
671 PatternList FunctionsToSkip;
675 const bool DevirtSpeculatively;
678 const IPOOptions &Opts, ModuleSummaryIndex &ExportSummary,
679 std::set<GlobalValue::GUID> &ExportedGUIDs,
680 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap,
681 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr)
682 : Opts(Opts), ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs),
683 LocalWPDTargetsMap(LocalWPDTargetsMap),
684 ExternallyVisibleSymbolNamesPtr(ExternallyVisibleSymbolNamesPtr),
685 DevirtSpeculatively(ExportSummary.withSpeculativeDevirt()) {
686 FunctionsToSkip.init(Opts.wholeprogramdevirt_skip);
689 bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot,
691 uint64_t ByteOffset,
bool &HasPublicTarget);
694 VTableSlotSummary &SlotSummary,
695 VTableSlotInfo &SlotInfo,
696 WholeProgramDevirtResolution *Res,
697 std::set<ValueInfo> &DevirtTargets,
698 bool HasPublicTarget);
706 const bool DevirtualizeSpeculatively =
715 if (!DevirtModule::runForTesting(M,
MAM, DevirtualizeSpeculatively))
723 std::optional<ModuleSummaryIndex> Index;
741 bool WholeProgramVisibilityEnabledInLTO) {
742 const IPOOptions &Opts = LibraryOptions.
get<IPOOptions>();
743 return (WholeProgramVisibilityEnabledInLTO ||
744 Opts.whole_program_visibility) &&
745 !Opts.disable_whole_program_visibility;
754 if (
TypeID.ends_with(
".virtual"))
760 if (!
TypeID.consume_front(
"_ZTS"))
768 std::string TypeInfo = (
"_ZTI" +
TypeID).str();
769 return IsVisibleToRegularObj(TypeInfo);
778 for (
auto *
Type : Types)
781 IsVisibleToRegularObj);
790 Module &M,
bool WholeProgramVisibilityEnabledInLTO,
792 bool ValidateAllVtablesHaveTypeInfos,
795 WholeProgramVisibilityEnabledInLTO))
811 !(ValidateAllVtablesHaveTypeInfos &&
818 bool WholeProgramVisibilityEnabledInLTO,
819 bool DevirtSpeculativelyInIndex) {
823 if (!PublicTypeTestFunc)
826 WholeProgramVisibilityEnabledInLTO)) {
832 TypeTestFunc, {CI->getArgOperand(0), CI->getArgOperand(1)}, {},
"",
834 CI->replaceAllUsesWith(NewCI);
835 CI->eraseFromParent();
837 }
else if (!DevirtSpeculativelyInIndex &&
846 CI->replaceAllUsesWith(
True);
847 CI->eraseFromParent();
858 for (
const auto &TypeID : Index.typeIdCompatibleVtableMap()) {
861 VisibleToRegularObjSymbols.
insert(
P.VTableVI.getGUID());
870 bool WholeProgramVisibilityEnabledInLTO,
874 WholeProgramVisibilityEnabledInLTO))
876 for (
auto &
P : Index) {
879 if (DynamicExportSymbols.
count(
P.first))
885 if (VisibleToRegularObjSymbols.
count(
P.first))
887 for (
auto &S :
P.second.getSummaryList()) {
900 std::map<
ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap,
902 const IPOOptions &Opts = LibraryOptions.
get<IPOOptions>();
907 if (Opts.devirtualize_speculatively)
908 Summary.setWithSpeculativeDevirt();
909 DevirtIndex(Opts, Summary, ExportedGUIDs, LocalWPDTargetsMap,
910 ExternallyVisibleSymbolNamesPtr)
917 std::map<
ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap,
919 for (
auto &
T : LocalWPDTargetsMap) {
922 assert(VI.getSummaryList().size() == 1 &&
923 "Devirt of local target has more than one copy");
924 auto &S = VI.getSummaryList()[0];
925 if (!IsExported(S->modulePath(), VI))
929 for (
auto &SlotSummary :
T.second) {
930 auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID);
932 auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset);
933 assert(WPDRes != TIdSum->WPDRes.end());
934 if (ExternallyVisibleSymbolNamesPtr)
935 ExternallyVisibleSymbolNamesPtr->
insert(WPDRes->second.SingleImplName);
937 WPDRes->second.SingleImplName,
938 Summary.getModuleHash(S->modulePath()));
949 const auto &ModPaths = Summary->modulePaths();
954 "combined summary should contain Regular LTO module");
959 bool DevirtSpeculatively) {
961 StringRef ReadSummary = Opts.wholeprogramdevirt_read_summary;
962 StringRef WriteSummary = Opts.wholeprogramdevirt_write_summary;
964 std::unique_ptr<ModuleSummaryIndex>
Summary =
965 std::make_unique<ModuleSummaryIndex>(
false);
969 if (!ReadSummary.
empty()) {
970 ExitOnError ExitOnErr(
971 (
"-wholeprogramdevirt-read-summary: " + ReadSummary +
": ").str());
972 auto ReadSummaryFile =
974 if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr =
976 Summary = std::move(*SummaryOrErr);
981 yaml::Input
In(ReadSummaryFile->getBuffer());
995 if (!WriteSummary.
empty()) {
996 ExitOnError ExitOnErr(
997 (
"-wholeprogramdevirt-write-summary: " + WriteSummary +
": ").str());
1006 yaml::Output
Out(OS);
1014void DevirtModule::buildTypeIdentifierMap(
1015 std::vector<VTableBits> &Bits,
1016 DenseMap<
Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
1017 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
1018 Bits.reserve(
M.global_size());
1020 for (GlobalVariable &GV :
M.globals()) {
1028 Bits.emplace_back();
1029 Bits.back().GV = &GV;
1030 Bits.back().ObjectSize =
1032 BitsPtr = &
Bits.back();
1035 for (MDNode *
Type : Types) {
1048bool DevirtModule::tryFindVirtualCallTargets(
1049 std::vector<VirtualCallTarget> &TargetsForSlot,
1050 const std::set<TypeMemberInfo> &TypeMemberInfos,
uint64_t ByteOffset,
1051 ModuleSummaryIndex *ExportSummary,
bool &HasPublicTarget) {
1052 HasPublicTarget =
false;
1055 if (!TM.Bits->GV->isConstant())
1058 if (TM.Bits->GV->getVCallVisibility() ==
1060 HasPublicTarget =
true;
1061 if (!DevirtSpeculatively)
1067 if (TM.Bits->GV->hasLocalLinkage() && TM.Bits->GV->hasZeroLiveUses())
1078 if (FunctionsToSkip.match(Fn->
getName()))
1083 if (Fn->
getName() ==
"__cxa_pure_virtual")
1088 if (!Opts.wholeprogramdevirt_keep_unreachable_function &&
1097 if (!GA->isInterposable() && !GA->getAliaseeObject()->isInterposable())
1099 TargetsForSlot.push_back({GV, &TM});
1105 if (HasPublicTarget) {
1119 return !TargetsForSlot.empty();
1122bool DevirtIndex::tryFindVirtualCallTargets(
1123 std::vector<ValueInfo> &TargetsForSlot,
1125 bool &HasPublicTarget) {
1126 HasPublicTarget =
false;
1128 for (
const TypeIdOffsetVtableInfo &
P : TIdInfo) {
1139 if (
P.VTableVI.hasLocal() &&
P.VTableVI.getSummaryList().size() > 1)
1141 const GlobalVarSummary *
VS =
nullptr;
1142 for (
const auto &S :
P.VTableVI.getSummaryList()) {
1144 if (!CurVS->vTableFuncs().empty() ||
1157 HasPublicTarget =
true;
1158 if (!DevirtSpeculatively)
1170 for (
auto VTP :
VS->vTableFuncs()) {
1171 if (VTP.VTableOffset !=
P.AddressPointOffset + ByteOffset)
1174 if (!Opts.wholeprogramdevirt_keep_unreachable_function &&
1178 TargetsForSlot.push_back(VTP.FuncVI);
1183 return !TargetsForSlot.empty();
1186void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
1187 Constant *TheFn,
bool HasPublicTarget,
1194 for (
auto &&VCallSite : CSInfo.CallSites) {
1195 if (!OptimizedCalls.
insert(&VCallSite.CB).second)
1203 VCallSite.emitRemark(
"single-impl",
1206 auto &CB = VCallSite.CB;
1219 MDBuilder(
M.getContext()).createUnlikelyBranchWeights());
1220 Builder.SetInsertPoint(ThenTerm);
1223 auto *CallTrap = Builder.CreateCall(TrapFn);
1234 MDBuilder MDB(
M.getContext());
1237 CB, InstrProfValueKind::IPVK_IndirectCallTarget,
1238 std::numeric_limits<uint32_t>::max(), TotalCount);
1239 MDNode *Weights =
nullptr;
1240 if (ValueData.
empty() || TotalCount == 0) {
1241 Weights = MDB.createLikelyBranchWeights();
1244 auto It =
llvm::find_if(ValueData, [&](
const InstrProfValueData &VD) {
1245 return VD.Value == TargetGUID;
1247 if (It == ValueData.
end()) {
1248 Weights = MDB.createLikelyBranchWeights();
1251 TotalCount - std::min(TotalCount, It->Count);
1252 assert((FallbackCount != 0 || It->Count != 0) &&
1253 "devirt branch weights are both zero.");
1255 MDB.createBranchWeights(
fitWeights({It->Count, FallbackCount}));
1266 NewInst.
setMetadata(LLVMContext::MD_prof,
nullptr);
1267 NewInst.
setMetadata(LLVMContext::MD_callees,
nullptr);
1277 assert(!HasPublicTarget);
1290 CallsWithPtrAuthBundleRemoved.
push_back(&CB);
1294 if (VCallSite.NumUnsafeUses)
1295 --*VCallSite.NumUnsafeUses;
1298 if (CSInfo.isExported())
1300 if (!HasPublicTarget &&
1302 CSInfo.markDevirt();
1304 Apply(SlotInfo.CSInfo);
1305 for (
auto &
P : SlotInfo.ConstCSInfo)
1311 if (Callee.getSummaryList().empty())
1318 bool IsExported =
false;
1319 auto &S = Callee.getSummaryList()[0];
1321 auto AddCalls = [&](CallSiteInfo &CSInfo) {
1322 for (
auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) {
1323 FS->addCall({Callee, CI});
1324 IsExported |= S->modulePath() != FS->modulePath();
1326 for (
auto *FS : CSInfo.SummaryTypeTestAssumeUsers) {
1327 FS->addCall({Callee, CI});
1328 IsExported |= S->modulePath() != FS->modulePath();
1331 AddCalls(SlotInfo.CSInfo);
1332 for (
auto &
P : SlotInfo.ConstCSInfo)
1337bool DevirtModule::trySingleImplDevirt(
1338 ModuleSummaryIndex *ExportSummary,
1340 WholeProgramDevirtResolution *Res,
bool HasPublicTarget) {
1343 auto *TheFn = TargetsForSlot[0].Fn;
1344 for (
auto &&Target : TargetsForSlot)
1350 TargetsForSlot[0].WasDevirt =
true;
1352 bool IsExported =
false;
1353 applySingleImplDevirt(SlotInfo, TheFn, HasPublicTarget, IsExported);
1360 if (TheFn->hasLocalLinkage()) {
1361 std::string NewName = (TheFn->
getName() +
".llvm.merged").str();
1366 if (Comdat *
C = TheFn->getComdat()) {
1367 if (
C->getName() == TheFn->
getName()) {
1368 Comdat *NewC =
M.getOrInsertComdat(NewName);
1370 for (GlobalObject &GO :
M.global_objects())
1371 if (GO.getComdat() ==
C)
1380 if (ValueInfo TheFnVI = ExportSummary->
getValueInfo(TheFn->getGUID()))
1385 if (HasPublicTarget)
1396 VTableSlotSummary &SlotSummary,
1397 VTableSlotInfo &SlotInfo,
1398 WholeProgramDevirtResolution *Res,
1399 std::set<ValueInfo> &DevirtTargets,
1400 bool HasPublicTarget) {
1403 auto TheFn = TargetsForSlot[0];
1404 for (
auto &&Target : TargetsForSlot)
1405 if (TheFn != Target)
1409 auto Size = TheFn.getSummaryList().size();
1415 if (FunctionsToSkip.match(TheFn.name()))
1420 if (TheFn.hasLocal() &&
Size > 1)
1425 DevirtTargets.insert(TheFn);
1427 auto &S = TheFn.getSummaryList()[0];
1428 bool IsExported =
addCalls(SlotInfo, TheFn);
1430 ExportedGUIDs.insert(TheFn.getGUID());
1434 if (HasPublicTarget)
1444 if (ExternallyVisibleSymbolNamesPtr)
1445 ExternallyVisibleSymbolNamesPtr->insert(TheFn.name());
1447 TheFn.name(), ExportSummary.
getModuleHash(S->modulePath()));
1449 LocalWPDTargetsMap[TheFn].push_back(SlotSummary);
1463void DevirtModule::tryICallBranchFunnel(
1465 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1466 Triple
T(
M.getTargetTriple());
1470 if (TargetsForSlot.
size() > Opts.wholeprogramdevirt_branch_funnel_threshold)
1473 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
1475 for (
auto &
P : SlotInfo.ConstCSInfo)
1476 if (!
P.second.AllCallSitesDevirted) {
1477 HasNonDevirt =
true;
1495 for (
auto &
T : TargetsForSlot) {
1496 if (
T.TM->Bits->GV->hasAvailableExternallyLinkage())
1505 M.getDataLayout().getProgramAddressSpace(),
1506 getGlobalName(Slot, {},
"branch_funnel"), &
M);
1510 M.getDataLayout().getProgramAddressSpace(),
1511 "branch_funnel", &M);
1515 std::vector<Value *> JTArgs;
1517 for (
auto &
T : TargetsForSlot) {
1518 JTArgs.push_back(getMemberAddr(
T.TM));
1519 JTArgs.push_back(
T.Fn);
1524 &M, llvm::Intrinsic::icall_branch_funnel, {});
1530 bool IsExported =
false;
1531 applyICallBranchFunnel(SlotInfo, *JT, IsExported);
1541void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
1543 DenseMap<Function *, double> FunctionEntryCounts;
1545 if (CSInfo.isExported())
1547 if (CSInfo.AllCallSitesDevirted)
1550 std::map<CallBase *, CallBase *> CallBases;
1551 for (
auto &&VCallSite : CSInfo.CallSites) {
1552 CallBase &CB = VCallSite.CB;
1554 if (CallBases.find(&CB) != CallBases.end()) {
1571 VCallSite.emitRemark(
"branch-funnel", JT.
getName(), OREGetter);
1575 std::vector<Type *> NewArgs;
1576 NewArgs.push_back(Int8PtrTy);
1578 FunctionType *NewFT =
1582 std::vector<Value *>
Args;
1583 Args.push_back(VCallSite.VTable);
1586 CallBase *NewCS =
nullptr;
1592 auto EC = BFI.getBlockFreq(&
F.getEntryBlock());
1593 auto CC =
F.getEntryCount();
1594 double CallCount = 0.0;
1595 if (
EC.getFrequency() != 0 &&
CC && *
CC != 0) {
1597 static_cast<double>(
1598 BFI.getBlockFreq(CB.
getParent()).getFrequency()) /
1600 CallCount = CallFreq * *
CC;
1602 FunctionEntryCounts[&JT] += CallCount;
1605 NewCS = IRB.CreateCall(NewFT, &JT, Args);
1613 std::vector<AttributeSet> NewArgAttrs;
1616 M.getContext(), Attribute::Nest)}));
1617 for (
unsigned I = 0;
I + 2 <
Attrs.getNumAttrSets(); ++
I)
1618 NewArgAttrs.push_back(
Attrs.getParamAttrs(
I));
1620 AttributeList::get(
M.getContext(),
Attrs.getFnAttrs(),
1621 Attrs.getRetAttrs(), NewArgAttrs));
1623 CallBases[&CB] = NewCS;
1626 if (VCallSite.NumUnsafeUses)
1627 --*VCallSite.NumUnsafeUses;
1634 for (
auto &[Old, New] : CallBases) {
1635 Old->replaceAllUsesWith(New);
1636 Old->eraseFromParent();
1639 Apply(SlotInfo.CSInfo);
1640 for (
auto &
P : SlotInfo.ConstCSInfo)
1642 for (
auto &[
F,
C] : FunctionEntryCounts) {
1644 "Unexpected entry count for funnel that was freshly synthesized");
1645 F->setEntryCount(
static_cast<uint64_t>(std::round(
C)));
1649bool DevirtModule::tryEvaluateFunctionsWithArgs(
1651 ArrayRef<uint64_t> Args) {
1665 Evaluator Eval(
M.getDataLayout(),
nullptr);
1669 for (
unsigned I = 0;
I !=
Args.size(); ++
I) {
1674 EvalArgs.
push_back(ConstantInt::get(ArgTy, Args[
I]));
1678 if (!Eval.EvaluateFunction(Fn, RetVal, EvalArgs) ||
1686void DevirtModule::applyUniformRetValOpt(
CallSiteInfo &CSInfo, StringRef FnName,
1688 for (
auto Call : CSInfo.CallSites) {
1692 Call.replaceAndErase(
1693 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
1696 CSInfo.markDevirt();
1699bool DevirtModule::tryUniformRetValOpt(
1701 WholeProgramDevirtResolution::ByArg *Res) {
1704 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
1706 if (
Target.RetVal != TheRetVal)
1709 if (CSInfo.isExported()) {
1711 Res->
Info = TheRetVal;
1714 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->
getName(), TheRetVal);
1716 for (
auto &&Target : TargetsForSlot)
1721std::string DevirtModule::getGlobalName(VTableSlot Slot,
1722 ArrayRef<uint64_t> Args,
1724 std::string FullName =
"__typeid_";
1725 raw_string_ostream OS(FullName);
1726 OS << cast<MDString>(
Slot.TypeID)->getString() <<
'_' <<
Slot.ByteOffset;
1733bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1734 Triple
T(
M.getTargetTriple());
1738void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1739 StringRef Name, Constant *
C) {
1741 getGlobalName(Slot, Args, Name),
C, &M);
1745void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1746 StringRef Name, uint32_t Const,
1747 uint32_t &Storage) {
1748 if (shouldExportConstantsAsAbsoluteSymbols()) {
1758Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1760 GlobalVariable *GV =
1761 M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Arr0Ty);
1766Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1767 StringRef Name, IntegerType *IntTy,
1769 if (!shouldExportConstantsAsAbsoluteSymbols())
1770 return ConstantInt::get(IntTy, Storage);
1772 Constant *
C = importGlobal(Slot, Args, Name);
1778 if (GV->
hasMetadata(LLVMContext::MD_absolute_symbol))
1788 if (AbsWidth ==
IntPtrTy->getBitWidth()) {
1792 SetAbsRange(0, 1ull << AbsWidth);
1797void DevirtModule::applyUniqueRetValOpt(
CallSiteInfo &CSInfo, StringRef FnName,
1799 Constant *UniqueMemberAddr) {
1800 for (
auto &&
Call : CSInfo.CallSites) {
1806 B.CreateBitCast(UniqueMemberAddr,
Call.VTable->
getType()));
1809 Call.replaceAndErase(
"unique-ret-val", FnName, RemarksEnabled, OREGetter,
1812 CSInfo.markDevirt();
1817 ConstantInt::get(Int64Ty,
M->Offset));
1820bool DevirtModule::tryUniqueRetValOpt(
1822 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1823 VTableSlot Slot, ArrayRef<uint64_t> Args) {
1825 auto tryUniqueRetValOptFor = [&](
bool IsOne) {
1828 if (
Target.RetVal == (IsOne ? 1 : 0)) {
1831 UniqueMember =
Target.TM;
1839 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
1840 if (CSInfo.isExported()) {
1844 exportGlobal(Slot, Args,
"unique_member", UniqueMemberAddr);
1848 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->
getName(), IsOne,
1853 for (
auto &&Target : TargetsForSlot)
1860 if (tryUniqueRetValOptFor(
true))
1862 if (tryUniqueRetValOptFor(
false))
1868void DevirtModule::applyVirtualConstProp(
CallSiteInfo &CSInfo, StringRef FnName,
1869 Constant *Byte, Constant *Bit) {
1870 for (
auto Call : CSInfo.CallSites) {
1875 Value *Addr =
B.CreatePtrAddWithSExtOrTrunc(
Call.VTable, Byte);
1876 if (RetType->getBitWidth() == 1) {
1878 Value *BitsAndBit =
B.CreateAnd(Bits, Bit);
1879 auto IsBitSet =
B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1880 NumVirtConstProp1Bit++;
1881 Call.replaceAndErase(
"virtual-const-prop-1-bit", FnName, RemarksEnabled,
1882 OREGetter, IsBitSet);
1884 Value *Val =
B.CreateLoad(RetType, Addr);
1886 Call.replaceAndErase(
"virtual-const-prop", FnName, RemarksEnabled,
1890 CSInfo.markDevirt();
1893bool DevirtModule::tryVirtualConstProp(
1895 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1906 unsigned BitWidth = RetType->getBitWidth();
1918 Align TypeAlignment =
M.getDataLayout().getABIIntegerTypeAlignment(
BitWidth);
1951 GlobalVariable *GV =
Target.TM->Bits->GV;
1952 Align TableAlignment =
M.getDataLayout().getValueOrABITypeAlignment(
1954 if (TypeAlignment > TableAlignment)
1958 for (
auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
1959 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1962 WholeProgramDevirtResolution::ByArg *ResByArg =
nullptr;
1964 ResByArg = &Res->
ResByArg[CSByConstantArg.first];
1966 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
1969 if (tryUniqueRetValOpt(
BitWidth, TargetsForSlot, CSByConstantArg.second,
1970 ResByArg, Slot, CSByConstantArg.first))
1985 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1986 for (
auto &&Target : TargetsForSlot) {
1987 TotalPaddingBefore += std::max<int64_t>(
1988 (AllocBefore + 7) / 8 -
Target.allocatedBeforeBytes() - 1, 0);
1989 TotalPaddingAfter += std::max<int64_t>(
1990 (AllocAfter + 7) / 8 -
Target.allocatedAfterBytes() - 1, 0);
1995 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
2002 if (TotalPaddingBefore <= TotalPaddingAfter)
2018 for (
auto &&Target : TargetsForSlot)
2022 if (CSByConstantArg.second.isExported()) {
2024 ResByArg->
Byte = OffsetByte;
2025 exportConstant(Slot, CSByConstantArg.first,
"bit", 1ULL << OffsetBit,
2031 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
2032 applyVirtualConstProp(CSByConstantArg.second,
2033 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
2039 if (
B.Before.Bytes.empty() &&
B.After.Bytes.empty())
2045 B.GV->getAlign(),
B.GV->getValueType());
2046 B.Before.Bytes.resize(
alignTo(
B.Before.Bytes.size(), Alignment));
2049 for (
size_t I = 0,
Size =
B.Before.Bytes.size();
I !=
Size / 2; ++
I)
2056 B.GV->getInitializer(),
2059 new GlobalVariable(M, NewInit->getType(),
B.GV->isConstant(),
2061 NewGV->setSection(
B.GV->getSection());
2062 NewGV->setComdat(
B.GV->getComdat());
2063 NewGV->setAlignment(
B.GV->getAlign());
2067 NewGV->copyMetadata(
B.GV,
B.Before.Bytes.size());
2072 B.GV->getInitializer()->getType(), 0,
B.GV->getLinkage(),
"",
2074 M.getDataLayout(), NewInit->getType(), NewGV,
2075 {ConstantInt::get(Int32Ty, 0), ConstantInt::get(Int32Ty, 1)},
2078 Alias->setVisibility(
B.GV->getVisibility());
2079 Alias->takeName(
B.GV);
2081 B.GV->replaceAllUsesWith(Alias);
2082 B.GV->eraseFromParent();
2085bool DevirtModule::areRemarksEnabled() {
2086 const auto &FL =
M.getFunctionList();
2091 return DI.isEnabled();
2121 if (
Value *
Merge = GetMergeUser(U, &TypeTest))
2124 while (!Worklist.
empty()) {
2126 if (!VisitedMerges.
insert(
V).second)
2129 for (
User *U :
V->users()) {
2131 if (Assume->getArgOperand(0) ==
V) {
2133 "assume must not be both direct and merged");
2145void DevirtModule::scanTypeTestUsers(
2147 DenseMap<
Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
2150 SmallPtrSet<Value *, 8> VisitedMerges;
2165 auto &DT =
FAM.
getResult<DominatorTreeAnalysis>(*CI->getFunction());
2171 if (!Assumes.
empty()) {
2172 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
2173 for (DevirtCallSite
Call : DevirtCalls)
2174 CallSlots[{TypeId,
Call.Offset}].addCallSite(Ptr,
Call.CB,
nullptr);
2177 auto RemoveTypeTestAssumes = [&]() {
2185 for (
auto *Assume : Assumes)
2186 Assume->eraseFromParent();
2189 if (CI->use_empty())
2190 CI->eraseFromParent();
2205 if (!TypeIdMap.count(TypeId))
2206 RemoveTypeTestAssumes();
2218 const TypeIdSummary *TidSummary =
2221 RemoveTypeTestAssumes();
2230void DevirtModule::scanTypeCheckedLoadUsers(
Function *TypeCheckedLoadFunc) {
2239 Value *Ptr = CI->getArgOperand(0);
2241 Value *TypeIdValue = CI->getArgOperand(2);
2247 bool HasNonCallUses =
false;
2248 auto &DT =
FAM.
getResult<DominatorTreeAnalysis>(*CI->getFunction());
2250 HasNonCallUses, CI, DT);
2259 (LoadedPtrs.
size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
2261 Value *LoadedValue =
nullptr;
2263 Intrinsic::type_checked_load_relative) {
2265 &M, Intrinsic::load_relative, {Int32Ty});
2266 LoadedValue = LoadB.CreateCall(LoadRelFunc, {Ptr,
Offset});
2269 LoadedValue = LoadB.CreateLoad(Int8PtrTy,
GEP);
2272 for (Instruction *LoadedPtr : LoadedPtrs) {
2273 LoadedPtr->replaceAllUsesWith(LoadedValue);
2274 LoadedPtr->eraseFromParent();
2278 IRBuilder<> CallB((Preds.
size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
2279 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
2281 for (Instruction *
Pred : Preds) {
2282 Pred->replaceAllUsesWith(TypeTestCall);
2283 Pred->eraseFromParent();
2290 if (!CI->use_empty()) {
2293 Pair =
B.CreateInsertValue(Pair, LoadedValue, {0});
2294 Pair =
B.CreateInsertValue(Pair, TypeTestCall, {1});
2299 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
2300 NumUnsafeUses = DevirtCalls.
size();
2307 for (DevirtCallSite
Call : DevirtCalls) {
2308 CallSlots[{TypeId,
Call.Offset}].addCallSite(Ptr,
Call.CB,
2312 CI->eraseFromParent();
2316void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
2320 const TypeIdSummary *TidSummary =
2324 auto ResI = TidSummary->
WPDRes.find(
Slot.ByteOffset);
2325 if (ResI == TidSummary->
WPDRes.end())
2327 const WholeProgramDevirtResolution &Res = ResI->second;
2334 Value *SingleImplVal =
2339 if (!
A->isInterposable() && !
A->getAliaseeObject()->isInterposable())
2340 SingleImplVal =
A->getAliaseeObject();
2344 bool IsExported =
false;
2345 bool IsSpeculative =
2347 applySingleImplDevirt(SlotInfo, SingleImpl, IsSpeculative, IsExported);
2351 for (
auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
2352 auto I = Res.
ResByArg.find(CSByConstantArg.first);
2355 auto &ResByArg =
I->second;
2362 applyUniformRetValOpt(CSByConstantArg.second,
"", ResByArg.
Info);
2366 importGlobal(Slot, CSByConstantArg.first,
"unique_member");
2367 applyUniqueRetValOpt(CSByConstantArg.second,
"", ResByArg.
Info,
2373 Constant *
Bit = importConstant(Slot, CSByConstantArg.first,
"bit", Int8Ty,
2375 applyVirtualConstProp(CSByConstantArg.second,
"", Byte, Bit);
2387 M.getOrInsertFunction(getGlobalName(Slot, {},
"branch_funnel"),
2390 bool IsExported =
false;
2391 applyICallBranchFunnel(SlotInfo, *JT, IsExported);
2396void DevirtModule::removeRedundantTypeTests() {
2398 for (
auto &&U : NumUnsafeUsesForTypeTest) {
2399 if (
U.second == 0) {
2400 U.first->replaceAllUsesWith(
True);
2401 U.first->eraseFromParent();
2407DevirtModule::lookUpFunctionValueInfo(
Function *TheFn,
2408 ModuleSummaryIndex *ExportSummary) {
2409 assert((ExportSummary !=
nullptr) &&
2410 "Caller guarantees ExportSummary is not nullptr");
2412 const auto TheFnGUID = TheFn->
getGUID();
2413 const auto TheFnGUIDWithExportedName =
2416 ValueInfo TheFnVI = ExportSummary->
getValueInfo(TheFnGUID);
2425 if ((!TheFnVI) && (TheFnGUID != TheFnGUIDWithExportedName)) {
2426 TheFnVI = ExportSummary->
getValueInfo(TheFnGUIDWithExportedName);
2431bool DevirtModule::mustBeUnreachableFunction(
2432 Function *
const F, ModuleSummaryIndex *ExportSummary) {
2434 if (!
F->isDeclaration()) {
2440 return ExportSummary &&
2442 DevirtModule::lookUpFunctionValueInfo(
F, ExportSummary));
2445bool DevirtModule::run() {
2454 Function *PublicTypeTestFunc =
nullptr;
2457 if (DevirtSpeculatively)
2458 PublicTypeTestFunc =
2465 &M, Intrinsic::type_checked_load_relative);
2472 if (!ExportSummary &&
2473 (((!PublicTypeTestFunc || PublicTypeTestFunc->
use_empty()) &&
2474 (!TypeTestFunc || TypeTestFunc->
use_empty())) ||
2475 !AssumeFunc || AssumeFunc->
use_empty()) &&
2476 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->
use_empty()) &&
2477 (!TypeCheckedLoadRelativeFunc ||
2478 TypeCheckedLoadRelativeFunc->
use_empty()))
2482 std::vector<VTableBits>
Bits;
2483 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
2484 buildTypeIdentifierMap(Bits, TypeIdMap);
2486 if (PublicTypeTestFunc && AssumeFunc)
2487 scanTypeTestUsers(PublicTypeTestFunc, TypeIdMap);
2489 if (TypeTestFunc && AssumeFunc)
2490 scanTypeTestUsers(TypeTestFunc, TypeIdMap);
2492 if (TypeCheckedLoadFunc)
2493 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
2495 if (TypeCheckedLoadRelativeFunc)
2496 scanTypeCheckedLoadUsers(TypeCheckedLoadRelativeFunc);
2498 if (ImportSummary) {
2499 for (
auto &S : CallSlots)
2500 importResolution(S.first, S.second);
2502 removeRedundantTypeTests();
2507 for (GlobalVariable &GV :
M.globals())
2515 if (TypeIdMap.
empty())
2519 if (ExportSummary) {
2520 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
2521 for (
auto &
P : TypeIdMap) {
2524 TypeId->getString())]
2528 for (
auto &
P : *ExportSummary) {
2529 for (
auto &S :
P.second.getSummaryList()) {
2534 for (FunctionSummary::VFuncId VF :
FS->type_test_assume_vcalls()) {
2535 for (
Metadata *MD : MetadataByGUID[VF.GUID]) {
2536 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
2539 for (FunctionSummary::VFuncId VF :
FS->type_checked_load_vcalls()) {
2540 for (
Metadata *MD : MetadataByGUID[VF.GUID]) {
2541 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2544 for (
const FunctionSummary::ConstVCall &VC :
2545 FS->type_test_assume_const_vcalls()) {
2546 for (
Metadata *MD : MetadataByGUID[
VC.VFunc.GUID]) {
2547 CallSlots[{MD,
VC.VFunc.Offset}]
2548 .ConstCSInfo[
VC.Args]
2549 .addSummaryTypeTestAssumeUser(FS);
2552 for (
const FunctionSummary::ConstVCall &VC :
2553 FS->type_checked_load_const_vcalls()) {
2554 for (
Metadata *MD : MetadataByGUID[
VC.VFunc.GUID]) {
2555 CallSlots[{MD,
VC.VFunc.Offset}]
2556 .ConstCSInfo[
VC.Args]
2557 .addSummaryTypeCheckedLoadUser(FS);
2565 bool DidVirtualConstProp =
false;
2566 std::map<std::string, GlobalValue *> DevirtTargets;
2567 for (
auto &S : CallSlots) {
2571 std::vector<VirtualCallTarget> TargetsForSlot;
2572 WholeProgramDevirtResolution *Res =
nullptr;
2573 const std::set<TypeMemberInfo> &TypeMemberInfos = TypeIdMap[S.first.TypeID];
2575 TypeMemberInfos.size())
2582 Res = &ExportSummary
2583 ->getOrInsertTypeIdSummary(
2585 .WPDRes[S.first.ByteOffset];
2587 bool HasPublicTarget =
true;
2588 if (tryFindVirtualCallTargets(TargetsForSlot, TypeMemberInfos,
2589 S.first.ByteOffset, ExportSummary,
2591 bool SingleImplDevirt = trySingleImplDevirt(
2592 ExportSummary, TargetsForSlot, S.second, Res, HasPublicTarget);
2593 if (!SingleImplDevirt && !HasPublicTarget) {
2594 DidVirtualConstProp |=
2595 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
2597 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
2602 for (
const auto &
T : TargetsForSlot)
2604 DevirtTargets[std::string(
T.Fn->getName())] =
T.Fn;
2614 auto AddTypeTestsForTypeCheckedLoads = [&](
CallSiteInfo &CSI) {
2615 if (!CSI.AllCallSitesDevirted)
2616 for (
auto *FS : CSI.SummaryTypeCheckedLoadUsers)
2617 FS->addTypeTest(GUID);
2619 AddTypeTestsForTypeCheckedLoads(S.second.CSInfo);
2620 for (
auto &CCS : S.second.ConstCSInfo)
2621 AddTypeTestsForTypeCheckedLoads(CCS.second);
2625 if (RemarksEnabled) {
2627 for (
const auto &DT : DevirtTargets) {
2628 GlobalValue *GV = DT.second;
2637 using namespace ore;
2638 OREGetter(*F).emit(OptimizationRemark(
DEBUG_TYPE,
"Devirtualized",
F)
2639 <<
"devirtualized " <<
NV(
"FunctionName", DT.first));
2643 NumDevirtTargets += DevirtTargets.size();
2645 removeRedundantTypeTests();
2649 if (DidVirtualConstProp)
2656 for (GlobalVariable &GV :
M.globals())
2659 for (
auto *CI : CallsWithPtrAuthBundleRemoved)
2660 CI->eraseFromParent();
2665void DevirtIndex::run() {
2666 if (ExportSummary.typeIdCompatibleVtableMap().empty())
2671 assert(!ExportSummary.withInternalizeAndPromote() &&
2672 "Expect index-based WPD to run before internalization and promotion");
2674 DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID;
2675 for (
const auto &
P : ExportSummary.typeIdCompatibleVtableMap()) {
2684 ExportSummary.getOrInsertTypeIdSummary(
P.first);
2688 for (
auto &
P : ExportSummary) {
2689 for (
auto &S :
P.second.getSummaryList()) {
2694 for (FunctionSummary::VFuncId VF :
FS->type_test_assume_vcalls()) {
2695 for (StringRef Name : NameByGUID[VF.GUID]) {
2696 CallSlots[{
Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
2699 for (FunctionSummary::VFuncId VF :
FS->type_checked_load_vcalls()) {
2700 for (StringRef Name : NameByGUID[VF.GUID]) {
2701 CallSlots[{
Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2704 for (
const FunctionSummary::ConstVCall &VC :
2705 FS->type_test_assume_const_vcalls()) {
2706 for (StringRef Name : NameByGUID[
VC.VFunc.GUID]) {
2707 CallSlots[{
Name,
VC.VFunc.Offset}]
2708 .ConstCSInfo[
VC.Args]
2709 .addSummaryTypeTestAssumeUser(FS);
2712 for (
const FunctionSummary::ConstVCall &VC :
2713 FS->type_checked_load_const_vcalls()) {
2714 for (StringRef Name : NameByGUID[
VC.VFunc.GUID]) {
2715 CallSlots[{
Name,
VC.VFunc.Offset}]
2716 .ConstCSInfo[
VC.Args]
2717 .addSummaryTypeCheckedLoadUser(FS);
2723 std::set<ValueInfo> DevirtTargets;
2725 for (
auto &S : CallSlots) {
2729 std::vector<ValueInfo> TargetsForSlot;
2730 auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID);
2734 WholeProgramDevirtResolution *Res =
2735 &ExportSummary.getTypeIdSummary(S.first.TypeID)
2736 ->WPDRes[S.first.ByteOffset];
2738 bool HasPublicTarget =
true;
2739 if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary,
2740 S.first.ByteOffset, HasPublicTarget)) {
2742 if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res,
2743 DevirtTargets, HasPublicTarget))
2750 if (Opts.wholeprogramdevirt_print_index_based)
2751 for (
const auto &DT : DevirtTargets)
2752 errs() <<
"Devirtualized call to " << DT <<
"\n";
2754 NumDevirtTargets += DevirtTargets.size();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Provides passes for computing function attributes based on interprocedural analyses.
static void emitRemark(const Function &F, OptimizationRemarkEmitter &ORE, bool Skip)
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
SmallVector< MachineOperand, 4 > Cond
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static bool mustBeUnreachableFunction(const Function &F)
This is the interface to build a ModuleSummaryIndex for a module.
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file contains the declarations for profiling metadata utility functions.
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static void findAssumesThroughMergesForTypeTest(SmallVectorImpl< CallInst * > &Assumes, CallInst &TypeTest, SmallPtrSetImpl< Value * > &VisitedMerges)
Find assumes whose conditions depend on this type test through phi or select nodes.
static bool typeIDVisibleToRegularObj(StringRef TypeID, function_ref< bool(StringRef)> IsVisibleToRegularObj)
static bool addCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee)
static bool skipUpdateDueToValidation(GlobalVariable &GV, function_ref< bool(StringRef)> IsVisibleToRegularObj)
static Error checkCombinedSummaryForTesting(const IPOOptions &Opts, ModuleSummaryIndex *Summary)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
void setCallingConv(CallingConv::ID CC)
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
FunctionType * getFunctionType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
void setCalledOperand(Value *V)
static LLVM_ABI CallBase * removeOperandBundle(CallBase *CB, uint32_t ID, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle ID removed.
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void setSelectionKind(SelectionKind Val)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
const Constant * stripPointerCasts() const
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static bool shouldExecute(CounterInfo &Counter)
Implements a dense probed hash-table based set.
Subclass of Error for the sole purpose of identifying the success path in the type system.
Lightweight error class with error context and mandatory checking.
Tagged union holding either a T or a Error.
Type * getParamType(unsigned i) const
Parameter type accessors.
ArrayRef< Type * > params() const
Type * getReturnType() const
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)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
const BasicBlock & front() const
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
std::optional< uint64_t > getEntryCount() const
Get the entry count for this function.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Type * getReturnType() const
Returns the type of the ret val.
unsigned getInstructionCount() const
Returns the number of non-debug IR instructions in this function.
static GEPNoWrapFlags inBounds()
static LLVM_ABI Expected< GlobPattern > create(StringRef Pat, std::optional< size_t > MaxSubPatterns={}, bool SlashAgnostic=false)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
LLVM_ABI VCallVisibility getVCallVisibility() const
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
@ VCallVisibilityLinkageUnit
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
LLVM_ABI void setVCallVisibilityMetadata(VCallVisibility Visibility)
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
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...
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
LLVM_ABI const GlobalObject * getAliaseeObject() const
LLVM_ABI GUID getGUID() const
Return a 64-bit global unique ID for this value.
@ HiddenVisibility
The GV is hidden.
void setVisibility(VisibilityTypes V)
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ InternalLinkage
Rename collisions when linking (static functions).
@ ExternalLinkage
Externally visible function.
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
uint64_t getBitMask() const
Return a bitmask with ones set for all of the bits that can be set by an unsigned version of this typ...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
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,...
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
const TypeIdSummary * getTypeIdSummary(StringRef TypeId) const
This returns either a pointer to the type id summary (if present in the summary map) or null (if not ...
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
static constexpr const char * getRegularLTOModuleName()
bool partiallySplitLTOUnits() const
static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash)
Convenience method for creating a promoted global name for the given value name of a local,...
bool withSpeculativeDevirt() const
A Module instance is used to store all the information related to an LLVM module.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Analysis providing profile information.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Target - Wrapper for Target specific information.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
bool isVoidTy() const
Return true if this is 'void'.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
A Use represents the edge between a Value definition and its users.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
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 const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
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.
const ParentTy * getParent() const
self_iterator getIterator()
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ BasicBlock
Various leaf nodes.
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.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
DiagnosticInfoOptimizationBase::Argument NV
friend class Instruction
Iterator for Instructions in a `BasicBlock.
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
LLVM_ABI uint64_t findLowestOffset(ArrayRef< VirtualCallTarget > Targets, bool IsAfter, uint64_t Size)
LLVM_ABI void setAfterReturnValues(MutableArrayRef< VirtualCallTarget > Targets, uint64_t AllocAfter, unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit)
LLVM_ABI void setBeforeReturnValues(MutableArrayRef< VirtualCallTarget > Targets, uint64_t AllocBefore, unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
LLVM_ABI MemoryEffects computeFunctionBodyMemoryAccess(Function &F, AAResults &AAR)
Returns the memory access properties of this copy of the function.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO, bool DevirtSpeculativelyInIndex=false)
Convert llvm.public.type.test calls to llvm.type.test when whole program visibility is available,...
PassSummaryAction
What to do with the summary when running passes that operate on it.
@ Export
Export information to summary.
@ Import
Import information from summary.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI, std::function< const StackSafetyInfo *(const Function &F)> GetSSICallback=[](const Function &F) -> const StackSafetyInfo *{ return nullptr;})
Direct function to compute a ModuleSummaryIndex from a given module.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
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 Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
const IPOOptions & getIPOOptions(const LLVMContext &C)
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...
LLVM_ABI SmallVector< uint32_t > fitWeights(ArrayRef< uint64_t > Weights)
Push the weights right to fit in uint32_t.
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.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
LLVM_ABI void findDevirtualizableCallsForTypeCheckedLoad(SmallVectorImpl< DevirtCallSite > &DevirtCalls, SmallVectorImpl< Instruction * > &LoadedPtrs, SmallVectorImpl< Instruction * > &Preds, bool &HasNonCallUses, const CallInst *CI, DominatorTree &DT)
Given a call to the intrinsic @llvm.type.checked.load, find all devirtualizable call sites based on t...
LLVM_ABI CallBase & versionCallSite(CallBase &CB, Value *Callee, MDNode *BranchWeights)
Predicate and clone the given call site.
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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_ABI void setExplicitlyUnknownFunctionEntryCount(Function &F, StringRef PassName)
Analogous to setExplicitlyUnknownBranchWeights, but for functions and their entry counts.
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool hasWholeProgramVisibility(const cl::LibraryOptionsContext &LibraryOptions, bool WholeProgramVisibilityEnabledInLTO)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void runWholeProgramDevirtOnIndex(const cl::LibraryOptionsContext &LibraryOptions, ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr)
Perform index-based whole program devirtualization on the Summary index.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI void findDevirtualizableCallsForTypeTest(SmallVectorImpl< DevirtCallSite > &DevirtCalls, SmallVectorImpl< CallInst * > &Assumes, const CallInst *CI, DominatorTree &DT)
Given a call to the intrinsic @llvm.type.test, find all devirtualizable call sites based on the call ...
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...
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
LLVM_ABI void updateVCallVisibilityInIndex(const cl::LibraryOptionsContext &LibraryOptions, ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, const DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
LLVM_ABI std::pair< Function *, Constant * > getFunctionAtVTableOffset(GlobalVariable *GV, uint64_t Offset, Module &M)
Given a vtable and a specified offset, returns the function and the trivial pointer at the specified ...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Class to accumulate and hold information about a callee.
static unsigned getHashValue(const VTableSlotSummary &I)
static bool isEqual(const VTableSlotSummary &LHS, const VTableSlotSummary &RHS)
static bool isEqual(const VTableSlot &LHS, const VTableSlot &RHS)
static unsigned getHashValue(const VTableSlot &I)
An information struct used to provide DenseMap with the various necessary components for a given valu...
The following data structures summarize type metadata information.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
enum llvm::TypeTestResolution::Kind TheKind
Struct that holds a reference to a particular GUID in a global value summary.
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
const ModuleSummaryIndex * ImportSummary
ModuleSummaryIndex * ExportSummary
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName
@ SingleImpl
Single implementation devirtualization.
@ Speculative
Speculative devirtualization.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.
LLVM_ABI VirtualCallTarget(GlobalValue *Fn, const TypeMemberInfo *TM)
const TypeMemberInfo * TM