1 //===- SimplifyCFG.cpp - CFG Simplification Routines -------------*- C++ -*--=//
3 // This file provides several routines that are useful for simplifying CFGs in
6 //===----------------------------------------------------------------------===//
8 #include "llvm/Analysis/SimplifyCFG.h"
9 #include "llvm/Transforms/UnifyMethodExitNodes.h"
10 #include "llvm/BasicBlock.h"
11 #include "llvm/Method.h"
12 #include "llvm/iTerminators.h"
13 #include "llvm/iPHINode.h"
14 #include "llvm/Type.h"
17 AnalysisID UnifyMethodExitNodes::ID(AnalysisID::create<UnifyMethodExitNodes>());
20 // UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new
21 // BasicBlock, and converting all returns to unconditional branches to this
22 // new basic block. The singular exit node is returned.
24 // If there are no return stmts in the Method, a null pointer is returned.
26 BasicBlock *cfg::UnifyAllExitNodes(Method *M) {
27 vector<BasicBlock*> ReturningBlocks;
29 // Loop over all of the blocks in a method, tracking all of the blocks that
32 for(Method::iterator I = M->begin(), E = M->end(); I != E; ++I)
33 if ((*I)->getTerminator()->getOpcode() == Instruction::Ret)
34 ReturningBlocks.push_back(*I);
36 if (ReturningBlocks.size() == 0)
37 return 0; // No blocks return
38 else if (ReturningBlocks.size() == 1)
39 return ReturningBlocks.front(); // Already has a single return block
41 // Otherwise, we need to insert a new basic block into the method, add a PHI
42 // node (if the function returns a value), and convert all of the return
43 // instructions into unconditional branches.
45 BasicBlock *NewRetBlock = new BasicBlock("", M);
47 if (M->getReturnType() != Type::VoidTy) {
48 // If the method doesn't return void... add a PHI node to the block...
49 PHINode *PN = new PHINode(M->getReturnType());
50 NewRetBlock->getInstList().push_back(PN);
52 // Add an incoming element to the PHI node for every return instruction that
53 // is merging into this new block...
54 for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(),
55 E = ReturningBlocks.end(); I != E; ++I)
56 PN->addIncoming((*I)->getTerminator()->getOperand(0), *I);
58 // Add a return instruction to return the result of the PHI node...
59 NewRetBlock->getInstList().push_back(new ReturnInst(PN));
61 // If it returns void, just add a return void instruction to the block
62 NewRetBlock->getInstList().push_back(new ReturnInst());
65 // Loop over all of the blocks, replacing the return instruction with an
66 // unconditional branch.
68 for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(),
69 E = ReturningBlocks.end(); I != E; ++I) {
70 delete (*I)->getInstList().pop_back(); // Remove the return insn
71 (*I)->getInstList().push_back(new BranchInst(NewRetBlock));