61#define DEBUG_TYPE "if-converter"
63STATISTIC(NumSimple,
"Number of simple if-conversions performed");
64STATISTIC(NumSimpleFalse,
"Number of simple (F) if-conversions performed");
65STATISTIC(NumTriangle,
"Number of triangle if-conversions performed");
66STATISTIC(NumTriangleRev,
"Number of triangle (R) if-conversions performed");
67STATISTIC(NumTriangleFalse,
"Number of triangle (F) if-conversions performed");
68STATISTIC(NumTriangleFRev,
"Number of triangle (F/R) if-conversions performed");
69STATISTIC(NumDiamonds,
"Number of diamond if-conversions performed");
70STATISTIC(NumForkedDiamonds,
"Number of forked-diamond if-conversions performed");
71STATISTIC(NumIfConvBBs,
"Number of if-converted blocks");
73STATISTIC(NumUnpred,
"Number of true blocks of diamonds unpredicated");
77class IfConverterImpl {
123 bool IsBeingAnalyzed : 1;
126 bool IsBrAnalyzable : 1;
127 bool IsBrReversible : 1;
128 bool HasFallThrough : 1;
129 bool IsUnpredicable : 1;
130 bool CannotBeCopied : 1;
131 bool ClobbersPred : 1;
132 unsigned NonPredSize = 0;
133 unsigned ExtraCost = 0;
134 unsigned ExtraCost2 = 0;
135 MachineBasicBlock *BB =
nullptr;
136 MachineBasicBlock *TrueBB =
nullptr;
137 MachineBasicBlock *FalseBB =
nullptr;
138 SmallVector<MachineOperand, 4> BrCond;
139 SmallVector<MachineOperand, 4> Predicate;
145 ClobbersPred(
false) {}
164 bool NeedSubsumption : 1;
165 bool TClobbersPred : 1;
166 bool FClobbersPred : 1;
168 IfcvtToken(BBInfo &b, IfcvtKind k,
bool s,
unsigned d,
unsigned d2 = 0,
169 bool tc =
false,
bool fc =
false)
170 : BBI(
b), Kind(
k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
171 TClobbersPred(tc), FClobbersPred(fc) {}
176 std::vector<BBInfo> BBAnalysis;
177 TargetSchedModel SchedModel;
179 const TargetInstrInfo *TII =
nullptr;
180 const TargetRegisterInfo *TRI =
nullptr;
181 const MachineBranchProbabilityInfo *MBPI =
nullptr;
182 MachineRegisterInfo *MRI =
nullptr;
186 bool PreRegAlloc =
true;
187 bool MadeChange =
false;
190 bool reverseBranchCondition(BBInfo &BBI)
const;
191 bool ValidSimple(BBInfo &TrueBBI,
unsigned &Dups,
192 BranchProbability Prediction)
const;
193 bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
bool FalseBranch,
194 unsigned &Dups, BranchProbability Prediction)
const;
195 bool CountDuplicatedInstructions(
198 unsigned &Dups1,
unsigned &Dups2, MachineBasicBlock &
TBB,
199 MachineBasicBlock &FBB,
bool SkipUnconditionalBranches)
const;
200 bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
unsigned &Dups1,
201 unsigned &Dups2, BBInfo &TrueBBICalc,
202 BBInfo &FalseBBICalc)
const;
203 bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
unsigned &Dups1,
204 unsigned &Dups2, BBInfo &TrueBBICalc,
205 BBInfo &FalseBBICalc)
const;
206 void AnalyzeBranches(BBInfo &BBI);
209 bool BranchUnpredicable =
false)
const;
214 BBInfo &FalseBBI)
const;
215 void AnalyzeBlock(MachineBasicBlock &
MBB,
216 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
217 bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &
Pred,
218 bool isTriangle =
false,
bool RevBranch =
false,
219 bool hasCommonTail =
false);
221 std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
222 void InvalidatePreds(MachineBasicBlock &
MBB);
223 bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
224 bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
225 bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
226 unsigned NumDups1,
unsigned NumDups2,
227 bool TClobbersPred,
bool FClobbersPred,
228 bool RemoveBranch,
bool MergeAddEdges);
229 bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
unsigned NumDups1,
230 unsigned NumDups2,
bool TClobbers,
bool FClobbers);
231 bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
unsigned NumDups1,
232 unsigned NumDups2,
bool TClobbers,
235 SmallVectorImpl<MachineOperand> &
Cond,
236 SmallSet<MCRegister, 4> *LaterRedefs =
nullptr);
237 void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
238 SmallVectorImpl<MachineOperand> &
Cond,
239 bool IgnoreBr =
false);
240 void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI,
bool AddEdges =
true);
242 bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
unsigned Cycle,
unsigned Extra,
243 BranchProbability Prediction)
const {
244 return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra, Prediction);
247 bool MeetIfcvtSizeLimit(BBInfo &TBBInfo, BBInfo &FBBInfo,
248 MachineBasicBlock &CommBB,
unsigned Dups,
249 BranchProbability Prediction,
bool Forked)
const {
257 unsigned Dups1 = 0, Dups2 = 0;
258 if (!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
259 *TBBInfo.BB, *FBBInfo.BB,
263 unsigned BranchBytes = 0;
264 unsigned CommonBytes = 0;
267 for (
auto &
I :
make_range(TBBInfo.BB->begin(), TIB)) {
269 CommonBytes += TII->getInstSizeInBytes(
I);
271 for (
auto &
I :
make_range(FBBInfo.BB->begin(), FIB)) {
273 CommonBytes += TII->getInstSizeInBytes(
I);
280 for (
auto &
I :
make_range(TIE, TBBInfo.BB->end())) {
281 if (
I.isBranch() && TBBInfo.IsBrAnalyzable && !Forked) {
283 BranchBytes += TII->predictBranchSizeForIfCvt(
I);
286 CommonBytes += TII->getInstSizeInBytes(
I);
289 for (
auto &
I :
make_range(FIE, FBBInfo.BB->end())) {
290 if (
I.isBranch() && FBBInfo.IsBrAnalyzable && !Forked) {
292 BranchBytes += TII->predictBranchSizeForIfCvt(
I);
295 CommonBytes += TII->getInstSizeInBytes(
I);
301 BranchBytes += TII->predictBranchSizeForIfCvt(
I);
310 unsigned NumPredicatedInstructions = 0;
312 if (!
I.isDebugInstr()) {
314 NumPredicatedInstructions++;
318 if (!
I.isDebugInstr()) {
320 NumPredicatedInstructions++;
326 if (NumPredicatedInstructions > 15)
331 unsigned ExtraPredicateBytes =
332 TII->extraSizeToPredicateInstructions(MF, NumPredicatedInstructions);
335 dbgs() <<
"MeetIfcvtSizeLimit(BranchBytes=" << BranchBytes
336 <<
", CommonBytes=" << CommonBytes
337 <<
", NumPredicatedInstructions=" << NumPredicatedInstructions
338 <<
", ExtraPredicateBytes=" << ExtraPredicateBytes <<
")\n");
339 return (BranchBytes + CommonBytes) > ExtraPredicateBytes;
341 unsigned TCycle = TBBInfo.NonPredSize + TBBInfo.ExtraCost - Dups;
342 unsigned FCycle = FBBInfo.NonPredSize + FBBInfo.ExtraCost - Dups;
343 bool Res = TCycle > 0 && FCycle > 0 &&
344 TII->isProfitableToIfCvt(
345 *TBBInfo.BB, TCycle, TBBInfo.ExtraCost2, *FBBInfo.BB,
346 FCycle, FBBInfo.ExtraCost2, Prediction);
347 LLVM_DEBUG(
dbgs() <<
"MeetIfcvtSizeLimit(TCycle=" << TCycle <<
", FCycle="
348 << FCycle <<
", TExtra=" << TBBInfo.ExtraCost2
349 <<
", FExtra=" << FBBInfo.ExtraCost2 <<
") = " << Res
356 bool blockAlwaysFallThrough(BBInfo &BBI)
const {
357 return BBI.IsBrAnalyzable && BBI.TrueBB ==
nullptr;
361 bool blockNeverFallThrough(BBInfo &BBI)
const {
363 if (BBI.IsBrAnalyzable)
364 return !BBI.HasFallThrough;
369 if (
I == BBI.BB->getParent()->end() || !PI->isSuccessor(&*
I))
376 static bool IfcvtTokenCmp(
const std::unique_ptr<IfcvtToken> &
C1,
377 const std::unique_ptr<IfcvtToken> &C2) {
378 int Incr1 = (
C1->Kind == ICDiamond) ? -(
int)(
C1->NumDups +
C1->NumDups2)
380 int Incr2 = (C2->Kind == ICDiamond) ? -(int)(C2->NumDups + C2->NumDups2)
384 else if (Incr1 == Incr2) {
386 if (!
C1->NeedSubsumption && C2->NeedSubsumption)
388 else if (
C1->NeedSubsumption == C2->NeedSubsumption) {
390 if ((
unsigned)
C1->Kind < (
unsigned)C2->Kind)
392 else if (
C1->Kind == C2->Kind)
393 return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
400 bool runOnMachineFunction(
401 MachineFunction &MF, function_ref<MachineBlockFrequencyInfo &()> GetMBFI,
402 function_ref<MachineBranchProbabilityInfo *()> GetMBPI,
403 function_ref<ProfileSummaryInfo *()> GetPSI,
413 IfConverterLegacy(std::function<
bool(
const MachineFunction &)> Ftor =
nullptr)
414 : MachineFunctionPass(ID), PredicateFtor(std::
move(Ftor)) {}
416 void getAnalysisUsage(AnalysisUsage &AU)
const override {
417 AU.
addRequired<MachineBlockFrequencyInfoWrapperPass>();
418 AU.
addRequired<MachineBranchProbabilityInfoWrapperPass>();
426 MachineFunctionProperties getRequiredProperties()
const override {
427 return MachineFunctionProperties().setNoVRegs();
433char IfConverterLegacy::ID = 0;
443bool IfConverterImpl::runOnMachineFunction(
448 if (PredicateFtor(MF))
453 TII = ST.getInstrInfo();
454 TRI = ST.getRegisterInfo();
458 MRI = &MF.getRegInfo();
459 SchedModel.
init(&ST);
461 if (!
TII)
return false;
463 PreRegAlloc =
MRI->isSSA();
465 bool BFChange =
false;
473 << MF.getName() <<
"\'");
475 if (FnNum < Opts.ifcvt_fn_start ||
476 (Opts.ifcvt_fn_stop != -1 && FnNum > Opts.ifcvt_fn_stop)) {
483 BBAnalysis.resize(MF.getNumBlockIDs());
485 std::vector<std::unique_ptr<IfcvtToken>> Tokens;
487 unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
488 NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
489 while (Opts.ifcvt_limit == -1 || (
int)NumIfCvts < Opts.ifcvt_limit) {
493 AnalyzeBlocks(MF, Tokens);
494 while (!Tokens.empty()) {
495 std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
497 BBInfo &BBI = Token->BBI;
498 IfcvtKind Kind = Token->Kind;
499 unsigned NumDups = Token->NumDups;
500 unsigned NumDups2 = Token->NumDups2;
505 BBI.IsEnqueued =
false;
509 BBI.IsEnqueued =
false;
515 case ICSimpleFalse: {
516 bool isFalse = Kind == ICSimpleFalse;
517 if ((isFalse && !Opts.ifcvt_simple_false) ||
518 (!isFalse && !Opts.ifcvt_simple))
521 << (Kind == ICSimpleFalse ?
" false" :
"")
523 << ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
524 : BBI.TrueBB->getNumber())
526 RetVal = IfConvertSimple(BBI, Kind);
527 LLVM_DEBUG(
dbgs() << (RetVal ?
"succeeded!" :
"failed!") <<
"\n");
529 if (isFalse) ++NumSimpleFalse;
536 case ICTriangleFalse:
537 case ICTriangleFRev: {
538 bool isFalse = Kind == ICTriangleFalse;
539 bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
540 if (!Opts.ifcvt_triangle && !isFalse && !isRev)
542 if (!Opts.ifcvt_triangle_rev && !isFalse && isRev)
544 if (!Opts.ifcvt_triangle_false && isFalse && !isRev)
552 <<
" (T:" << BBI.TrueBB->getNumber()
553 <<
",F:" << BBI.FalseBB->getNumber() <<
") ");
554 RetVal = IfConvertTriangle(BBI, Kind);
555 LLVM_DEBUG(
dbgs() << (RetVal ?
"succeeded!" :
"failed!") <<
"\n");
567 if (!Opts.ifcvt_diamond)
570 <<
" (T:" << BBI.TrueBB->getNumber()
571 <<
",F:" << BBI.FalseBB->getNumber() <<
") ");
572 RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
573 Token->TClobbersPred,
574 Token->FClobbersPred);
575 LLVM_DEBUG(
dbgs() << (RetVal ?
"succeeded!" :
"failed!") <<
"\n");
576 if (RetVal) ++NumDiamonds;
578 case ICForkedDiamond:
579 if (!Opts.ifcvt_forked_diamond)
583 <<
" (T:" << BBI.TrueBB->getNumber()
584 <<
",F:" << BBI.FalseBB->getNumber() <<
") ");
585 RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
586 Token->TClobbersPred,
587 Token->FClobbersPred);
588 LLVM_DEBUG(
dbgs() << (RetVal ?
"succeeded!" :
"failed!") <<
"\n");
589 if (RetVal) ++NumForkedDiamonds;
593 if (RetVal &&
MRI->tracksLiveness())
598 NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
599 NumTriangleFalse + NumTriangleFRev + NumDiamonds;
600 if (Opts.ifcvt_limit != -1 && (
int)NumIfCvts >= Opts.ifcvt_limit)
606 MadeChange |= Change;
612 if (MadeChange && Opts.ifcvt_branch_fold) {
617 MadeChange |= BFChange;
625 if (SuccBB != TrueBB)
633bool IfConverterImpl::reverseBranchCondition(BBInfo &BBI)
const {
657bool IfConverterImpl::ValidSimple(BBInfo &TrueBBI,
unsigned &Dups,
658 BranchProbability Prediction)
const {
660 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
663 if (TrueBBI.IsBrAnalyzable)
666 if (TrueBBI.BB->pred_size() > 1) {
667 if (TrueBBI.CannotBeCopied ||
671 Dups = TrueBBI.NonPredSize;
682bool IfConverterImpl::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
683 bool FalseBranch,
unsigned &Dups,
684 BranchProbability Prediction)
const {
686 if (TrueBBI.BB == FalseBBI.BB)
689 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
692 if (TrueBBI.BB->pred_size() > 1) {
693 if (TrueBBI.CannotBeCopied)
696 unsigned Size = TrueBBI.NonPredSize;
697 if (TrueBBI.IsBrAnalyzable) {
698 if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
702 MachineBasicBlock *FExit = FalseBranch
703 ? TrueBBI.TrueBB : TrueBBI.FalseBB;
714 MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
715 if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
717 if (++
I == TrueBBI.BB->getParent()->end())
721 return TExit && TExit == FalseBBI.BB;
744bool IfConverterImpl::CountDuplicatedInstructions(
747 unsigned &Dups1,
unsigned &Dups2, MachineBasicBlock &
TBB,
748 MachineBasicBlock &FBB,
bool SkipUnconditionalBranches)
const {
749 while (TIB != TIE && FIB != FIE) {
753 if (TIB == TIE || FIB == FIE)
755 if (!TIB->isIdenticalTo(*FIB))
759 std::vector<MachineOperand> PredDefs;
763 if (!TIB->isBranch())
770 if (TIB == TIE || FIB == FIE)
782 if (SkipUnconditionalBranches) {
783 while (RTIE != RTIB && RTIE->isUnconditionalBranch())
785 while (RFIE != RFIB && RFIE->isUnconditionalBranch())
791 while (RTIE != RTIB && RFIE != RFIB) {
796 if (RTIE == RTIB || RFIE == RFIB)
798 if (!RTIE->isIdenticalTo(*RFIE))
802 if (!RTIE->isBranch())
826 BBInfo &FalseBBI)
const {
827 bool BranchUnpredicable =
true;
828 TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable =
false;
829 ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
830 if (TrueBBI.IsUnpredicable)
832 ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
833 if (FalseBBI.IsUnpredicable)
835 if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
848 while (E1 != B1 && E2 != B2) {
851 if (E1 == B1 && E2 == B2)
855 assert(!E2->isBranch() &&
"Branch mis-match, one block is empty.");
859 assert(!E1->isBranch() &&
"Branch mis-match, one block is empty.");
863 if (E1->isBranch() || E2->isBranch())
864 assert(E1->isIdenticalTo(*E2) &&
865 "Branch mis-match, branch instructions don't match.");
887bool IfConverterImpl::ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
888 unsigned &Dups1,
unsigned &Dups2,
890 BBInfo &FalseBBICalc)
const {
892 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
893 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
896 if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
899 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
904 if (TrueBBI.BrCond.size() == 0 ||
905 FalseBBI.BrCond.size() == 0)
908 MachineBasicBlock *
TT = TrueBBI.TrueBB;
909 MachineBasicBlock *TF = TrueBBI.FalseBB;
910 MachineBasicBlock *FT = FalseBBI.TrueBB;
911 MachineBasicBlock *FF = FalseBBI.FalseBB;
926 if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
929 bool FalseReversed =
false;
930 if (TF == FT && TT == FF) {
932 if (!FalseBBI.IsBrReversible)
934 FalseReversed =
true;
935 reverseBranchCondition(FalseBBI);
939 reverseBranchCondition(FalseBBI);
947 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
948 *TrueBBI.BB, *FalseBBI.BB,
952 TrueBBICalc.BB = TrueBBI.BB;
953 FalseBBICalc.BB = FalseBBI.BB;
954 TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
955 FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
956 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
962 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
963 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
969bool IfConverterImpl::ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
970 unsigned &Dups1,
unsigned &Dups2,
972 BBInfo &FalseBBICalc)
const {
974 if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
975 FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
980 if (TrueBBI.BB == FalseBBI.BB)
983 MachineBasicBlock *
TT = TrueBBI.TrueBB;
984 MachineBasicBlock *FT = FalseBBI.TrueBB;
986 if (!TT && blockAlwaysFallThrough(TrueBBI))
988 if (!FT && blockAlwaysFallThrough(FalseBBI))
992 if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
994 if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
998 if (TrueBBI.FalseBB || FalseBBI.FalseBB)
1005 bool SkipUnconditionalBranches =
1006 TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
1011 if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
1012 *TrueBBI.BB, *FalseBBI.BB,
1013 SkipUnconditionalBranches))
1016 TrueBBICalc.BB = TrueBBI.BB;
1017 FalseBBICalc.BB = FalseBBI.BB;
1018 TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
1019 FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
1020 if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
1025 TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
1026 FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
1032void IfConverterImpl::AnalyzeBranches(BBInfo &BBI) {
1036 BBI.TrueBB = BBI.FalseBB =
nullptr;
1038 BBI.IsBrAnalyzable =
1040 if (!BBI.IsBrAnalyzable) {
1041 BBI.TrueBB =
nullptr;
1042 BBI.FalseBB =
nullptr;
1046 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1047 BBI.IsBrReversible = (RevCond.size() == 0) ||
1049 BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB ==
nullptr;
1051 if (BBI.BrCond.size()) {
1058 BBI.IsUnpredicable =
true;
1068void IfConverterImpl::ScanInstructions(BBInfo &BBI,
1071 bool BranchUnpredicable)
const {
1072 if (BBI.IsDone || BBI.IsUnpredicable)
1075 bool AlreadyPredicated = !BBI.Predicate.empty();
1077 BBI.NonPredSize = 0;
1080 BBI.ClobbersPred =
false;
1082 if (
MI.isDebugInstr())
1115 if (
MI.isNotDuplicable() ||
MI.isConvergent())
1116 BBI.CannotBeCopied =
true;
1119 bool isCondBr = BBI.IsBrAnalyzable &&
MI.isConditionalBranch();
1121 if (BranchUnpredicable &&
MI.isBranch()) {
1122 BBI.IsUnpredicable =
true;
1130 if (!isPredicated) {
1132 unsigned ExtraPredCost =
TII->getPredicationCost(
MI);
1133 unsigned NumCycles = SchedModel.computeInstrLatency(&
MI,
false);
1135 BBI.ExtraCost += NumCycles-1;
1136 BBI.ExtraCost2 += ExtraPredCost;
1137 }
else if (!AlreadyPredicated) {
1141 BBI.IsUnpredicable =
true;
1145 if (BBI.ClobbersPred && !isPredicated) {
1150 BBI.IsUnpredicable =
true;
1156 std::vector<MachineOperand> PredDefs;
1158 BBI.ClobbersPred =
true;
1161 BBI.IsUnpredicable =
true;
1176bool IfConverterImpl::FeasibilityAnalysis(BBInfo &BBI,
1177 SmallVectorImpl<MachineOperand> &
Pred,
1178 bool isTriangle,
bool RevBranch,
1179 bool hasCommonTail) {
1184 if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
1190 if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
1198 if (!hasCommonTail && BBI.BrCond.size()) {
1203 SmallVector<MachineOperand, 4> RevPred(
Pred.begin(),
Pred.end());
1204 SmallVector<MachineOperand, 4>
Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1219void IfConverterImpl::AnalyzeBlock(
1220 MachineBasicBlock &
MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1222 BBState(MachineBasicBlock &
MBB) :
MBB(&
MBB) {}
1223 MachineBasicBlock *
MBB;
1226 bool SuccsAnalyzed =
false;
1232 while (!BBStack.empty()) {
1233 BBState &State = BBStack.back();
1234 MachineBasicBlock *BB = State.MBB;
1235 BBInfo &BBI = BBAnalysis[BB->
getNumber()];
1237 if (!State.SuccsAnalyzed) {
1238 if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
1244 BBI.IsBeingAnalyzed =
true;
1246 AnalyzeBranches(BBI);
1249 ScanInstructions(BBI, Begin,
End);
1253 if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
1254 BBI.IsBeingAnalyzed =
false;
1255 BBI.IsAnalyzed =
true;
1261 if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
1262 BBI.IsBeingAnalyzed =
false;
1263 BBI.IsAnalyzed =
true;
1270 BBI.IsBeingAnalyzed =
false;
1271 BBI.IsAnalyzed =
true;
1277 State.SuccsAnalyzed =
true;
1278 BBStack.push_back(*BBI.FalseBB);
1279 BBStack.push_back(*BBI.TrueBB);
1283 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1284 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1286 if (TrueBBI.IsDone && FalseBBI.IsDone) {
1287 BBI.IsBeingAnalyzed =
false;
1288 BBI.IsAnalyzed =
true;
1293 SmallVector<MachineOperand, 4>
1294 RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1299 bool TNeedSub = !TrueBBI.Predicate.empty();
1300 bool FNeedSub = !FalseBBI.Predicate.empty();
1301 bool Enqueued =
false;
1306 BBInfo TrueBBICalc, FalseBBICalc;
1307 auto feasibleDiamond = [&](
bool Forked) {
1308 bool MeetsSize = MeetIfcvtSizeLimit(TrueBBICalc, FalseBBICalc, *BB,
1309 Dups + Dups2, Prediction, Forked);
1310 bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
1313 bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
1316 return MeetsSize && TrueFeasible && FalseFeasible;
1319 if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1320 TrueBBICalc, FalseBBICalc)) {
1321 if (feasibleDiamond(
false)) {
1330 Tokens.push_back(std::make_unique<IfcvtToken>(
1331 BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1332 (
bool) TrueBBICalc.ClobbersPred, (
bool) FalseBBICalc.ClobbersPred));
1335 }
else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
1336 TrueBBICalc, FalseBBICalc)) {
1337 if (feasibleDiamond(
true)) {
1348 Tokens.push_back(std::make_unique<IfcvtToken>(
1349 BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
1350 (
bool) TrueBBICalc.ClobbersPred, (
bool) FalseBBICalc.ClobbersPred));
1356 if (ValidTriangle(TrueBBI, FalseBBI,
false, Dups, Prediction) &&
1357 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1358 TrueBBI.ExtraCost2, Prediction) &&
1359 FeasibilityAnalysis(TrueBBI, BBI.BrCond,
true)) {
1368 std::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
1372 if (ValidTriangle(TrueBBI, FalseBBI,
true, Dups, Prediction) &&
1373 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1374 TrueBBI.ExtraCost2, Prediction) &&
1375 FeasibilityAnalysis(TrueBBI, BBI.BrCond,
true,
true)) {
1377 std::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
1381 if (ValidSimple(TrueBBI, Dups, Prediction) &&
1382 MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
1383 TrueBBI.ExtraCost2, Prediction) &&
1384 FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
1393 std::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
1399 if (ValidTriangle(FalseBBI, TrueBBI,
false, Dups,
1401 MeetIfcvtSizeLimit(*FalseBBI.BB,
1402 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1403 FalseBBI.ExtraCost2, Prediction.
getCompl()) &&
1404 FeasibilityAnalysis(FalseBBI, RevCond,
true)) {
1405 Tokens.push_back(std::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
1410 if (ValidTriangle(FalseBBI, TrueBBI,
true, Dups,
1412 MeetIfcvtSizeLimit(*FalseBBI.BB,
1413 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1414 FalseBBI.ExtraCost2, Prediction.
getCompl()) &&
1415 FeasibilityAnalysis(FalseBBI, RevCond,
true,
true)) {
1417 std::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
1421 if (ValidSimple(FalseBBI, Dups, Prediction.
getCompl()) &&
1422 MeetIfcvtSizeLimit(*FalseBBI.BB,
1423 FalseBBI.NonPredSize + FalseBBI.ExtraCost,
1424 FalseBBI.ExtraCost2, Prediction.
getCompl()) &&
1425 FeasibilityAnalysis(FalseBBI, RevCond)) {
1427 std::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
1432 BBI.IsEnqueued = Enqueued;
1433 BBI.IsBeingAnalyzed =
false;
1434 BBI.IsAnalyzed =
true;
1440void IfConverterImpl::AnalyzeBlocks(
1441 MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
1442 for (MachineBasicBlock &
MBB : MF)
1443 AnalyzeBlock(
MBB, Tokens);
1459 if (
I ==
E || !
I->empty() || !PI->isSuccessor(&*
I))
1464 return PI->isSuccessor(&*
I);
1469void IfConverterImpl::InvalidatePreds(MachineBasicBlock &
MBB) {
1471 BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
1472 if (PBBI.IsDone || PBBI.BB == &
MBB)
1474 PBBI.IsAnalyzed =
false;
1475 PBBI.IsEnqueued =
false;
1484 TII->insertBranch(
MBB, &ToMBB,
nullptr, NoCond, dl);
1497 for (
unsigned Reg : Redefs)
1504 for (
auto Clobber : Clobbers) {
1507 unsigned Reg = Clobber.first;
1511 if (
Op.isRegMask()) {
1526 [&](
MCPhysReg S) { return LiveBeforeMI.count(S); }))
1532bool IfConverterImpl::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
1533 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1534 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1535 BBInfo *CvtBBI = &TrueBBI;
1536 BBInfo *NextBBI = &FalseBBI;
1538 SmallVector<MachineOperand, 4>
Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1539 if (Kind == ICSimpleFalse)
1542 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1543 MachineBasicBlock &NextMBB = *NextBBI->BB;
1544 if (CvtBBI->IsDone ||
1545 (CvtBBI->CannotBeCopied && CvtMBB.
pred_size() > 1)) {
1547 BBI.IsAnalyzed =
false;
1548 CvtBBI->IsAnalyzed =
false;
1556 if (Kind == ICSimpleFalse)
1576 CopyAndPredicateBlock(BBI, *CvtBBI,
Cond);
1579 BBI.BB->removeSuccessor(&CvtMBB,
true);
1582 PredicateBlock(*CvtBBI, CvtMBB.
end(),
Cond);
1586 MergeBlocks(BBI, *CvtBBI);
1589 bool IterIfcvt =
true;
1592 BBI.HasFallThrough =
false;
1609 InvalidatePreds(*BBI.BB);
1610 CvtBBI->IsDone =
true;
1617bool IfConverterImpl::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
1618 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
1619 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
1620 BBInfo *CvtBBI = &TrueBBI;
1621 BBInfo *NextBBI = &FalseBBI;
1624 SmallVector<MachineOperand, 4>
Cond(BBI.BrCond.begin(), BBI.BrCond.end());
1625 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1628 MachineBasicBlock &CvtMBB = *CvtBBI->BB;
1629 MachineBasicBlock &NextMBB = *NextBBI->BB;
1630 if (CvtBBI->IsDone ||
1631 (CvtBBI->CannotBeCopied && CvtMBB.
pred_size() > 1)) {
1633 BBI.IsAnalyzed =
false;
1634 CvtBBI->IsAnalyzed =
false;
1642 if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
1646 if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
1647 if (reverseBranchCondition(*CvtBBI)) {
1653 BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
1654 if (PBBI.IsEnqueued) {
1655 PBBI.IsAnalyzed =
false;
1656 PBBI.IsEnqueued =
false;
1670 bool HasEarlyExit = CvtBBI->FalseBB !=
nullptr;
1671 BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
1688 CopyAndPredicateBlock(BBI, *CvtBBI,
Cond,
true);
1692 PredicateBlock(*CvtBBI, CvtMBB.
end(),
Cond);
1695 MergeBlocks(BBI, *CvtBBI,
false);
1699 BBI.BB->removeSuccessor(&CvtMBB,
true);
1703 SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
1704 CvtBBI->BrCond.end());
1715 auto NewNext = BBNext + BBCvt * CvtNext;
1716 auto NewTrueBBIter =
find(BBI.BB->successors(), NewTrueBB);
1717 if (NewTrueBBIter != BBI.BB->succ_end())
1718 BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
1720 auto NewFalse = BBCvt * CvtFalse;
1722 BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
1727 bool FalseBBDead =
false;
1728 bool IterIfcvt =
true;
1730 if (!isFallThrough) {
1734 if (!HasEarlyExit && NextMBB.
pred_size() == 1 &&
1736 MergeBlocks(BBI, *NextBBI);
1740 BBI.HasFallThrough =
false;
1750 InvalidatePreds(*BBI.BB);
1751 CvtBBI->IsDone =
true;
1753 NextBBI->IsDone =
true;
1770bool IfConverterImpl::IfConvertDiamondCommon(
1771 BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
unsigned NumDups1,
1772 unsigned NumDups2,
bool TClobbersPred,
bool FClobbersPred,
1773 bool RemoveBranch,
bool MergeAddEdges) {
1775 if (TrueBBI.IsDone || FalseBBI.IsDone ||
1776 TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
1778 BBI.IsAnalyzed =
false;
1779 TrueBBI.IsAnalyzed =
false;
1780 FalseBBI.IsAnalyzed =
false;
1784 if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
1791 BBInfo *BBI1 = &TrueBBI;
1792 BBInfo *BBI2 = &FalseBBI;
1793 SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
1796 SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
1797 SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
1800 bool DoSwap =
false;
1801 if (TClobbersPred && !FClobbersPred)
1803 else if (!TClobbersPred && !FClobbersPred) {
1804 if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
1806 }
else if (TClobbersPred && FClobbersPred)
1816 MachineBasicBlock &MBB1 = *BBI1->BB;
1817 MachineBasicBlock &MBB2 = *BBI2->BB;
1835 BBI1->NonPredSize -= NumDups1;
1836 BBI2->NonPredSize -= NumDups1;
1841 for (
unsigned i = 0; i < NumDups1; ++DI1) {
1842 if (DI1 == MBB1.
end())
1844 if (!DI1->isDebugInstr())
1847 while (NumDups1 != 0) {
1850 if (DI2->shouldUpdateAdditionalCallInfo())
1854 if (DI2 == MBB2.
end())
1856 if (!DI2->isDebugInstr())
1867 BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.
begin(), DI1);
1878 if (!BBI1->IsBrAnalyzable)
1884 while (DI1 != MBB1.
begin()) {
1886 if (!Prev->isBranch() && !Prev->isDebugInstr())
1890 for (
unsigned i = 0; i != NumDups2; ) {
1899 if (DI1->shouldUpdateAdditionalCallInfo())
1903 if (!DI1->isDebugInstr())
1908 DI2 = BBI2->BB->end();
1916 while (DI2 != MBB2.
begin()) {
1918 if (!Prev->isBranch() && !Prev->isDebugInstr())
1923 while (NumDups2 != 0) {
1929 if (!DI2->isDebugInstr())
1941 SmallSet<MCRegister, 4> RedefsByFalse;
1942 SmallSet<MCRegister, 4> ExtUses;
1943 if (
TII->isProfitableToUnpredicate(MBB1, MBB2)) {
1945 if (FI.isDebugInstr())
1948 for (
const MachineOperand &MO : FI.operands()) {
1956 }
else if (!RedefsByFalse.
count(
Reg)) {
1963 for (MCRegister
Reg : Defs) {
1971 PredicateBlock(*BBI1, MBB1.
end(), *Cond1, &RedefsByFalse);
1980 if (!MBB2.
empty() && (DI2 == MBB2.
end())) {
1985 if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
1990 PredicateBlock(*BBI2, DI2, *Cond2);
1993 MergeBlocks(BBI, *BBI1, MergeAddEdges);
1994 MergeBlocks(BBI, *BBI2, MergeAddEdges);
2000bool IfConverterImpl::IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
2004 bool FClobbersPred) {
2005 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
2006 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
2011 if (TIE != TrueBBI.BB->end())
2012 dl = TIE->getDebugLoc();
2016 if (!IfConvertDiamondCommon(
2017 BBI, TrueBBI, FalseBBI,
2019 TClobbersPred, FClobbersPred,
2026 TrueBBI.BrCond, dl);
2029 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone =
true;
2030 InvalidatePreds(*BBI.BB);
2037bool IfConverterImpl::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
2038 unsigned NumDups1,
unsigned NumDups2,
2039 bool TClobbersPred,
bool FClobbersPred) {
2040 BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
2041 BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
2042 MachineBasicBlock *TailBB = TrueBBI.TrueBB;
2046 if (blockAlwaysFallThrough(TrueBBI))
2047 TailBB = FalseBBI.TrueBB;
2048 assert((TailBB || !TrueBBI.IsBrAnalyzable) &&
"Unexpected!");
2051 if (!IfConvertDiamondCommon(
2052 BBI, TrueBBI, FalseBBI,
2054 TClobbersPred, FClobbersPred,
2055 TrueBBI.IsBrAnalyzable,
2066 BBI.BB->removeSuccessor(TrueBBI.BB);
2067 BBI.BB->removeSuccessor(FalseBBI.BB,
true);
2069 BBInfo &TailBBI = BBAnalysis[TailBB->
getNumber()];
2071 blockNeverFallThrough(TailBBI) && !TailBBI.BB->hasAddressTaken();
2077 CanMergeTail =
false;
2080 unsigned NumPreds = TailBB->
pred_size();
2082 CanMergeTail =
false;
2083 else if (NumPreds == 1 && CanMergeTail) {
2085 if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
2086 CanMergeTail =
false;
2089 MergeBlocks(BBI, TailBBI);
2090 TailBBI.IsDone =
true;
2094 BBI.HasFallThrough =
false;
2099 BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone =
true;
2100 InvalidatePreds(*BBI.BB);
2108 bool SawStore =
true;
2109 if (!
MI.isSafeToMove(SawStore))
2118 if (MO.isDef() && !LaterRedefs.
count(
Reg))
2128 SmallVectorImpl<MachineOperand> &
Cond,
2129 SmallSet<MCRegister, 4> *LaterRedefs) {
2130 bool AnyUnpred =
false;
2131 bool MaySpec = LaterRedefs !=
nullptr;
2132 for (MachineInstr &
I :
make_range(BBI.BB->begin(),
E)) {
2147 dbgs() <<
"Unable to predicate " <<
I <<
"!\n";
2159 BBI.IsAnalyzed =
false;
2160 BBI.NonPredSize = 0;
2169void IfConverterImpl::CopyAndPredicateBlock(
2170 BBInfo &ToBBI, BBInfo &FromBBI, SmallVectorImpl<MachineOperand> &
Cond,
2174 MachineBasicBlock &FromMBB = *FromBBI.BB;
2175 for (MachineInstr &
I : FromMBB) {
2177 if (IgnoreBr &&
I.isBranch())
2180 MachineInstr *
MI = MF.CloneMachineInstr(&
I);
2182 if (
I.isCandidateForAdditionalCallInfo())
2185 ToBBI.BB->insert(ToBBI.BB->end(),
MI);
2186 ToBBI.NonPredSize++;
2187 unsigned ExtraPredCost =
TII->getPredicationCost(
I);
2188 unsigned NumCycles = SchedModel.computeInstrLatency(&
I,
false);
2190 ToBBI.ExtraCost += NumCycles-1;
2191 ToBBI.ExtraCost2 += ExtraPredCost;
2196 dbgs() <<
"Unable to predicate " <<
I <<
"!\n";
2208 std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
2209 FromMBB.succ_end());
2211 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB :
nullptr;
2213 for (MachineBasicBlock *Succ : Succs) {
2215 if (Succ == FallThrough)
2217 ToBBI.BB->addSuccessor(Succ);
2221 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2224 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2225 ToBBI.IsAnalyzed =
false;
2235void IfConverterImpl::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI,
2237 MachineBasicBlock &FromMBB = *FromBBI.BB;
2239 "Removing a BB whose address is taken!");
2244 for (MachineInstr &
MI : FromMBB)
2245 if (
MI.getOpcode() == TargetOpcode::INLINEASM_BR)
2246 for (MachineOperand &MO :
MI.operands())
2247 if (MO.isMBB() && !ToBBI.BB->isSuccessor(MO.getMBB()))
2254 ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
2258 ToTI = ToBBI.BB->end();
2259 ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
2265 if (ToBBI.IsBrAnalyzable)
2266 ToBBI.BB->normalizeSuccProbs();
2268 SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.successors());
2270 MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB :
nullptr;
2274 if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
2278 ToBBI.BB->removeSuccessor(&FromMBB);
2281 for (MachineBasicBlock *Succ : FromSuccs) {
2283 if (Succ == FallThrough) {
2284 FromMBB.removeSuccessor(Succ);
2301 if (!To2FromProb.isZero())
2302 NewProb *= To2FromProb;
2305 FromMBB.removeSuccessor(Succ);
2330 if (ToBBI.BB->isSuccessor(Succ))
2331 ToBBI.BB->setSuccProbability(
2332 find(ToBBI.BB->successors(), Succ),
2335 ToBBI.BB->addSuccessor(Succ, NewProb);
2341 MachineBasicBlock *
Last = &*FromMBB.getParent()->rbegin();
2342 if (
Last != &FromMBB)
2343 FromMBB.moveAfter(
Last);
2347 if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
2348 ToBBI.BB->normalizeSuccProbs();
2350 ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
2351 FromBBI.Predicate.clear();
2353 ToBBI.NonPredSize += FromBBI.NonPredSize;
2354 ToBBI.ExtraCost += FromBBI.ExtraCost;
2355 ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
2356 FromBBI.NonPredSize = 0;
2357 FromBBI.ExtraCost = 0;
2358 FromBBI.ExtraCost2 = 0;
2360 ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
2361 ToBBI.HasFallThrough = FromBBI.HasFallThrough;
2362 ToBBI.IsAnalyzed =
false;
2363 FromBBI.IsAnalyzed =
false;
2368 return new IfConverterLegacy(std::move(Ftor));
2374 IfConverterImpl Impl;
2375 return Impl.runOnMachineFunction(
2378 return getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
2381 return &getAnalysis<MachineBranchProbabilityInfoWrapperPass>()
2384 [&]() {
return &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); },
2386 return PredicateFtor && !PredicateFtor(MF);
2392 IfConverterImpl Impl;
2393 bool Changed = Impl.runOnMachineFunction(
2402 .getCachedResult<ProfileSummaryAnalysis>(
2409 return PredicateFtor && !PredicateFtor(MF);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis false
static MachineBasicBlock * findFalseBlock(MachineBasicBlock *BB, MachineBasicBlock *TrueBB)
findFalseBlock - BB has a fallthrough.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const HexagonInstrInfo * TII
static MachineBasicBlock * findFalseBlock(MachineBasicBlock *BB, MachineBasicBlock *TrueBB)
BB has a fallthrough. Find its 'false' successor given its 'true' successor.
static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB, const TargetInstrInfo *TII)
Inserts an unconditional branch from MBB to ToMBB.
static void verifySameBranchInstructions(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2)
static MachineBasicBlock * getNextBlock(MachineBasicBlock &MBB)
Returns the next block in the function blocks ordering.
static bool MaySpeculate(const MachineInstr &MI, SmallSet< MCRegister, 4 > &LaterRedefs)
static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs)
Behaves like LivePhysRegs::stepForward() but also adds implicit uses to all values defined in MI whic...
static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB)
Returns true either if ToMBB is the next block after MBB or that all the intervening blocks are empty...
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
SmallVector< MachineOperand, 4 > Cond
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the SparseSet class derived from the version described in Briggs,...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
bool OptimizeFunction(MachineFunction &MF, const TargetInstrInfo *tii, const TargetRegisterInfo *tri, MachineLoopInfo *mli=nullptr, bool AfterPlacement=false)
Perhaps branch folding, tail merging and other CFG optimizations on the given function.
static constexpr BranchProbability getOne()
static constexpr BranchProbability getZero()
BranchProbability getCompl() const
FunctionPass class - This class is used to implement most global optimizations.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Module * getParent()
Get the module that this global value is contained inside of...
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
bool isPredicated(const MachineInstr &MI) const override
Returns true if the instruction is already predicated.
bool ClobbersPredicate(MachineInstr &MI, std::vector< MachineOperand > &Pred, bool SkipDead) const override
If the specified instruction defines any predicate or condition code register(s) used for predication...
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
Insert branch code into the end of the specified MachineBasicBlock.
bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, BranchProbability Probability) const override
Return true if it's profitable for if-converter to duplicate instructions of specified accumulated in...
bool SubsumesPredicate(ArrayRef< MachineOperand > Pred1, ArrayRef< MachineOperand > Pred2) const override
Returns true if the first specified predicate subsumes the second, e.g.
bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Cond) const override
Convert the instruction into a predicated instruction.
bool isPredicable(const MachineInstr &MI) const override
Return true if the specified instruction can be predicated.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A set of physical registers with utility functions to track liveness when walking backward/forward th...
LLVM_ABI void stepForward(const MachineInstr &MI, SmallVectorImpl< std::pair< MCPhysReg, const MachineOperand * > > &Clobbers)
Simulates liveness when stepping forward over an instruction(bundle).
void init(const TargetRegisterInfo &TRI)
(re-)initializes and clears the set.
LLVM_ABI void addLiveInsNoPristines(const MachineBasicBlock &MBB)
Adds all live-in registers of basic block MBB but skips pristine registers.
unsigned pred_size() const
MachineInstrBundleIterator< const MachineInstr > const_iterator
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator getFirstNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the first non-debug instruction in the basic block, or end().
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool hasAddressTaken() const
Test whether this block is used as something other than the target of a terminator,...
SmallVectorImpl< MachineBasicBlock * >::iterator pred_iterator
pred_iterator pred_begin()
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< iterator > terminators()
iterator_range< succ_iterator > successors()
reverse_iterator rbegin()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool mayHaveInlineAsmBr() const
Returns true if this block may have an INLINEASM_BR (overestimate, by checking if any of the successo...
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
void eraseAdditionalCallInfo(const MachineInstr *MI)
Following functions update call site info.
void copyAdditionalCallInfo(const MachineInstr *Old, const MachineInstr *New)
Copy the call site info from Old to \ New.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Representation of each machine instruction.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
MachineOperand class - Representation of each machine instruction operand.
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
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.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
Wrapper class representing virtual and physical registers.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
void insert_range(Range &&R)
bool contains(const T &V) const
Check if the SmallSet contains the given element.
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.
SparseSet - Fast set implementation for objects that can be identified by small unsigned keys.
std::pair< iterator, bool > insert(const ValueT &Val)
insert - Attempts to insert a new element.
size_type count(const KeyT &Key) const
count - Returns 1 if this set contains an element identified by Key, 0 otherwise.
void setUniverse(unsigned U)
setUniverse - Set the universe size which determines the largest key the set can hold.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
TargetSubtargetInfo - Generic base class for all target subtargets.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isPredicated(const MCInst &MI, const MCInstrInfo *MCII)
This is an optimization pass for GlobalISel generic memory operations.
void stable_sort(R &&Range)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Define
Register definition.
LLVM_ABI FunctionPass * createIfConverterLegacyPass(std::function< bool(const MachineFunction &)> Ftor)
scope_exit(Callable) -> scope_exit< Callable >
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
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...
LLVM_ABI void recomputeLivenessFlags(MachineBasicBlock &MBB)
Recomputes dead and kill flags in MBB.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
DWARFExpression::Operation Op
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI char & IfConverterID
IfConverter - This pass performs machine code if conversion.
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.