#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include <cassert>
using namespace llvm;
#define DEBUG_TYPE "flattencfg"
namespace {
class FlattenCFGOpt {
AliasAnalysis *AA;
bool FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder);
bool MergeIfRegion(BasicBlock *BB, IRBuilder<> &Builder);
bool CompareIfRegionBlock(BasicBlock *Block1, BasicBlock *Block2,
BasicBlock *Head2);
public:
FlattenCFGOpt(AliasAnalysis *AA) : AA(AA) {}
bool run(BasicBlock *BB);
};
}
bool FlattenCFGOpt::FlattenParallelAndOr(BasicBlock *BB, IRBuilder<> &Builder) {
PHINode *PHI = dyn_cast<PHINode>(BB->begin());
if (PHI)
return false;
BasicBlock *LastCondBlock = nullptr;
BasicBlock *FirstCondBlock = nullptr;
BasicBlock *UnCondBlock = nullptr;
int Idx = -1;
SmallPtrSet<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
for (SmallPtrSetIterator<BasicBlock *> PI = Preds.begin(), PE = Preds.end();
PI != PE; ++PI) {
BasicBlock *Pred = *PI;
BranchInst *PBI = dyn_cast<BranchInst>(Pred->getTerminator());
if (!PBI)
return false;
BasicBlock *PP = Pred->getSinglePredecessor();
if (PBI->isUnconditional()) {
if (UnCondBlock || !PP || !Preds.contains(PP) ||
Pred->hasAddressTaken())
return false;
UnCondBlock = Pred;
continue;
}
assert(PBI->isConditional());
Value *PC = PBI->getCondition();
if (!PC || !PC->hasOneUse())
return false;
if (PP && Preds.count(PP)) {
if (Pred->hasAddressTaken())
return false;
for (BasicBlock::iterator BI = Pred->begin(), BE = PBI->getIterator();
BI != BE;) {
Instruction *CI = &*BI++;
if (isa<PHINode>(CI) || !isSafeToSpeculativelyExecute(CI))
return false;
}
} else {
if (FirstCondBlock)
return false;
FirstCondBlock = Pred;
}
BasicBlock *PS1 = PBI->getSuccessor(0);
BasicBlock *PS2 = PBI->getSuccessor(1);
BasicBlock *PS = (PS1 == BB) ? PS2 : PS1;
int CIdx = (PS1 == BB) ? 0 : 1;
if (Idx == -1)
Idx = CIdx;
else if (CIdx != Idx)
return false;
if (!Preds.contains(PS)) {
LastCondBlock = Pred;
} else {
BranchInst *BPS = dyn_cast<BranchInst>(PS->getTerminator());
if (BPS && BPS->isUnconditional()) {
LastCondBlock = Pred;
}
}
}
if (!FirstCondBlock || !LastCondBlock || (FirstCondBlock == LastCondBlock))
return false;
Instruction *TBB = LastCondBlock->getTerminator();
BasicBlock *PS1 = TBB->getSuccessor(0);
BasicBlock *PS2 = TBB->getSuccessor(1);
BranchInst *PBI1 = dyn_cast<BranchInst>(PS1->getTerminator());
BranchInst *PBI2 = dyn_cast<BranchInst>(PS2->getTerminator());
if (!PBI1 || !PBI1->isUnconditional() ||
(PS1->getTerminator()->getSuccessor(0) != PS2)) {
if (!PBI2 || !PBI2->isUnconditional() ||
(PS2->getTerminator()->getSuccessor(0) != PS1))
return false;
BasicBlock *CurrBlock = LastCondBlock;
bool EverChanged = false;
for (; CurrBlock != FirstCondBlock;
CurrBlock = CurrBlock->getSinglePredecessor()) {
auto *BI = cast<BranchInst>(CurrBlock->getTerminator());
auto *CI = dyn_cast<CmpInst>(BI->getCondition());
if (!CI)
continue;
CmpInst::Predicate Predicate = CI->getPredicate();
if ((Predicate == CmpInst::ICMP_NE) || (Predicate == CmpInst::FCMP_ONE)) {
CI->setPredicate(ICmpInst::getInversePredicate(Predicate));
BI->swapSuccessors();
EverChanged = true;
}
}
return EverChanged;
}
if (!PBI1 || !PBI1->isUnconditional())
return false;
PHI = dyn_cast<PHINode>(PS2->begin());
if (PHI)
return false;
BasicBlock *CB;
BranchInst *PBI = cast<BranchInst>(FirstCondBlock->getTerminator());
bool Iteration = true;
IRBuilder<>::InsertPointGuard Guard(Builder);
Value *PC = PBI->getCondition();
do {
CB = PBI->getSuccessor(1 - Idx);
FirstCondBlock->getInstList().pop_back();
FirstCondBlock->getInstList()
.splice(FirstCondBlock->end(), CB->getInstList());
PBI = cast<BranchInst>(FirstCondBlock->getTerminator());
Value *CC = PBI->getCondition();
Builder.SetInsertPoint(PBI);
Value *NC;
if (Idx == 0)
NC = Builder.CreateOr(PC, CC);
else
NC = Builder.CreateAnd(PC, CC);
PBI->replaceUsesOfWith(CC, NC);
PC = NC;
if (CB == LastCondBlock)
Iteration = false;
CB->dropAllReferences();
new UnreachableInst(CB->getContext(), CB);
} while (Iteration);
LLVM_DEBUG(dbgs() << "Use parallel and/or in:\n" << *FirstCondBlock);
return true;
}
bool FlattenCFGOpt::CompareIfRegionBlock(BasicBlock *Block1, BasicBlock *Block2,
BasicBlock *Head2) {
Instruction *PTI2 = Head2->getTerminator();
Instruction *PBI2 = &Head2->front();
BasicBlock::iterator iter1 = Block1->begin();
BasicBlock::iterator end1 = Block1->getTerminator()->getIterator();
BasicBlock::iterator iter2 = Block2->begin();
BasicBlock::iterator end2 = Block2->getTerminator()->getIterator();
while (true) {
if (iter1 == end1) {
if (iter2 != end2)
return false;
break;
}
if (!iter1->isIdenticalTo(&*iter2))
return false;
if (iter1->mayHaveSideEffects()) {
Instruction *CurI = &*iter1;
StoreInst *SI = dyn_cast<StoreInst>(CurI);
if (!SI || SI->isVolatile())
return false;
}
if (iter1->mayReadFromMemory())
return false;
if (iter1->mayWriteToMemory()) {
for (BasicBlock::iterator BI(PBI2), BE(PTI2); BI != BE; ++BI) {
if (BI->mayReadFromMemory() || BI->mayWriteToMemory()) {
if (!AA || !AA->isNoAlias(&*iter1, &*BI))
return false;
}
}
}
++iter1;
++iter2;
}
return true;
}
bool FlattenCFGOpt::MergeIfRegion(BasicBlock *BB, IRBuilder<> &Builder) {
BasicBlock *IfTrue2, *IfFalse2;
BranchInst *DomBI2 = GetIfCondition(BB, IfTrue2, IfFalse2);
if (!DomBI2)
return false;
Instruction *CInst2 = dyn_cast<Instruction>(DomBI2->getCondition());
if (!CInst2)
return false;
BasicBlock *SecondEntryBlock = CInst2->getParent();
if (SecondEntryBlock->hasAddressTaken())
return false;
BasicBlock *IfTrue1, *IfFalse1;
BranchInst *DomBI1 = GetIfCondition(SecondEntryBlock, IfTrue1, IfFalse1);
if (!DomBI1)
return false;
Instruction *CInst1 = dyn_cast<Instruction>(DomBI1->getCondition());
if (!CInst1)
return false;
BasicBlock *FirstEntryBlock = CInst1->getParent();
bool InvertCond2 = false;
BinaryOperator::BinaryOps CombineOp;
if (IfFalse1 == FirstEntryBlock) {
CombineOp = BinaryOperator::Or;
if (IfFalse2 != SecondEntryBlock) {
if (IfTrue2 != SecondEntryBlock)
return false;
InvertCond2 = true;
std::swap(IfTrue2, IfFalse2);
}
if (!CompareIfRegionBlock(IfTrue1, IfTrue2, SecondEntryBlock))
return false;
} else if (IfTrue1 == FirstEntryBlock) {
CombineOp = BinaryOperator::And;
if (IfTrue2 != SecondEntryBlock) {
if (IfFalse2 != SecondEntryBlock)
return false;
InvertCond2 = true;
std::swap(IfTrue2, IfFalse2);
}
if (!CompareIfRegionBlock(IfFalse1, IfFalse2, SecondEntryBlock))
return false;
} else
return false;
Instruction *PTI2 = SecondEntryBlock->getTerminator();
Instruction *PBI2 = &SecondEntryBlock->front();
for (BasicBlock::iterator BI(PBI2), BE(PTI2); BI != BE; ++BI) {
Instruction *CI = &*BI;
if (isa<PHINode>(CI) || CI->mayHaveSideEffects() ||
!isSafeToSpeculativelyExecute(CI))
return false;
}
FirstEntryBlock->getInstList().pop_back();
FirstEntryBlock->getInstList()
.splice(FirstEntryBlock->end(), SecondEntryBlock->getInstList());
BranchInst *PBI = cast<BranchInst>(FirstEntryBlock->getTerminator());
assert(PBI->getCondition() == CInst2);
BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Builder.SetInsertPoint(PBI);
if (InvertCond2) {
auto Cmp2 = dyn_cast<CmpInst>(CInst2);
if (Cmp2 && Cmp2->hasOneUse())
Cmp2->setPredicate(Cmp2->getInversePredicate());
else
CInst2 = cast<Instruction>(Builder.CreateNot(CInst2));
PBI->swapSuccessors();
}
Value *NC = Builder.CreateBinOp(CombineOp, CInst1, CInst2);
PBI->replaceUsesOfWith(CInst2, NC);
Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
for (BasicBlock *Succ : successors(PBI)) {
for (PHINode &Phi : Succ->phis()) {
for (unsigned i = 0, e = Phi.getNumIncomingValues(); i != e; ++i) {
if (Phi.getIncomingBlock(i) == SecondEntryBlock)
Phi.setIncomingBlock(i, FirstEntryBlock);
}
}
}
if (IfTrue1 != FirstEntryBlock) {
IfTrue1->dropAllReferences();
IfTrue1->eraseFromParent();
}
if (IfFalse1 != FirstEntryBlock) {
IfFalse1->dropAllReferences();
IfFalse1->eraseFromParent();
}
SecondEntryBlock->dropAllReferences();
SecondEntryBlock->eraseFromParent();
LLVM_DEBUG(dbgs() << "If conditions merged into:\n" << *FirstEntryBlock);
return true;
}
bool FlattenCFGOpt::run(BasicBlock *BB) {
assert(BB && BB->getParent() && "Block not embedded in function!");
assert(BB->getTerminator() && "Degenerate basic block encountered!");
IRBuilder<> Builder(BB);
if (FlattenParallelAndOr(BB, Builder) || MergeIfRegion(BB, Builder))
return true;
return false;
}
bool llvm::FlattenCFG(BasicBlock *BB, AAResults *AA) {
return FlattenCFGOpt(AA).run(BB);
}