1 //===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements dead code elimination and basic block merging, along 11 // with a collection of other peephole control flow optimizations. For example: 12 // 13 // * Removes basic blocks with no predecessors. 14 // * Merges a basic block into its predecessor if there is only one and the 15 // predecessor only has one successor. 16 // * Eliminates PHI nodes for basic blocks with a single predecessor. 17 // * Eliminates a basic block that only contains an unconditional branch. 18 // * Changes invoke instructions to nounwind functions to be calls. 19 // * Change things like "if (x) if (y)" into "if (x&y)". 20 // * etc.. 21 // 22 //===----------------------------------------------------------------------===// 23 24 #include "llvm/Transforms/Scalar.h" 25 #include "llvm/ADT/SmallPtrSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/Analysis/AssumptionTracker.h" 29 #include "llvm/Analysis/TargetTransformInfo.h" 30 #include "llvm/IR/Attributes.h" 31 #include "llvm/IR/CFG.h" 32 #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" 37 #include "llvm/Pass.h" 38 #include "llvm/Support/CommandLine.h" 39 #include "llvm/Transforms/Utils/Local.h" 40 using namespace llvm; 41 42 #define DEBUG_TYPE "simplifycfg" 43 44 static cl::opt<unsigned> 45 UserBonusInstThreshold("bonus-inst-threshold", cl::Hidden, cl::init(1), 46 cl::desc("Control the number of bonus instructions (default = 1)")); 47 48 STATISTIC(NumSimpl, "Number of blocks simplified"); 49 50 namespace { 51 struct CFGSimplifyPass : public FunctionPass { 52 static char ID; // Pass identification, replacement for typeid 53 unsigned BonusInstThreshold; 54 CFGSimplifyPass(int T = -1) : FunctionPass(ID) { 55 BonusInstThreshold = (T == -1) ? UserBonusInstThreshold : unsigned(T); 56 initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry()); 57 } 58 bool runOnFunction(Function &F) override; 59 60 void getAnalysisUsage(AnalysisUsage &AU) const override { 61 AU.addRequired<AssumptionTracker>(); 62 AU.addRequired<TargetTransformInfo>(); 63 } 64 }; 65 } 66 67 char CFGSimplifyPass::ID = 0; 68 INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false, 69 false) 70 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 71 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker) 72 INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false, 73 false) 74 75 // Public interface to the CFGSimplification pass 76 FunctionPass *llvm::createCFGSimplificationPass(int Threshold) { 77 return new CFGSimplifyPass(Threshold); 78 } 79 80 /// mergeEmptyReturnBlocks - If we have more than one empty (other than phi 81 /// node) return blocks, merge them together to promote recursive block merging. 82 static bool mergeEmptyReturnBlocks(Function &F) { 83 bool Changed = false; 84 85 BasicBlock *RetBlock = nullptr; 86 87 // Scan all the blocks in the function, looking for empty return blocks. 88 for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) { 89 BasicBlock &BB = *BBI++; 90 91 // Only look at return blocks. 92 ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()); 93 if (!Ret) continue; 94 95 // Only look at the block if it is empty or the only other thing in it is a 96 // single PHI node that is the operand to the return. 97 if (Ret != &BB.front()) { 98 // Check for something else in the block. 99 BasicBlock::iterator I = Ret; 100 --I; 101 // Skip over debug info. 102 while (isa<DbgInfoIntrinsic>(I) && I != BB.begin()) 103 --I; 104 if (!isa<DbgInfoIntrinsic>(I) && 105 (!isa<PHINode>(I) || I != BB.begin() || 106 Ret->getNumOperands() == 0 || 107 Ret->getOperand(0) != I)) 108 continue; 109 } 110 111 // If this is the first returning block, remember it and keep going. 112 if (!RetBlock) { 113 RetBlock = &BB; 114 continue; 115 } 116 117 // Otherwise, we found a duplicate return block. Merge the two. 118 Changed = true; 119 120 // Case when there is no input to the return or when the returned values 121 // agree is trivial. Note that they can't agree if there are phis in the 122 // blocks. 123 if (Ret->getNumOperands() == 0 || 124 Ret->getOperand(0) == 125 cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) { 126 BB.replaceAllUsesWith(RetBlock); 127 BB.eraseFromParent(); 128 continue; 129 } 130 131 // If the canonical return block has no PHI node, create one now. 132 PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin()); 133 if (!RetBlockPHI) { 134 Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0); 135 pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock); 136 RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(), 137 std::distance(PB, PE), "merge", 138 &RetBlock->front()); 139 140 for (pred_iterator PI = PB; PI != PE; ++PI) 141 RetBlockPHI->addIncoming(InVal, *PI); 142 RetBlock->getTerminator()->setOperand(0, RetBlockPHI); 143 } 144 145 // Turn BB into a block that just unconditionally branches to the return 146 // block. This handles the case when the two return blocks have a common 147 // predecessor but that return different things. 148 RetBlockPHI->addIncoming(Ret->getOperand(0), &BB); 149 BB.getTerminator()->eraseFromParent(); 150 BranchInst::Create(RetBlock, &BB); 151 } 152 153 return Changed; 154 } 155 156 /// iterativelySimplifyCFG - Call SimplifyCFG on all the blocks in the function, 157 /// iterating until no more changes are made. 158 static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI, 159 const DataLayout *DL, 160 AssumptionTracker *AT, 161 unsigned BonusInstThreshold) { 162 bool Changed = false; 163 bool LocalChange = true; 164 while (LocalChange) { 165 LocalChange = false; 166 167 // Loop over all of the basic blocks and remove them if they are unneeded... 168 // 169 for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) { 170 if (SimplifyCFG(BBIt++, TTI, BonusInstThreshold, DL, AT)) { 171 LocalChange = true; 172 ++NumSimpl; 173 } 174 } 175 Changed |= LocalChange; 176 } 177 return Changed; 178 } 179 180 // It is possible that we may require multiple passes over the code to fully 181 // simplify the CFG. 182 // 183 bool CFGSimplifyPass::runOnFunction(Function &F) { 184 if (skipOptnoneFunction(F)) 185 return false; 186 187 AssumptionTracker *AT = &getAnalysis<AssumptionTracker>(); 188 const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>(); 189 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); 190 const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr; 191 bool EverChanged = removeUnreachableBlocks(F); 192 EverChanged |= mergeEmptyReturnBlocks(F); 193 EverChanged |= iterativelySimplifyCFG(F, TTI, DL, AT, BonusInstThreshold); 194 195 // If neither pass changed anything, we're done. 196 if (!EverChanged) return false; 197 198 // iterativelySimplifyCFG can (rarely) make some loops dead. If this happens, 199 // removeUnreachableBlocks is needed to nuke them, which means we should 200 // iterate between the two optimizations. We structure the code like this to 201 // avoid reruning iterativelySimplifyCFG if the second pass of 202 // removeUnreachableBlocks doesn't do anything. 203 if (!removeUnreachableBlocks(F)) 204 return true; 205 206 do { 207 EverChanged = iterativelySimplifyCFG(F, TTI, DL, AT, BonusInstThreshold); 208 EverChanged |= removeUnreachableBlocks(F); 209 } while (EverChanged); 210 211 return true; 212 } 213