blob: 692a8af0a2ae98cc15bbcf9c1f4b15f6b9d565a4 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- SimplifyCFG.cpp - CFG Simplification Pass --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements dead code elimination and basic block merging.
Gordon Henriksen79ed5872007-11-04 16:15:04 +000011// Specifically:
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012//
Gordon Henriksen79ed5872007-11-04 16:15:04 +000013// * Removes basic blocks with no predecessors.
14// * Merges a basic block into its predecessor if there is only one and the
Dan Gohmanf17a25c2007-07-18 16:29:46 +000015// predecessor only has one successor.
Gordon Henriksen79ed5872007-11-04 16:15:04 +000016// * Eliminates PHI nodes for basic blocks with a single predecessor.
17// * Eliminates a basic block that only contains an unconditional branch.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018//
19//===----------------------------------------------------------------------===//
20
21#define DEBUG_TYPE "simplifycfg"
22#include "llvm/Transforms/Scalar.h"
23#include "llvm/Transforms/Utils/Local.h"
24#include "llvm/Constants.h"
25#include "llvm/Instructions.h"
26#include "llvm/Module.h"
Chris Lattner6d79e882007-11-14 06:19:25 +000027#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/Support/CFG.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Pass.h"
Chris Lattnereeaa8f62007-11-13 07:32:38 +000031#include "llvm/ADT/SmallVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/Statistic.h"
34using namespace llvm;
35
36STATISTIC(NumSimpl, "Number of blocks simplified");
37
38namespace {
39 struct VISIBILITY_HIDDEN CFGSimplifyPass : public FunctionPass {
40 static char ID; // Pass identification, replacement for typeid
41 CFGSimplifyPass() : FunctionPass((intptr_t)&ID) {}
42
43 virtual bool runOnFunction(Function &F);
44 };
45 char CFGSimplifyPass::ID = 0;
46 RegisterPass<CFGSimplifyPass> X("simplifycfg", "Simplify the CFG");
47}
48
49// Public interface to the CFGSimplification pass
50FunctionPass *llvm::createCFGSimplificationPass() {
51 return new CFGSimplifyPass();
52}
53
Chris Lattner6d79e882007-11-14 06:19:25 +000054/// ChangeToUnreachable - Insert an unreachable instruction before the specified
55/// instruction, making it and the rest of the code in the block dead.
56static void ChangeToUnreachable(Instruction *I) {
57 BasicBlock *BB = I->getParent();
58 // Loop over all of the successors, removing BB's entry from any PHI
59 // nodes.
60 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
61 (*SI)->removePredecessor(BB);
62
63 new UnreachableInst(I);
64
65 // All instructions after this are dead.
66 BasicBlock::iterator BBI = I, BBE = BB->end();
67 while (BBI != BBE) {
68 if (!BBI->use_empty())
69 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
70 BB->getInstList().erase(BBI++);
71 }
72}
73
Duncan Sands21010b42007-11-22 22:24:59 +000074/// ChangeToCall - Convert the specified invoke into a normal call.
75static void ChangeToCall(InvokeInst *II) {
76 BasicBlock *BB = II->getParent();
77 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
78 CallInst *NewCall = new CallInst(II->getCalledValue(), Args.begin(),
79 Args.end(), "", II);
80 NewCall->takeName(II);
81 NewCall->setCallingConv(II->getCallingConv());
82 NewCall->setParamAttrs(II->getParamAttrs());
83 II->replaceAllUsesWith(NewCall);
84
85 // Follow the call by a branch to the normal destination.
86 new BranchInst(II->getNormalDest(), II);
87
88 // Update PHI nodes in the unwind destination
89 II->getUnwindDest()->removePredecessor(BB);
90 BB->getInstList().erase(II);
91
92 if (NewCall->use_empty())
93 BB->getInstList().erase(NewCall);
94}
95
Chris Lattner6d79e882007-11-14 06:19:25 +000096/// IsNoReturn - Return true if the specified call is to a no-return function.
97static bool IsNoReturn(const CallInst *CI) {
98 if (const ParamAttrsList *Attrs = CI->getParamAttrs())
99 if (Attrs->paramHasAttr(0, ParamAttr::NoReturn))
100 return true;
101
102 if (const Function *Callee = CI->getCalledFunction()) {
103 if (const ParamAttrsList *Attrs = Callee->getParamAttrs())
104 if (Attrs->paramHasAttr(0, ParamAttr::NoReturn))
105 return true;
106
107 const FunctionType *FT = Callee->getFunctionType();
108 if (const ParamAttrsList *Attrs = FT->getParamAttrs())
109 if (Attrs->paramHasAttr(0, ParamAttr::NoReturn))
110 return true;
111 }
112 return false;
113}
114
Duncan Sands21010b42007-11-22 22:24:59 +0000115/// IsNoUnwind - Return true if the specified invoke is to a no-unwind function.
116static bool IsNoUnwind(const InvokeInst *II) {
117 if (const ParamAttrsList *Attrs = II->getParamAttrs())
118 if (Attrs->paramHasAttr(0, ParamAttr::NoUnwind))
119 return true;
120
121 if (const Function *Callee = II->getCalledFunction()) {
122 if (const ParamAttrsList *Attrs = Callee->getParamAttrs())
123 if (Attrs->paramHasAttr(0, ParamAttr::NoUnwind))
124 return true;
125
126 const FunctionType *FT = Callee->getFunctionType();
127 if (const ParamAttrsList *Attrs = FT->getParamAttrs())
128 if (Attrs->paramHasAttr(0, ParamAttr::NoUnwind))
129 return true;
130 }
131 return false;
132}
133
Chris Lattner6d79e882007-11-14 06:19:25 +0000134
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135static bool MarkAliveBlocks(BasicBlock *BB,
Chris Lattnereeaa8f62007-11-13 07:32:38 +0000136 SmallPtrSet<BasicBlock*, 128> &Reachable) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137
Chris Lattnereeaa8f62007-11-13 07:32:38 +0000138 SmallVector<BasicBlock*, 128> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139 Worklist.push_back(BB);
140 bool Changed = false;
141 while (!Worklist.empty()) {
142 BB = Worklist.back();
143 Worklist.pop_back();
144
145 if (!Reachable.insert(BB))
146 continue;
147
148 // Do a quick scan of the basic block, turning any obviously unreachable
149 // instructions into LLVM unreachable insts. The instruction combining pass
Duncan Sands21010b42007-11-22 22:24:59 +0000150 // canonicalizes unreachable insts into stores to null or undef.
Chris Lattner6d79e882007-11-14 06:19:25 +0000151 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
152 if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
153 if (IsNoReturn(CI)) {
154 // If we found a call to a no-return function, insert an unreachable
155 // instruction after it. Make sure there isn't *already* one there
156 // though.
157 ++BBI;
158 if (!isa<UnreachableInst>(BBI)) {
159 ChangeToUnreachable(BBI);
160 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 }
162 break;
163 }
Chris Lattner6d79e882007-11-14 06:19:25 +0000164 }
165
166 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
167 if (isa<ConstantPointerNull>(SI->getOperand(1)) ||
168 isa<UndefValue>(SI->getOperand(1))) {
169 ChangeToUnreachable(SI);
170 Changed = true;
171 break;
172 }
173 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174
Duncan Sands21010b42007-11-22 22:24:59 +0000175 // Turn invokes that call 'nounwind' functions into ordinary calls.
176 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
177 if (IsNoUnwind(II)) {
178 ChangeToCall(II);
179 Changed = true;
180 }
181
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 Changed |= ConstantFoldTerminator(BB);
183 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
184 Worklist.push_back(*SI);
185 }
186 return Changed;
187}
188
Chris Lattnereeaa8f62007-11-13 07:32:38 +0000189/// RemoveUnreachableBlocks - Remove blocks that are not reachable, even if they
190/// are in a dead cycle. Return true if a change was made, false otherwise.
191static bool RemoveUnreachableBlocks(Function &F) {
192 SmallPtrSet<BasicBlock*, 128> Reachable;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 bool Changed = MarkAliveBlocks(F.begin(), Reachable);
Chris Lattnereeaa8f62007-11-13 07:32:38 +0000194
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 // If there are unreachable blocks in the CFG...
Chris Lattnereeaa8f62007-11-13 07:32:38 +0000196 if (Reachable.size() == F.size())
197 return Changed;
198
199 assert(Reachable.size() < F.size());
200 NumSimpl += F.size()-Reachable.size();
201
202 // Loop over all of the basic blocks that are not reachable, dropping all of
203 // their internal references...
204 for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB)
205 if (!Reachable.count(BB)) {
206 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI!=SE; ++SI)
207 if (Reachable.count(*SI))
208 (*SI)->removePredecessor(BB);
209 BB->dropAllReferences();
210 }
211
212 for (Function::iterator I = ++F.begin(); I != F.end();)
213 if (!Reachable.count(I))
214 I = F.getBasicBlockList().erase(I);
215 else
216 ++I;
217
218 return true;
219}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220
Chris Lattnereeaa8f62007-11-13 07:32:38 +0000221/// IterativeSimplifyCFG - Call SimplifyCFG on all the blocks in the function,
222/// iterating until no more changes are made.
223static bool IterativeSimplifyCFG(Function &F) {
224 bool Changed = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 bool LocalChange = true;
226 while (LocalChange) {
227 LocalChange = false;
Chris Lattnereeaa8f62007-11-13 07:32:38 +0000228
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229 // Loop over all of the basic blocks (except the first one) and remove them
230 // if they are unneeded...
231 //
232 for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) {
233 if (SimplifyCFG(BBIt++)) {
234 LocalChange = true;
235 ++NumSimpl;
236 }
237 }
238 Changed |= LocalChange;
239 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 return Changed;
241}
Chris Lattnereeaa8f62007-11-13 07:32:38 +0000242
243// It is possible that we may require multiple passes over the code to fully
244// simplify the CFG.
245//
246bool CFGSimplifyPass::runOnFunction(Function &F) {
247 bool EverChanged = RemoveUnreachableBlocks(F);
248 EverChanged |= IterativeSimplifyCFG(F);
249
250 // If neither pass changed anything, we're done.
251 if (!EverChanged) return false;
252
253 // IterativeSimplifyCFG can (rarely) make some loops dead. If this happens,
254 // RemoveUnreachableBlocks is needed to nuke them, which means we should
255 // iterate between the two optimizations. We structure the code like this to
256 // avoid reruning IterativeSimplifyCFG if the second pass of
257 // RemoveUnreachableBlocks doesn't do anything.
258 if (!RemoveUnreachableBlocks(F))
259 return true;
260
261 do {
262 EverChanged = IterativeSimplifyCFG(F);
263 EverChanged |= RemoveUnreachableBlocks(F);
264 } while (EverChanged);
265
266 return true;
267}