48#define DEBUG_TYPE "select-optimize"
51 "Number of select groups considered for conversion to branch");
53 "Number of select groups converted due to expensive cold operand");
55 "Number of select groups converted due to high-predictability");
57 "Number of select groups not converted due to unpredictability");
59 "Number of select groups not converted due to cold basic block");
61 "Number of select groups converted due to loop-level analysis");
62STATISTIC(NumSelectsConverted,
"Number of selects converted");
70class SelectOptimizeImpl {
71 const CodeGenOptions *Opts =
nullptr;
72 const TargetMachine *TM =
nullptr;
73 const TargetSubtargetInfo *TSI =
nullptr;
74 const TargetLowering *TLI =
nullptr;
75 const TargetTransformInfo *TTI =
nullptr;
76 const LoopInfo *LI =
nullptr;
77 BlockFrequencyInfo *BFI;
78 ProfileSummaryInfo *PSI =
nullptr;
79 OptimizationRemarkEmitter *ORE =
nullptr;
80 TargetSchedModel TSchedModel;
83 SelectOptimizeImpl() =
default;
84 SelectOptimizeImpl(
const TargetMachine *TM) : TM(TM){};
88 using Scaled64 = ScaledNumber<uint64_t>;
105 bool Inverted =
false;
112 SelectLike(Instruction *I,
bool Inverted =
false,
unsigned CondIdx = 0)
113 : I(I), Inverted(Inverted), CondIdx(CondIdx) {}
120 unsigned getConditionOpIndex() {
return CondIdx; };
126 Value *getTrueValue(
bool HonorInverts =
true)
const {
127 if (Inverted && HonorInverts)
128 return getFalseValue(
false);
130 return Sel->getTrueValue();
142 Value *getFalseValue(
bool HonorInverts =
true)
const {
143 if (Inverted && HonorInverts)
144 return getTrueValue(
false);
146 return Sel->getFalseValue();
151 return BO->getOperand(1 - CondIdx);
159 Scaled64 getOpCostOnBranch(
160 bool IsTrue,
const DenseMap<const Instruction *, CostInfo> &InstCostMap,
161 const TargetTransformInfo *
TTI) {
162 auto *
V = IsTrue ? getTrueValue() : getFalseValue();
165 auto It = InstCostMap.
find(
IV);
166 return It != InstCostMap.
end() ? It->second.NonPredCost
177 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
178 {TTI::OK_UniformConstantValue, TTI::OP_PowerOf2});
181 auto It = InstCostMap.find(OpI);
182 if (It != InstCostMap.end())
183 TotalCost += It->second.NonPredCost;
197 bool isUnpredictable()
const {
198 return any_of(Selects, [](
const SelectLike &SI) {
199 return SI.getI()->getMetadata(LLVMContext::MD_unpredictable);
203 using SelectGroups = SmallVector<SelectGroup, 2>;
213 void optimizeSelectsBase(
Function &
F, SelectGroups &ProfSIGroups);
214 void optimizeSelectsInnerLoops(
Function &
F, SelectGroups &ProfSIGroups);
218 void convertProfitableSIGroups(SelectGroups &ProfSIGroups);
221 void collectSelectGroups(BasicBlock &BB, SelectGroups &SIGroups);
225 void findProfitableSIGroupsBase(SelectGroups &SIGroups,
226 SelectGroups &ProfSIGroups);
227 void findProfitableSIGroupsInnerLoops(
const Loop *L, SelectGroups &SIGroups,
228 SelectGroups &ProfSIGroups);
232 bool isConvertToBranchProfitableBase(
const SelectGroup &ASI);
237 bool hasExpensiveColdOperand(
const SelectGroup &ASI);
243 void getExclBackwardsSlice(Instruction *
I, std::stack<Instruction *> &Slice,
244 Instruction *SI,
bool ForSinking =
false,
245 const SelectGroup *Group =
nullptr);
248 bool isSelectHighlyPredictable(
const SelectLike SI);
252 bool checkLoopHeuristics(
const Loop *L,
const CostInfo LoopDepth[2]);
256 bool computeLoopCosts(
const Loop *L,
const SelectGroups &SIGroups,
257 DenseMap<const Instruction *, CostInfo> &InstCostMap,
261 SmallDenseMap<const Instruction *, SelectLike, 2>
262 getSImap(
const SelectGroups &SIGroups);
266 SmallDenseMap<const Instruction *, const SelectGroup *, 2>
267 getSGmap(
const SelectGroups &SIGroups);
270 std::optional<uint64_t> computeInstCost(
const Instruction *
I);
273 Scaled64 getMispredictionCost(
const SelectLike SI,
const Scaled64 CondCost);
276 Scaled64 getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
277 const SelectLike SI);
280 bool isSelectKindSupported(
const SelectLike SI);
284 SelectOptimizeImpl Impl;
289 SelectOptimize() : FunctionPass(ID) {}
295 return Impl.runOnFunction(
F, *
this);
298 void getAnalysisUsage(AnalysisUsage &AU)
const override {
304 AU.
addRequired<OptimizationRemarkEmitterWrapperPass>();
312 SelectOptimizeImpl Impl(TM);
313 return Impl.run(
F,
FAM);
316char SelectOptimize::ID = 0;
345 if (!
TTI->enableSelectOptimize())
349 .getCachedResult<ProfileSummaryAnalysis>(*
F.getParent());
352 "analysis to be available");
361 TSchedModel.
init(TSI);
382 if (!
TTI->enableSelectOptimize())
389 TSchedModel.
init(TSI);
395 return optimizeSelects(
F);
398bool SelectOptimizeImpl::optimizeSelects(
Function &
F) {
401 SelectGroups ProfSIGroups;
403 optimizeSelectsBase(
F, ProfSIGroups);
405 optimizeSelectsInnerLoops(
F, ProfSIGroups);
409 convertProfitableSIGroups(ProfSIGroups);
412 return !ProfSIGroups.empty();
415void SelectOptimizeImpl::optimizeSelectsBase(
Function &
F,
416 SelectGroups &ProfSIGroups) {
418 SelectGroups SIGroups;
422 if (L &&
L->isInnermost())
424 collectSelectGroups(BB, SIGroups);
428 findProfitableSIGroupsBase(SIGroups, ProfSIGroups);
431void SelectOptimizeImpl::optimizeSelectsInnerLoops(
Function &
F,
432 SelectGroups &ProfSIGroups) {
435 for (
unsigned long i = 0; i <
Loops.size(); ++i)
439 if (!
L->isInnermost())
442 SelectGroups SIGroups;
444 collectSelectGroups(*BB, SIGroups);
446 findProfitableSIGroupsInnerLoops(L, SIGroups, ProfSIGroups);
462 SelectOptimizeImpl::SelectLike &
SI,
bool isTrue,
465 Value *
V = isTrue ?
SI.getTrueValue() :
SI.getFalseValue();
468 if (
auto It = OptSelects.find(
IV); It != OptSelects.end())
469 return isTrue ? It->second.first : It->second.second;
474 assert((BO->getOpcode() == Instruction::Add ||
475 BO->getOpcode() == Instruction::Or ||
476 BO->getOpcode() == Instruction::Sub) &&
477 "Only currently handling Add, Or and Sub binary operators.");
479 auto *CBO = BO->clone();
480 auto CondIdx =
SI.getConditionOpIndex();
483 CBO->setOperand(CondIdx, ConstantInt::get(CBO->getType(), 1));
486 "Unexpected opcode");
490 unsigned OtherIdx = 1 - CondIdx;
492 if (
auto It = OptSelects.find(
IV); It != OptSelects.end())
493 CBO->setOperand(OtherIdx, isTrue ? It->second.first : It->second.second);
495 CBO->insertBefore(
B->getTerminator()->getIterator());
499void SelectOptimizeImpl::convertProfitableSIGroups(SelectGroups &ProfSIGroups) {
500 for (SelectGroup &ASI : ProfSIGroups) {
540 typedef std::stack<Instruction *>::size_type StackSizeType;
541 StackSizeType maxTrueSliceLen = 0, maxFalseSliceLen = 0;
543 bool SelectWithProfileIsInverted =
false;
544 for (SelectLike &
SI : ASI.Selects) {
550 std::stack<Instruction *> TrueSlice;
551 getExclBackwardsSlice(TI, TrueSlice,
SI.getI(),
true, &ASI);
552 maxTrueSliceLen = std::max(maxTrueSliceLen, TrueSlice.size());
557 std::stack<Instruction *> FalseSlice;
558 getExclBackwardsSlice(FI, FalseSlice,
SI.getI(),
true, &ASI);
559 maxFalseSliceLen = std::max(maxFalseSliceLen, FalseSlice.size());
566 if (
hasProfMD(*
SI.getI()) && ASI.Condition == SelectCondition) {
567 SelectWithProfile =
SI.getI();
570 SelectWithProfile =
SI.getI();
571 SelectWithProfileIsInverted =
true;
585 for (StackSizeType IS = 0;
IS < maxTrueSliceLen; ++
IS) {
586 for (
auto &S : TrueSlices) {
588 TrueSlicesInterleaved.
push_back(S.top());
593 for (StackSizeType IS = 0;
IS < maxFalseSliceLen; ++
IS) {
594 for (
auto &S : FalseSlices) {
596 FalseSlicesInterleaved.
push_back(S.top());
603 SelectLike &
SI = ASI.Selects.front();
604 SelectLike &LastSI = ASI.Selects.back();
612 SplitPt.setHeadBit(
true);
621 auto DIt =
SI.getI()->getIterator();
622 auto NIt = ASI.Selects.begin();
623 while (&*DIt != LastSI.getI()) {
624 if (NIt != ASI.Selects.end() && &*DIt == NIt->getI())
630 for (
auto *HI : HoistInstrs)
631 HI->moveBefore(
SI.getI()->getIterator());
648 std::next(LastSI.getI()->getIterator()));
653 BasicBlock *TrueBlock =
nullptr, *FalseBlock =
nullptr;
654 UncondBrInst *TrueBranch =
nullptr, *FalseBranch =
nullptr;
656 auto HasSelectLike = [](SelectGroup &SG,
bool IsTrue) {
657 for (
auto &SL : SG.Selects) {
658 if ((IsTrue ? SL.getTrueValue() : SL.getFalseValue()) ==
nullptr)
663 if (!TrueSlicesInterleaved.
empty() || HasSelectLike(ASI,
true)) {
667 TrueBranch->
setDebugLoc(LastSI.getI()->getDebugLoc());
668 for (
Instruction *TrueInst : TrueSlicesInterleaved)
671 if (!FalseSlicesInterleaved.
empty() || HasSelectLike(ASI,
false)) {
676 FalseBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
677 for (
Instruction *FalseInst : FalseSlicesInterleaved)
678 FalseInst->moveBefore(FalseBranch->getIterator());
682 if (TrueBlock == FalseBlock) {
683 assert(TrueBlock ==
nullptr &&
684 "Unexpected basic block transform while optimizing select");
689 FalseBranch->setDebugLoc(
SI.getI()->getDebugLoc());
698 if (TrueBlock ==
nullptr) {
701 TrueBlock = StartBlock;
702 }
else if (FalseBlock ==
nullptr) {
705 FalseBlock = StartBlock;
712 IB.CreateFreeze(ASI.Condition, ASI.Condition->getName() +
".frozen");
719 auto InsertionPoint = EndBlock->
begin();
720 for (SelectLike &
SI : ASI.Selects) {
728 for (
auto &SG : ProfSIGroups) {
729 if (SG.Condition ==
SI.getI())
733 SI.getI()->replaceAllUsesWith(PN);
740 ++NumSelectsConverted;
744 CondBr->
copyMetadata(*SelectWithProfile, {llvm::LLVMContext::MD_prof});
745 if (SelectWithProfileIsInverted)
752 for (SelectLike &
SI : ASI.Selects)
753 SI.getI()->eraseFromParent();
757void SelectOptimizeImpl::collectSelectGroups(
BasicBlock &BB,
758 SelectGroups &SIGroups) {
768 struct SelectLikeInfo {
772 unsigned ConditionIdx;
783 auto ProcessSelectInfo = [&SelectInfo, &SeenCmp](
Instruction *
I) {
786 return SelectInfo.
end();
791 Cond->getType()->isIntegerTy(1)) {
793 return SelectInfo.
insert({
I, {
Cond,
true, Inverted, 0}}).first;
797 return SelectInfo.
insert({
I, {
Cond,
true,
true, 0}}).first;
803 return SelectInfo.
insert({
I, {
Cond,
false, Inverted, 0}}).first;
808 I->getType()->getIntegerBitWidth() == Shift->
getZExtValue() + 1) {
809 for (
auto *CmpI : SeenCmp) {
810 auto Pred = CmpI->getPredicate();
811 if (Val != CmpI->getOperand(0))
823 return SelectInfo.
insert({
I, {CmpI,
true, Inverted, 0}}).first;
826 return SelectInfo.
end();
834 auto MatchZExtOrSExtPattern =
836 auto MatchShiftPattern =
841 if ((
match(
I, MatchZExtOrSExtPattern) &&
X->getType()->isIntegerTy(1)) ||
842 (
match(
I, MatchShiftPattern) &&
843 X->getType()->getIntegerBitWidth() == Shift->
getZExtValue() + 1)) {
844 if (
I->getOpcode() != Instruction::Add &&
845 I->getOpcode() != Instruction::Sub &&
846 I->getOpcode() != Instruction::Or)
847 return SelectInfo.
end();
849 if (
I->getOpcode() == Instruction::Or &&
I->getType()->isIntegerTy(1))
850 return SelectInfo.
end();
856 unsigned Idx =
I->getOpcode() == Instruction::Sub ? 1 : 0;
858 auto *
Op =
I->getOperand(Idx);
859 auto It = SelectInfo.
find(
Op);
860 if (It != SelectInfo.
end() && It->second.IsAuxiliary) {
861 Cond = It->second.Cond;
862 bool Inverted = It->second.IsInverted;
863 return SelectInfo.
insert({
I, {
Cond,
false, Inverted,
Idx}}).first;
867 return SelectInfo.
end();
870 bool AlreadyProcessed =
false;
873 while (BBIt != BB.
end()) {
878 if (!AlreadyProcessed)
879 It = ProcessSelectInfo(
I);
881 AlreadyProcessed =
false;
883 if (It == SelectInfo.
end() || It->second.IsAuxiliary)
886 if (!
TTI->shouldTreatInstructionLikeSelect(
I))
891 if (!
Cond->getType()->isIntegerTy(1))
894 SelectGroup SIGroup = {
Cond, {}};
895 SIGroup.Selects.emplace_back(
I, It->second.IsInverted,
896 It->second.ConditionIdx);
900 if (!isSelectKindSupported(SIGroup.Selects.front()))
903 while (BBIt != BB.
end()) {
912 It = ProcessSelectInfo(NI);
913 if (It == SelectInfo.
end()) {
914 AlreadyProcessed =
true;
919 auto [CurrCond, IsAux, IsRev, CondIdx] = It->second;
920 if (
Cond != CurrCond) {
921 AlreadyProcessed =
true;
926 SIGroup.Selects.emplace_back(NI, IsRev, CondIdx);
930 dbgs() <<
"New Select group (" << SIGroup.Selects.size() <<
") with\n";
931 for (
auto &
SI : SIGroup.Selects)
932 dbgs() <<
" " << *
SI.getI() <<
"\n";
935 SIGroups.push_back(SIGroup);
939void SelectOptimizeImpl::findProfitableSIGroupsBase(
940 SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
941 for (SelectGroup &ASI : SIGroups) {
942 ++NumSelectOptAnalyzed;
943 if (isConvertToBranchProfitableBase(ASI))
944 ProfSIGroups.push_back(ASI);
954void SelectOptimizeImpl::findProfitableSIGroupsInnerLoops(
955 const Loop *L, SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
956 NumSelectOptAnalyzed += SIGroups.size();
968 erase_if(SIGroups, [&](
const SelectGroup &ASI) {
969 if (!ASI.isUnpredictable())
973 ASI.Selects.front().getI());
974 ORmiss <<
"Not converted to branch because of unpredictable branch. ";
980 CostInfo LoopCost[2] = {{Scaled64::getZero(), Scaled64::getZero()},
981 {Scaled64::getZero(), Scaled64::getZero()}};
982 if (!computeLoopCosts(L, SIGroups, InstCostMap, LoopCost) ||
983 !checkLoopHeuristics(L, LoopCost)) {
987 for (SelectGroup &ASI : SIGroups) {
990 Scaled64 SelectCost = Scaled64::getZero(), BranchCost = Scaled64::getZero();
991 for (SelectLike &
SI : ASI.Selects) {
992 const auto &ICM = InstCostMap[
SI.getI()];
993 SelectCost = std::max(SelectCost, ICM.PredCost);
994 BranchCost = std::max(BranchCost, ICM.NonPredCost);
996 if (BranchCost < SelectCost) {
998 ASI.Selects.front().getI());
999 OR <<
"Profitable to convert to branch (loop analysis). BranchCost="
1000 << BranchCost.toString() <<
", SelectCost=" << SelectCost.toString()
1003 ++NumSelectConvertedLoop;
1004 ProfSIGroups.push_back(ASI);
1007 ASI.Selects.front().getI());
1008 ORmiss <<
"Select is more profitable (loop analysis). BranchCost="
1009 << BranchCost.toString()
1010 <<
", SelectCost=" << SelectCost.toString() <<
". ";
1016bool SelectOptimizeImpl::isConvertToBranchProfitableBase(
1017 const SelectGroup &ASI) {
1018 const SelectLike &
SI = ASI.Selects.front();
1027 ORmiss <<
"Not converted to branch because of cold basic block. ";
1033 if (
SI.getI()->getMetadata(LLVMContext::MD_unpredictable)) {
1035 ORmiss <<
"Not converted to branch because of unpredictable branch. ";
1043 ++NumSelectConvertedHighPred;
1044 OR <<
"Converted to branch because of highly predictable branch. ";
1051 if (hasExpensiveColdOperand(ASI)) {
1052 ++NumSelectConvertedExpColdOperand;
1053 OR <<
"Converted to branch because of expensive cold operand.";
1061 auto *BB =
SI.getI()->getParent();
1063 if (L && !
L->isInnermost() &&
L->getLoopLatch() == BB &&
1064 ASI.Selects.size() >= 3) {
1065 OR <<
"Converted to branch because select group in the latch block is big.";
1070 ORmiss <<
"Not profitable to convert to branch (base heuristic).";
1077 return (Numerator + (Denominator / 2)) / Denominator;
1087bool SelectOptimizeImpl::hasExpensiveColdOperand(
const SelectGroup &ASI) {
1088 bool ColdOperand =
false;
1089 uint64_t TrueWeight, FalseWeight, TotalWeight;
1091 uint64_t MinWeight = std::min(TrueWeight, FalseWeight);
1092 TotalWeight = TrueWeight + FalseWeight;
1094 ColdOperand = TotalWeight * Opts->cold_operand_threshold > 100 * MinWeight;
1097 ASI.Selects.front().getI());
1098 ORmiss <<
"Profile data available but missing branch-weights metadata for "
1099 "select instruction. ";
1106 for (SelectLike
SI : ASI.Selects) {
1109 if (TrueWeight < FalseWeight) {
1111 HotWeight = FalseWeight;
1114 HotWeight = TrueWeight;
1117 std::stack<Instruction *> ColdSlice;
1118 getExclBackwardsSlice(ColdI, ColdSlice,
SI.getI());
1120 while (!ColdSlice.empty()) {
1121 SliceCost +=
TTI->getInstructionCost(ColdSlice.top(),
1131 if (AdjSliceCost >= Opts->cold_operand_max_cost_multiplier *
1147 while (&*It !=
SI) {
1148 if (It->mayWriteToMemory())
1161void SelectOptimizeImpl::getExclBackwardsSlice(
Instruction *
I,
1162 std::stack<Instruction *> &Slice,
1164 const SelectGroup *Group) {
1166 std::queue<Instruction *> Worklist;
1168 while (!Worklist.empty()) {
1176 if (!
II->hasOneUse())
1182 if (ForSinking && (
II->isTerminator() ||
II->mayHaveSideEffects() ||
1188 if (ForSinking && Group &&
1189 llvm::any_of(Group->Selects, [&](
auto &S) { return S.getI() == II; }))
1214bool SelectOptimizeImpl::isSelectHighlyPredictable(
const SelectLike
SI) {
1218 uint64_t Sum = TrueWeight + FalseWeight;
1221 if (Probability >
TTI->getPredictableBranchThreshold())
1228bool SelectOptimizeImpl::checkLoopHeuristics(
const Loop *L,
1229 const CostInfo LoopCost[2]) {
1233 if (!Opts->select_opti_loop_level_heuristics)
1237 &*
L->getHeader()->getFirstNonPHIIt());
1239 if (LoopCost[0].NonPredCost > LoopCost[0].PredCost ||
1240 LoopCost[1].NonPredCost >= LoopCost[1].PredCost) {
1241 ORmissL <<
"No select conversion in the loop due to no reduction of loop's "
1247 Scaled64 Gain[2] = {LoopCost[0].PredCost - LoopCost[0].NonPredCost,
1248 LoopCost[1].PredCost - LoopCost[1].NonPredCost};
1253 if (Gain[1] < Scaled64::get(Opts->select_opti_loop_cycle_gain_threshold) ||
1254 Gain[1] * Scaled64::get(Opts->select_opti_loop_relative_gain_threshold) <
1255 LoopCost[1].PredCost) {
1256 Scaled64 RelativeGain = Scaled64::get(100) * Gain[1] / LoopCost[1].PredCost;
1257 ORmissL <<
"No select conversion in the loop due to small reduction of "
1258 "loop's critical path. Gain="
1259 << Gain[1].toString()
1260 <<
", RelativeGain=" << RelativeGain.toString() <<
"%. ";
1270 if (Gain[1] > Gain[0]) {
1271 Scaled64 GradientGain = Scaled64::get(100) * (Gain[1] - Gain[0]) /
1272 (LoopCost[1].PredCost - LoopCost[0].PredCost);
1274 Scaled64::get(Opts->select_opti_loop_gradient_gain_threshold)) {
1275 ORmissL <<
"No select conversion in the loop due to small gradient gain. "
1277 << GradientGain.toString() <<
"%. ";
1283 else if (Gain[1] < Gain[0]) {
1285 <<
"No select conversion in the loop due to negative gradient gain. ";
1299bool SelectOptimizeImpl::computeLoopCosts(
1300 const Loop *L,
const SelectGroups &SIGroups,
1302 LLVM_DEBUG(
dbgs() <<
"Calculating Latency / IPredCost / INonPredCost of loop "
1303 <<
L->getHeader()->getName() <<
"\n");
1304 const auto SImap = getSImap(SIGroups);
1305 const auto SGmap = getSGmap(SIGroups);
1308 const unsigned Iterations = 2;
1309 for (
unsigned Iter = 0; Iter < Iterations; ++Iter) {
1311 CostInfo &MaxCost = LoopCost[Iter];
1317 Scaled64 IPredCost = Scaled64::getZero(),
1318 INonPredCost = Scaled64::getZero();
1323 for (
const Use &U :
I.operands()) {
1327 if (
auto It = InstCostMap.
find(UI); It != InstCostMap.
end()) {
1328 IPredCost = std::max(IPredCost, It->second.PredCost);
1329 INonPredCost = std::max(INonPredCost, It->second.NonPredCost);
1332 auto ILatency = computeInstCost(&
I);
1335 ORmissL <<
"Invalid instruction cost preventing analysis and "
1336 "optimization of the inner-most loop containing this "
1341 IPredCost += Scaled64::get(*ILatency);
1342 INonPredCost += Scaled64::get(*ILatency);
1350 if (
auto It = SImap.find(&
I); It != SImap.end()) {
1351 auto SI = It->second;
1352 const auto *SG = SGmap.at(&
I);
1353 Scaled64 TrueOpCost =
SI.getOpCostOnBranch(
true, InstCostMap,
TTI);
1354 Scaled64 FalseOpCost =
SI.getOpCostOnBranch(
false, InstCostMap,
TTI);
1355 Scaled64 PredictedPathCost =
1356 getPredictedPathCost(TrueOpCost, FalseOpCost,
SI);
1358 Scaled64 CondCost = Scaled64::getZero();
1360 if (
auto It = InstCostMap.
find(CI); It != InstCostMap.
end())
1361 CondCost = It->second.NonPredCost;
1362 Scaled64 MispredictCost = getMispredictionCost(
SI, CondCost);
1364 INonPredCost = PredictedPathCost + MispredictCost;
1367 << INonPredCost <<
" for " <<
I <<
"\n");
1369 InstCostMap[&
I] = {IPredCost, INonPredCost};
1370 MaxCost.PredCost = std::max(MaxCost.PredCost, IPredCost);
1371 MaxCost.NonPredCost = std::max(MaxCost.NonPredCost, INonPredCost);
1375 <<
" MaxCost = " << MaxCost.PredCost <<
" "
1376 << MaxCost.NonPredCost <<
"\n");
1382SelectOptimizeImpl::getSImap(
const SelectGroups &SIGroups) {
1384 for (
const SelectGroup &ASI : SIGroups)
1385 for (
const SelectLike &
SI : ASI.Selects)
1391SelectOptimizeImpl::getSGmap(
const SelectGroups &SIGroups) {
1393 for (
const SelectGroup &ASI : SIGroups)
1394 for (
const SelectLike &
SI : ASI.Selects)
1399std::optional<uint64_t>
1400SelectOptimizeImpl::computeInstCost(
const Instruction *
I) {
1404 return std::optional<uint64_t>(ICost.
getValue());
1405 return std::nullopt;
1409SelectOptimizeImpl::getMispredictionCost(
const SelectLike
SI,
1410 const Scaled64 CondCost) {
1415 uint64_t MispredictRate = Opts->mispredict_default_rate;
1418 if (isSelectHighlyPredictable(
SI))
1424 Scaled64 MispredictCost =
1425 std::max(Scaled64::get(MispredictPenalty), CondCost) *
1426 Scaled64::get(MispredictRate);
1427 MispredictCost /= Scaled64::get(100);
1429 return MispredictCost;
1435SelectOptimizeImpl::getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
1436 const SelectLike
SI) {
1437 Scaled64 PredPathCost;
1440 uint64_t SumWeight = TrueWeight + FalseWeight;
1441 if (SumWeight != 0) {
1442 PredPathCost = TrueCost * Scaled64::get(TrueWeight) +
1443 FalseCost * Scaled64::get(FalseWeight);
1444 PredPathCost /= Scaled64::get(SumWeight);
1445 return PredPathCost;
1450 PredPathCost = std::max(TrueCost * Scaled64::get(3) + FalseCost,
1451 FalseCost * Scaled64::get(3) + TrueCost);
1452 PredPathCost /= Scaled64::get(4);
1453 return PredPathCost;
1456bool SelectOptimizeImpl::isSelectKindSupported(
const SelectLike
SI) {
1458 if (
SI.getType()->isVectorTy())
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
static bool runOnFunction(Function &F, bool PostInlining)
print mir2vec MIR2Vec Vocabulary Printer Pass
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
static bool isSafeToSinkLoad(Instruction *LoadI, Instruction *SI)
static void EmitAndPrintRemark(OptimizationRemarkEmitter *ORE, DiagnosticInfoOptimizationBase &Rem)
This file contains the declaration of the SelectOptimizePass class, its corresponding pass name is se...
This file implements a set that has insertion order iteration characteristics.
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 SymbolRef::Type getType(const Symbol *Sym)
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
static const uint32_t IV[8]
AnalysisUsage & addRequired()
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes BlockFrequencyInfo.
Legacy analysis pass which computes BlockFrequencyInfo.
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ ICMP_SGT
signed greater than
@ ICMP_SGE
signed greater or equal
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void removeFromParent()
iterator find(const_arg_type_t< KeyT > Val)
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Common features for diagnostics dealing with optimization remarks that are used by both IR and MIR pa...
std::string getMsg() const
FunctionPass class - This class is used to implement most global optimizations.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Analysis pass that exposes the LoopInfo for a function.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Represents a single loop in the control flow graph.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Pass interface - Implemented by all 'passes'.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
bool hasProfileSummary() const
Returns true if profile summary is available.
bool isColdBlock(const BBType *BB, BFIT *BFI) const
Returns true if BasicBlock BB is considered cold.
Simple representation of a scaled number.
static ScaledNumber get(uint64_t N)
static ScaledNumber getZero()
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
bool insert(const value_type &X)
Insert a new element into the SetVector.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
virtual bool isSelectSupported(SelectSupportKind) const
SelectSupportKind
Enum that describes what type of support for selects the target has.
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
Target-Independent Code Generator Pass Configuration Options.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
virtual unsigned getMispredictionPenalty() const
Return the number of extra cycles the processor takes to recover from a branch misprediction.
virtual const TargetLowering * getTargetLowering() const
bool isIntegerTy() const
True if this is an instance of IntegerType.
Unconditional Branch instruction.
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 takeName(Value *V)
Transfer the name from V to this value.
const ParentTy * getParent() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI FunctionPass * createSelectOptimizePass()
This pass converts conditional moves to conditional jumps when profitable.
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.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
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...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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 bool hasProfMD(const Instruction &I)
Checks if an Instruction has MD_prof Metadata.
DWARFExpression::Operation Op
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.