#define DEBUG_TYPE "simplifycfg"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Type.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ConstantRange.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/IRBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <set>
#include <map>
using namespace llvm;
static cl::opt<unsigned>
PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
cl::desc("Control the amount of phi node folding to perform (default = 1)"));
static cl::opt<bool>
DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
cl::desc("Duplicate return instructions into unconditional branches"));
STATISTIC(NumSpeculations, "Number of speculative executed instructions");
namespace {
class SimplifyCFGOpt {
const TargetData *const TD;
Value *isValueEqualityComparison(TerminatorInst *TI);
BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases);
bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
BasicBlock *Pred,
IRBuilder<> &Builder);
bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
IRBuilder<> &Builder);
bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
bool SimplifyUnwind(UnwindInst *UI, IRBuilder<> &Builder);
bool SimplifyUnreachable(UnreachableInst *UI);
bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
bool SimplifyIndirectBr(IndirectBrInst *IBI);
bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
public:
explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
bool run(BasicBlock *BB);
};
}
static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
if (SI1 == SI2) return false;
BasicBlock *SI1BB = SI1->getParent();
BasicBlock *SI2BB = SI2->getParent();
SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
if (SI1Succs.count(*I))
for (BasicBlock::iterator BBI = (*I)->begin();
isa<PHINode>(BBI); ++BBI) {
PHINode *PN = cast<PHINode>(BBI);
if (PN->getIncomingValueForBlock(SI1BB) !=
PN->getIncomingValueForBlock(SI2BB))
return false;
}
return true;
}
static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
BasicBlock *ExistPred) {
if (!isa<PHINode>(Succ->begin())) return;
PHINode *PN;
for (BasicBlock::iterator I = Succ->begin();
(PN = dyn_cast<PHINode>(I)); ++I)
PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
}
static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
BasicBlock *&IfFalse) {
PHINode *SomePHI = cast<PHINode>(BB->begin());
assert(SomePHI->getNumIncomingValues() == 2 &&
"Function can only handle blocks with 2 predecessors!");
BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
if (Pred1Br == 0 || Pred2Br == 0)
return 0;
if (Pred2Br->isConditional()) {
if (Pred1Br->isConditional())
return 0;
std::swap(Pred1, Pred2);
std::swap(Pred1Br, Pred2Br);
}
if (Pred1Br->isConditional()) {
if (Pred2->getSinglePredecessor() == 0)
return 0;
if (Pred1Br->getSuccessor(0) == BB &&
Pred1Br->getSuccessor(1) == Pred2) {
IfTrue = Pred1;
IfFalse = Pred2;
} else if (Pred1Br->getSuccessor(0) == Pred2 &&
Pred1Br->getSuccessor(1) == BB) {
IfTrue = Pred2;
IfFalse = Pred1;
} else {
return 0;
}
return Pred1Br->getCondition();
}
BasicBlock *CommonPred = Pred1->getSinglePredecessor();
if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
return 0;
BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
if (BI == 0) return 0;
assert(BI->isConditional() && "Two successors but not conditional?");
if (BI->getSuccessor(0) == Pred1) {
IfTrue = Pred1;
IfFalse = Pred2;
} else {
IfTrue = Pred2;
IfFalse = Pred1;
}
return BI->getCondition();
}
static bool DominatesMergePoint(Value *V, BasicBlock *BB,
SmallPtrSet<Instruction*, 4> *AggressiveInsts,
unsigned &CostRemaining) {
Instruction *I = dyn_cast<Instruction>(V);
if (!I) {
if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
if (C->canTrap())
return false;
return true;
}
BasicBlock *PBB = I->getParent();
if (PBB == BB) return false;
BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
return true;
if (AggressiveInsts == 0) return false;
if (AggressiveInsts->count(I)) return true;
if (!I->isSafeToSpeculativelyExecute())
return false;
unsigned Cost = 0;
switch (I->getOpcode()) {
default: return false; case Instruction::Load:
if (PBB->getFirstNonPHIOrDbg() != I)
return false;
Cost = 1;
break;
case Instruction::GetElementPtr:
if (!cast<GetElementPtrInst>(I)->hasAllConstantIndices())
return false;
Cost = 1;
break;
case Instruction::Add:
case Instruction::Sub:
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
case Instruction::ICmp:
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
Cost = 1;
break;
case Instruction::Select:
Cost = 2;
break;
}
if (Cost > CostRemaining)
return false;
CostRemaining -= Cost;
for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining))
return false;
AggressiveInsts->insert(I);
return true;
}
static ConstantInt *GetConstantInt(Value *V, const TargetData *TD) {
ConstantInt *CI = dyn_cast<ConstantInt>(V);
if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
return CI;
const IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
if (isa<ConstantPointerNull>(V))
return ConstantInt::get(PtrTy, 0);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == Instruction::IntToPtr)
if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
if (CI->getType() == PtrTy)
return CI;
else
return cast<ConstantInt>
(ConstantExpr::getIntegerCast(CI, PtrTy, false));
}
return 0;
}
static Value *
GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
const TargetData *TD, bool isEQ, unsigned &UsedICmps) {
Instruction *I = dyn_cast<Instruction>(V);
if (I == 0) return 0;
if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
UsedICmps++;
Vals.push_back(C);
return I->getOperand(0);
}
ConstantRange Span =
ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
if (!isEQ)
Span = Span.inverse();
if (Span.getSetSize().ugt(8) || Span.isEmptySet() ||
Span.isWrappedSet())
return 0;
for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
UsedICmps++;
return I->getOperand(0);
}
return 0;
}
if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
return 0;
unsigned NumValsBeforeLHS = Vals.size();
unsigned UsedICmpsBeforeLHS = UsedICmps;
if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
isEQ, UsedICmps)) {
unsigned NumVals = Vals.size();
unsigned UsedICmpsBeforeRHS = UsedICmps;
if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
isEQ, UsedICmps)) {
if (LHS == RHS)
return LHS;
Vals.resize(NumVals);
UsedICmps = UsedICmpsBeforeRHS;
}
if (Extra == 0 || Extra == I->getOperand(1)) {
Extra = I->getOperand(1);
return LHS;
}
Vals.resize(NumValsBeforeLHS);
UsedICmps = UsedICmpsBeforeLHS;
return 0;
}
if (Extra == 0 || Extra == I->getOperand(0)) {
Value *OldExtra = Extra;
Extra = I->getOperand(0);
if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
isEQ, UsedICmps))
return RHS;
assert(Vals.size() == NumValsBeforeLHS);
Extra = OldExtra;
}
return 0;
}
static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Instruction* Cond = 0;
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Cond = dyn_cast<Instruction>(SI->getCondition());
} else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
if (BI->isConditional())
Cond = dyn_cast<Instruction>(BI->getCondition());
} else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
Cond = dyn_cast<Instruction>(IBI->getAddress());
}
TI->eraseFromParent();
if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
}
Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Value *CV = 0;
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
pred_end(SI->getParent())) <= 128)
CV = SI->getCondition();
} else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
if (BI->isConditional() && BI->getCondition()->hasOneUse())
if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
ICI->getPredicate() == ICmpInst::ICMP_NE) &&
GetConstantInt(ICI->getOperand(1), TD))
CV = ICI->getOperand(0);
if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
CV = PTII->getOperand(0);
return CV;
}
BasicBlock *SimplifyCFGOpt::
GetValueEqualityComparisonCases(TerminatorInst *TI,
std::vector<std::pair<ConstantInt*,
BasicBlock*> > &Cases) {
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Cases.reserve(SI->getNumCases());
for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
return SI->getDefaultDest();
}
BranchInst *BI = cast<BranchInst>(TI);
ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Cases.push_back(std::make_pair(GetConstantInt(ICI->getOperand(1), TD),
BI->getSuccessor(ICI->getPredicate() ==
ICmpInst::ICMP_NE)));
return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
}
static void EliminateBlockCases(BasicBlock *BB,
std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
for (unsigned i = 0, e = Cases.size(); i != e; ++i)
if (Cases[i].second == BB) {
Cases.erase(Cases.begin()+i);
--i; --e;
}
}
static bool
ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
if (V1->size() > V2->size())
std::swap(V1, V2);
if (V1->size() == 0) return false;
if (V1->size() == 1) {
ConstantInt *TheVal = (*V1)[0].first;
for (unsigned i = 0, e = V2->size(); i != e; ++i)
if (TheVal == (*V2)[i].first)
return true;
}
array_pod_sort(V1->begin(), V1->end());
array_pod_sort(V2->begin(), V2->end());
unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
while (i1 != e1 && i2 != e2) {
if ((*V1)[i1].first == (*V2)[i2].first)
return true;
if ((*V1)[i1].first < (*V2)[i2].first)
++i1;
else
++i2;
}
return false;
}
bool SimplifyCFGOpt::
SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
BasicBlock *Pred,
IRBuilder<> &Builder) {
Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
if (!PredVal) return false;
Value *ThisVal = isValueEqualityComparison(TI);
assert(ThisVal && "This isn't a value comparison!!");
if (ThisVal != PredVal) return false;
std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
PredCases);
EliminateBlockCases(PredDef, PredCases);
std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
EliminateBlockCases(ThisDef, ThisCases);
if (PredDef == TI->getParent()) {
if (!ValuesOverlap(PredCases, ThisCases))
return false;
if (isa<BranchInst>(TI)) {
assert(ThisCases.size() == 1 && "Branch can only have one case!");
Instruction *NI = Builder.CreateBr(ThisDef);
(void) NI;
ThisCases[0].second->removePredecessor(TI->getParent());
DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
<< "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
EraseTerminatorInstAndDCECond(TI);
return true;
}
SwitchInst *SI = cast<SwitchInst>(TI);
SmallPtrSet<Constant*, 16> DeadCases;
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
DeadCases.insert(PredCases[i].first);
DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
<< "Through successor TI: " << *TI);
for (unsigned i = SI->getNumCases()-1; i != 0; --i)
if (DeadCases.count(SI->getCaseValue(i))) {
SI->getSuccessor(i)->removePredecessor(TI->getParent());
SI->removeCase(i);
}
DEBUG(dbgs() << "Leaving: " << *TI << "\n");
return true;
}
ConstantInt *TIV = 0;
BasicBlock *TIBB = TI->getParent();
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
if (PredCases[i].second == TIBB) {
if (TIV != 0)
return false; TIV = PredCases[i].first;
}
assert(TIV && "No edge from pred to succ?");
BasicBlock *TheRealDest = 0;
for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
if (ThisCases[i].first == TIV) {
TheRealDest = ThisCases[i].second;
break;
}
if (TheRealDest == 0) TheRealDest = ThisDef;
BasicBlock *CheckEdge = TheRealDest;
for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
if (*SI != CheckEdge)
(*SI)->removePredecessor(TIBB);
else
CheckEdge = 0;
Instruction *NI = Builder.CreateBr(TheRealDest);
(void) NI;
DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
<< "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
EraseTerminatorInstAndDCECond(TI);
return true;
}
namespace {
struct ConstantIntOrdering {
bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
return LHS->getValue().ult(RHS->getValue());
}
};
}
static int ConstantIntSortPredicate(const void *P1, const void *P2) {
const ConstantInt *LHS = *(const ConstantInt**)P1;
const ConstantInt *RHS = *(const ConstantInt**)P2;
if (LHS->getValue().ult(RHS->getValue()))
return 1;
if (LHS->getValue() == RHS->getValue())
return 0;
return -1;
}
bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
IRBuilder<> &Builder) {
BasicBlock *BB = TI->getParent();
Value *CV = isValueEqualityComparison(TI); assert(CV && "Not a comparison?");
bool Changed = false;
SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
while (!Preds.empty()) {
BasicBlock *Pred = Preds.pop_back_val();
TerminatorInst *PTI = Pred->getTerminator();
Value *PCV = isValueEqualityComparison(PTI);
if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
SmallVector<BasicBlock*, 8> NewSuccessors;
if (PredDefault == BB) {
std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
if (PredCases[i].second != BB)
PTIHandled.insert(PredCases[i].first);
else {
std::swap(PredCases[i], PredCases.back());
PredCases.pop_back();
--i; --e;
}
if (PredDefault != BBDefault) {
PredDefault->removePredecessor(Pred);
PredDefault = BBDefault;
NewSuccessors.push_back(BBDefault);
}
for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
if (!PTIHandled.count(BBCases[i].first) &&
BBCases[i].second != BBDefault) {
PredCases.push_back(BBCases[i]);
NewSuccessors.push_back(BBCases[i].second);
}
} else {
std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
if (PredCases[i].second == BB) {
PTIHandled.insert(PredCases[i].first);
std::swap(PredCases[i], PredCases.back());
PredCases.pop_back();
--i; --e;
}
for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
if (PTIHandled.count(BBCases[i].first)) {
PredCases.push_back(BBCases[i]);
NewSuccessors.push_back(BBCases[i].second);
PTIHandled.erase(BBCases[i].first); }
for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
PTIHandled.begin(),
E = PTIHandled.end(); I != E; ++I) {
PredCases.push_back(std::make_pair(*I, BBDefault));
NewSuccessors.push_back(BBDefault);
}
}
for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
Builder.SetInsertPoint(PTI);
if (CV->getType()->isPointerTy()) {
assert(TD && "Cannot switch on pointer without TargetData");
CV = Builder.CreatePtrToInt(CV, TD->getIntPtrType(CV->getContext()),
"magicptr");
}
SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
PredCases.size());
NewSI->setDebugLoc(PTI->getDebugLoc());
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
NewSI->addCase(PredCases[i].first, PredCases[i].second);
EraseTerminatorInstAndDCECond(PTI);
BasicBlock *InfLoopBlock = 0;
for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
if (NewSI->getSuccessor(i) == BB) {
if (InfLoopBlock == 0) {
InfLoopBlock = BasicBlock::Create(BB->getContext(),
"infloop", BB->getParent());
BranchInst::Create(InfLoopBlock, InfLoopBlock);
}
NewSI->setSuccessor(i, InfLoopBlock);
}
Changed = true;
}
}
return Changed;
}
static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
Instruction *I1, Instruction *I2) {
for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
PHINode *PN;
for (BasicBlock::iterator BBI = SI->begin();
(PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Value *BB1V = PN->getIncomingValueForBlock(BB1);
Value *BB2V = PN->getIncomingValueForBlock(BB2);
if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
return false;
}
}
}
return true;
}
static bool HoistThenElseCodeToIf(BranchInst *BI) {
BasicBlock *BB1 = BI->getSuccessor(0); BasicBlock *BB2 = BI->getSuccessor(1);
BasicBlock::iterator BB1_Itr = BB1->begin();
BasicBlock::iterator BB2_Itr = BB2->begin();
Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
while (isa<DbgInfoIntrinsic>(I1))
I1 = BB1_Itr++;
while (isa<DbgInfoIntrinsic>(I2))
I2 = BB2_Itr++;
}
if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
(isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
return false;
BasicBlock *BIParent = BI->getParent();
do {
if (isa<TerminatorInst>(I1))
goto HoistTerminator;
BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
if (!I2->use_empty())
I2->replaceAllUsesWith(I1);
I1->intersectOptionalDataWith(I2);
I2->eraseFromParent();
I1 = BB1_Itr++;
I2 = BB2_Itr++;
DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
while (isa<DbgInfoIntrinsic>(I1))
I1 = BB1_Itr++;
while (isa<DbgInfoIntrinsic>(I2))
I2 = BB2_Itr++;
}
} while (I1->isIdenticalToWhenDefined(I2));
return true;
HoistTerminator:
if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
return true;
Instruction *NT = I1->clone();
BIParent->getInstList().insert(BI, NT);
if (!NT->getType()->isVoidTy()) {
I1->replaceAllUsesWith(NT);
I2->replaceAllUsesWith(NT);
NT->takeName(I1);
}
std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
PHINode *PN;
for (BasicBlock::iterator BBI = SI->begin();
(PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Value *BB1V = PN->getIncomingValueForBlock(BB1);
Value *BB2V = PN->getIncomingValueForBlock(BB2);
if (BB1V == BB2V) continue;
SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
if (SI == 0) {
SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
BB1V->getName()+"."+BB2V->getName(), NT);
SI->setDebugLoc(BI->getDebugLoc());
}
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
PN->setIncomingValue(i, SI);
}
}
for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
AddPredecessorToBlock(*SI, BIParent, BB1);
EraseTerminatorInstAndDCECond(BI);
return true;
}
static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
Instruction *HInst = NULL;
Instruction *Term = BB1->getTerminator();
for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
BBI != BBE; ++BBI) {
Instruction *I = BBI;
if (isa<DbgInfoIntrinsic>(I)) continue;
if (I == Term) break;
if (HInst)
return false;
HInst = I;
}
if (!HInst)
return false;
Value *BrCond = BI->getCondition();
if (isa<FCmpInst>(BrCond))
return false;
bool Invert = false;
if (BB1 != BI->getSuccessor(0)) {
assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
Invert = true;
}
switch (HInst->getOpcode()) {
default: return false; case Instruction::Add:
case Instruction::Sub:
if (HInst->getType()->isVectorTy())
return false;
break;
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
if (HInst->getType()->isVectorTy())
return false;
break; }
if (HInst->use_empty()) {
HInst->eraseFromParent();
return true;
}
BasicBlock *BIParent = BI->getParent();
SmallVector<PHINode*, 4> PHIUses;
Value *FalseV = NULL;
BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
for (Value::use_iterator UI = HInst->use_begin(), E = HInst->use_end();
UI != E; ++UI) {
PHINode *PN = dyn_cast<PHINode>(*UI);
if (!PN || PN->getParent() != BB2)
return false;
PHIUses.push_back(PN);
Value *PHIV = PN->getIncomingValueForBlock(BIParent);
if (!FalseV)
FalseV = PHIV;
else if (FalseV != PHIV)
return false; }
assert(FalseV && "Must have at least one user, and it must be a PHI");
for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
i != e; ++i) {
Instruction *OpI = dyn_cast<Instruction>(*i);
if (OpI && OpI->getParent() == BIParent &&
!OpI->isUsedInBasicBlock(BIParent))
return false;
}
BasicBlock::iterator InsertPos = BI;
if (InsertPos != BIParent->begin())
--InsertPos;
while (InsertPos != BIParent->begin() && isa<DbgInfoIntrinsic>(InsertPos))
--InsertPos;
if (InsertPos == BrCond && !isa<PHINode>(BrCond)) {
SmallPtrSet<Instruction *, 4> BB1Insns;
for(BasicBlock::iterator BB1I = BB1->begin(), BB1E = BB1->end();
BB1I != BB1E; ++BB1I)
BB1Insns.insert(BB1I);
for(Value::use_iterator UI = BrCond->use_begin(), UE = BrCond->use_end();
UI != UE; ++UI) {
Instruction *Use = cast<Instruction>(*UI);
if (!BB1Insns.count(Use)) continue;
InsertPos = BI;
break;
}
} else
InsertPos = BI;
BIParent->getInstList().splice(InsertPos, BB1->getInstList(), HInst);
SelectInst *SI;
if (Invert)
SI = SelectInst::Create(BrCond, FalseV, HInst,
FalseV->getName() + "." + HInst->getName(), BI);
else
SI = SelectInst::Create(BrCond, HInst, FalseV,
HInst->getName() + "." + FalseV->getName(), BI);
SI->setDebugLoc(BI->getDebugLoc());
for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
PHINode *PN = PHIUses[i];
for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
if (PN->getIncomingBlock(j) == BB1 || PN->getIncomingBlock(j) == BIParent)
PN->setIncomingValue(j, SI);
}
++NumSpeculations;
return true;
}
static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
BranchInst *BI = cast<BranchInst>(BB->getTerminator());
unsigned Size = 0;
for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
if (isa<DbgInfoIntrinsic>(BBI))
continue;
if (Size > 10) return false; ++Size;
for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
UI != E; ++UI) {
Instruction *U = cast<Instruction>(*UI);
if (U->getParent() != BB || isa<PHINode>(U)) return false;
}
}
return true;
}
static bool FoldCondBranchOnPHI(BranchInst *BI, const TargetData *TD) {
BasicBlock *BB = BI->getParent();
PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
if (!PN || PN->getParent() != BB || !PN->hasOneUse())
return false;
if (PN->getNumIncomingValues() == 1) {
FoldSingleEntryPHINodes(PN->getParent());
return true;
}
if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
BasicBlock *PredBB = PN->getIncomingBlock(i);
BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
if (RealDest == BB) continue;
BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
RealDest->getName()+".critedge",
RealDest->getParent(), RealDest);
BranchInst::Create(RealDest, EdgeBB);
AddPredecessorToBlock(RealDest, EdgeBB, BB);
BasicBlock::iterator InsertPt = EdgeBB->begin();
DenseMap<Value*, Value*> TranslateMap; for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
continue;
}
Instruction *N = BBI->clone();
if (BBI->hasName()) N->setName(BBI->getName()+".c");
for (User::op_iterator i = N->op_begin(), e = N->op_end();
i != e; ++i) {
DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
if (PI != TranslateMap.end())
*i = PI->second;
}
if (Value *V = SimplifyInstruction(N, TD)) {
TranslateMap[BBI] = V;
delete N; } else {
EdgeBB->getInstList().insert(InsertPt, N);
if (!BBI->use_empty())
TranslateMap[BBI] = N;
}
}
TerminatorInst *PredBBTI = PredBB->getTerminator();
for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
if (PredBBTI->getSuccessor(i) == BB) {
BB->removePredecessor(PredBB);
PredBBTI->setSuccessor(i, EdgeBB);
}
return FoldCondBranchOnPHI(BI, TD) | true;
}
return false;
}
static bool FoldTwoEntryPHINode(PHINode *PN, const TargetData *TD,
IRBuilder<> &Builder) {
BasicBlock *BB = PN->getParent();
BasicBlock *IfTrue, *IfFalse;
Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
if (!IfCond ||
isa<ConstantInt>(IfCond))
return false;
unsigned NumPhis = 0;
for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
if (NumPhis > 2)
return false;
SmallPtrSet<Instruction*, 4> AggressiveInsts;
unsigned MaxCostVal0 = PHINodeFoldingThreshold,
MaxCostVal1 = PHINodeFoldingThreshold;
for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
PHINode *PN = cast<PHINode>(II++);
if (Value *V = SimplifyInstruction(PN, TD)) {
PN->replaceAllUsesWith(V);
PN->eraseFromParent();
continue;
}
if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
MaxCostVal0) ||
!DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
MaxCostVal1))
return false;
}
PN = dyn_cast<PHINode>(BB->begin());
if (PN == 0) return true;
if (PN->getType()->isIntegerTy(1) &&
(isa<BinaryOperator>(PN->getIncomingValue(0)) ||
isa<BinaryOperator>(PN->getIncomingValue(1)) ||
isa<BinaryOperator>(IfCond)))
return false;
BasicBlock *DomBlock = 0;
BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
IfBlock1 = 0;
} else {
DomBlock = *pred_begin(IfBlock1);
for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
return false;
}
}
if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
IfBlock2 = 0;
} else {
DomBlock = *pred_begin(IfBlock2);
for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
return false;
}
}
DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
<< IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Instruction *InsertPt = DomBlock->getTerminator();
Builder.SetInsertPoint(InsertPt);
if (IfBlock1)
DomBlock->getInstList().splice(InsertPt,
IfBlock1->getInstList(), IfBlock1->begin(),
IfBlock1->getTerminator());
if (IfBlock2)
DomBlock->getInstList().splice(InsertPt,
IfBlock2->getInstList(), IfBlock2->begin(),
IfBlock2->getTerminator());
while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
SelectInst *NV =
cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
PN->replaceAllUsesWith(NV);
NV->takeName(PN);
PN->eraseFromParent();
}
TerminatorInst *OldTI = DomBlock->getTerminator();
Builder.SetInsertPoint(OldTI);
Builder.CreateBr(BB);
OldTI->eraseFromParent();
return true;
}
static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
IRBuilder<> &Builder) {
assert(BI->isConditional() && "Must be a conditional branch");
BasicBlock *TrueSucc = BI->getSuccessor(0);
BasicBlock *FalseSucc = BI->getSuccessor(1);
ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
return false;
if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
return false;
Builder.SetInsertPoint(BI);
if (FalseRet->getNumOperands() == 0) {
TrueSucc->removePredecessor(BI->getParent());
FalseSucc->removePredecessor(BI->getParent());
Builder.CreateRetVoid();
EraseTerminatorInstAndDCECond(BI);
return true;
}
Value *TrueValue = TrueRet->getReturnValue();
Value *FalseValue = FalseRet->getReturnValue();
if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
if (TVPN->getParent() == TrueSucc)
TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
if (FVPN->getParent() == FalseSucc)
FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
if (TCV->canTrap())
return false;
if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
if (FCV->canTrap())
return false;
TrueSucc->removePredecessor(BI->getParent());
FalseSucc->removePredecessor(BI->getParent());
Value *BrCond = BI->getCondition();
if (TrueValue) {
if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
} else if (isa<UndefValue>(TrueValue)) {
TrueValue = FalseValue;
} else {
TrueValue = Builder.CreateSelect(BrCond, TrueValue,
FalseValue, "retval");
}
}
Value *RI = !TrueValue ?
Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
(void) RI;
DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
<< "\n " << *BI << "NewRet = " << *RI
<< "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
EraseTerminatorInstAndDCECond(BI);
return true;
}
bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
BasicBlock *BB = BI->getParent();
Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
Cond->getParent() != BB || !Cond->hasOneUse())
return false;
BasicBlock::iterator FrontIt = BB->front();
while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
Instruction *BonusInst = 0;
if (&*FrontIt != Cond &&
FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
FrontIt->isSafeToSpeculativelyExecute()) {
BonusInst = &*FrontIt;
++FrontIt;
while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
}
if (&*FrontIt != Cond)
return false;
BasicBlock::iterator CondIt = Cond; ++CondIt;
while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
if (&*CondIt != BI)
return false;
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
if (CE->canTrap())
return false;
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
if (CE->canTrap())
return false;
BasicBlock *TrueDest = BI->getSuccessor(0);
BasicBlock *FalseDest = BI->getSuccessor(1);
if (TrueDest == BB || FalseDest == BB)
return false;
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
BasicBlock *PredBlock = *PI;
BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
if (PBI == 0 || PBI->isUnconditional() || !SafeToMergeTerminators(BI, PBI))
continue;
Instruction::BinaryOps Opc;
bool InvertPredCond = false;
if (PBI->getSuccessor(0) == TrueDest)
Opc = Instruction::Or;
else if (PBI->getSuccessor(1) == FalseDest)
Opc = Instruction::And;
else if (PBI->getSuccessor(0) == FalseDest)
Opc = Instruction::And, InvertPredCond = true;
else if (PBI->getSuccessor(1) == TrueDest)
Opc = Instruction::Or, InvertPredCond = true;
else
continue;
if (BonusInst) {
SmallPtrSet<Value*, 4> UsedValues;
for (Instruction::op_iterator OI = BonusInst->op_begin(),
OE = BonusInst->op_end(); OI != OE; ++OI) {
Value* V = *OI;
if (!isa<Constant>(V))
UsedValues.insert(V);
}
SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
while (!Worklist.empty()) {
std::pair<Value*, unsigned> Pair = Worklist.back();
Worklist.pop_back();
if (Pair.second >= 4) continue;
UsedValues.erase(Pair.first);
if (UsedValues.empty()) break;
if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
OI != OE; ++OI)
Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
}
}
if (!UsedValues.empty()) return false;
}
DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
if (InvertPredCond) {
Value *NewCond = PBI->getCondition();
if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
CmpInst *CI = cast<CmpInst>(NewCond);
CI->setPredicate(CI->getInversePredicate());
} else {
NewCond = BinaryOperator::CreateNot(NewCond,
PBI->getCondition()->getName()+".not", PBI);
}
PBI->setCondition(NewCond);
BasicBlock *OldTrue = PBI->getSuccessor(0);
BasicBlock *OldFalse = PBI->getSuccessor(1);
PBI->setSuccessor(0, OldFalse);
PBI->setSuccessor(1, OldTrue);
}
Instruction *NewBonus = 0;
if (BonusInst) {
NewBonus = BonusInst->clone();
PredBlock->getInstList().insert(PBI, NewBonus);
NewBonus->takeName(BonusInst);
BonusInst->setName(BonusInst->getName()+".old");
}
Instruction *New = Cond->clone();
if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
PredBlock->getInstList().insert(PBI, New);
New->takeName(Cond);
Cond->setName(New->getName()+".old");
Instruction *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
New, "or.cond", PBI);
NewCond->setDebugLoc(PBI->getDebugLoc());
PBI->setCondition(NewCond);
if (PBI->getSuccessor(0) == BB) {
AddPredecessorToBlock(TrueDest, PredBlock, BB);
PBI->setSuccessor(0, TrueDest);
}
if (PBI->getSuccessor(1) == BB) {
AddPredecessorToBlock(FalseDest, PredBlock, BB);
PBI->setSuccessor(1, FalseDest);
}
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
if (isa<DbgInfoIntrinsic>(*I))
I->clone()->insertBefore(PBI);
return true;
}
return false;
}
static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
assert(PBI->isConditional() && BI->isConditional());
BasicBlock *BB = BI->getParent();
if (PBI->getCondition() == BI->getCondition() &&
PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
if (BB->getSinglePredecessor()) {
bool CondIsTrue = PBI->getSuccessor(0) == BB;
BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
CondIsTrue));
return true; }
if (BlockIsSimpleEnoughToThreadThrough(BB)) {
pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
std::distance(PB, PE),
BI->getCondition()->getName() + ".pr",
BB->begin());
for (pred_iterator PI = PB; PI != PE; ++PI) {
BasicBlock *P = *PI;
if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
PBI != BI && PBI->isConditional() &&
PBI->getCondition() == BI->getCondition() &&
PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
bool CondIsTrue = PBI->getSuccessor(0) == BB;
NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
CondIsTrue), P);
} else {
NewPN->addIncoming(BI->getCondition(), P);
}
}
BI->setCondition(NewPN);
return true;
}
}
BasicBlock::iterator BBI = BB->begin();
while (isa<DbgInfoIntrinsic>(BBI))
++BBI;
if (&*BBI != BI)
return false;
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
if (CE->canTrap())
return false;
int PBIOp, BIOp;
if (PBI->getSuccessor(0) == BI->getSuccessor(0))
PBIOp = BIOp = 0;
else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
PBIOp = 0, BIOp = 1;
else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
PBIOp = 1, BIOp = 0;
else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
PBIOp = BIOp = 1;
else
return false;
if (PBI->getSuccessor(PBIOp) == BB)
return false;
BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
unsigned NumPhis = 0;
for (BasicBlock::iterator II = CommonDest->begin();
isa<PHINode>(II); ++II, ++NumPhis)
if (NumPhis > 2) return false;
BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
<< "AND: " << *BI->getParent());
if (OtherDest == BB) {
BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
"infloop", BB->getParent());
BranchInst::Create(InfLoopBlock, InfLoopBlock);
OtherDest = InfLoopBlock;
}
DEBUG(dbgs() << *PBI->getParent()->getParent());
Value *PBICond = PBI->getCondition();
if (PBIOp)
PBICond = BinaryOperator::CreateNot(PBICond,
PBICond->getName()+".not",
PBI);
Value *BICond = BI->getCondition();
if (BIOp)
BICond = BinaryOperator::CreateNot(BICond,
BICond->getName()+".not",
PBI);
Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
PBI->setCondition(Cond);
PBI->setSuccessor(0, CommonDest);
PBI->setSuccessor(1, OtherDest);
AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
PHINode *PN;
for (BasicBlock::iterator II = CommonDest->begin();
(PN = dyn_cast<PHINode>(II)); ++II) {
Value *BIV = PN->getIncomingValueForBlock(BB);
unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
Value *PBIV = PN->getIncomingValue(PBBIdx);
if (BIV != PBIV) {
Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
PBIV->getName()+".mux", PBI);
PN->setIncomingValue(PBBIdx, NV);
}
}
DEBUG(dbgs() << "INTO: " << *PBI->getParent());
DEBUG(dbgs() << *PBI->getParent()->getParent());
return true;
}
static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
BasicBlock *TrueBB, BasicBlock *FalseBB){
BasicBlock *KeepEdge1 = TrueBB;
BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
BasicBlock *Succ = OldTerm->getSuccessor(I);
if (Succ == KeepEdge1)
KeepEdge1 = 0;
else if (Succ == KeepEdge2)
KeepEdge2 = 0;
else
Succ->removePredecessor(OldTerm->getParent());
}
IRBuilder<> Builder(OldTerm);
Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
if (TrueBB == FalseBB)
Builder.CreateBr(TrueBB);
else
Builder.CreateCondBr(Cond, TrueBB, FalseBB);
} else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
new UnreachableInst(OldTerm->getContext(), OldTerm);
} else {
if (KeepEdge1 == 0)
Builder.CreateBr(TrueBB);
else
Builder.CreateBr(FalseBB);
}
EraseTerminatorInstAndDCECond(OldTerm);
return true;
}
static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
if (!TrueVal || !FalseVal)
return false;
Value *Condition = Select->getCondition();
BasicBlock *TrueBB = SI->getSuccessor(SI->findCaseValue(TrueVal));
BasicBlock *FalseBB = SI->getSuccessor(SI->findCaseValue(FalseVal));
return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB);
}
static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
if (!TBA || !FBA)
return false;
BasicBlock *TrueBB = TBA->getBasicBlock();
BasicBlock *FalseBB = FBA->getBasicBlock();
return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB);
}
static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
const TargetData *TD,
IRBuilder<> &Builder) {
BasicBlock *BB = ICI->getParent();
if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
Value *V = ICI->getOperand(0);
ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
BasicBlock *Pred = BB->getSinglePredecessor();
if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
if (SI->getCondition() != V)
return false;
if (SI->getDefaultDest() != BB) {
ConstantInt *VVal = SI->findCaseDest(BB);
assert(VVal && "Should have a unique destination value");
ICI->setOperand(0, VVal);
if (Value *V = SimplifyInstruction(ICI, TD)) {
ICI->replaceAllUsesWith(V);
ICI->eraseFromParent();
}
return SimplifyCFG(BB) | true;
}
if (SI->findCaseValue(Cst) != 0) {
Value *V;
if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
V = ConstantInt::getFalse(BB->getContext());
else
V = ConstantInt::getTrue(BB->getContext());
ICI->replaceAllUsesWith(V);
ICI->eraseFromParent();
return SimplifyCFG(BB) | true;
}
BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
isa<PHINode>(++BasicBlock::iterator(PHIUse)))
return false;
Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
Constant *NewCst = ConstantInt::getFalse(BB->getContext());
if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
std::swap(DefaultCst, NewCst);
ICI->replaceAllUsesWith(DefaultCst);
ICI->eraseFromParent();
BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
BB->getParent(), BB);
SI->addCase(Cst, NewBB);
Builder.SetInsertPoint(NewBB);
Builder.SetCurrentDebugLocation(SI->getDebugLoc());
Builder.CreateBr(SuccBlock);
PHIUse->addIncoming(NewCst, NewBB);
return true;
}
static bool SimplifyBranchOnICmpChain(BranchInst *BI, const TargetData *TD,
IRBuilder<> &Builder) {
Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
if (Cond == 0) return false;
Value *CompVal = 0;
std::vector<ConstantInt*> Values;
bool TrueWhenEqual = true;
Value *ExtraCase = 0;
unsigned UsedICmps = 0;
if (Cond->getOpcode() == Instruction::Or) {
CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true,
UsedICmps);
} else if (Cond->getOpcode() == Instruction::And) {
CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false,
UsedICmps);
TrueWhenEqual = false;
}
if (CompVal == 0) return false;
if (UsedICmps <= 1)
return false;
array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
if (ExtraCase && Values.size() < 2) return false;
BasicBlock *DefaultBB = BI->getSuccessor(1);
BasicBlock *EdgeBB = BI->getSuccessor(0);
if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
BasicBlock *BB = BI->getParent();
DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
<< " cases into SWITCH. BB is:\n" << *BB);
if (ExtraCase) {
BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
TerminatorInst *OldTI = BB->getTerminator();
Builder.SetInsertPoint(OldTI);
if (TrueWhenEqual)
Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
else
Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
OldTI->eraseFromParent();
AddPredecessorToBlock(EdgeBB, BB, NewBB);
DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
<< "\nEXTRABB = " << *BB);
BB = NewBB;
}
Builder.SetInsertPoint(BI);
if (CompVal->getType()->isPointerTy()) {
assert(TD && "Cannot switch on pointer without TargetData");
CompVal = Builder.CreatePtrToInt(CompVal,
TD->getIntPtrType(CompVal->getContext()),
"magicptr");
}
SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
for (unsigned i = 0, e = Values.size(); i != e; ++i)
New->addCase(Values[i], EdgeBB);
for (BasicBlock::iterator BBI = EdgeBB->begin();
isa<PHINode>(BBI); ++BBI) {
PHINode *PN = cast<PHINode>(BBI);
Value *InVal = PN->getIncomingValueForBlock(BB);
for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
PN->addIncoming(InVal, BB);
}
EraseTerminatorInstAndDCECond(BI);
DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
return true;
}
bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
BasicBlock *BB = RI->getParent();
if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
SmallVector<BasicBlock*, 8> UncondBranchPreds;
SmallVector<BranchInst*, 8> CondBranchPreds;
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
BasicBlock *P = *PI;
TerminatorInst *PTI = P->getTerminator();
if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
if (BI->isUnconditional())
UncondBranchPreds.push_back(P);
else
CondBranchPreds.push_back(BI);
}
}
if (!UncondBranchPreds.empty() && DupRet) {
while (!UncondBranchPreds.empty()) {
BasicBlock *Pred = UncondBranchPreds.pop_back_val();
DEBUG(dbgs() << "FOLDING: " << *BB
<< "INTO UNCOND BRANCH PRED: " << *Pred);
(void)FoldReturnIntoUncondBranch(RI, BB, Pred);
}
if (pred_begin(BB) == pred_end(BB))
BB->eraseFromParent();
return true;
}
while (!CondBranchPreds.empty()) {
BranchInst *BI = CondBranchPreds.pop_back_val();
if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
SimplifyCondBranchToTwoReturns(BI, Builder))
return true;
}
return false;
}
bool SimplifyCFGOpt::SimplifyUnwind(UnwindInst *UI, IRBuilder<> &Builder) {
BasicBlock *BB = UI->getParent();
if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
bool Changed = false;
SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
while (!Preds.empty()) {
BasicBlock *Pred = Preds.back();
InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator());
if (II && II->getUnwindDest() == BB) {
Builder.SetInsertPoint(II);
BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Pred->getInstList().remove(II);
SmallVector<Value*,8> Args(II->op_begin(), II->op_end()-3);
Builder.SetInsertPoint(BI);
CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Args.begin(), Args.end(),
II->getName());
CI->setCallingConv(II->getCallingConv());
CI->setAttributes(II->getAttributes());
II->replaceAllUsesWith(CI);
delete II;
Changed = true;
}
Preds.pop_back();
}
if (pred_begin(BB) == pred_end(BB) &&
BB != &BB->getParent()->getEntryBlock()) {
BB->eraseFromParent();
return true;
}
return Changed;
}
bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
BasicBlock *BB = UI->getParent();
bool Changed = false;
while (UI != BB->begin()) {
BasicBlock::iterator BBI = UI;
--BBI;
if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
if (SI->isVolatile())
break;
if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
if (LI->isVolatile())
break;
if (!BBI->use_empty())
BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
BBI->eraseFromParent();
Changed = true;
}
if (&BB->front() != UI) return Changed;
SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
TerminatorInst *TI = Preds[i]->getTerminator();
IRBuilder<> Builder(TI);
if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
if (BI->isUnconditional()) {
if (BI->getSuccessor(0) == BB) {
new UnreachableInst(TI->getContext(), TI);
TI->eraseFromParent();
Changed = true;
}
} else {
if (BI->getSuccessor(0) == BB) {
Builder.CreateBr(BI->getSuccessor(1));
EraseTerminatorInstAndDCECond(BI);
} else if (BI->getSuccessor(1) == BB) {
Builder.CreateBr(BI->getSuccessor(0));
EraseTerminatorInstAndDCECond(BI);
Changed = true;
}
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
if (SI->getSuccessor(i) == BB) {
BB->removePredecessor(SI->getParent());
SI->removeCase(i);
--i; --e;
Changed = true;
}
if (SI->getSuccessor(0) == BB) {
std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
std::pair<unsigned, unsigned>& entry =
Popularity[SI->getSuccessor(i)];
if (entry.first == 0) {
entry.first = 1;
entry.second = i;
} else {
entry.first++;
}
}
unsigned MaxPop = 0;
unsigned MaxIndex = 0;
BasicBlock *MaxBlock = 0;
for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
if (I->second.first > MaxPop ||
(I->second.first == MaxPop && MaxIndex > I->second.second)) {
MaxPop = I->second.first;
MaxIndex = I->second.second;
MaxBlock = I->first;
}
}
if (MaxBlock) {
SI->setSuccessor(0, MaxBlock);
Changed = true;
if (isa<PHINode>(MaxBlock->begin()))
for (unsigned i = 0; i != MaxPop-1; ++i)
MaxBlock->removePredecessor(SI->getParent());
for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
if (SI->getSuccessor(i) == MaxBlock) {
SI->removeCase(i);
--i; --e;
}
}
}
} else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
if (II->getUnwindDest() == BB) {
BranchInst *BI = Builder.CreateBr(II->getNormalDest());
II->removeFromParent();
SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Builder.SetInsertPoint(BI);
CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Args.begin(), Args.end(),
II->getName());
CI->setCallingConv(II->getCallingConv());
CI->setAttributes(II->getAttributes());
II->replaceAllUsesWith(CI);
delete II;
Changed = true;
}
}
}
if (pred_begin(BB) == pred_end(BB) &&
BB != &BB->getParent()->getEntryBlock()) {
BB->eraseFromParent();
return true;
}
return Changed;
}
static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
assert(SI->getNumCases() > 2 && "Degenerate switch?");
SmallVector<ConstantInt *, 16> Cases;
Cases.push_back(SI->getCaseValue(1));
for (unsigned I = 2, E = SI->getNumCases(); I != E; ++I) {
if (SI->getSuccessor(I-1) != SI->getSuccessor(I))
return false;
Cases.push_back(SI->getCaseValue(I));
}
assert(Cases.size() == SI->getNumCases()-1 && "Not all cases gathered");
array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
return false;
}
Constant *Offset = ConstantExpr::getNeg(Cases.back());
Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases()-1);
Value *Sub = SI->getCondition();
if (!Offset->isNullValue())
Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
Value *Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Builder.CreateCondBr(Cmp, SI->getSuccessor(1), SI->getDefaultDest());
for (BasicBlock::iterator BBI = SI->getSuccessor(1)->begin();
isa<PHINode>(BBI); ++BBI) {
for (unsigned I = 0, E = SI->getNumCases()-2; I != E; ++I)
cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
}
SI->eraseFromParent();
return true;
}
static bool EliminateDeadSwitchCases(SwitchInst *SI) {
Value *Cond = SI->getCondition();
unsigned Bits = cast<IntegerType>(Cond->getType())->getBitWidth();
APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
ComputeMaskedBits(Cond, APInt::getAllOnesValue(Bits), KnownZero, KnownOne);
SmallVector<ConstantInt*, 8> DeadCases;
for (unsigned I = 1, E = SI->getNumCases(); I != E; ++I) {
if ((SI->getCaseValue(I)->getValue() & KnownZero) != 0 ||
(SI->getCaseValue(I)->getValue() & KnownOne) != KnownOne) {
DeadCases.push_back(SI->getCaseValue(I));
DEBUG(dbgs() << "SimplifyCFG: switch case '"
<< SI->getCaseValue(I)->getValue() << "' is dead.\n");
}
}
for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
unsigned Case = SI->findCaseValue(DeadCases[I]);
SI->getSuccessor(Case)->removePredecessor(SI->getParent());
SI->removeCase(Case);
}
return !DeadCases.empty();
}
bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
if (!isValueEqualityComparison(SI))
return false;
BasicBlock *BB = SI->getParent();
if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
return SimplifyCFG(BB) | true;
Value *Cond = SI->getCondition();
if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
if (SimplifySwitchOnSelect(SI, Select))
return SimplifyCFG(BB) | true;
BasicBlock::iterator BBI = BB->begin();
while (isa<DbgInfoIntrinsic>(BBI))
++BBI;
if (SI == &*BBI)
if (FoldValueComparisonIntoPredecessors(SI, Builder))
return SimplifyCFG(BB) | true;
if (TurnSwitchRangeIntoICmp(SI, Builder))
return SimplifyCFG(BB) | true;
if (EliminateDeadSwitchCases(SI))
return SimplifyCFG(BB) | true;
return false;
}
bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
BasicBlock *BB = IBI->getParent();
bool Changed = false;
SmallPtrSet<Value *, 8> Succs;
for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
BasicBlock *Dest = IBI->getDestination(i);
if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
Dest->removePredecessor(BB);
IBI->removeDestination(i);
--i; --e;
Changed = true;
}
}
if (IBI->getNumDestinations() == 0) {
new UnreachableInst(IBI->getContext(), IBI);
EraseTerminatorInstAndDCECond(IBI);
return true;
}
if (IBI->getNumDestinations() == 1) {
BranchInst::Create(IBI->getDestination(0), IBI);
EraseTerminatorInstAndDCECond(IBI);
return true;
}
if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
if (SimplifyIndirectBrOnSelect(IBI, SI))
return SimplifyCFG(BB) | true;
}
return Changed;
}
bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
BasicBlock *BB = BI->getParent();
BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
TryToSimplifyUncondBranchFromEmptyBlock(BB))
return true;
if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
for (++I; isa<DbgInfoIntrinsic>(I); ++I)
;
if (I->isTerminator()
&& TryToSimplifyUncondBranchWithICmpInIt(ICI, TD, Builder))
return true;
}
return false;
}
bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
BasicBlock *BB = BI->getParent();
if (isValueEqualityComparison(BI)) {
if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
return SimplifyCFG(BB) | true;
BasicBlock::iterator I = BB->begin();
while (isa<DbgInfoIntrinsic>(I))
++I;
if (&*I == BI) {
if (FoldValueComparisonIntoPredecessors(BI, Builder))
return SimplifyCFG(BB) | true;
} else if (&*I == cast<Instruction>(BI->getCondition())){
++I;
while (isa<DbgInfoIntrinsic>(I))
++I;
if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
return SimplifyCFG(BB) | true;
}
}
if (SimplifyBranchOnICmpChain(BI, TD, Builder))
return true;
if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
if (HoistThenElseCodeToIf(BI))
return SimplifyCFG(BB) | true;
} else {
TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
if (Succ0TI->getNumSuccessors() == 1 &&
Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
return SimplifyCFG(BB) | true;
}
} else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
if (Succ1TI->getNumSuccessors() == 1 &&
Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
return SimplifyCFG(BB) | true;
}
if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
if (PN->getParent() == BI->getParent())
if (FoldCondBranchOnPHI(BI, TD))
return SimplifyCFG(BB) | true;
if (FoldBranchToCommonDest(BI))
return SimplifyCFG(BB) | true;
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
if (PBI != BI && PBI->isConditional())
if (SimplifyCondBranchToCondBranch(PBI, BI))
return SimplifyCFG(BB) | true;
return false;
}
bool SimplifyCFGOpt::run(BasicBlock *BB) {
bool Changed = false;
assert(BB && BB->getParent() && "Block not embedded in function!");
assert(BB->getTerminator() && "Degenerate basic block encountered!");
if ((pred_begin(BB) == pred_end(BB) &&
BB != &BB->getParent()->getEntryBlock()) ||
BB->getSinglePredecessor() == BB) {
DEBUG(dbgs() << "Removing BB: \n" << *BB);
DeleteDeadBlock(BB);
return true;
}
Changed |= ConstantFoldTerminator(BB);
Changed |= EliminateDuplicatePHINodes(BB);
if (MergeBlockIntoPredecessor(BB))
return true;
IRBuilder<> Builder(BB);
if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
if (PN->getNumIncomingValues() == 2)
Changed |= FoldTwoEntryPHINode(PN, TD, Builder);
Builder.SetInsertPoint(BB->getTerminator());
if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
if (BI->isUnconditional()) {
if (SimplifyUncondBranch(BI, Builder)) return true;
} else {
if (SimplifyCondBranch(BI, Builder)) return true;
}
} else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
if (SimplifyReturn(RI, Builder)) return true;
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
if (SimplifySwitch(SI, Builder)) return true;
} else if (UnreachableInst *UI =
dyn_cast<UnreachableInst>(BB->getTerminator())) {
if (SimplifyUnreachable(UI)) return true;
} else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
if (SimplifyUnwind(UI, Builder)) return true;
} else if (IndirectBrInst *IBI =
dyn_cast<IndirectBrInst>(BB->getTerminator())) {
if (SimplifyIndirectBr(IBI)) return true;
}
return Changed;
}
bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
return SimplifyCFGOpt(TD).run(BB);
}