#include "BranchFolding.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/SparseSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/CodeGen/LivePhysRegs.h"
#include "llvm/CodeGen/MBFIWrapper.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSchedule.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/InitializePasses.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Pass.h"
#include "llvm/Support/BranchProbability.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <functional>
#include <iterator>
#include <memory>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "if-converter"
static cl::opt<int> IfCvtFnStart("ifcvt-fn-start", cl::init(-1), cl::Hidden);
static cl::opt<int> IfCvtFnStop("ifcvt-fn-stop", cl::init(-1), cl::Hidden);
static cl::opt<int> IfCvtLimit("ifcvt-limit", cl::init(-1), cl::Hidden);
static cl::opt<bool> DisableSimple("disable-ifcvt-simple",
cl::init(false), cl::Hidden);
static cl::opt<bool> DisableSimpleF("disable-ifcvt-simple-false",
cl::init(false), cl::Hidden);
static cl::opt<bool> DisableTriangle("disable-ifcvt-triangle",
cl::init(false), cl::Hidden);
static cl::opt<bool> DisableTriangleR("disable-ifcvt-triangle-rev",
cl::init(false), cl::Hidden);
static cl::opt<bool> DisableTriangleF("disable-ifcvt-triangle-false",
cl::init(false), cl::Hidden);
static cl::opt<bool> DisableTriangleFR("disable-ifcvt-triangle-false-rev",
cl::init(false), cl::Hidden);
static cl::opt<bool> DisableDiamond("disable-ifcvt-diamond",
cl::init(false), cl::Hidden);
static cl::opt<bool> DisableForkedDiamond("disable-ifcvt-forked-diamond",
cl::init(false), cl::Hidden);
static cl::opt<bool> IfCvtBranchFold("ifcvt-branch-fold",
cl::init(true), cl::Hidden);
STATISTIC(NumSimple, "Number of simple if-conversions performed");
STATISTIC(NumSimpleFalse, "Number of simple (F) if-conversions performed");
STATISTIC(NumTriangle, "Number of triangle if-conversions performed");
STATISTIC(NumTriangleRev, "Number of triangle (R) if-conversions performed");
STATISTIC(NumTriangleFalse,"Number of triangle (F) if-conversions performed");
STATISTIC(NumTriangleFRev, "Number of triangle (F/R) if-conversions performed");
STATISTIC(NumDiamonds, "Number of diamond if-conversions performed");
STATISTIC(NumForkedDiamonds, "Number of forked-diamond if-conversions performed");
STATISTIC(NumIfConvBBs, "Number of if-converted blocks");
STATISTIC(NumDupBBs, "Number of duplicated blocks");
STATISTIC(NumUnpred, "Number of true blocks of diamonds unpredicated");
namespace {
class IfConverter : public MachineFunctionPass {
enum IfcvtKind {
ICNotClassfied, ICSimpleFalse, ICSimple, ICTriangleFRev, ICTriangleRev, ICTriangleFalse, ICTriangle, ICDiamond, ICForkedDiamond };
struct BBInfo {
bool IsDone : 1;
bool IsBeingAnalyzed : 1;
bool IsAnalyzed : 1;
bool IsEnqueued : 1;
bool IsBrAnalyzable : 1;
bool IsBrReversible : 1;
bool HasFallThrough : 1;
bool IsUnpredicable : 1;
bool CannotBeCopied : 1;
bool ClobbersPred : 1;
unsigned NonPredSize = 0;
unsigned ExtraCost = 0;
unsigned ExtraCost2 = 0;
MachineBasicBlock *BB = nullptr;
MachineBasicBlock *TrueBB = nullptr;
MachineBasicBlock *FalseBB = nullptr;
SmallVector<MachineOperand, 4> BrCond;
SmallVector<MachineOperand, 4> Predicate;
BBInfo() : IsDone(false), IsBeingAnalyzed(false),
IsAnalyzed(false), IsEnqueued(false), IsBrAnalyzable(false),
IsBrReversible(false), HasFallThrough(false),
IsUnpredicable(false), CannotBeCopied(false),
ClobbersPred(false) {}
};
struct IfcvtToken {
BBInfo &BBI;
IfcvtKind Kind;
unsigned NumDups;
unsigned NumDups2;
bool NeedSubsumption : 1;
bool TClobbersPred : 1;
bool FClobbersPred : 1;
IfcvtToken(BBInfo &b, IfcvtKind k, bool s, unsigned d, unsigned d2 = 0,
bool tc = false, bool fc = false)
: BBI(b), Kind(k), NumDups(d), NumDups2(d2), NeedSubsumption(s),
TClobbersPred(tc), FClobbersPred(fc) {}
};
std::vector<BBInfo> BBAnalysis;
TargetSchedModel SchedModel;
const TargetLoweringBase *TLI;
const TargetInstrInfo *TII;
const TargetRegisterInfo *TRI;
const MachineBranchProbabilityInfo *MBPI;
MachineRegisterInfo *MRI;
LivePhysRegs Redefs;
bool PreRegAlloc;
bool MadeChange;
int FnNum = -1;
std::function<bool(const MachineFunction &)> PredicateFtor;
public:
static char ID;
IfConverter(std::function<bool(const MachineFunction &)> Ftor = nullptr)
: MachineFunctionPass(ID), PredicateFtor(std::move(Ftor)) {
initializeIfConverterPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MachineBlockFrequencyInfo>();
AU.addRequired<MachineBranchProbabilityInfo>();
AU.addRequired<ProfileSummaryInfoWrapperPass>();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override;
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::NoVRegs);
}
private:
bool reverseBranchCondition(BBInfo &BBI) const;
bool ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
BranchProbability Prediction) const;
bool ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
bool FalseBranch, unsigned &Dups,
BranchProbability Prediction) const;
bool CountDuplicatedInstructions(
MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
unsigned &Dups1, unsigned &Dups2,
MachineBasicBlock &TBB, MachineBasicBlock &FBB,
bool SkipUnconditionalBranches) const;
bool ValidDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
unsigned &Dups1, unsigned &Dups2,
BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
bool ValidForkedDiamond(BBInfo &TrueBBI, BBInfo &FalseBBI,
unsigned &Dups1, unsigned &Dups2,
BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const;
void AnalyzeBranches(BBInfo &BBI);
void ScanInstructions(BBInfo &BBI,
MachineBasicBlock::iterator &Begin,
MachineBasicBlock::iterator &End,
bool BranchUnpredicable = false) const;
bool RescanInstructions(
MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
BBInfo &TrueBBI, BBInfo &FalseBBI) const;
void AnalyzeBlock(MachineBasicBlock &MBB,
std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
bool FeasibilityAnalysis(BBInfo &BBI, SmallVectorImpl<MachineOperand> &Pred,
bool isTriangle = false, bool RevBranch = false,
bool hasCommonTail = false);
void AnalyzeBlocks(MachineFunction &MF,
std::vector<std::unique_ptr<IfcvtToken>> &Tokens);
void InvalidatePreds(MachineBasicBlock &MBB);
bool IfConvertSimple(BBInfo &BBI, IfcvtKind Kind);
bool IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind);
bool IfConvertDiamondCommon(BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
unsigned NumDups1, unsigned NumDups2,
bool TClobbersPred, bool FClobbersPred,
bool RemoveBranch, bool MergeAddEdges);
bool IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
unsigned NumDups1, unsigned NumDups2,
bool TClobbers, bool FClobbers);
bool IfConvertForkedDiamond(BBInfo &BBI, IfcvtKind Kind,
unsigned NumDups1, unsigned NumDups2,
bool TClobbers, bool FClobbers);
void PredicateBlock(BBInfo &BBI,
MachineBasicBlock::iterator E,
SmallVectorImpl<MachineOperand> &Cond,
SmallSet<MCPhysReg, 4> *LaterRedefs = nullptr);
void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
SmallVectorImpl<MachineOperand> &Cond,
bool IgnoreBr = false);
void MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges = true);
bool MeetIfcvtSizeLimit(MachineBasicBlock &BB,
unsigned Cycle, unsigned Extra,
BranchProbability Prediction) const {
return Cycle > 0 && TII->isProfitableToIfCvt(BB, Cycle, Extra,
Prediction);
}
bool MeetIfcvtSizeLimit(BBInfo &TBBInfo, BBInfo &FBBInfo,
MachineBasicBlock &CommBB, unsigned Dups,
BranchProbability Prediction, bool Forked) const {
const MachineFunction &MF = *TBBInfo.BB->getParent();
if (MF.getFunction().hasMinSize()) {
MachineBasicBlock::iterator TIB = TBBInfo.BB->begin();
MachineBasicBlock::iterator FIB = FBBInfo.BB->begin();
MachineBasicBlock::iterator TIE = TBBInfo.BB->end();
MachineBasicBlock::iterator FIE = FBBInfo.BB->end();
unsigned Dups1 = 0, Dups2 = 0;
if (!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
*TBBInfo.BB, *FBBInfo.BB,
true))
llvm_unreachable("should already have been checked by ValidDiamond");
unsigned BranchBytes = 0;
unsigned CommonBytes = 0;
for (auto &I : make_range(TBBInfo.BB->begin(), TIB)) {
LLVM_DEBUG(dbgs() << "Common inst: " << I);
CommonBytes += TII->getInstSizeInBytes(I);
}
for (auto &I : make_range(FBBInfo.BB->begin(), FIB)) {
LLVM_DEBUG(dbgs() << "Common inst: " << I);
CommonBytes += TII->getInstSizeInBytes(I);
}
for (auto &I : make_range(TIE, TBBInfo.BB->end())) {
if (I.isBranch() && TBBInfo.IsBrAnalyzable && !Forked) {
LLVM_DEBUG(dbgs() << "Saving branch: " << I);
BranchBytes += TII->predictBranchSizeForIfCvt(I);
} else {
LLVM_DEBUG(dbgs() << "Common inst: " << I);
CommonBytes += TII->getInstSizeInBytes(I);
}
}
for (auto &I : make_range(FIE, FBBInfo.BB->end())) {
if (I.isBranch() && FBBInfo.IsBrAnalyzable && !Forked) {
LLVM_DEBUG(dbgs() << "Saving branch: " << I);
BranchBytes += TII->predictBranchSizeForIfCvt(I);
} else {
LLVM_DEBUG(dbgs() << "Common inst: " << I);
CommonBytes += TII->getInstSizeInBytes(I);
}
}
for (auto &I : CommBB.terminators()) {
if (I.isBranch()) {
LLVM_DEBUG(dbgs() << "Saving branch: " << I);
BranchBytes += TII->predictBranchSizeForIfCvt(I);
}
}
CommonBytes /= 2;
unsigned NumPredicatedInstructions = 0;
for (auto &I : make_range(TIB, TIE)) {
if (!I.isDebugInstr()) {
LLVM_DEBUG(dbgs() << "Predicating: " << I);
NumPredicatedInstructions++;
}
}
for (auto &I : make_range(FIB, FIE)) {
if (!I.isDebugInstr()) {
LLVM_DEBUG(dbgs() << "Predicating: " << I);
NumPredicatedInstructions++;
}
}
if (NumPredicatedInstructions > 15)
return false;
unsigned ExtraPredicateBytes = TII->extraSizeToPredicateInstructions(
MF, NumPredicatedInstructions);
LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(BranchBytes=" << BranchBytes
<< ", CommonBytes=" << CommonBytes
<< ", NumPredicatedInstructions="
<< NumPredicatedInstructions
<< ", ExtraPredicateBytes=" << ExtraPredicateBytes
<< ")\n");
return (BranchBytes + CommonBytes) > ExtraPredicateBytes;
} else {
unsigned TCycle = TBBInfo.NonPredSize + TBBInfo.ExtraCost - Dups;
unsigned FCycle = FBBInfo.NonPredSize + FBBInfo.ExtraCost - Dups;
bool Res = TCycle > 0 && FCycle > 0 &&
TII->isProfitableToIfCvt(
*TBBInfo.BB, TCycle, TBBInfo.ExtraCost2, *FBBInfo.BB,
FCycle, FBBInfo.ExtraCost2, Prediction);
LLVM_DEBUG(dbgs() << "MeetIfcvtSizeLimit(TCycle=" << TCycle
<< ", FCycle=" << FCycle
<< ", TExtra=" << TBBInfo.ExtraCost2 << ", FExtra="
<< FBBInfo.ExtraCost2 << ") = " << Res << "\n");
return Res;
}
}
bool blockAlwaysFallThrough(BBInfo &BBI) const {
return BBI.IsBrAnalyzable && BBI.TrueBB == nullptr;
}
static bool IfcvtTokenCmp(const std::unique_ptr<IfcvtToken> &C1,
const std::unique_ptr<IfcvtToken> &C2) {
int Incr1 = (C1->Kind == ICDiamond)
? -(int)(C1->NumDups + C1->NumDups2) : (int)C1->NumDups;
int Incr2 = (C2->Kind == ICDiamond)
? -(int)(C2->NumDups + C2->NumDups2) : (int)C2->NumDups;
if (Incr1 > Incr2)
return true;
else if (Incr1 == Incr2) {
if (!C1->NeedSubsumption && C2->NeedSubsumption)
return true;
else if (C1->NeedSubsumption == C2->NeedSubsumption) {
if ((unsigned)C1->Kind < (unsigned)C2->Kind)
return true;
else if (C1->Kind == C2->Kind)
return C1->BBI.BB->getNumber() < C2->BBI.BB->getNumber();
}
}
return false;
}
};
}
char IfConverter::ID = 0;
char &llvm::IfConverterID = IfConverter::ID;
INITIALIZE_PASS_BEGIN(IfConverter, DEBUG_TYPE, "If Converter", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
INITIALIZE_PASS_END(IfConverter, DEBUG_TYPE, "If Converter", false, false)
bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
if (skipFunction(MF.getFunction()) || (PredicateFtor && !PredicateFtor(MF)))
return false;
const TargetSubtargetInfo &ST = MF.getSubtarget();
TLI = ST.getTargetLowering();
TII = ST.getInstrInfo();
TRI = ST.getRegisterInfo();
MBFIWrapper MBFI(getAnalysis<MachineBlockFrequencyInfo>());
MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
ProfileSummaryInfo *PSI =
&getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
MRI = &MF.getRegInfo();
SchedModel.init(&ST);
if (!TII) return false;
PreRegAlloc = MRI->isSSA();
bool BFChange = false;
if (!PreRegAlloc) {
BranchFolder BF(true, false, MBFI, *MBPI, PSI);
BFChange = BF.OptimizeFunction(MF, TII, ST.getRegisterInfo());
}
LLVM_DEBUG(dbgs() << "\nIfcvt: function (" << ++FnNum << ") \'"
<< MF.getName() << "\'");
if (FnNum < IfCvtFnStart || (IfCvtFnStop != -1 && FnNum > IfCvtFnStop)) {
LLVM_DEBUG(dbgs() << " skipped\n");
return false;
}
LLVM_DEBUG(dbgs() << "\n");
MF.RenumberBlocks();
BBAnalysis.resize(MF.getNumBlockIDs());
std::vector<std::unique_ptr<IfcvtToken>> Tokens;
MadeChange = false;
unsigned NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle +
NumTriangleRev + NumTriangleFalse + NumTriangleFRev + NumDiamonds;
while (IfCvtLimit == -1 || (int)NumIfCvts < IfCvtLimit) {
bool Change = false;
AnalyzeBlocks(MF, Tokens);
while (!Tokens.empty()) {
std::unique_ptr<IfcvtToken> Token = std::move(Tokens.back());
Tokens.pop_back();
BBInfo &BBI = Token->BBI;
IfcvtKind Kind = Token->Kind;
unsigned NumDups = Token->NumDups;
unsigned NumDups2 = Token->NumDups2;
if (BBI.IsDone)
BBI.IsEnqueued = false;
if (!BBI.IsEnqueued)
continue;
BBI.IsEnqueued = false;
bool RetVal = false;
switch (Kind) {
default: llvm_unreachable("Unexpected!");
case ICSimple:
case ICSimpleFalse: {
bool isFalse = Kind == ICSimpleFalse;
if ((isFalse && DisableSimpleF) || (!isFalse && DisableSimple)) break;
LLVM_DEBUG(dbgs() << "Ifcvt (Simple"
<< (Kind == ICSimpleFalse ? " false" : "")
<< "): " << printMBBReference(*BBI.BB) << " ("
<< ((Kind == ICSimpleFalse) ? BBI.FalseBB->getNumber()
: BBI.TrueBB->getNumber())
<< ") ");
RetVal = IfConvertSimple(BBI, Kind);
LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
if (RetVal) {
if (isFalse) ++NumSimpleFalse;
else ++NumSimple;
}
break;
}
case ICTriangle:
case ICTriangleRev:
case ICTriangleFalse:
case ICTriangleFRev: {
bool isFalse = Kind == ICTriangleFalse;
bool isRev = (Kind == ICTriangleRev || Kind == ICTriangleFRev);
if (DisableTriangle && !isFalse && !isRev) break;
if (DisableTriangleR && !isFalse && isRev) break;
if (DisableTriangleF && isFalse && !isRev) break;
if (DisableTriangleFR && isFalse && isRev) break;
LLVM_DEBUG(dbgs() << "Ifcvt (Triangle");
if (isFalse)
LLVM_DEBUG(dbgs() << " false");
if (isRev)
LLVM_DEBUG(dbgs() << " rev");
LLVM_DEBUG(dbgs() << "): " << printMBBReference(*BBI.BB)
<< " (T:" << BBI.TrueBB->getNumber()
<< ",F:" << BBI.FalseBB->getNumber() << ") ");
RetVal = IfConvertTriangle(BBI, Kind);
LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
if (RetVal) {
if (isFalse) {
if (isRev) ++NumTriangleFRev;
else ++NumTriangleFalse;
} else {
if (isRev) ++NumTriangleRev;
else ++NumTriangle;
}
}
break;
}
case ICDiamond:
if (DisableDiamond) break;
LLVM_DEBUG(dbgs() << "Ifcvt (Diamond): " << printMBBReference(*BBI.BB)
<< " (T:" << BBI.TrueBB->getNumber()
<< ",F:" << BBI.FalseBB->getNumber() << ") ");
RetVal = IfConvertDiamond(BBI, Kind, NumDups, NumDups2,
Token->TClobbersPred,
Token->FClobbersPred);
LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
if (RetVal) ++NumDiamonds;
break;
case ICForkedDiamond:
if (DisableForkedDiamond) break;
LLVM_DEBUG(dbgs() << "Ifcvt (Forked Diamond): "
<< printMBBReference(*BBI.BB)
<< " (T:" << BBI.TrueBB->getNumber()
<< ",F:" << BBI.FalseBB->getNumber() << ") ");
RetVal = IfConvertForkedDiamond(BBI, Kind, NumDups, NumDups2,
Token->TClobbersPred,
Token->FClobbersPred);
LLVM_DEBUG(dbgs() << (RetVal ? "succeeded!" : "failed!") << "\n");
if (RetVal) ++NumForkedDiamonds;
break;
}
if (RetVal && MRI->tracksLiveness())
recomputeLivenessFlags(*BBI.BB);
Change |= RetVal;
NumIfCvts = NumSimple + NumSimpleFalse + NumTriangle + NumTriangleRev +
NumTriangleFalse + NumTriangleFRev + NumDiamonds;
if (IfCvtLimit != -1 && (int)NumIfCvts >= IfCvtLimit)
break;
}
if (!Change)
break;
MadeChange |= Change;
}
Tokens.clear();
BBAnalysis.clear();
if (MadeChange && IfCvtBranchFold) {
BranchFolder BF(false, false, MBFI, *MBPI, PSI);
BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo());
}
MadeChange |= BFChange;
return MadeChange;
}
static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
MachineBasicBlock *TrueBB) {
for (MachineBasicBlock *SuccBB : BB->successors()) {
if (SuccBB != TrueBB)
return SuccBB;
}
return nullptr;
}
bool IfConverter::reverseBranchCondition(BBInfo &BBI) const {
DebugLoc dl; if (!TII->reverseBranchCondition(BBI.BrCond)) {
TII->removeBranch(*BBI.BB);
TII->insertBranch(*BBI.BB, BBI.FalseBB, BBI.TrueBB, BBI.BrCond, dl);
std::swap(BBI.TrueBB, BBI.FalseBB);
return true;
}
return false;
}
static inline MachineBasicBlock *getNextBlock(MachineBasicBlock &MBB) {
MachineFunction::iterator I = MBB.getIterator();
MachineFunction::iterator E = MBB.getParent()->end();
if (++I == E)
return nullptr;
return &*I;
}
bool IfConverter::ValidSimple(BBInfo &TrueBBI, unsigned &Dups,
BranchProbability Prediction) const {
Dups = 0;
if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
return false;
if (TrueBBI.IsBrAnalyzable)
return false;
if (TrueBBI.BB->pred_size() > 1) {
if (TrueBBI.CannotBeCopied ||
!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, TrueBBI.NonPredSize,
Prediction))
return false;
Dups = TrueBBI.NonPredSize;
}
return true;
}
bool IfConverter::ValidTriangle(BBInfo &TrueBBI, BBInfo &FalseBBI,
bool FalseBranch, unsigned &Dups,
BranchProbability Prediction) const {
Dups = 0;
if (TrueBBI.BB == FalseBBI.BB)
return false;
if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone)
return false;
if (TrueBBI.BB->pred_size() > 1) {
if (TrueBBI.CannotBeCopied)
return false;
unsigned Size = TrueBBI.NonPredSize;
if (TrueBBI.IsBrAnalyzable) {
if (TrueBBI.TrueBB && TrueBBI.BrCond.empty())
--Size;
else {
MachineBasicBlock *FExit = FalseBranch
? TrueBBI.TrueBB : TrueBBI.FalseBB;
if (FExit)
++Size;
}
}
if (!TII->isProfitableToDupForIfCvt(*TrueBBI.BB, Size, Prediction))
return false;
Dups = Size;
}
MachineBasicBlock *TExit = FalseBranch ? TrueBBI.FalseBB : TrueBBI.TrueBB;
if (!TExit && blockAlwaysFallThrough(TrueBBI)) {
MachineFunction::iterator I = TrueBBI.BB->getIterator();
if (++I == TrueBBI.BB->getParent()->end())
return false;
TExit = &*I;
}
return TExit && TExit == FalseBBI.BB;
}
bool IfConverter::CountDuplicatedInstructions(
MachineBasicBlock::iterator &TIB,
MachineBasicBlock::iterator &FIB,
MachineBasicBlock::iterator &TIE,
MachineBasicBlock::iterator &FIE,
unsigned &Dups1, unsigned &Dups2,
MachineBasicBlock &TBB, MachineBasicBlock &FBB,
bool SkipUnconditionalBranches) const {
while (TIB != TIE && FIB != FIE) {
TIB = skipDebugInstructionsForward(TIB, TIE, false);
FIB = skipDebugInstructionsForward(FIB, FIE, false);
if (TIB == TIE || FIB == FIE)
break;
if (!TIB->isIdenticalTo(*FIB))
break;
std::vector<MachineOperand> PredDefs;
if (TII->ClobbersPredicate(*TIB, PredDefs, false))
return false;
if (!TIB->isBranch())
++Dups1;
++TIB;
++FIB;
}
if (TIB == TIE || FIB == FIE)
return true;
MachineBasicBlock::reverse_iterator RTIE = std::next(TIE.getReverse());
MachineBasicBlock::reverse_iterator RFIE = std::next(FIE.getReverse());
const MachineBasicBlock::reverse_iterator RTIB = std::next(TIB.getReverse());
const MachineBasicBlock::reverse_iterator RFIB = std::next(FIB.getReverse());
if (!TBB.succ_empty() || !FBB.succ_empty()) {
if (SkipUnconditionalBranches) {
while (RTIE != RTIB && RTIE->isUnconditionalBranch())
++RTIE;
while (RFIE != RFIB && RFIE->isUnconditionalBranch())
++RFIE;
}
}
while (RTIE != RTIB && RFIE != RFIB) {
RTIE = skipDebugInstructionsForward(RTIE, RTIB, false);
RFIE = skipDebugInstructionsForward(RFIE, RFIB, false);
if (RTIE == RTIB || RFIE == RFIB)
break;
if (!RTIE->isIdenticalTo(*RFIE))
break;
if (!RTIE->isBranch())
++Dups2;
++RTIE;
++RFIE;
}
TIE = std::next(RTIE.getReverse());
FIE = std::next(RFIE.getReverse());
return true;
}
bool IfConverter::RescanInstructions(
MachineBasicBlock::iterator &TIB, MachineBasicBlock::iterator &FIB,
MachineBasicBlock::iterator &TIE, MachineBasicBlock::iterator &FIE,
BBInfo &TrueBBI, BBInfo &FalseBBI) const {
bool BranchUnpredicable = true;
TrueBBI.IsUnpredicable = FalseBBI.IsUnpredicable = false;
ScanInstructions(TrueBBI, TIB, TIE, BranchUnpredicable);
if (TrueBBI.IsUnpredicable)
return false;
ScanInstructions(FalseBBI, FIB, FIE, BranchUnpredicable);
if (FalseBBI.IsUnpredicable)
return false;
if (TrueBBI.ClobbersPred && FalseBBI.ClobbersPred)
return false;
return true;
}
#ifndef NDEBUG
static void verifySameBranchInstructions(
MachineBasicBlock *MBB1,
MachineBasicBlock *MBB2) {
const MachineBasicBlock::reverse_iterator B1 = MBB1->rend();
const MachineBasicBlock::reverse_iterator B2 = MBB2->rend();
MachineBasicBlock::reverse_iterator E1 = MBB1->rbegin();
MachineBasicBlock::reverse_iterator E2 = MBB2->rbegin();
while (E1 != B1 && E2 != B2) {
skipDebugInstructionsForward(E1, B1, false);
skipDebugInstructionsForward(E2, B2, false);
if (E1 == B1 && E2 == B2)
break;
if (E1 == B1) {
assert(!E2->isBranch() && "Branch mis-match, one block is empty.");
break;
}
if (E2 == B2) {
assert(!E1->isBranch() && "Branch mis-match, one block is empty.");
break;
}
if (E1->isBranch() || E2->isBranch())
assert(E1->isIdenticalTo(*E2) &&
"Branch mis-match, branch instructions don't match.");
else
break;
++E1;
++E2;
}
}
#endif
bool IfConverter::ValidForkedDiamond(
BBInfo &TrueBBI, BBInfo &FalseBBI,
unsigned &Dups1, unsigned &Dups2,
BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Dups1 = Dups2 = 0;
if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
return false;
if (!TrueBBI.IsBrAnalyzable || !FalseBBI.IsBrAnalyzable)
return false;
if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
return false;
if (TrueBBI.BrCond.size() == 0 ||
FalseBBI.BrCond.size() == 0)
return false;
MachineBasicBlock *TT = TrueBBI.TrueBB;
MachineBasicBlock *TF = TrueBBI.FalseBB;
MachineBasicBlock *FT = FalseBBI.TrueBB;
MachineBasicBlock *FF = FalseBBI.FalseBB;
if (!TT)
TT = getNextBlock(*TrueBBI.BB);
if (!TF)
TF = getNextBlock(*TrueBBI.BB);
if (!FT)
FT = getNextBlock(*FalseBBI.BB);
if (!FF)
FF = getNextBlock(*FalseBBI.BB);
if (!TT || !TF)
return false;
if (!((TT == FT && TF == FF) || (TF == FT && TT == FF)))
return false;
bool FalseReversed = false;
if (TF == FT && TT == FF) {
if (!FalseBBI.IsBrReversible)
return false;
FalseReversed = true;
reverseBranchCondition(FalseBBI);
}
auto UnReverseOnExit = make_scope_exit([&]() {
if (FalseReversed)
reverseBranchCondition(FalseBBI);
});
MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
*TrueBBI.BB, *FalseBBI.BB,
true))
return false;
TrueBBICalc.BB = TrueBBI.BB;
FalseBBICalc.BB = FalseBBI.BB;
TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
return false;
TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
return true;
}
bool IfConverter::ValidDiamond(
BBInfo &TrueBBI, BBInfo &FalseBBI,
unsigned &Dups1, unsigned &Dups2,
BBInfo &TrueBBICalc, BBInfo &FalseBBICalc) const {
Dups1 = Dups2 = 0;
if (TrueBBI.IsBeingAnalyzed || TrueBBI.IsDone ||
FalseBBI.IsBeingAnalyzed || FalseBBI.IsDone)
return false;
if (TrueBBI.BB == FalseBBI.BB)
return false;
MachineBasicBlock *TT = TrueBBI.TrueBB;
MachineBasicBlock *FT = FalseBBI.TrueBB;
if (!TT && blockAlwaysFallThrough(TrueBBI))
TT = getNextBlock(*TrueBBI.BB);
if (!FT && blockAlwaysFallThrough(FalseBBI))
FT = getNextBlock(*FalseBBI.BB);
if (TT != FT)
return false;
if (!TT && (TrueBBI.IsBrAnalyzable || FalseBBI.IsBrAnalyzable))
return false;
if (TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1)
return false;
if (TrueBBI.FalseBB || FalseBBI.FalseBB)
return false;
bool SkipUnconditionalBranches =
TrueBBI.IsBrAnalyzable && FalseBBI.IsBrAnalyzable;
MachineBasicBlock::iterator TIB = TrueBBI.BB->begin();
MachineBasicBlock::iterator FIB = FalseBBI.BB->begin();
MachineBasicBlock::iterator TIE = TrueBBI.BB->end();
MachineBasicBlock::iterator FIE = FalseBBI.BB->end();
if(!CountDuplicatedInstructions(TIB, FIB, TIE, FIE, Dups1, Dups2,
*TrueBBI.BB, *FalseBBI.BB,
SkipUnconditionalBranches))
return false;
TrueBBICalc.BB = TrueBBI.BB;
FalseBBICalc.BB = FalseBBI.BB;
TrueBBICalc.IsBrAnalyzable = TrueBBI.IsBrAnalyzable;
FalseBBICalc.IsBrAnalyzable = FalseBBI.IsBrAnalyzable;
if (!RescanInstructions(TIB, FIB, TIE, FIE, TrueBBICalc, FalseBBICalc))
return false;
TrueBBICalc.NonPredSize = TrueBBI.NonPredSize;
FalseBBICalc.NonPredSize = FalseBBI.NonPredSize;
return true;
}
void IfConverter::AnalyzeBranches(BBInfo &BBI) {
if (BBI.IsDone)
return;
BBI.TrueBB = BBI.FalseBB = nullptr;
BBI.BrCond.clear();
BBI.IsBrAnalyzable =
!TII->analyzeBranch(*BBI.BB, BBI.TrueBB, BBI.FalseBB, BBI.BrCond);
if (!BBI.IsBrAnalyzable) {
BBI.TrueBB = nullptr;
BBI.FalseBB = nullptr;
BBI.BrCond.clear();
}
SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
BBI.IsBrReversible = (RevCond.size() == 0) ||
!TII->reverseBranchCondition(RevCond);
BBI.HasFallThrough = BBI.IsBrAnalyzable && BBI.FalseBB == nullptr;
if (BBI.BrCond.size()) {
if (!BBI.FalseBB)
BBI.FalseBB = findFalseBlock(BBI.BB, BBI.TrueBB);
if (!BBI.FalseBB) {
BBI.IsUnpredicable = true;
}
}
}
void IfConverter::ScanInstructions(BBInfo &BBI,
MachineBasicBlock::iterator &Begin,
MachineBasicBlock::iterator &End,
bool BranchUnpredicable) const {
if (BBI.IsDone || BBI.IsUnpredicable)
return;
bool AlreadyPredicated = !BBI.Predicate.empty();
BBI.NonPredSize = 0;
BBI.ExtraCost = 0;
BBI.ExtraCost2 = 0;
BBI.ClobbersPred = false;
for (MachineInstr &MI : make_range(Begin, End)) {
if (MI.isDebugInstr())
continue;
if (MI.isNotDuplicable() || MI.isConvergent())
BBI.CannotBeCopied = true;
bool isPredicated = TII->isPredicated(MI);
bool isCondBr = BBI.IsBrAnalyzable && MI.isConditionalBranch();
if (BranchUnpredicable && MI.isBranch()) {
BBI.IsUnpredicable = true;
return;
}
if (isCondBr)
continue;
if (!isPredicated) {
BBI.NonPredSize++;
unsigned ExtraPredCost = TII->getPredicationCost(MI);
unsigned NumCycles = SchedModel.computeInstrLatency(&MI, false);
if (NumCycles > 1)
BBI.ExtraCost += NumCycles-1;
BBI.ExtraCost2 += ExtraPredCost;
} else if (!AlreadyPredicated) {
BBI.IsUnpredicable = true;
return;
}
if (BBI.ClobbersPred && !isPredicated) {
BBI.IsUnpredicable = true;
return;
}
std::vector<MachineOperand> PredDefs;
if (TII->ClobbersPredicate(MI, PredDefs, true))
BBI.ClobbersPred = true;
if (!TII->isPredicable(MI)) {
BBI.IsUnpredicable = true;
return;
}
}
}
bool IfConverter::FeasibilityAnalysis(BBInfo &BBI,
SmallVectorImpl<MachineOperand> &Pred,
bool isTriangle, bool RevBranch,
bool hasCommonTail) {
if (BBI.IsDone || (BBI.IsUnpredicable && !hasCommonTail))
return false;
if (BBI.Predicate.size() && !BBI.IsBrAnalyzable)
return false;
if (BBI.Predicate.size() && !TII->SubsumesPredicate(Pred, BBI.Predicate))
return false;
if (!hasCommonTail && BBI.BrCond.size()) {
if (!isTriangle)
return false;
SmallVector<MachineOperand, 4> RevPred(Pred.begin(), Pred.end());
SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
if (RevBranch) {
if (TII->reverseBranchCondition(Cond))
return false;
}
if (TII->reverseBranchCondition(RevPred) ||
!TII->SubsumesPredicate(Cond, RevPred))
return false;
}
return true;
}
void IfConverter::AnalyzeBlock(
MachineBasicBlock &MBB, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
struct BBState {
BBState(MachineBasicBlock &MBB) : MBB(&MBB) {}
MachineBasicBlock *MBB;
bool SuccsAnalyzed = false;
};
SmallVector<BBState, 16> BBStack(1, MBB);
while (!BBStack.empty()) {
BBState &State = BBStack.back();
MachineBasicBlock *BB = State.MBB;
BBInfo &BBI = BBAnalysis[BB->getNumber()];
if (!State.SuccsAnalyzed) {
if (BBI.IsAnalyzed || BBI.IsBeingAnalyzed) {
BBStack.pop_back();
continue;
}
BBI.BB = BB;
BBI.IsBeingAnalyzed = true;
AnalyzeBranches(BBI);
MachineBasicBlock::iterator Begin = BBI.BB->begin();
MachineBasicBlock::iterator End = BBI.BB->end();
ScanInstructions(BBI, Begin, End);
if (!BBI.IsBrAnalyzable || BBI.BrCond.empty() || BBI.IsDone) {
BBI.IsBeingAnalyzed = false;
BBI.IsAnalyzed = true;
BBStack.pop_back();
continue;
}
if (BBI.TrueBB == BB || BBI.FalseBB == BB) {
BBI.IsBeingAnalyzed = false;
BBI.IsAnalyzed = true;
BBStack.pop_back();
continue;
}
if (!BBI.FalseBB) {
BBI.IsBeingAnalyzed = false;
BBI.IsAnalyzed = true;
BBStack.pop_back();
continue;
}
State.SuccsAnalyzed = true;
BBStack.push_back(*BBI.FalseBB);
BBStack.push_back(*BBI.TrueBB);
continue;
}
BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
if (TrueBBI.IsDone && FalseBBI.IsDone) {
BBI.IsBeingAnalyzed = false;
BBI.IsAnalyzed = true;
BBStack.pop_back();
continue;
}
SmallVector<MachineOperand, 4>
RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
bool CanRevCond = !TII->reverseBranchCondition(RevCond);
unsigned Dups = 0;
unsigned Dups2 = 0;
bool TNeedSub = !TrueBBI.Predicate.empty();
bool FNeedSub = !FalseBBI.Predicate.empty();
bool Enqueued = false;
BranchProbability Prediction = MBPI->getEdgeProbability(BB, TrueBBI.BB);
if (CanRevCond) {
BBInfo TrueBBICalc, FalseBBICalc;
auto feasibleDiamond = [&](bool Forked) {
bool MeetsSize = MeetIfcvtSizeLimit(TrueBBICalc, FalseBBICalc, *BB,
Dups + Dups2, Prediction, Forked);
bool TrueFeasible = FeasibilityAnalysis(TrueBBI, BBI.BrCond,
false, false,
true);
bool FalseFeasible = FeasibilityAnalysis(FalseBBI, RevCond,
false, false,
true);
return MeetsSize && TrueFeasible && FalseFeasible;
};
if (ValidDiamond(TrueBBI, FalseBBI, Dups, Dups2,
TrueBBICalc, FalseBBICalc)) {
if (feasibleDiamond(false)) {
Tokens.push_back(std::make_unique<IfcvtToken>(
BBI, ICDiamond, TNeedSub | FNeedSub, Dups, Dups2,
(bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
Enqueued = true;
}
} else if (ValidForkedDiamond(TrueBBI, FalseBBI, Dups, Dups2,
TrueBBICalc, FalseBBICalc)) {
if (feasibleDiamond(true)) {
Tokens.push_back(std::make_unique<IfcvtToken>(
BBI, ICForkedDiamond, TNeedSub | FNeedSub, Dups, Dups2,
(bool) TrueBBICalc.ClobbersPred, (bool) FalseBBICalc.ClobbersPred));
Enqueued = true;
}
}
}
if (ValidTriangle(TrueBBI, FalseBBI, false, Dups, Prediction) &&
MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
TrueBBI.ExtraCost2, Prediction) &&
FeasibilityAnalysis(TrueBBI, BBI.BrCond, true)) {
Tokens.push_back(
std::make_unique<IfcvtToken>(BBI, ICTriangle, TNeedSub, Dups));
Enqueued = true;
}
if (ValidTriangle(TrueBBI, FalseBBI, true, Dups, Prediction) &&
MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
TrueBBI.ExtraCost2, Prediction) &&
FeasibilityAnalysis(TrueBBI, BBI.BrCond, true, true)) {
Tokens.push_back(
std::make_unique<IfcvtToken>(BBI, ICTriangleRev, TNeedSub, Dups));
Enqueued = true;
}
if (ValidSimple(TrueBBI, Dups, Prediction) &&
MeetIfcvtSizeLimit(*TrueBBI.BB, TrueBBI.NonPredSize + TrueBBI.ExtraCost,
TrueBBI.ExtraCost2, Prediction) &&
FeasibilityAnalysis(TrueBBI, BBI.BrCond)) {
Tokens.push_back(
std::make_unique<IfcvtToken>(BBI, ICSimple, TNeedSub, Dups));
Enqueued = true;
}
if (CanRevCond) {
if (ValidTriangle(FalseBBI, TrueBBI, false, Dups,
Prediction.getCompl()) &&
MeetIfcvtSizeLimit(*FalseBBI.BB,
FalseBBI.NonPredSize + FalseBBI.ExtraCost,
FalseBBI.ExtraCost2, Prediction.getCompl()) &&
FeasibilityAnalysis(FalseBBI, RevCond, true)) {
Tokens.push_back(std::make_unique<IfcvtToken>(BBI, ICTriangleFalse,
FNeedSub, Dups));
Enqueued = true;
}
if (ValidTriangle(FalseBBI, TrueBBI, true, Dups,
Prediction.getCompl()) &&
MeetIfcvtSizeLimit(*FalseBBI.BB,
FalseBBI.NonPredSize + FalseBBI.ExtraCost,
FalseBBI.ExtraCost2, Prediction.getCompl()) &&
FeasibilityAnalysis(FalseBBI, RevCond, true, true)) {
Tokens.push_back(
std::make_unique<IfcvtToken>(BBI, ICTriangleFRev, FNeedSub, Dups));
Enqueued = true;
}
if (ValidSimple(FalseBBI, Dups, Prediction.getCompl()) &&
MeetIfcvtSizeLimit(*FalseBBI.BB,
FalseBBI.NonPredSize + FalseBBI.ExtraCost,
FalseBBI.ExtraCost2, Prediction.getCompl()) &&
FeasibilityAnalysis(FalseBBI, RevCond)) {
Tokens.push_back(
std::make_unique<IfcvtToken>(BBI, ICSimpleFalse, FNeedSub, Dups));
Enqueued = true;
}
}
BBI.IsEnqueued = Enqueued;
BBI.IsBeingAnalyzed = false;
BBI.IsAnalyzed = true;
BBStack.pop_back();
}
}
void IfConverter::AnalyzeBlocks(
MachineFunction &MF, std::vector<std::unique_ptr<IfcvtToken>> &Tokens) {
for (MachineBasicBlock &MBB : MF)
AnalyzeBlock(MBB, Tokens);
llvm::stable_sort(Tokens, IfcvtTokenCmp);
}
static bool canFallThroughTo(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB) {
MachineFunction::iterator PI = MBB.getIterator();
MachineFunction::iterator I = std::next(PI);
MachineFunction::iterator TI = ToMBB.getIterator();
MachineFunction::iterator E = MBB.getParent()->end();
while (I != TI) {
if (I == E || !I->empty() || !PI->isSuccessor(&*I))
return false;
PI = I++;
}
return PI->isSuccessor(&*I);
}
void IfConverter::InvalidatePreds(MachineBasicBlock &MBB) {
for (const MachineBasicBlock *Predecessor : MBB.predecessors()) {
BBInfo &PBBI = BBAnalysis[Predecessor->getNumber()];
if (PBBI.IsDone || PBBI.BB == &MBB)
continue;
PBBI.IsAnalyzed = false;
PBBI.IsEnqueued = false;
}
}
static void InsertUncondBranch(MachineBasicBlock &MBB, MachineBasicBlock &ToMBB,
const TargetInstrInfo *TII) {
DebugLoc dl; SmallVector<MachineOperand, 0> NoCond;
TII->insertBranch(MBB, &ToMBB, nullptr, NoCond, dl);
}
static void UpdatePredRedefs(MachineInstr &MI, LivePhysRegs &Redefs) {
const TargetRegisterInfo *TRI = MI.getMF()->getSubtarget().getRegisterInfo();
SparseSet<MCPhysReg, identity<MCPhysReg>> LiveBeforeMI;
LiveBeforeMI.setUniverse(TRI->getNumRegs());
for (unsigned Reg : Redefs)
LiveBeforeMI.insert(Reg);
SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Clobbers;
Redefs.stepForward(MI, Clobbers);
for (auto Clobber : Clobbers) {
unsigned Reg = Clobber.first;
MachineOperand &Op = const_cast<MachineOperand&>(*Clobber.second);
MachineInstr *OpMI = Op.getParent();
MachineInstrBuilder MIB(*OpMI->getMF(), OpMI);
if (Op.isRegMask()) {
if (LiveBeforeMI.count(Reg))
MIB.addReg(Reg, RegState::Implicit);
MIB.addReg(Reg, RegState::Implicit | RegState::Define);
continue;
}
if (LiveBeforeMI.count(Reg))
MIB.addReg(Reg, RegState::Implicit);
else {
bool HasLiveSubReg = false;
for (MCSubRegIterator S(Reg, TRI); S.isValid(); ++S) {
if (!LiveBeforeMI.count(*S))
continue;
HasLiveSubReg = true;
break;
}
if (HasLiveSubReg)
MIB.addReg(Reg, RegState::Implicit);
}
}
}
bool IfConverter::IfConvertSimple(BBInfo &BBI, IfcvtKind Kind) {
BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
BBInfo *CvtBBI = &TrueBBI;
BBInfo *NextBBI = &FalseBBI;
SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
if (Kind == ICSimpleFalse)
std::swap(CvtBBI, NextBBI);
MachineBasicBlock &CvtMBB = *CvtBBI->BB;
MachineBasicBlock &NextMBB = *NextBBI->BB;
if (CvtBBI->IsDone ||
(CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
BBI.IsAnalyzed = false;
CvtBBI->IsAnalyzed = false;
return false;
}
if (CvtMBB.hasAddressTaken())
return false;
if (Kind == ICSimpleFalse)
if (TII->reverseBranchCondition(Cond))
llvm_unreachable("Unable to reverse branch condition!");
Redefs.init(*TRI);
if (MRI->tracksLiveness()) {
Redefs.addLiveInsNoPristines(CvtMBB);
Redefs.addLiveInsNoPristines(NextMBB);
}
BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
if (CvtMBB.pred_size() > 1) {
CopyAndPredicateBlock(BBI, *CvtBBI, Cond);
BBI.BB->removeSuccessor(&CvtMBB, true);
} else {
PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
MergeBlocks(BBI, *CvtBBI);
}
bool IterIfcvt = true;
if (!canFallThroughTo(*BBI.BB, NextMBB)) {
InsertUncondBranch(*BBI.BB, NextMBB, TII);
BBI.HasFallThrough = false;
IterIfcvt = false;
}
if (!IterIfcvt)
BBI.IsDone = true;
InvalidatePreds(*BBI.BB);
CvtBBI->IsDone = true;
return true;
}
bool IfConverter::IfConvertTriangle(BBInfo &BBI, IfcvtKind Kind) {
BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
BBInfo *CvtBBI = &TrueBBI;
BBInfo *NextBBI = &FalseBBI;
DebugLoc dl;
SmallVector<MachineOperand, 4> Cond(BBI.BrCond.begin(), BBI.BrCond.end());
if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
std::swap(CvtBBI, NextBBI);
MachineBasicBlock &CvtMBB = *CvtBBI->BB;
MachineBasicBlock &NextMBB = *NextBBI->BB;
if (CvtBBI->IsDone ||
(CvtBBI->CannotBeCopied && CvtMBB.pred_size() > 1)) {
BBI.IsAnalyzed = false;
CvtBBI->IsAnalyzed = false;
return false;
}
if (CvtMBB.hasAddressTaken())
return false;
if (Kind == ICTriangleFalse || Kind == ICTriangleFRev)
if (TII->reverseBranchCondition(Cond))
llvm_unreachable("Unable to reverse branch condition!");
if (Kind == ICTriangleRev || Kind == ICTriangleFRev) {
if (reverseBranchCondition(*CvtBBI)) {
for (MachineBasicBlock *PBB : CvtMBB.predecessors()) {
if (PBB == BBI.BB)
continue;
BBInfo &PBBI = BBAnalysis[PBB->getNumber()];
if (PBBI.IsEnqueued) {
PBBI.IsAnalyzed = false;
PBBI.IsEnqueued = false;
}
}
}
}
Redefs.init(*TRI);
if (MRI->tracksLiveness()) {
Redefs.addLiveInsNoPristines(CvtMBB);
Redefs.addLiveInsNoPristines(NextMBB);
}
bool HasEarlyExit = CvtBBI->FalseBB != nullptr;
BranchProbability CvtNext, CvtFalse, BBNext, BBCvt;
if (HasEarlyExit) {
CvtNext = MBPI->getEdgeProbability(&CvtMBB, &NextMBB);
CvtFalse = MBPI->getEdgeProbability(&CvtMBB, CvtBBI->FalseBB);
BBNext = MBPI->getEdgeProbability(BBI.BB, &NextMBB);
BBCvt = MBPI->getEdgeProbability(BBI.BB, &CvtMBB);
}
BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
if (CvtMBB.pred_size() > 1) {
CopyAndPredicateBlock(BBI, *CvtBBI, Cond, true);
} else {
CvtBBI->NonPredSize -= TII->removeBranch(CvtMBB);
PredicateBlock(*CvtBBI, CvtMBB.end(), Cond);
MergeBlocks(BBI, *CvtBBI, false);
}
BBI.BB->removeSuccessor(&CvtMBB, true);
if (HasEarlyExit) {
SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
CvtBBI->BrCond.end());
if (TII->reverseBranchCondition(RevCond))
llvm_unreachable("Unable to reverse branch condition!");
auto NewTrueBB = getNextBlock(*BBI.BB);
auto NewNext = BBNext + BBCvt * CvtNext;
auto NewTrueBBIter = find(BBI.BB->successors(), NewTrueBB);
if (NewTrueBBIter != BBI.BB->succ_end())
BBI.BB->setSuccProbability(NewTrueBBIter, NewNext);
auto NewFalse = BBCvt * CvtFalse;
TII->insertBranch(*BBI.BB, CvtBBI->FalseBB, nullptr, RevCond, dl);
BBI.BB->addSuccessor(CvtBBI->FalseBB, NewFalse);
}
bool FalseBBDead = false;
bool IterIfcvt = true;
bool isFallThrough = canFallThroughTo(*BBI.BB, NextMBB);
if (!isFallThrough) {
if (!HasEarlyExit &&
NextMBB.pred_size() == 1 && !NextBBI->HasFallThrough &&
!NextMBB.hasAddressTaken()) {
MergeBlocks(BBI, *NextBBI);
FalseBBDead = true;
} else {
InsertUncondBranch(*BBI.BB, NextMBB, TII);
BBI.HasFallThrough = false;
}
IterIfcvt = false;
}
if (!IterIfcvt)
BBI.IsDone = true;
InvalidatePreds(*BBI.BB);
CvtBBI->IsDone = true;
if (FalseBBDead)
NextBBI->IsDone = true;
return true;
}
bool IfConverter::IfConvertDiamondCommon(
BBInfo &BBI, BBInfo &TrueBBI, BBInfo &FalseBBI,
unsigned NumDups1, unsigned NumDups2,
bool TClobbersPred, bool FClobbersPred,
bool RemoveBranch, bool MergeAddEdges) {
if (TrueBBI.IsDone || FalseBBI.IsDone ||
TrueBBI.BB->pred_size() > 1 || FalseBBI.BB->pred_size() > 1) {
BBI.IsAnalyzed = false;
TrueBBI.IsAnalyzed = false;
FalseBBI.IsAnalyzed = false;
return false;
}
if (TrueBBI.BB->hasAddressTaken() || FalseBBI.BB->hasAddressTaken())
return false;
BBInfo *BBI1 = &TrueBBI;
BBInfo *BBI2 = &FalseBBI;
SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.end());
if (TII->reverseBranchCondition(RevCond))
llvm_unreachable("Unable to reverse branch condition!");
SmallVector<MachineOperand, 4> *Cond1 = &BBI.BrCond;
SmallVector<MachineOperand, 4> *Cond2 = &RevCond;
bool DoSwap = false;
if (TClobbersPred && !FClobbersPred)
DoSwap = true;
else if (!TClobbersPred && !FClobbersPred) {
if (TrueBBI.NonPredSize > FalseBBI.NonPredSize)
DoSwap = true;
} else if (TClobbersPred && FClobbersPred)
llvm_unreachable("Predicate info cannot be clobbered by both sides.");
if (DoSwap) {
std::swap(BBI1, BBI2);
std::swap(Cond1, Cond2);
}
BBI.NonPredSize -= TII->removeBranch(*BBI.BB);
MachineBasicBlock &MBB1 = *BBI1->BB;
MachineBasicBlock &MBB2 = *BBI2->BB;
Redefs.init(*TRI);
if (MRI->tracksLiveness()) {
Redefs.addLiveInsNoPristines(MBB1);
Redefs.addLiveInsNoPristines(MBB2);
}
MachineBasicBlock::iterator DI1 = MBB1.getFirstNonDebugInstr(false);
MachineBasicBlock::iterator DI2 = MBB2.getFirstNonDebugInstr(false);
BBI1->NonPredSize -= NumDups1;
BBI2->NonPredSize -= NumDups1;
for (unsigned i = 0; i < NumDups1; ++DI1) {
if (DI1 == MBB1.end())
break;
if (!DI1->isDebugInstr())
++i;
}
while (NumDups1 != 0) {
if (DI2->shouldUpdateCallSiteInfo())
MBB2.getParent()->eraseCallSiteInfo(&*DI2);
++DI2;
if (DI2 == MBB2.end())
break;
if (!DI2->isDebugInstr())
--NumDups1;
}
if (MRI->tracksLiveness()) {
for (const MachineInstr &MI : make_range(MBB1.begin(), DI1)) {
SmallVector<std::pair<MCPhysReg, const MachineOperand*>, 4> Dummy;
Redefs.stepForward(MI, Dummy);
}
}
BBI.BB->splice(BBI.BB->end(), &MBB1, MBB1.begin(), DI1);
MBB2.erase(MBB2.begin(), DI2);
#ifndef NDEBUG
if (!BBI1->IsBrAnalyzable)
verifySameBranchInstructions(&MBB1, &MBB2);
#endif
DI1 = MBB1.end();
while (DI1 != MBB1.begin()) {
MachineBasicBlock::iterator Prev = std::prev(DI1);
if (!Prev->isBranch() && !Prev->isDebugInstr())
break;
DI1 = Prev;
}
for (unsigned i = 0; i != NumDups2; ) {
assert(DI1 != MBB1.begin());
--DI1;
if (DI1->shouldUpdateCallSiteInfo())
MBB1.getParent()->eraseCallSiteInfo(&*DI1);
if (!DI1->isDebugInstr())
++i;
}
MBB1.erase(DI1, MBB1.end());
DI2 = BBI2->BB->end();
if (RemoveBranch)
BBI2->NonPredSize -= TII->removeBranch(*BBI2->BB);
else {
while (DI2 != MBB2.begin()) {
MachineBasicBlock::iterator Prev = std::prev(DI2);
if (!Prev->isBranch() && !Prev->isDebugInstr())
break;
DI2 = Prev;
}
}
while (NumDups2 != 0) {
assert(DI2 != MBB2.begin());
--DI2;
if (!DI2->isDebugInstr())
--NumDups2;
}
SmallSet<MCPhysReg, 4> RedefsByFalse;
SmallSet<MCPhysReg, 4> ExtUses;
if (TII->isProfitableToUnpredicate(MBB1, MBB2)) {
for (const MachineInstr &FI : make_range(MBB2.begin(), DI2)) {
if (FI.isDebugInstr())
continue;
SmallVector<MCPhysReg, 4> Defs;
for (const MachineOperand &MO : FI.operands()) {
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (!Reg)
continue;
if (MO.isDef()) {
Defs.push_back(Reg);
} else if (!RedefsByFalse.count(Reg)) {
for (MCSubRegIterator SubRegs(Reg, TRI, true);
SubRegs.isValid(); ++SubRegs)
ExtUses.insert(*SubRegs);
}
}
for (MCPhysReg Reg : Defs) {
if (!ExtUses.count(Reg)) {
for (MCSubRegIterator SubRegs(Reg, TRI, true);
SubRegs.isValid(); ++SubRegs)
RedefsByFalse.insert(*SubRegs);
}
}
}
}
PredicateBlock(*BBI1, MBB1.end(), *Cond1, &RedefsByFalse);
if (!MBB2.empty() && (DI2 == MBB2.end())) {
MachineBasicBlock::iterator BBI1T = MBB1.getFirstTerminator();
MachineBasicBlock::iterator BBI2T = MBB2.getFirstTerminator();
bool BB1Predicated = BBI1T != MBB1.end() && TII->isPredicated(*BBI1T);
bool BB2NonPredicated = BBI2T != MBB2.end() && !TII->isPredicated(*BBI2T);
if (BB2NonPredicated && (BB1Predicated || !BBI2->IsBrAnalyzable))
--DI2;
}
PredicateBlock(*BBI2, DI2, *Cond2);
MergeBlocks(BBI, *BBI1, MergeAddEdges);
MergeBlocks(BBI, *BBI2, MergeAddEdges);
return true;
}
bool IfConverter::IfConvertForkedDiamond(
BBInfo &BBI, IfcvtKind Kind,
unsigned NumDups1, unsigned NumDups2,
bool TClobbersPred, bool FClobbersPred) {
BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
DebugLoc dl;
MachineBasicBlock::iterator TIE = TrueBBI.BB->getFirstTerminator();
if (TIE != TrueBBI.BB->end())
dl = TIE->getDebugLoc();
if (!IfConvertDiamondCommon(
BBI, TrueBBI, FalseBBI,
NumDups1, NumDups2,
TClobbersPred, FClobbersPred,
true, true))
return false;
TII->insertBranch(*BBI.BB, TrueBBI.TrueBB, TrueBBI.FalseBB,
TrueBBI.BrCond, dl);
BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
InvalidatePreds(*BBI.BB);
return true;
}
bool IfConverter::IfConvertDiamond(BBInfo &BBI, IfcvtKind Kind,
unsigned NumDups1, unsigned NumDups2,
bool TClobbersPred, bool FClobbersPred) {
BBInfo &TrueBBI = BBAnalysis[BBI.TrueBB->getNumber()];
BBInfo &FalseBBI = BBAnalysis[BBI.FalseBB->getNumber()];
MachineBasicBlock *TailBB = TrueBBI.TrueBB;
if (!TailBB) {
if (blockAlwaysFallThrough(TrueBBI))
TailBB = FalseBBI.TrueBB;
assert((TailBB || !TrueBBI.IsBrAnalyzable) && "Unexpected!");
}
if (!IfConvertDiamondCommon(
BBI, TrueBBI, FalseBBI,
NumDups1, NumDups2,
TClobbersPred, FClobbersPred,
TrueBBI.IsBrAnalyzable,
TailBB == nullptr))
return false;
if (TailBB) {
BBI.BB->removeSuccessor(TrueBBI.BB);
BBI.BB->removeSuccessor(FalseBBI.BB, true);
BBInfo &TailBBI = BBAnalysis[TailBB->getNumber()];
bool CanMergeTail = !TailBBI.HasFallThrough &&
!TailBBI.BB->hasAddressTaken();
MachineBasicBlock::const_iterator TI = BBI.BB->getFirstTerminator();
if (TI != BBI.BB->end() && TII->isPredicated(*TI))
CanMergeTail = false;
unsigned NumPreds = TailBB->pred_size();
if (NumPreds > 1)
CanMergeTail = false;
else if (NumPreds == 1 && CanMergeTail) {
MachineBasicBlock::pred_iterator PI = TailBB->pred_begin();
if (*PI != TrueBBI.BB && *PI != FalseBBI.BB)
CanMergeTail = false;
}
if (CanMergeTail) {
MergeBlocks(BBI, TailBBI);
TailBBI.IsDone = true;
} else {
BBI.BB->addSuccessor(TailBB, BranchProbability::getOne());
InsertUncondBranch(*BBI.BB, *TailBB, TII);
BBI.HasFallThrough = false;
}
}
BBI.IsDone = TrueBBI.IsDone = FalseBBI.IsDone = true;
InvalidatePreds(*BBI.BB);
return true;
}
static bool MaySpeculate(const MachineInstr &MI,
SmallSet<MCPhysReg, 4> &LaterRedefs) {
bool SawStore = true;
if (!MI.isSafeToMove(nullptr, SawStore))
return false;
for (const MachineOperand &MO : MI.operands()) {
if (!MO.isReg())
continue;
Register Reg = MO.getReg();
if (!Reg)
continue;
if (MO.isDef() && !LaterRedefs.count(Reg))
return false;
}
return true;
}
void IfConverter::PredicateBlock(BBInfo &BBI,
MachineBasicBlock::iterator E,
SmallVectorImpl<MachineOperand> &Cond,
SmallSet<MCPhysReg, 4> *LaterRedefs) {
bool AnyUnpred = false;
bool MaySpec = LaterRedefs != nullptr;
for (MachineInstr &I : make_range(BBI.BB->begin(), E)) {
if (I.isDebugInstr() || TII->isPredicated(I))
continue;
if (MaySpec && MaySpeculate(I, *LaterRedefs)) {
AnyUnpred = true;
continue;
}
MaySpec = false;
if (!TII->PredicateInstruction(I, Cond)) {
#ifndef NDEBUG
dbgs() << "Unable to predicate " << I << "!\n";
#endif
llvm_unreachable(nullptr);
}
UpdatePredRedefs(I, Redefs);
}
BBI.Predicate.append(Cond.begin(), Cond.end());
BBI.IsAnalyzed = false;
BBI.NonPredSize = 0;
++NumIfConvBBs;
if (AnyUnpred)
++NumUnpred;
}
void IfConverter::CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
SmallVectorImpl<MachineOperand> &Cond,
bool IgnoreBr) {
MachineFunction &MF = *ToBBI.BB->getParent();
MachineBasicBlock &FromMBB = *FromBBI.BB;
for (MachineInstr &I : FromMBB) {
if (IgnoreBr && I.isBranch())
break;
MachineInstr *MI = MF.CloneMachineInstr(&I);
if (I.isCandidateForCallSiteEntry())
MF.copyCallSiteInfo(&I, MI);
ToBBI.BB->insert(ToBBI.BB->end(), MI);
ToBBI.NonPredSize++;
unsigned ExtraPredCost = TII->getPredicationCost(I);
unsigned NumCycles = SchedModel.computeInstrLatency(&I, false);
if (NumCycles > 1)
ToBBI.ExtraCost += NumCycles-1;
ToBBI.ExtraCost2 += ExtraPredCost;
if (!TII->isPredicated(I) && !MI->isDebugInstr()) {
if (!TII->PredicateInstruction(*MI, Cond)) {
#ifndef NDEBUG
dbgs() << "Unable to predicate " << I << "!\n";
#endif
llvm_unreachable(nullptr);
}
}
UpdatePredRedefs(*MI, Redefs);
}
if (!IgnoreBr) {
std::vector<MachineBasicBlock *> Succs(FromMBB.succ_begin(),
FromMBB.succ_end());
MachineBasicBlock *NBB = getNextBlock(FromMBB);
MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
for (MachineBasicBlock *Succ : Succs) {
if (Succ == FallThrough)
continue;
ToBBI.BB->addSuccessor(Succ);
}
}
ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
ToBBI.Predicate.append(Cond.begin(), Cond.end());
ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
ToBBI.IsAnalyzed = false;
++NumDupBBs;
}
void IfConverter::MergeBlocks(BBInfo &ToBBI, BBInfo &FromBBI, bool AddEdges) {
MachineBasicBlock &FromMBB = *FromBBI.BB;
assert(!FromMBB.hasAddressTaken() &&
"Removing a BB whose address is taken!");
MachineBasicBlock::iterator FromTI = FromMBB.getFirstTerminator();
MachineBasicBlock::iterator ToTI = ToBBI.BB->getFirstTerminator();
ToBBI.BB->splice(ToTI, &FromMBB, FromMBB.begin(), FromTI);
if (FromTI != FromMBB.end() && !TII->isPredicated(*FromTI))
ToTI = ToBBI.BB->end();
ToBBI.BB->splice(ToTI, &FromMBB, FromTI, FromMBB.end());
if (ToBBI.IsBrAnalyzable)
ToBBI.BB->normalizeSuccProbs();
SmallVector<MachineBasicBlock *, 4> FromSuccs(FromMBB.successors());
MachineBasicBlock *NBB = getNextBlock(FromMBB);
MachineBasicBlock *FallThrough = FromBBI.HasFallThrough ? NBB : nullptr;
auto To2FromProb = BranchProbability::getZero();
if (AddEdges && ToBBI.BB->isSuccessor(&FromMBB)) {
To2FromProb = MBPI->getEdgeProbability(ToBBI.BB, &FromMBB);
ToBBI.BB->removeSuccessor(&FromMBB);
}
for (MachineBasicBlock *Succ : FromSuccs) {
if (Succ == FallThrough) {
FromMBB.removeSuccessor(Succ);
continue;
}
auto NewProb = BranchProbability::getZero();
if (AddEdges) {
NewProb = MBPI->getEdgeProbability(&FromMBB, Succ);
if (!To2FromProb.isZero())
NewProb *= To2FromProb;
}
FromMBB.removeSuccessor(Succ);
if (AddEdges) {
if (ToBBI.BB->isSuccessor(Succ))
ToBBI.BB->setSuccProbability(
find(ToBBI.BB->successors(), Succ),
MBPI->getEdgeProbability(ToBBI.BB, Succ) + NewProb);
else
ToBBI.BB->addSuccessor(Succ, NewProb);
}
}
MachineBasicBlock *Last = &*FromMBB.getParent()->rbegin();
if (Last != &FromMBB)
FromMBB.moveAfter(Last);
if (ToBBI.IsBrAnalyzable && FromBBI.IsBrAnalyzable)
ToBBI.BB->normalizeSuccProbs();
ToBBI.Predicate.append(FromBBI.Predicate.begin(), FromBBI.Predicate.end());
FromBBI.Predicate.clear();
ToBBI.NonPredSize += FromBBI.NonPredSize;
ToBBI.ExtraCost += FromBBI.ExtraCost;
ToBBI.ExtraCost2 += FromBBI.ExtraCost2;
FromBBI.NonPredSize = 0;
FromBBI.ExtraCost = 0;
FromBBI.ExtraCost2 = 0;
ToBBI.ClobbersPred |= FromBBI.ClobbersPred;
ToBBI.HasFallThrough = FromBBI.HasFallThrough;
ToBBI.IsAnalyzed = false;
FromBBI.IsAnalyzed = false;
}
FunctionPass *
llvm::createIfConverter(std::function<bool(const MachineFunction &)> Ftor) {
return new IfConverter(std::move(Ftor));
}