blob: 6d05640216ac82424ffa6ff632d518fc35f1a9f7 [file] [log] [blame]
Chris Lattner4186ad52008-05-14 20:38:44 +00001//===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner573527b2002-05-21 20:49:37 +00009//
Chris Lattner4cf4b692007-12-03 19:43:18 +000010// This file implements dead code elimination and basic block merging, along
11// with a collection of other peephole control flow optimizations. For example:
Chris Lattner573527b2002-05-21 20:49:37 +000012//
Gordon Henriksenc86b6772007-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
Chris Lattner573527b2002-05-21 20:49:37 +000015// predecessor only has one successor.
Gordon Henriksenc86b6772007-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.
Chris Lattner4cf4b692007-12-03 19:43:18 +000018// * Changes invoke instructions to nounwind functions to be calls.
19// * Change things like "if (x) if (y)" into "if (x&y)".
20// * etc..
Chris Lattner573527b2002-05-21 20:49:37 +000021//
22//===----------------------------------------------------------------------===//
23
Chris Lattner0e5f4992006-12-19 21:40:18 +000024#define DEBUG_TYPE "simplifycfg"
Chris Lattner573527b2002-05-21 20:49:37 +000025#include "llvm/Transforms/Scalar.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000026#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/Statistic.h"
Chandler Carruthbe049292013-01-07 03:08:10 +000029#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/Attributes.h"
31#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/Module.h"
Chris Lattner573527b2002-05-21 20:49:37 +000036#include "llvm/Pass.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000037#include "llvm/Support/CFG.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000038#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerd7456022004-01-09 06:02:20 +000039using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000040
Chris Lattner0e5f4992006-12-19 21:40:18 +000041STATISTIC(NumSimpl, "Number of blocks simplified");
Chris Lattnera92f6962002-10-01 22:38:41 +000042
Chris Lattner0e5f4992006-12-19 21:40:18 +000043namespace {
Tom Stellard57e6b2d2013-07-27 00:01:07 +000044struct CFGSimplifyPass : public FunctionPass {
Tom Stellard01d72032013-08-06 02:43:45 +000045 static char ID; // Pass identification, replacement for typeid
46 CFGSimplifyPass() : FunctionPass(ID) {
47 initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry());
48 }
Tom Stellard57e6b2d2013-07-27 00:01:07 +000049 virtual bool runOnFunction(Function &F);
Devang Patel794fd752007-05-01 21:15:47 +000050
Tom Stellard57e6b2d2013-07-27 00:01:07 +000051 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52 AU.addRequired<TargetTransformInfo>();
53 }
Tom Stellard57e6b2d2013-07-27 00:01:07 +000054};
Chris Lattner573527b2002-05-21 20:49:37 +000055}
56
Tom Stellard01d72032013-08-06 02:43:45 +000057char CFGSimplifyPass::ID = 0;
58INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
Tom Stellard57e6b2d2013-07-27 00:01:07 +000059 false)
Chandler Carruth5f46c3c2013-01-07 03:53:25 +000060INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
Tom Stellard01d72032013-08-06 02:43:45 +000061INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
Tom Stellard57e6b2d2013-07-27 00:01:07 +000062 false)
Dan Gohman844731a2008-05-13 00:00:25 +000063
Brian Gaeked0fde302003-11-11 22:41:34 +000064// Public interface to the CFGSimplification pass
Tom Stellard01d72032013-08-06 02:43:45 +000065FunctionPass *llvm::createCFGSimplificationPass() {
66 return new CFGSimplifyPass();
Chris Lattner573527b2002-05-21 20:49:37 +000067}
68
Arnold Schwaighofer5cf14912013-08-10 20:16:06 +000069/// changeToUnreachable - Insert an unreachable instruction before the specified
70/// instruction, making it and the rest of the code in the block dead.
71static void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
72 BasicBlock *BB = I->getParent();
73 // Loop over all of the successors, removing BB's entry from any PHI
74 // nodes.
75 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
76 (*SI)->removePredecessor(BB);
77
78 // Insert a call to llvm.trap right before this. This turns the undefined
79 // behavior into a hard fail instead of falling through into random code.
80 if (UseLLVMTrap) {
81 Function *TrapFn =
82 Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
83 CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
84 CallTrap->setDebugLoc(I->getDebugLoc());
85 }
86 new UnreachableInst(I->getContext(), I);
87
88 // All instructions after this are dead.
89 BasicBlock::iterator BBI = I, BBE = BB->end();
90 while (BBI != BBE) {
91 if (!BBI->use_empty())
92 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
93 BB->getInstList().erase(BBI++);
94 }
95}
96
97/// changeToCall - Convert the specified invoke into a normal call.
98static void changeToCall(InvokeInst *II) {
99 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
100 CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
101 NewCall->takeName(II);
102 NewCall->setCallingConv(II->getCallingConv());
103 NewCall->setAttributes(II->getAttributes());
104 NewCall->setDebugLoc(II->getDebugLoc());
105 II->replaceAllUsesWith(NewCall);
106
107 // Follow the call by a branch to the normal destination.
108 BranchInst::Create(II->getNormalDest(), II);
109
110 // Update PHI nodes in the unwind destination
111 II->getUnwindDest()->removePredecessor(II->getParent());
112 II->eraseFromParent();
113}
114
115static bool markAliveBlocks(BasicBlock *BB,
116 SmallPtrSet<BasicBlock*, 128> &Reachable) {
117
118 SmallVector<BasicBlock*, 128> Worklist;
119 Worklist.push_back(BB);
120 Reachable.insert(BB);
121 bool Changed = false;
122 do {
123 BB = Worklist.pop_back_val();
124
125 // Do a quick scan of the basic block, turning any obviously unreachable
126 // instructions into LLVM unreachable insts. The instruction combining pass
127 // canonicalizes unreachable insts into stores to null or undef.
128 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
129 if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
130 if (CI->doesNotReturn()) {
131 // If we found a call to a no-return function, insert an unreachable
132 // instruction after it. Make sure there isn't *already* one there
133 // though.
134 ++BBI;
135 if (!isa<UnreachableInst>(BBI)) {
136 // Don't insert a call to llvm.trap right before the unreachable.
137 changeToUnreachable(BBI, false);
138 Changed = true;
139 }
140 break;
141 }
142 }
143
144 // Store to undef and store to null are undefined and used to signal that
145 // they should be changed to unreachable by passes that can't modify the
146 // CFG.
147 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
148 // Don't touch volatile stores.
149 if (SI->isVolatile()) continue;
150
151 Value *Ptr = SI->getOperand(1);
152
153 if (isa<UndefValue>(Ptr) ||
154 (isa<ConstantPointerNull>(Ptr) &&
155 SI->getPointerAddressSpace() == 0)) {
156 changeToUnreachable(SI, true);
157 Changed = true;
158 break;
159 }
160 }
161 }
162
163 // Turn invokes that call 'nounwind' functions into ordinary calls.
164 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
165 Value *Callee = II->getCalledValue();
166 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
167 changeToUnreachable(II, true);
168 Changed = true;
169 } else if (II->doesNotThrow()) {
170 if (II->use_empty() && II->onlyReadsMemory()) {
171 // jump to the normal destination branch.
172 BranchInst::Create(II->getNormalDest(), II);
173 II->getUnwindDest()->removePredecessor(II->getParent());
174 II->eraseFromParent();
175 } else
176 changeToCall(II);
177 Changed = true;
178 }
179 }
180
181 Changed |= ConstantFoldTerminator(BB, true);
182 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
183 if (Reachable.insert(*SI))
184 Worklist.push_back(*SI);
185 } while (!Worklist.empty());
186 return Changed;
187}
188
189/// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
190/// if they are in a dead cycle. Return true if a change was made, false
191/// otherwise.
192static bool removeUnreachableBlocksFromFn(Function &F) {
193 SmallPtrSet<BasicBlock*, 128> Reachable;
194 bool Changed = markAliveBlocks(F.begin(), Reachable);
195
196 // If there are unreachable blocks in the CFG...
197 if (Reachable.size() == F.size())
198 return Changed;
199
200 assert(Reachable.size() < F.size());
201 NumSimpl += F.size()-Reachable.size();
202
203 // Loop over all of the basic blocks that are not reachable, dropping all of
204 // their internal references...
205 for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
206 if (Reachable.count(BB))
207 continue;
208
209 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
210 if (Reachable.count(*SI))
211 (*SI)->removePredecessor(BB);
212 BB->dropAllReferences();
213 }
214
215 for (Function::iterator I = ++F.begin(); I != F.end();)
216 if (!Reachable.count(I))
217 I = F.getBasicBlockList().erase(I);
218 else
219 ++I;
220
221 return true;
222}
223
Jim Grosbach557a20a2012-09-06 00:59:08 +0000224/// mergeEmptyReturnBlocks - If we have more than one empty (other than phi
Chris Lattner1a0e7082009-12-22 06:07:30 +0000225/// node) return blocks, merge them together to promote recursive block merging.
Jim Grosbach557a20a2012-09-06 00:59:08 +0000226static bool mergeEmptyReturnBlocks(Function &F) {
Chris Lattner1a0e7082009-12-22 06:07:30 +0000227 bool Changed = false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000228
Chris Lattner1a0e7082009-12-22 06:07:30 +0000229 BasicBlock *RetBlock = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000230
Chris Lattner1a0e7082009-12-22 06:07:30 +0000231 // Scan all the blocks in the function, looking for empty return blocks.
232 for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) {
233 BasicBlock &BB = *BBI++;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000234
Chris Lattner1a0e7082009-12-22 06:07:30 +0000235 // Only look at return blocks.
236 ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
237 if (Ret == 0) continue;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000238
Chris Lattner1a0e7082009-12-22 06:07:30 +0000239 // Only look at the block if it is empty or the only other thing in it is a
240 // single PHI node that is the operand to the return.
241 if (Ret != &BB.front()) {
242 // Check for something else in the block.
243 BasicBlock::iterator I = Ret;
244 --I;
Bill Wendlingead138b2010-03-14 10:40:55 +0000245 // Skip over debug info.
246 while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
247 --I;
248 if (!isa<DbgInfoIntrinsic>(I) &&
249 (!isa<PHINode>(I) || I != BB.begin() ||
250 Ret->getNumOperands() == 0 ||
251 Ret->getOperand(0) != I))
Chris Lattner1a0e7082009-12-22 06:07:30 +0000252 continue;
253 }
Bill Wendlingead138b2010-03-14 10:40:55 +0000254
Chris Lattner1a0e7082009-12-22 06:07:30 +0000255 // If this is the first returning block, remember it and keep going.
256 if (RetBlock == 0) {
257 RetBlock = &BB;
258 continue;
259 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000260
Chris Lattner1a0e7082009-12-22 06:07:30 +0000261 // Otherwise, we found a duplicate return block. Merge the two.
262 Changed = true;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000263
Chris Lattner1a0e7082009-12-22 06:07:30 +0000264 // Case when there is no input to the return or when the returned values
265 // agree is trivial. Note that they can't agree if there are phis in the
266 // blocks.
267 if (Ret->getNumOperands() == 0 ||
Nadav Rotema94d6e82012-07-24 10:51:42 +0000268 Ret->getOperand(0) ==
Chris Lattner1a0e7082009-12-22 06:07:30 +0000269 cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) {
270 BB.replaceAllUsesWith(RetBlock);
271 BB.eraseFromParent();
272 continue;
273 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000274
Chris Lattner1a0e7082009-12-22 06:07:30 +0000275 // If the canonical return block has no PHI node, create one now.
276 PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin());
277 if (RetBlockPHI == 0) {
Devang Patelca704952010-03-15 19:05:46 +0000278 Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0);
Jay Foadd8b4fb42011-03-30 11:19:20 +0000279 pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock);
Jay Foad3ecfc862011-03-30 11:28:46 +0000280 RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(),
281 std::distance(PB, PE), "merge",
Chris Lattner1a0e7082009-12-22 06:07:30 +0000282 &RetBlock->front());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000283
Jay Foadd8b4fb42011-03-30 11:19:20 +0000284 for (pred_iterator PI = PB; PI != PE; ++PI)
Chris Lattner1a0e7082009-12-22 06:07:30 +0000285 RetBlockPHI->addIncoming(InVal, *PI);
286 RetBlock->getTerminator()->setOperand(0, RetBlockPHI);
287 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000288
Chris Lattner1a0e7082009-12-22 06:07:30 +0000289 // Turn BB into a block that just unconditionally branches to the return
290 // block. This handles the case when the two return blocks have a common
291 // predecessor but that return different things.
292 RetBlockPHI->addIncoming(Ret->getOperand(0), &BB);
293 BB.getTerminator()->eraseFromParent();
294 BranchInst::Create(RetBlock, &BB);
295 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000296
Chris Lattner1a0e7082009-12-22 06:07:30 +0000297 return Changed;
298}
299
Jim Grosbach557a20a2012-09-06 00:59:08 +0000300/// iterativelySimplifyCFG - Call SimplifyCFG on all the blocks in the function,
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000301/// iterating until no more changes are made.
Chandler Carruth5f46c3c2013-01-07 03:53:25 +0000302static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI,
Tom Stellard01d72032013-08-06 02:43:45 +0000303 const DataLayout *TD) {
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000304 bool Changed = false;
Chris Lattner573527b2002-05-21 20:49:37 +0000305 bool LocalChange = true;
306 while (LocalChange) {
307 LocalChange = false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000308
Dan Gohmane2c6d132010-08-14 00:29:42 +0000309 // Loop over all of the basic blocks and remove them if they are unneeded...
Chris Lattner573527b2002-05-21 20:49:37 +0000310 //
Dan Gohmane2c6d132010-08-14 00:29:42 +0000311 for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
Tom Stellard01d72032013-08-06 02:43:45 +0000312 if (SimplifyCFG(BBIt++, TTI, TD)) {
Chris Lattner573527b2002-05-21 20:49:37 +0000313 LocalChange = true;
314 ++NumSimpl;
Chris Lattner573527b2002-05-21 20:49:37 +0000315 }
316 }
317 Changed |= LocalChange;
318 }
Chris Lattner573527b2002-05-21 20:49:37 +0000319 return Changed;
320}
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000321
322// It is possible that we may require multiple passes over the code to fully
323// simplify the CFG.
324//
325bool CFGSimplifyPass::runOnFunction(Function &F) {
Chandler Carruth5f46c3c2013-01-07 03:53:25 +0000326 const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
Micah Villmow3574eca2012-10-08 16:38:25 +0000327 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
Arnold Schwaighofer5cf14912013-08-10 20:16:06 +0000328 bool EverChanged = removeUnreachableBlocksFromFn(F);
Jim Grosbach557a20a2012-09-06 00:59:08 +0000329 EverChanged |= mergeEmptyReturnBlocks(F);
Tom Stellard01d72032013-08-06 02:43:45 +0000330 EverChanged |= iterativelySimplifyCFG(F, TTI, TD);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000331
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000332 // If neither pass changed anything, we're done.
333 if (!EverChanged) return false;
334
Jim Grosbach557a20a2012-09-06 00:59:08 +0000335 // iterativelySimplifyCFG can (rarely) make some loops dead. If this happens,
Arnold Schwaighofer5cf14912013-08-10 20:16:06 +0000336 // removeUnreachableBlocksFromFn is needed to nuke them, which means we should
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000337 // iterate between the two optimizations. We structure the code like this to
Jim Grosbach557a20a2012-09-06 00:59:08 +0000338 // avoid reruning iterativelySimplifyCFG if the second pass of
Arnold Schwaighofer5cf14912013-08-10 20:16:06 +0000339 // removeUnreachableBlocksFromFn doesn't do anything.
340 if (!removeUnreachableBlocksFromFn(F))
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000341 return true;
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000342
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000343 do {
Tom Stellard01d72032013-08-06 02:43:45 +0000344 EverChanged = iterativelySimplifyCFG(F, TTI, TD);
Arnold Schwaighofer5cf14912013-08-10 20:16:06 +0000345 EverChanged |= removeUnreachableBlocksFromFn(F);
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000346 } while (EverChanged);
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000347
Chris Lattnerb42c8f72007-11-13 07:32:38 +0000348 return true;
349}