50#define DEBUG_TYPE "early-ifcvt"
53STATISTIC(NumDiamondsConv,
"Number of diamonds converted");
55STATISTIC(NumTrianglesConv,
"Number of triangles converted");
57 "Number of data dependent conditional branches encountered");
58STATISTIC(NumLikelyBiased,
"Number of branches with a hot path encountered");
60 "Number of branches with reduced critical-path budget");
85 const CodeGenOptions *Opts;
105 bool isTriangle()
const {
return TBB == Tail || FBB == Tail; }
108 MachineBasicBlock *getTPred()
const {
return TBB == Tail ? Head : TBB; }
111 MachineBasicBlock *getFPred()
const {
return FBB == Tail ? Head : FBB; }
118 TargetInstrInfo::SelectExpansion Select;
120 PHIInfo(MachineInstr *phi) : PHI(
phi) {}
126 SmallVector<MachineOperand, 4> Cond;
131 SmallPtrSet<MachineInstr*, 8> InsertAfter;
134 BitVector ClobberedRegUnits;
137 SparseSet<MCRegUnit, MCRegUnit, MCRegUnitToIndex> LiveRegUnits;
145 bool canSpeculateInstrs(MachineBasicBlock *
MBB);
149 bool canPredicateInstrs(MachineBasicBlock *
MBB);
153 bool InstrDependenciesAllowIfConv(MachineInstr *
I);
157 void PredicateBlock(MachineBasicBlock *
MBB,
bool ReversePredicate);
160 bool findInsertionPoint();
163 void replacePHIInstrs();
166 void rewritePHIOperands();
175 LiveRegUnits.clear();
176 LiveRegUnits.setUniverse(TRI->getNumRegUnits());
177 ClobberedRegUnits.clear();
178 ClobberedRegUnits.resize(TRI->getNumRegUnits());
185 bool canConvertIf(MachineBasicBlock *
MBB,
bool Predicate =
false);
189 void convertIf(SmallVectorImpl<MachineBasicBlock *> &RemoveBlocks,
190 bool Predicate =
false);
214 for (MachineInstr &
MI :
216 if (
MI.isDebugInstr())
219 if (++
InstrCount > Opts->early_ifcvt_limit && !Opts->stress_early_ifcvt) {
221 << Opts->early_ifcvt_limit <<
" instructions.\n");
240 bool DontMoveAcrossStore =
true;
241 if (!
MI.isSafeToMove(DontMoveAcrossStore)) {
247 if (!InstrDependenciesAllowIfConv(&
MI))
257bool SSAIfConv::InstrDependenciesAllowIfConv(MachineInstr *
I) {
258 for (
const MachineOperand &MO :
I->operands()) {
259 if (MO.isRegMask()) {
270 ClobberedRegUnits.
set(
static_cast<unsigned>(Unit));
281 LLVM_DEBUG(
dbgs() <<
"Can't insert instructions below terminator.\n");
296bool SSAIfConv::canPredicateInstrs(MachineBasicBlock *
MBB) {
311 if (
I->isDebugInstr())
314 if (++
InstrCount > Opts->early_ifcvt_limit && !Opts->stress_early_ifcvt) {
316 << Opts->early_ifcvt_limit <<
" instructions.\n");
339 if (!InstrDependenciesAllowIfConv(&(*
I)))
346void SSAIfConv::PredicateBlock(MachineBasicBlock *
MBB,
bool ReversePredicate) {
347 auto Condition =
Cond;
348 if (ReversePredicate) {
350 assert(CanRevCond &&
"Reversed predicate is not supported");
357 if (
I->isDebugInstr())
373bool SSAIfConv::findInsertionPoint() {
376 LiveRegUnits.
clear();
384 if (InsertAfter.
count(&*
I)) {
390 for (
const MachineOperand &MO :
I->operands()) {
400 LiveRegUnits.
erase(Unit);
406 while (!Reads.
empty())
408 if (ClobberedRegUnits.
test(
static_cast<unsigned>(Unit)))
409 LiveRegUnits.
insert(Unit);
412 if (
I != FirstTerm &&
I->isTerminator())
417 if (!LiveRegUnits.
empty()) {
419 dbgs() <<
"Would clobber";
420 for (MCRegUnit LRU : LiveRegUnits)
422 dbgs() <<
" live before " << *
I;
441bool SSAIfConv::canConvertIf(MachineBasicBlock *
MBB,
bool Predicate) {
447 MachineBasicBlock *Succ0 = Head->
succ_begin()[0];
448 MachineBasicBlock *Succ1 = Head->
succ_begin()[1];
471 if (!
Tail->livein_empty()) {
484 if (!Predicate && (
Tail->empty() || !
Tail->front().isPHI())) {
498 LLVM_DEBUG(
dbgs() <<
"analyzeBranch didn't find conditional branch.\n");
505 LLVM_DEBUG(
dbgs() <<
"analyzeBranch found an unconditional branch.\n");
511 FBB =
TBB == Succ0 ? Succ1 : Succ0;
515 MachineBasicBlock *TPred = getTPred();
516 MachineBasicBlock *FPred = getFPred();
518 I !=
E &&
I->isPHI(); ++
I) {
520 PHIInfo &PI = PHIs.
back();
522 for (
unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
523 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
524 PI.TReg = PI.PHI->getOperand(i).getReg();
525 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
526 PI.FReg = PI.PHI->getOperand(i).getReg();
528 assert(PI.TReg.isVirtual() &&
"Bad PHI");
529 assert(PI.FReg.isVirtual() &&
"Bad PHI");
532 if (!
TII->canInsertSelect(*Head,
Cond, PI.PHI->getOperand(0).getReg(),
533 PI.TReg, PI.FReg, PI.Select)) {
541 ClobberedRegUnits.
reset();
543 if (
TBB != Tail && !canPredicateInstrs(
TBB))
545 if (FBB != Tail && !canPredicateInstrs(FBB))
548 if (
TBB != Tail && !canSpeculateInstrs(
TBB))
550 if (FBB != Tail && !canSpeculateInstrs(FBB))
556 if (!findInsertionPoint())
573 if (!TReg.isVirtual() || !FReg.
isVirtual())
595 return MO.isReg() && MO.getReg().isPhysical();
600 if (!
TII->produceSameValue(*TDef, *FDef, &
MRI))
606 if (TIdx == -1 || FIdx == -1)
615void SSAIfConv::replacePHIInstrs() {
616 assert(
Tail->pred_size() == 2 &&
"Cannot replace PHIs");
618 assert(FirstTerm != Head->
end() &&
"No terminators");
619 DebugLoc HeadDL = FirstTerm->getDebugLoc();
622 for (PHIInfo &PI : PHIs) {
624 Register DstReg = PI.PHI->getOperand(0).getReg();
628 BuildMI(*Head, FirstTerm, HeadDL,
TII->get(TargetOpcode::COPY), DstReg)
631 TII->insertSelect(*Head, FirstTerm, HeadDL, DstReg,
Cond, PI.TReg,
635 PI.PHI->eraseFromParent();
643void SSAIfConv::rewritePHIOperands() {
645 assert(FirstTerm != Head->
end() &&
"No terminators");
646 DebugLoc HeadDL = FirstTerm->getDebugLoc();
649 for (PHIInfo &PI : PHIs) {
658 Register PHIDst = PI.PHI->getOperand(0).getReg();
660 TII->insertSelect(*Head, FirstTerm, HeadDL,
661 DstReg,
Cond, PI.TReg, PI.FReg);
666 for (
unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
667 MachineBasicBlock *
MBB = PI.PHI->getOperand(i-1).getMBB();
668 if (
MBB == getTPred()) {
669 PI.PHI->getOperand(i-1).setMBB(Head);
670 PI.PHI->getOperand(i-2).setReg(DstReg);
671 }
else if (
MBB == getFPred()) {
672 PI.PHI->removeOperand(i-1);
673 PI.PHI->removeOperand(i-2);
685void SSAIfConv::convertIf(SmallVectorImpl<MachineBasicBlock *> &RemoveBlocks,
687 assert(Head && Tail &&
TBB && FBB &&
"Call canConvertIf first.");
698 PredicateBlock(
TBB,
false);
703 PredicateBlock(FBB,
true);
707 bool ExtraPreds =
Tail->pred_size() != 2;
709 rewritePHIOperands();
717 TBB->removeSuccessor(Tail,
true);
749 if (Tail != &
Tail->getParent()->back())
750 Tail->moveAfter(&
Tail->getParent()->back());
766class EarlyIfConverter {
767 const CodeGenOptions &Opts;
768 const TargetInstrInfo *
TII =
nullptr;
769 const TargetSubtargetInfo *STI =
nullptr;
770 MachineRegisterInfo *
MRI =
nullptr;
771 MachineDominatorTree *DomTree =
nullptr;
772 MachineLoopInfo *
Loops =
nullptr;
773 MachineTraceMetrics *Traces =
nullptr;
775 MachineBranchProbabilityInfo &MBPI;
780 DenseMap<const MachineBasicBlock *, unsigned> NoCallBlocksCache;
783 EarlyIfConverter(
const CodeGenOptions &Opts, MachineDominatorTree &DT,
784 MachineLoopInfo &LI, MachineTraceMetrics &MTM,
785 MachineBranchProbabilityInfo &MBPI)
786 : Opts(Opts), DomTree(&DT),
Loops(&LI), Traces(&MTM), MBPI(MBPI) {}
787 EarlyIfConverter() =
delete;
792 bool tryConvertIf(MachineBasicBlock *);
793 void invalidateTraces();
794 bool shouldConvertIf();
795 bool isConditionDataDependent();
796 bool doOperandsComeFromMemory(
const MachineInstr *ConditionDef);
797 bool hasCallOrLoopInRange(
const MachineInstr *From,
const MachineInstr *To);
800class EarlyIfConverterLegacy :
public MachineFunctionPass {
803 EarlyIfConverterLegacy() : MachineFunctionPass(
ID) {}
804 void getAnalysisUsage(AnalysisUsage &AU)
const override;
806 StringRef getPassName()
const override {
return "Early If-Conversion"; }
810char EarlyIfConverterLegacy::ID = 0;
821void EarlyIfConverterLegacy::getAnalysisUsage(
AnalysisUsage &AU)
const {
835void updateDomTree(MachineDominatorTree *DomTree,
const SSAIfConv &IfConv,
841 for (
auto *
B : Removed) {
843 assert(Node != HeadNode &&
"Cannot erase the head node");
844 while (!
Node->isLeaf()) {
845 assert(
Node->getBlock() == IfConv.Tail &&
"Unexpected children");
853void updateLoops(MachineLoopInfo *
Loops,
857 for (
auto *
B : Removed)
863void EarlyIfConverter::invalidateTraces() {
874 const PseudoSourceValue *PSV = MOp->getPseudoValue();
875 return PSV && PSV->isConstantPool();
885bool EarlyIfConverter::hasCallOrLoopInRange(
const MachineInstr *From,
886 const MachineInstr *To) {
890 LLVM_DEBUG(
dbgs() <<
" checking for a call or loop between " << *From
892 assert(DomTree->
dominates(From, To) &&
"From is expected to dominate To");
894 const MachineBasicBlock *FromBB = From->
getParent();
895 const MachineBasicBlock *ToBB = To->
getParent();
897 unsigned NumScanned = 0;
898 auto HitSearchLimit = [&](
unsigned N) {
900 if (NumScanned <= Opts.early_ifcvt_max_region_instrs)
903 << Opts.early_ifcvt_max_region_instrs
904 <<
" instructions\n");
907 auto FoundCall = [](
const MachineInstr &
MI) {
911 auto IsCallOrHitSearchLimit = [&](
const MachineInstr &
MI) {
912 if (HitSearchLimit(1))
916 return FoundCall(
MI);
920 if (FromBB == ToBB) {
924 if (IsCallOrHitSearchLimit(
MI))
933 if (IsCallOrHitSearchLimit(
MI))
935 for (
const MachineInstr &
MI :
938 if (IsCallOrHitSearchLimit(
MI))
943 SmallPtrSet<const MachineBasicBlock *, 16> Enqueued = {FromBB, ToBB};
945 auto Enqueue = [&](
const MachineBasicBlock *BB) {
953 while (!Worklist.
empty()) {
959 if (
const MachineLoop *BBLoop =
Loops->getLoopFor(BB)) {
960 if (!BBLoop->contains(ToBB) && !BBLoop->contains(FromBB)) {
968 auto CacheIt = NoCallBlocksCache.find(BB);
969 if (CacheIt != NoCallBlocksCache.end()) {
970 if (HitSearchLimit(CacheIt->second))
973 unsigned NumBlockInstrs = 0;
974 for (
const MachineInstr &
MI :
978 if (IsCallOrHitSearchLimit(
MI))
981 NoCallBlocksCache[BB] = NumBlockInstrs;
997bool EarlyIfConverter::doOperandsComeFromMemory(
998 const MachineInstr *ConditionDef) {
1003 LLVM_DEBUG(
dbgs() <<
" doOperandsComeFromMemory starting from reg "
1009 MachineLoop *IfConvLoop =
Loops->getLoopFor(IfConv.Head);
1012 SmallPtrSet<const MachineInstr *, 8> VisitedInstrs;
1013 SmallVector<const MachineInstr *> Worklist;
1023 while (!Worklist.
empty() &&
1024 VisitedInstrs.
size() < Opts.early_ifcvt_max_steps) {
1026 if (!VisitedInstrs.
insert(
MI).second)
1035 const MachineBasicBlock *Parent =
MI->getParent();
1036 MachineLoop *ParentLoop =
Loops->getLoopFor(Parent);
1039 if (IfConvLoop && ParentLoop != IfConvLoop)
1046 !
MI->isDereferenceableInvariantLoad()) {
1051 if (!DomTree->
dominates(
MI, Br) || hasCallOrLoopInRange(
MI, Br))
1058 for (
const MachineOperand &MO :
MI->operands()) {
1059 if (!MO.isReg() || !MO.isUse())
1066 if (!VisitedInstrs.
count(UseDef)) {
1077bool EarlyIfConverter::isConditionDataDependent() {
1078 TargetInstrInfo::MachineBranchPredicate MBP;
1079 if (
TII->analyzeBranchPredicate(*IfConv.Head, MBP,
false))
1090 if (TBBProb != FBBProb) {
1108 if (Delta < 0 && Cyc + Delta > Cyc)
1120 return R <<
ore::NV(
C.Key,
C.Value) << (
C.Value == 1 ?
" cycle" :
" cycles");
1127bool EarlyIfConverter::shouldConvertIf() {
1129 if (Opts.stress_early_ifcvt)
1134 MachineLoop *CurrentLoop =
Loops->getLoopFor(IfConv.Head);
1140 if (CurrentLoop &&
any_of(IfConv.Cond, [&](MachineOperand &MO) {
1141 if (!MO.isReg() || !MO.isUse())
1143 Register Reg = MO.getReg();
1144 if (Reg.isPhysical())
1147 MachineInstr *Def = MRI->getVRegDef(Reg);
1148 return CurrentLoop->isLoopInvariant(*Def) ||
1149 all_of(Def->operands(), [&](MachineOperand &Op) {
1152 if (!Op.isReg() || !Op.isUse())
1154 Register Reg = Op.getReg();
1155 if (Reg.isPhysical())
1158 MachineInstr *Def = MRI->getVRegDef(Reg);
1159 return CurrentLoop->isLoopInvariant(*Def);
1165 MinInstr = Traces->getEnsemble(MachineTraceStrategy::TS_MinInstrCount);
1169 LLVM_DEBUG(
dbgs() <<
"TBB: " << TBBTrace <<
"FBB: " << FBBTrace);
1178 bool DataDependent =
false;
1179 if (Opts.enable_early_ifcvt_data_dependent)
1180 DataDependent = isConditionDataDependent();
1182 const unsigned MispredictPenalty = STI->getMispredictionPenalty();
1183 unsigned CritLimit =
1184 DataDependent ? MispredictPenalty : MispredictPenalty / 2;
1185 const BranchProbability ColdProb =
1186 std::min(MBPI.getEdgeProbability(IfConv.Head, IfConv.TBB),
1187 MBPI.getEdgeProbability(IfConv.Head, IfConv.FBB));
1188 const unsigned ColdEdgePercent =
1189 std::min(Opts.early_ifcvt_cold_edge_threshold, 50U);
1190 const bool StronglyBiased =
1191 ColdProb < BranchProbability(ColdEdgePercent, 100);
1192 if (StronglyBiased) {
1194 ++NumStronglyBiased;
1197 MachineBasicBlock &
MBB = *IfConv.Head;
1201 <<
", critical-path budget: " << CritLimit <<
" cycles\n");
1202 if (StronglyBiased) {
1204 return MachineOptimizationRemarkAnalysis(
DEBUG_TYPE,
1205 "StronglyBiasedBranch",
1207 <<
"branch has a cold edge below "
1208 <<
ore::NV(
"ColdEdgeThreshold", ColdEdgePercent)
1209 <<
"%, using a critical-path "
1210 "extension budget of "
1211 <<
ore::NV(
"CritLimit", CritLimit) <<
" cycles";
1216 if (DataDependent) {
1218 return MachineOptimizationRemarkAnalysis(
DEBUG_TYPE,
1219 "DataDependentCondition",
1221 <<
"branch condition is data-dependent (from memory load), "
1222 <<
"using higher CritLimit of " <<
ore::NV(
"CritLimit", CritLimit)
1231 if (IfConv.TBB != IfConv.Tail)
1235 <<
", minimal critical path " << MinCrit <<
'\n');
1236 if (ResLength > MinCrit + CritLimit) {
1239 MachineOptimizationRemarkMissed
R(
DEBUG_TYPE,
"IfConversion",
1241 R <<
"did not if-convert branch: the resulting critical path ("
1242 << Cycles{
"ResLength", ResLength}
1243 <<
") would extend the shorter leg's critical path ("
1244 << Cycles{
"MinCrit", MinCrit} <<
") by more than the threshold of "
1245 << Cycles{
"CritLimit", CritLimit}
1246 <<
", which cannot be hidden by available ILP.";
1256 unsigned BranchDepth =
1263 struct CriticalPathInfo {
1267 CriticalPathInfo
Cond{};
1268 CriticalPathInfo TBlock{};
1269 CriticalPathInfo FBlock{};
1270 bool ShouldConvert =
true;
1271 for (SSAIfConv::PHIInfo &PI : IfConv.PHIs) {
1278 if (CondDepth > MaxDepth) {
1279 unsigned Extra = CondDepth - MaxDepth;
1280 LLVM_DEBUG(
dbgs() <<
"Condition adds " << Extra <<
" cycles.\n");
1281 if (Extra >
Cond.Extra)
1282 Cond = {Extra, CondDepth};
1283 if (Extra > CritLimit) {
1285 ShouldConvert =
false;
1292 if (TDepth > MaxDepth) {
1293 unsigned Extra = TDepth - MaxDepth;
1295 if (Extra > TBlock.Extra)
1296 TBlock = {Extra, TDepth};
1297 if (Extra > CritLimit) {
1299 ShouldConvert =
false;
1306 if (FDepth > MaxDepth) {
1307 unsigned Extra = FDepth - MaxDepth;
1309 if (Extra > FBlock.Extra)
1310 FBlock = {Extra, FDepth};
1311 if (Extra > CritLimit) {
1313 ShouldConvert =
false;
1321 const CriticalPathInfo
Short = TBlock.Extra > FBlock.Extra ? FBlock : TBlock;
1322 const CriticalPathInfo
Long = TBlock.Extra > FBlock.Extra ? TBlock : FBlock;
1324 if (ShouldConvert) {
1326 MachineOptimizationRemark
R(
DEBUG_TYPE,
"IfConversion",
1328 R <<
"performing if-conversion on branch: the condition adds "
1329 << Cycles{
"CondCycles",
Cond.Extra} <<
" to the critical path";
1330 if (
Short.Extra > 0)
1331 R <<
", and the short leg adds another "
1332 << Cycles{
"ShortCycles",
Short.Extra};
1334 R <<
", and the long leg adds another "
1335 << Cycles{
"LongCycles",
Long.Extra};
1336 R <<
", each staying under the threshold of "
1337 << Cycles{
"CritLimit", CritLimit} <<
".";
1342 MachineOptimizationRemarkMissed
R(
DEBUG_TYPE,
"IfConversion",
1344 R <<
"did not if-convert branch: the condition would add "
1345 << Cycles{
"CondCycles",
Cond.Extra} <<
" to the critical path";
1346 if (
Cond.Extra > CritLimit)
1347 R <<
" exceeding the limit of " << Cycles{
"CritLimit", CritLimit};
1348 if (
Short.Extra > 0) {
1349 R <<
", and the short leg would add another "
1350 << Cycles{
"ShortCycles",
Short.Extra};
1351 if (
Short.Extra > CritLimit)
1352 R <<
" exceeding the limit of " << Cycles{
"CritLimit", CritLimit};
1354 if (
Long.Extra > 0) {
1355 R <<
", and the long leg would add another "
1356 << Cycles{
"LongCycles",
Long.Extra};
1357 if (
Long.Extra > CritLimit)
1358 R <<
" exceeding the limit of " << Cycles{
"CritLimit", CritLimit};
1365 return ShouldConvert;
1370bool EarlyIfConverter::tryConvertIf(MachineBasicBlock *
MBB) {
1372 while (IfConv.canConvertIf(
MBB) && shouldConvertIf()) {
1375 SmallVector<MachineBasicBlock *, 4> RemoveBlocks;
1376 IfConv.convertIf(RemoveBlocks);
1378 updateDomTree(DomTree, IfConv, RemoveBlocks);
1379 updateLoops(
Loops, RemoveBlocks);
1382 NoCallBlocksCache.erase(IfConv.Head);
1383 for (MachineBasicBlock *
MBB : RemoveBlocks) {
1384 NoCallBlocksCache.erase(
MBB);
1392 LLVM_DEBUG(
dbgs() <<
"********** EARLY IF-CONVERSION **********\n"
1393 <<
"********** Function: " << MF.
getName() <<
'\n');
1412 if (tryConvertIf(DomNode->getBlock()))
1439bool EarlyIfConverterLegacy::runOnMachineFunction(
MachineFunction &MF) {
1444 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1445 MachineLoopInfo &LI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1447 getAnalysis<MachineTraceMetricsWrapperPass>().getMTM();
1449 getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
1470 void getAnalysisUsage(AnalysisUsage &AU)
const override;
1472 StringRef getPassName()
const override {
return "Early If-predicator"; }
1475 bool tryConvertIf(MachineBasicBlock *);
1476 bool shouldConvertIf();
1481#define DEBUG_TYPE "early-if-predicator"
1483char EarlyIfPredicator::ID = 0;
1493void EarlyIfPredicator::getAnalysisUsage(
AnalysisUsage &AU)
const {
1503bool EarlyIfPredicator::shouldConvertIf() {
1505 if (IfConv.isTriangle()) {
1506 MachineBasicBlock &IfBlock =
1507 (IfConv.TBB == IfConv.Tail) ? *IfConv.FBB : *IfConv.
TBB;
1509 unsigned ExtraPredCost = 0;
1510 unsigned Cycles = 0;
1511 for (MachineInstr &
I : IfBlock) {
1512 unsigned NumCycles = SchedModel.computeInstrLatency(&
I,
false);
1514 Cycles += NumCycles - 1;
1515 ExtraPredCost +=
TII->getPredicationCost(
I);
1521 unsigned TExtra = 0;
1522 unsigned FExtra = 0;
1523 unsigned TCycle = 0;
1524 unsigned FCycle = 0;
1525 for (MachineInstr &
I : *IfConv.TBB) {
1526 unsigned NumCycles = SchedModel.computeInstrLatency(&
I,
false);
1528 TCycle += NumCycles - 1;
1529 TExtra +=
TII->getPredicationCost(
I);
1531 for (MachineInstr &
I : *IfConv.FBB) {
1532 unsigned NumCycles = SchedModel.computeInstrLatency(&
I,
false);
1534 FCycle += NumCycles - 1;
1535 FExtra +=
TII->getPredicationCost(
I);
1538 FCycle, FExtra, TrueProbability);
1543bool EarlyIfPredicator::tryConvertIf(MachineBasicBlock *
MBB) {
1545 while (IfConv.canConvertIf(
MBB,
true) && shouldConvertIf()) {
1547 SmallVector<MachineBasicBlock *, 4> RemoveBlocks;
1548 IfConv.convertIf(RemoveBlocks,
true);
1550 updateDomTree(DomTree, IfConv, RemoveBlocks);
1551 updateLoops(
Loops, RemoveBlocks);
1552 for (MachineBasicBlock *
MBB : RemoveBlocks)
1559 LLVM_DEBUG(
dbgs() <<
"********** EARLY IF-PREDICATOR **********\n"
1560 <<
"********** Function: " << MF.
getName() <<
'\n');
1566 SchedModel.
init(&STI);
1567 DomTree = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
1568 Loops = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1569 MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
1579 if (tryConvertIf(DomNode->getBlock()))
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static unsigned InstrCount
This file defines the DenseMap class.
static bool hasSameValue(const MachineRegisterInfo &MRI, const TargetInstrInfo *TII, Register TReg, Register FReg)
static unsigned adjCycles(unsigned Cyc, int Delta)
static bool isConstantPoolLoad(const MachineInstr *MI)
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
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)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
SmallVector< MachineOperand, 4 > Cond
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file defines the SmallPtrSet 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.
Represent the analysis usage information of a pass.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
BitVector & reset()
Reset all bits in the bitvector.
BitVector & set()
Set all bits in the bitvector.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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 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 isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, unsigned ExtraPredCycles, BranchProbability Probability) const override
Return true if it's profitable to predicate instructions with accumulated instruction latency of "Num...
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.
unsigned pred_size() const
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
instr_iterator instr_begin()
succ_iterator succ_begin()
bool livein_empty() const
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
unsigned succ_size() const
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
instr_iterator instr_end()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< pred_iterator > predecessors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI void moveAfter(MachineBasicBlock *NewBefore)
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) 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.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & back() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
LLVM_ABI bool isDereferenceableInvariantLoad() const
Return true if this load instruction never traps and points to a memory location whose value doesn't ...
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
mop_range uses()
Returns all operands which may be register uses.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
Analysis pass that exposes the MachineLoopInfo for a machine function.
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI unsigned getResourceLength(ArrayRef< const MachineBasicBlock * > Extrablocks={}, ArrayRef< const MCSchedClassDesc * > ExtraInstrs={}, ArrayRef< const MCSchedClassDesc * > RemoveInstrs={}) const
Return the resource length of the trace.
InstrCycles getInstrCycles(const MachineInstr &MI) const
Return the depth and height of MI.
LLVM_ABI unsigned getInstrSlack(const MachineInstr &MI) const
Return the slack of MI.
unsigned getCriticalPath() const
Return the length of the (data dependency) critical path through the trace.
LLVM_ABI unsigned getPHIDepth(const MachineInstr &PHI) const
Return the Depth of a PHI instruction in a trace center block successor.
LLVM_ABI void verifyAnalysis() const
LLVM_ABI void invalidate(const MachineBasicBlock *MBB)
Invalidate cached information about MBB.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Wrapper class representing virtual and physical registers.
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
iterator erase(iterator I)
erase - Erases an existing element identified by a valid iterator.
void clear()
clear - Clears the set.
std::pair< iterator, bool > insert(const ValueT &Val)
insert - Attempts to insert a new element.
bool empty() const
empty - Returns true if the set is empty.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual bool enableEarlyIfConversion() const
Enable the use of the early if conversion pass.
self_iterator getIterator()
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< NodeBase * > Node
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI char & EarlyIfConverterLegacyID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions.
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
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...
auto post_order(const T &G)
Post-order traversal of a graph.
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
LLVM_ABI char & EarlyIfPredicatorID
EarlyIfPredicator - This pass performs if-conversion on SSA form by predicating if/else block and ins...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
unsigned Depth
Earliest issue cycle as determined by data dependencies and instruction latencies from the beginning ...
MachineInstr * ConditionDef