#include <algorithm>
#include <functional>
#include <set>
-
+#include <map>
using namespace llvm;
// PropagatePredecessorsForPHIs - This gets "Succ" ready to have the
return Changed;
}
+/// HoistThenElseCodeToIf - Given a conditional branch that codes to BB1 and
+/// BB2, hoist any common code in the two blocks up into the branch block. The
+/// caller of this function guarantees that BI's block dominates BB1 and BB2.
+static bool HoistThenElseCodeToIf(BranchInst *BI) {
+ // This does very trivial matching, with limited scanning, to find identical
+ // instructions in the two blocks. In particular, we don't want to get into
+ // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
+ // such, we currently just scan for obviously identical instructions in an
+ // identical order.
+ BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
+ BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
+
+ Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
+ if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2))
+ return false;
+
+ // If we get here, we can hoist at least one instruction.
+ BasicBlock *BIParent = BI->getParent();
+
+ do {
+ // If we are hoisting the terminator instruction, don't move one (making a
+ // broken BB), instead clone it, and remove BI.
+ if (isa<TerminatorInst>(I1))
+ goto HoistTerminator;
+
+ // For a normal instruction, we just move one to right before the branch,
+ // then replace all uses of the other with the first. Finally, we remove
+ // the now redundant second instruction.
+ BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
+ if (!I2->use_empty())
+ I2->replaceAllUsesWith(I1);
+ BB2->getInstList().erase(I2);
+
+ I1 = BB1->begin();
+ I2 = BB2->begin();
+ } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
+
+ return true;
+
+HoistTerminator:
+ // Okay, it is safe to hoist the terminator.
+ Instruction *NT = I1->clone();
+ BIParent->getInstList().insert(BI, NT);
+ if (NT->getType() != Type::VoidTy) {
+ I1->replaceAllUsesWith(NT);
+ I2->replaceAllUsesWith(NT);
+ NT->setName(I1->getName());
+ }
+
+ // Hoisting one of the terminators from our successor is a great thing.
+ // Unfortunately, the successors of the if/else blocks may have PHI nodes in
+ // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
+ // nodes, so we insert select instruction to compute the final result.
+ 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) {
+ // These values do not agree. Insert a select instruction before NT
+ // that determines the right value.
+ SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
+ if (SI == 0)
+ SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
+ BB1V->getName()+"."+BB2V->getName(), NT);
+ // Make the PHI node use the select for all incoming values for BB1/BB2
+ for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
+ if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
+ PN->setIncomingValue(i, SI);
+ }
+ }
+ }
+
+ // Update any PHI nodes in our new successors.
+ for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
+ AddPredecessorToBlock(*SI, BIParent, BB1);
+
+ BI->eraseFromParent();
+ return true;
+}
+
namespace {
/// ConstantIntOrdering - This class implements a stable ordering of constant
/// integers that does not depend on their address. This is important for
// to the successor.
succ_iterator SI(succ_begin(BB));
if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
-
BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
while (isa<PHINode>(*BBI)) ++BBI;
- if (BBI->isTerminator()) { // Terminator is the only non-phi instruction!
- BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
-
- if (Succ != BB) { // Arg, don't hurt infinite loops!
- // If our successor has PHI nodes, then we need to update them to
- // include entries for BB's predecessors, not for BB itself.
- // Be careful though, if this transformation fails (returns true) then
- // we cannot do this transformation!
- //
- if (!PropagatePredecessorsForPHIs(BB, Succ)) {
- DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
- std::string OldName = BB->getName();
-
+ BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor.
+ if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
+ Succ != BB) { // Don't hurt infinite loops!
+ // If our successor has PHI nodes, then we need to update them to include
+ // entries for BB's predecessors, not for BB itself. Be careful though,
+ // if this transformation fails (returns true) then we cannot do this
+ // transformation!
+ //
+ if (!PropagatePredecessorsForPHIs(BB, Succ)) {
+ DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
+
+ if (isa<PHINode>(&BB->front())) {
std::vector<BasicBlock*>
OldSuccPreds(pred_begin(Succ), pred_end(Succ));
-
+
// Move all PHI nodes in BB to Succ if they are alive, otherwise
// delete them.
while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
if (PN->use_empty())
- BB->getInstList().erase(BB->begin()); // Nuke instruction...
+ BB->getInstList().erase(BB->begin()); // Nuke instruction.
else {
// The instruction is alive, so this means that Succ must have
// *ONLY* had BB as a predecessor, and the PHI node is still valid
// strictly dominated Succ.
BB->getInstList().remove(BB->begin());
Succ->getInstList().push_front(PN);
-
+
// We need to add new entries for the PHI node to account for
// predecessors of Succ that the PHI node does not take into
// account. At this point, since we know that BB dominated succ,
if (OldSuccPreds[i] != BB)
PN->addIncoming(PN, OldSuccPreds[i]);
}
+ }
+
+ // Everything that jumped to BB now goes to Succ.
+ std::string OldName = BB->getName();
+ BB->replaceAllUsesWith(Succ);
+ BB->eraseFromParent(); // Delete the old basic block.
- // Everything that jumped to BB now goes to Succ...
- BB->replaceAllUsesWith(Succ);
-
- // Delete the old basic block...
- M->getBasicBlockList().erase(BB);
-
- if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
- Succ->setName(OldName);
- return true;
- }
+ if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
+ Succ->setName(OldName);
+ return true;
}
}
}
return SimplifyCFG(BB) | true;
}
}
+ } else if (isa<UnreachableInst>(BB->getTerminator())) {
+ // If there are any instructions immediately before the unreachable that can
+ // be removed, do so.
+ Instruction *Unreachable = BB->getTerminator();
+ while (Unreachable != BB->begin()) {
+ BasicBlock::iterator BBI = Unreachable;
+ --BBI;
+ if (isa<CallInst>(BBI)) break;
+ // Delete this instruction
+ BB->getInstList().erase(BBI);
+ Changed = true;
+ }
+
+ // If the unreachable instruction is the first in the block, take a gander
+ // at all of the predecessors of this instruction, and simplify them.
+ if (&BB->front() == Unreachable) {
+ std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
+ for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
+ TerminatorInst *TI = Preds[i]->getTerminator();
+
+ if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
+ if (BI->isUnconditional()) {
+ if (BI->getSuccessor(0) == BB) {
+ new UnreachableInst(TI);
+ TI->eraseFromParent();
+ Changed = true;
+ }
+ } else {
+ if (BI->getSuccessor(0) == BB) {
+ new BranchInst(BI->getSuccessor(1), BI);
+ BI->eraseFromParent();
+ } else if (BI->getSuccessor(1) == BB) {
+ new BranchInst(BI->getSuccessor(0), BI);
+ BI->eraseFromParent();
+ 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) {
+ SI->removeCase(i);
+ --i; --e;
+ Changed = true;
+ }
+ // If the default value is unreachable, figure out the most popular
+ // destination and make it the default.
+ if (SI->getSuccessor(0) == BB) {
+ std::map<BasicBlock*, unsigned> Popularity;
+ for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
+ Popularity[SI->getSuccessor(i)]++;
+
+ // Find the most popular block.
+ unsigned MaxPop = 0;
+ BasicBlock *MaxBlock = 0;
+ for (std::map<BasicBlock*, unsigned>::iterator
+ I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
+ if (I->second > MaxPop) {
+ MaxPop = I->second;
+ MaxBlock = I->first;
+ }
+ }
+ if (MaxBlock) {
+ // Make this the new default, allowing us to delete any explicit
+ // edges to it.
+ SI->setSuccessor(0, MaxBlock);
+ Changed = true;
+
+ 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) {
+ // Convert the invoke to a call instruction. This would be a good
+ // place to note that the call does not throw though.
+ BranchInst *BI = new BranchInst(II->getNormalDest(), II);
+ II->removeFromParent(); // Take out of symbol table
+
+ // Insert the call now...
+ std::vector<Value*> Args(II->op_begin()+3, II->op_end());
+ CallInst *CI = new CallInst(II->getCalledValue(), Args,
+ II->getName(), BI);
+ // If the invoke produced a value, the Call does now instead.
+ II->replaceAllUsesWith(CI);
+ delete II;
+ Changed = true;
+ }
+ }
+ }
+
+ // If this block is now dead, remove it.
+ if (pred_begin(BB) == pred_end(BB)) {
+ // We know there are no successors, so just nuke the block.
+ M->getBasicBlockList().erase(BB);
+ return true;
+ }
+ }
}
// Merge basic blocks into their predecessor if there is only one distinct
return true;
}
+ // Otherwise, if this block only has a single predecessor, and if that block
+ // is a conditional branch, see if we can hoist any code from this block up
+ // into our predecessor.
+ if (OnlyPred)
+ if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator())) {
+ // This is guaranteed to be a condbr at this point.
+ assert(BI->isConditional() && "Should have folded bb into pred!");
+ // Get the other block.
+ BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
+ PI = pred_begin(OtherBB);
+ ++PI;
+ if (PI == pred_end(OtherBB)) {
+ // We have a conditional branch to two blocks that are only reachable
+ // from the condbr. We know that the condbr dominates the two blocks,
+ // so see if there is any identical code in the "then" and "else"
+ // blocks. If so, we can hoist it up to the branching block.
+ Changed |= HoistThenElseCodeToIf(BI);
+ }
+ }
+
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
// Change br (X == 0 | X == 1), T, F into a switch instruction.
// instructions in the predecessor blocks can be promoted as well. If
// not, we won't be able to get rid of the control flow, so it's not
// worth promoting to select instructions.
- BasicBlock *DomBlock, *IfBlock1 = 0, *IfBlock2 = 0;
+ BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
if (CanPromote) {
PN = cast<PHINode>(BB->begin());
BasicBlock *Pred = PN->getIncomingBlock(0);