57 #define DEBUG_TYPE "x86-condbr-folding" 59 STATISTIC(NumFixedCondBrs,
"Number of x86 condbr folded");
65 StringRef getPassName()
const override {
return "X86 CondBr Folding"; }
80 INITIALIZE_PASS(X86CondBrFoldingPass,
"X86CondBrFolding",
"X86CondBrFolding",
false,
false)
83 return new X86CondBrFoldingPass();
88 struct TargetMBBInfo {
101 class X86CondBrFolding {
106 :
TII(TII), MBPI(MBPI), MF(MF) {}
113 std::vector<std::unique_ptr<TargetMBBInfo>> MBBInfos;
122 static bool analyzeCompare(
const MachineInstr &
MI,
unsigned &SrcReg,
137 bool X86CondBrFolding::findPath(
139 TargetMBBInfo *MBBInfo = getMBBInfo(MBB);
140 assert(MBBInfo &&
"Expecting a candidate MBB");
141 int CmpValue = MBBInfo->CmpValue;
146 TargetMBBInfo *PredMBBInfo = getMBBInfo(PredMBB);
147 if (!PredMBBInfo || PredMBBInfo->SrcReg != MBBInfo->SrcReg)
150 assert(SaveMBB == PredMBBInfo->TBB || SaveMBB == PredMBBInfo->FBB);
151 bool IsFalseBranch = (SaveMBB == PredMBBInfo->FBB);
155 int PredCmpValue = PredMBBInfo->CmpValue;
156 bool ValueCmpTrue = ((CmpValue < PredCmpValue && CC ==
X86::COND_L) ||
160 if (!(ValueCmpTrue ^ IsFalseBranch)) {
167 if ((CmpValue == PredCmpValue) ||
168 (CmpValue == PredCmpValue - 1 && CC ==
X86::COND_L) ||
169 (CmpValue == PredCmpValue + 1 && CC ==
X86::COND_G))
173 if (PredMBB->
pred_size() != 1 || !PredMBBInfo->CmpBrOnly)
185 if (NewMBB == OldMBB)
188 MI != ME &&
MI->isPHI(); ++
MI)
189 for (
unsigned i = 2,
e =
MI->getNumOperands() + 1; i !=
e; i += 2) {
191 if (MO.
getMBB() == OldMBB)
211 return MI.getOpcode() == X86::JMP_1;
220 TargetMBBInfo *MBBInfo = getMBBInfo(MBB);
222 if (MBBInfo->TBB == OrigDest) {
223 BrMI = MBBInfo->BrInstr;
226 .addMBB(NewDest).
addImm(MBBInfo->BranchCode);
227 MBBInfo->TBB = NewDest;
233 MBBInfo->FBB = NewDest;
239 setBranchProb(MBB, NewDest, MBPI->getEdgeProbability(MBB, OrigDest));
245 TargetMBBInfo *MBBInfo = getMBBInfo(MBB);
246 if (!MBBInfo->Modified)
252 TII->get(X86::JCC_1))
253 .addMBB(MBBInfo->TBB).
addImm(CC);
259 .addMBB(MBBInfo->FBB);
260 MBB->
erase(UncondBrI);
261 MBBInfo->Modified =
false;
278 void X86CondBrFolding::optimizeCondBr(
282 TargetMBBInfo *MBBInfo = getMBBInfo(&MBB);
283 assert(MBBInfo &&
"Expecting a candidate MBB");
289 TargetMBBInfo *PredMBBInfo = getMBBInfo(PredMBB);
290 assert(PredMBBInfo &&
"Expecting a candidate MBB");
291 if (PredMBBInfo->Modified)
292 fixupModifiedCond(PredMBB);
293 CC = PredMBBInfo->BranchCode;
297 replaceBrDest(PredMBB, &MBB, MBBInfo->FBB);
300 TargetMBBInfo *RootMBBInfo = getMBBInfo(RootMBB);
301 assert(RootMBBInfo &&
"Expecting a candidate MBB");
302 if (RootMBBInfo->Modified)
303 fixupModifiedCond(RootMBB);
304 CC = RootMBBInfo->BranchCode;
321 TII->get(X86::JCC_1))
322 .addMBB(RootMBBInfo->FBB).
addImm(NewCC);
326 TII->get(X86::JMP_1))
330 RootMBB->
erase(UncondBrI);
332 replaceBrDest(RootMBB, RootMBBInfo->TBB, TargetMBB);
337 if (RootMBBInfo->CmpValue != MBBInfo->CmpValue) {
340 RootMBB->
insert(RootMBBInfo->CmpInstr, NewCmp);
341 RootMBBInfo->CmpInstr->eraseFromParent();
347 for (
auto &
I : BranchPath) {
352 Prob = MBPI->getEdgeProbability(ThisMBB, NextMBB);
355 TargetProb = Prob * TargetProb;
356 Prob = Prob - TargetProb;
358 if (ThisMBB == RootMBB) {
362 if (ThisMBB == RootMBB)
369 fixBranchProb(MBBInfo->FBB);
376 MBBInfos[RootMBB->
getNumber()] =
nullptr;
378 LLVM_DEBUG(
dbgs() <<
"After optimization:\nRootMBB is: " << *RootMBB <<
"\n");
379 if (BranchPath.
size() > 1)
385 bool X86CondBrFolding::optimize() {
386 bool Changed =
false;
387 LLVM_DEBUG(
dbgs() <<
"***** X86CondBr Folding on Function: " << MF.getName()
390 MBBInfos.resize(MF.getNumBlockIDs());
392 MBBInfos[MBB.
getNumber()] = analyzeMBB(MBB);
394 for (
auto &MBB : MF) {
395 TargetMBBInfo *MBBInfo = getMBBInfo(&MBB);
396 if (!MBBInfo || !MBBInfo->CmpBrOnly)
401 <<
" CmpValue: " << MBBInfo->CmpValue <<
"\n");
403 if (!findPath(&MBB, BranchPath))
407 LLVM_DEBUG(
dbgs() <<
"Found one path (len=" << BranchPath.size() <<
"):\n");
410 for (
auto I = BranchPath.rbegin();
I != BranchPath.rend(); ++
I, ++
Index) {
412 TargetMBBInfo *PMBBInfo = getMBBInfo(PMBB);
413 LLVM_DEBUG(
dbgs() <<
"Path MBB (" << Index <<
" of " << BranchPath.size()
414 <<
") is " << *PMBB);
416 <<
" Val=" << PMBBInfo->CmpValue
417 <<
" CmpBrOnly=" << PMBBInfo->CmpBrOnly <<
"\n\n");
420 optimizeCondBr(MBB, BranchPath);
423 NumFixedCondBrs += RemoveList.size();
424 for (
auto MBBI : RemoveList) {
425 while (!MBBI->succ_empty())
426 MBBI->removeSuccessor(MBBI->succ_end() - 1);
428 MBBI->eraseFromParent();
435 bool X86CondBrFolding::analyzeCompare(
const MachineInstr &
MI,
unsigned &SrcReg,
437 unsigned SrcRegIndex = 0;
438 unsigned ValueIndex = 0;
478 std::unique_ptr<TargetMBBInfo>
497 while (I != MBB.
begin()) {
499 if (I->isDebugValue())
501 if (I->getOpcode() == X86::JMP_1) {
504 FBB = I->getOperand(0).getMBB();
522 TBB = I->getOperand(0).getMBB();
526 if (analyzeCompare(*I, SrcReg, CmpValue)) {
536 if (!TBB || !FBB || !CmpInstr)
548 if (CmpValue == INT_MAX)
555 if (CmpValue == INT_MIN)
565 return std::make_unique<TargetMBBInfo>(TargetMBBInfo{
566 TBB, FBB, BrInstr, CmpInstr, CC, SrcReg, CmpValue, Modified, CmpBrOnly});
575 &getAnalysis<MachineBranchProbabilityInfo>();
577 X86CondBrFolding CondBr(TII, MBPI, MF);
578 return CondBr.optimize();
bool hasSuccessorProbabilities() const
Return true if any of the successors have probabilities attached to them.
instr_iterator instr_begin()
instr_iterator instr_end()
MachineBasicBlock * getMBB() const
This class represents lattice values for constants.
static bool setBranchProb(MachineBasicBlock *MBB, MachineBasicBlock *SuccMBB, BranchProbability Prob)
const X86InstrInfo * getInstrInfo() const override
void push_back(const T &Elt)
STATISTIC(NumFunctions, "Total number of functions")
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
AnalysisUsage & addRequired()
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE and DBG_LABEL instructions...
void setMBB(MachineBasicBlock *MBB)
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
succ_iterator succ_begin()
pred_iterator pred_begin()
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
CondCode getCondFromBranch(const MachineInstr &MI)
bool threewayBranchProfitable() const
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly. ...
unsigned pred_size() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static MachineBasicBlock::iterator findUncondBrI(MachineBasicBlock *MBB)
unsigned succ_size() const
Representation of each machine instruction.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
static void fixPHIsInSucc(MachineBasicBlock *MBB, MachineBasicBlock *OldMBB, MachineBasicBlock *NewMBB)
void push_back(MachineInstr *MI)
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
FunctionPass * createX86CondBrFolding()
Return a pass that folds conditional branch jumps.
MachineInstr * removeFromParent()
Unlink 'this' from the containing basic block, and return it without deleting it. ...
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
StringRef - Represent a constant reference to a string, i.e.
Register getReg() const
getReg - Returns the register number.
const MachineOperand & getOperand(unsigned i) const