1 //===- UnifyFunctionExitNodes.cpp - Make all functions have a single exit -===//
3 // This file provides several routines that are useful for simplifying CFGs in
6 //===----------------------------------------------------------------------===//
8 #include "llvm/Transforms/UnifyFunctionExitNodes.h"
9 #include "llvm/BasicBlock.h"
10 #include "llvm/Function.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/Type.h"
16 AnalysisID UnifyFunctionExitNodes::ID(AnalysisID::create<UnifyFunctionExitNodes>());
19 // UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new
20 // BasicBlock, and converting all returns to unconditional branches to this
21 // new basic block. The singular exit node is returned.
23 // If there are no return stmts in the Function, a null pointer is returned.
25 bool UnifyFunctionExitNodes::doit(Function *M, BasicBlock *&ExitNode) {
26 // Loop over all of the blocks in a function, tracking all of the blocks that
29 vector<BasicBlock*> ReturningBlocks;
30 for(Function::iterator I = M->begin(), E = M->end(); I != E; ++I)
31 if (isa<ReturnInst>((*I)->getTerminator()))
32 ReturningBlocks.push_back(*I);
34 if (ReturningBlocks.empty()) {
36 return false; // No blocks return
37 } else if (ReturningBlocks.size() == 1) {
38 ExitNode = ReturningBlocks.front(); // Already has a single return block
42 // Otherwise, we need to insert a new basic block into the function, add a PHI
43 // node (if the function returns a value), and convert all of the return
44 // instructions into unconditional branches.
46 BasicBlock *NewRetBlock = new BasicBlock("UnifiedExitNode", M);
48 if (M->getReturnType() != Type::VoidTy) {
49 // If the function doesn't return void... add a PHI node to the block...
50 PHINode *PN = new PHINode(M->getReturnType());
51 NewRetBlock->getInstList().push_back(PN);
53 // Add an incoming element to the PHI node for every return instruction that
54 // is merging into this new block...
55 for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(),
56 E = ReturningBlocks.end(); I != E; ++I)
57 PN->addIncoming((*I)->getTerminator()->getOperand(0), *I);
59 // Add a return instruction to return the result of the PHI node...
60 NewRetBlock->getInstList().push_back(new ReturnInst(PN));
62 // If it returns void, just add a return void instruction to the block
63 NewRetBlock->getInstList().push_back(new ReturnInst());
66 // Loop over all of the blocks, replacing the return instruction with an
67 // unconditional branch.
69 for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(),
70 E = ReturningBlocks.end(); I != E; ++I) {
71 delete (*I)->getInstList().pop_back(); // Remove the return insn
72 (*I)->getInstList().push_back(new BranchInst(NewRetBlock));
74 ExitNode = NewRetBlock;