blob: 8566cd9736d3fe7d986b4d576d71753b17690924 [file] [log] [blame]
Chris Lattnere15051d2008-05-14 20:38:44 +00001//===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerfa7dad82002-05-21 20:49:37 +00009//
Chris Lattner19970e62007-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 Lattnerfa7dad82002-05-21 20:49:37 +000012//
Gordon Henriksend5687672007-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 Lattnerfa7dad82002-05-21 20:49:37 +000015// predecessor only has one successor.
Gordon Henriksend5687672007-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 Lattner19970e62007-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 Lattnerfa7dad82002-05-21 20:49:37 +000021//
22//===----------------------------------------------------------------------===//
23
Chandler Carruthfdffd872015-02-01 11:34:21 +000024#include "llvm/Transforms/Scalar/SimplifyCFG.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000028#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000029#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Attributes.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000031#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/Module.h"
Chris Lattnerfa7dad82002-05-21 20:49:37 +000037#include "llvm/Pass.h"
Jingyue Wufc029672014-09-30 22:23:38 +000038#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthfdffd872015-02-01 11:34:21 +000040#include "llvm/Transforms/Scalar.h"
Chris Lattner49525f82004-01-09 06:02:20 +000041using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000042
Chandler Carruth964daaa2014-04-22 02:55:47 +000043#define DEBUG_TYPE "simplifycfg"
44
Jingyue Wufc029672014-09-30 22:23:38 +000045static cl::opt<unsigned>
46UserBonusInstThreshold("bonus-inst-threshold", cl::Hidden, cl::init(1),
47 cl::desc("Control the number of bonus instructions (default = 1)"));
48
Chris Lattner79a42ac2006-12-19 21:40:18 +000049STATISTIC(NumSimpl, "Number of blocks simplified");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000050
Jim Grosbach30c42822012-09-06 00:59:08 +000051/// mergeEmptyReturnBlocks - If we have more than one empty (other than phi
Chris Lattnerf21a2202009-12-22 06:07:30 +000052/// node) return blocks, merge them together to promote recursive block merging.
Jim Grosbach30c42822012-09-06 00:59:08 +000053static bool mergeEmptyReturnBlocks(Function &F) {
Chris Lattnerf21a2202009-12-22 06:07:30 +000054 bool Changed = false;
Nadav Rotem465834c2012-07-24 10:51:42 +000055
Craig Topperf40110f2014-04-25 05:29:35 +000056 BasicBlock *RetBlock = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +000057
Chris Lattnerf21a2202009-12-22 06:07:30 +000058 // Scan all the blocks in the function, looking for empty return blocks.
59 for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) {
60 BasicBlock &BB = *BBI++;
Nadav Rotem465834c2012-07-24 10:51:42 +000061
Chris Lattnerf21a2202009-12-22 06:07:30 +000062 // Only look at return blocks.
63 ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +000064 if (!Ret) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +000065
Chris Lattnerf21a2202009-12-22 06:07:30 +000066 // Only look at the block if it is empty or the only other thing in it is a
67 // single PHI node that is the operand to the return.
68 if (Ret != &BB.front()) {
69 // Check for something else in the block.
70 BasicBlock::iterator I = Ret;
71 --I;
Bill Wendling55e69d12010-03-14 10:40:55 +000072 // Skip over debug info.
73 while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
74 --I;
75 if (!isa<DbgInfoIntrinsic>(I) &&
76 (!isa<PHINode>(I) || I != BB.begin() ||
77 Ret->getNumOperands() == 0 ||
78 Ret->getOperand(0) != I))
Chris Lattnerf21a2202009-12-22 06:07:30 +000079 continue;
80 }
Bill Wendling55e69d12010-03-14 10:40:55 +000081
Chris Lattnerf21a2202009-12-22 06:07:30 +000082 // If this is the first returning block, remember it and keep going.
Craig Topperf40110f2014-04-25 05:29:35 +000083 if (!RetBlock) {
Chris Lattnerf21a2202009-12-22 06:07:30 +000084 RetBlock = &BB;
85 continue;
86 }
Nadav Rotem465834c2012-07-24 10:51:42 +000087
Chris Lattnerf21a2202009-12-22 06:07:30 +000088 // Otherwise, we found a duplicate return block. Merge the two.
89 Changed = true;
Nadav Rotem465834c2012-07-24 10:51:42 +000090
Chris Lattnerf21a2202009-12-22 06:07:30 +000091 // Case when there is no input to the return or when the returned values
92 // agree is trivial. Note that they can't agree if there are phis in the
93 // blocks.
94 if (Ret->getNumOperands() == 0 ||
Nadav Rotem465834c2012-07-24 10:51:42 +000095 Ret->getOperand(0) ==
Chris Lattnerf21a2202009-12-22 06:07:30 +000096 cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) {
97 BB.replaceAllUsesWith(RetBlock);
98 BB.eraseFromParent();
99 continue;
100 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000101
Chris Lattnerf21a2202009-12-22 06:07:30 +0000102 // If the canonical return block has no PHI node, create one now.
103 PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000104 if (!RetBlockPHI) {
Devang Pateld3f41e82010-03-15 19:05:46 +0000105 Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0);
Jay Foade0938d82011-03-30 11:19:20 +0000106 pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock);
Jay Foad52131342011-03-30 11:28:46 +0000107 RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(),
108 std::distance(PB, PE), "merge",
Chris Lattnerf21a2202009-12-22 06:07:30 +0000109 &RetBlock->front());
Nadav Rotem465834c2012-07-24 10:51:42 +0000110
Jay Foade0938d82011-03-30 11:19:20 +0000111 for (pred_iterator PI = PB; PI != PE; ++PI)
Chris Lattnerf21a2202009-12-22 06:07:30 +0000112 RetBlockPHI->addIncoming(InVal, *PI);
113 RetBlock->getTerminator()->setOperand(0, RetBlockPHI);
114 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000115
Chris Lattnerf21a2202009-12-22 06:07:30 +0000116 // Turn BB into a block that just unconditionally branches to the return
117 // block. This handles the case when the two return blocks have a common
118 // predecessor but that return different things.
119 RetBlockPHI->addIncoming(Ret->getOperand(0), &BB);
120 BB.getTerminator()->eraseFromParent();
121 BranchInst::Create(RetBlock, &BB);
122 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000123
Chris Lattnerf21a2202009-12-22 06:07:30 +0000124 return Changed;
125}
126
Jim Grosbach30c42822012-09-06 00:59:08 +0000127/// iterativelySimplifyCFG - Call SimplifyCFG on all the blocks in the function,
Chris Lattner61ce4df2007-11-13 07:32:38 +0000128/// iterating until no more changes are made.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000129static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000130 AssumptionCache *AC,
Jingyue Wufc029672014-09-30 22:23:38 +0000131 unsigned BonusInstThreshold) {
Chris Lattner61ce4df2007-11-13 07:32:38 +0000132 bool Changed = false;
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000133 bool LocalChange = true;
134 while (LocalChange) {
135 LocalChange = false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000136
Dan Gohman4a63fad2010-08-14 00:29:42 +0000137 // Loop over all of the basic blocks and remove them if they are unneeded...
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000138 //
Dan Gohman4a63fad2010-08-14 00:29:42 +0000139 for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000140 if (SimplifyCFG(BBIt++, TTI, BonusInstThreshold, AC)) {
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000141 LocalChange = true;
142 ++NumSimpl;
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000143 }
144 }
145 Changed |= LocalChange;
146 }
Chris Lattnerfa7dad82002-05-21 20:49:37 +0000147 return Changed;
148}
Chris Lattner61ce4df2007-11-13 07:32:38 +0000149
Chandler Carruthfdffd872015-02-01 11:34:21 +0000150static bool simplifyFunctionCFG(Function &F, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000151 AssumptionCache *AC, int BonusInstThreshold) {
Peter Collingbourne8d642de2013-08-12 22:38:43 +0000152 bool EverChanged = removeUnreachableBlocks(F);
Jim Grosbach30c42822012-09-06 00:59:08 +0000153 EverChanged |= mergeEmptyReturnBlocks(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000154 EverChanged |= iterativelySimplifyCFG(F, TTI, AC, BonusInstThreshold);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000155
Chris Lattner61ce4df2007-11-13 07:32:38 +0000156 // If neither pass changed anything, we're done.
157 if (!EverChanged) return false;
158
Jim Grosbach30c42822012-09-06 00:59:08 +0000159 // iterativelySimplifyCFG can (rarely) make some loops dead. If this happens,
Peter Collingbourne8d642de2013-08-12 22:38:43 +0000160 // removeUnreachableBlocks is needed to nuke them, which means we should
Chris Lattner61ce4df2007-11-13 07:32:38 +0000161 // iterate between the two optimizations. We structure the code like this to
Jim Grosbach30c42822012-09-06 00:59:08 +0000162 // avoid reruning iterativelySimplifyCFG if the second pass of
Peter Collingbourne8d642de2013-08-12 22:38:43 +0000163 // removeUnreachableBlocks doesn't do anything.
164 if (!removeUnreachableBlocks(F))
Chris Lattner61ce4df2007-11-13 07:32:38 +0000165 return true;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000166
Chris Lattner61ce4df2007-11-13 07:32:38 +0000167 do {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000168 EverChanged = iterativelySimplifyCFG(F, TTI, AC, BonusInstThreshold);
Peter Collingbourne8d642de2013-08-12 22:38:43 +0000169 EverChanged |= removeUnreachableBlocks(F);
Chris Lattner61ce4df2007-11-13 07:32:38 +0000170 } while (EverChanged);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000171
Chris Lattner61ce4df2007-11-13 07:32:38 +0000172 return true;
173}
Chandler Carruthfdffd872015-02-01 11:34:21 +0000174
175SimplifyCFGPass::SimplifyCFGPass()
176 : BonusInstThreshold(UserBonusInstThreshold) {}
177
178SimplifyCFGPass::SimplifyCFGPass(int BonusInstThreshold)
179 : BonusInstThreshold(BonusInstThreshold) {}
180
181PreservedAnalyses SimplifyCFGPass::run(Function &F,
182 AnalysisManager<Function> *AM) {
Chandler Carruthfdffd872015-02-01 11:34:21 +0000183 auto &TTI = AM->getResult<TargetIRAnalysis>(F);
184 auto &AC = AM->getResult<AssumptionAnalysis>(F);
185
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000186 if (!simplifyFunctionCFG(F, TTI, &AC, BonusInstThreshold))
Chandler Carruthfdffd872015-02-01 11:34:21 +0000187 return PreservedAnalyses::none();
188
189 return PreservedAnalyses::all();
190}
191
192namespace {
193struct CFGSimplifyPass : public FunctionPass {
194 static char ID; // Pass identification, replacement for typeid
195 unsigned BonusInstThreshold;
196 CFGSimplifyPass(int T = -1) : FunctionPass(ID) {
197 BonusInstThreshold = (T == -1) ? UserBonusInstThreshold : unsigned(T);
198 initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry());
199 }
200 bool runOnFunction(Function &F) override {
201 if (skipOptnoneFunction(F))
202 return false;
203
204 AssumptionCache *AC =
205 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
206 const TargetTransformInfo &TTI =
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000207 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000208 return simplifyFunctionCFG(F, TTI, AC, BonusInstThreshold);
Chandler Carruthfdffd872015-02-01 11:34:21 +0000209 }
210
211 void getAnalysisUsage(AnalysisUsage &AU) const override {
212 AU.addRequired<AssumptionCacheTracker>();
213 AU.addRequired<TargetTransformInfoWrapperPass>();
214 }
215};
216}
217
218char CFGSimplifyPass::ID = 0;
219INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
220 false)
221INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
222INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
223INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
224 false)
225
226// Public interface to the CFGSimplification pass
227FunctionPass *llvm::createCFGSimplificationPass(int Threshold) {
228 return new CFGSimplifyPass(Threshold);
229}
230