1 //===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements dead code elimination and basic block merging, along 10 // with a collection of other peephole control flow optimizations. For example: 11 // 12 // * Removes basic blocks with no predecessors. 13 // * Merges a basic block into its predecessor if there is only one and the 14 // predecessor only has one successor. 15 // * Eliminates PHI nodes for basic blocks with a single predecessor. 16 // * Eliminates a basic block that only contains an unconditional branch. 17 // * Changes invoke instructions to nounwind functions to be calls. 18 // * Change things like "if (x) if (y)" into "if (x&y)". 19 // * etc.. 20 // 21 //===----------------------------------------------------------------------===// 22 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/Analysis/AssumptionCache.h" 27 #include "llvm/Analysis/CFG.h" 28 #include "llvm/Analysis/GlobalsModRef.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/InitializePasses.h" 38 #include "llvm/Pass.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Transforms/Scalar.h" 41 #include "llvm/Transforms/Scalar/SimplifyCFG.h" 42 #include "llvm/Transforms/Utils/Local.h" 43 #include "llvm/Transforms/Utils/SimplifyCFGOptions.h" 44 #include <utility> 45 using namespace llvm; 46 47 #define DEBUG_TYPE "simplifycfg" 48 49 static cl::opt<unsigned> UserBonusInstThreshold( 50 "bonus-inst-threshold", cl::Hidden, cl::init(1), 51 cl::desc("Control the number of bonus instructions (default = 1)")); 52 53 static cl::opt<bool> UserKeepLoops( 54 "keep-loops", cl::Hidden, cl::init(true), 55 cl::desc("Preserve canonical loop structure (default = true)")); 56 57 static cl::opt<bool> UserSwitchToLookup( 58 "switch-to-lookup", cl::Hidden, cl::init(false), 59 cl::desc("Convert switches to lookup tables (default = false)")); 60 61 static cl::opt<bool> UserForwardSwitchCond( 62 "forward-switch-cond", cl::Hidden, cl::init(false), 63 cl::desc("Forward switch condition to phi ops (default = false)")); 64 65 static cl::opt<bool> UserSinkCommonInsts( 66 "sink-common-insts", cl::Hidden, cl::init(false), 67 cl::desc("Sink common instructions (default = false)")); 68 69 70 STATISTIC(NumSimpl, "Number of blocks simplified"); 71 72 /// If we have more than one empty (other than phi node) return blocks, 73 /// merge them together to promote recursive block merging. 74 static bool mergeEmptyReturnBlocks(Function &F) { 75 bool Changed = false; 76 77 BasicBlock *RetBlock = nullptr; 78 79 // Scan all the blocks in the function, looking for empty return blocks. 80 for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) { 81 BasicBlock &BB = *BBI++; 82 83 // Only look at return blocks. 84 ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()); 85 if (!Ret) continue; 86 87 // Only look at the block if it is empty or the only other thing in it is a 88 // single PHI node that is the operand to the return. 89 if (Ret != &BB.front()) { 90 // Check for something else in the block. 91 BasicBlock::iterator I(Ret); 92 --I; 93 // Skip over debug info. 94 while (isa<DbgInfoIntrinsic>(I) && I != BB.begin()) 95 --I; 96 if (!isa<DbgInfoIntrinsic>(I) && 97 (!isa<PHINode>(I) || I != BB.begin() || Ret->getNumOperands() == 0 || 98 Ret->getOperand(0) != &*I)) 99 continue; 100 } 101 102 // If this is the first returning block, remember it and keep going. 103 if (!RetBlock) { 104 RetBlock = &BB; 105 continue; 106 } 107 108 // Skip merging if this would result in a CallBr instruction with a 109 // duplicate destination. FIXME: See note in CodeGenPrepare.cpp. 110 bool SkipCallBr = false; 111 for (pred_iterator PI = pred_begin(&BB), E = pred_end(&BB); 112 PI != E && !SkipCallBr; ++PI) { 113 if (auto *CBI = dyn_cast<CallBrInst>((*PI)->getTerminator())) 114 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i) 115 if (RetBlock == CBI->getSuccessor(i)) { 116 SkipCallBr = true; 117 break; 118 } 119 } 120 if (SkipCallBr) 121 continue; 122 123 // Otherwise, we found a duplicate return block. Merge the two. 124 Changed = true; 125 126 // Case when there is no input to the return or when the returned values 127 // agree is trivial. Note that they can't agree if there are phis in the 128 // blocks. 129 if (Ret->getNumOperands() == 0 || 130 Ret->getOperand(0) == 131 cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) { 132 BB.replaceAllUsesWith(RetBlock); 133 BB.eraseFromParent(); 134 continue; 135 } 136 137 // If the canonical return block has no PHI node, create one now. 138 PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin()); 139 if (!RetBlockPHI) { 140 Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0); 141 pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock); 142 RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(), 143 std::distance(PB, PE), "merge", 144 &RetBlock->front()); 145 146 for (pred_iterator PI = PB; PI != PE; ++PI) 147 RetBlockPHI->addIncoming(InVal, *PI); 148 RetBlock->getTerminator()->setOperand(0, RetBlockPHI); 149 } 150 151 // Turn BB into a block that just unconditionally branches to the return 152 // block. This handles the case when the two return blocks have a common 153 // predecessor but that return different things. 154 RetBlockPHI->addIncoming(Ret->getOperand(0), &BB); 155 BB.getTerminator()->eraseFromParent(); 156 BranchInst::Create(RetBlock, &BB); 157 } 158 159 return Changed; 160 } 161 162 /// Call SimplifyCFG on all the blocks in the function, 163 /// iterating until no more changes are made. 164 static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI, 165 const SimplifyCFGOptions &Options) { 166 bool Changed = false; 167 bool LocalChange = true; 168 169 SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 32> Edges; 170 FindFunctionBackedges(F, Edges); 171 SmallPtrSet<BasicBlock *, 16> LoopHeaders; 172 for (unsigned i = 0, e = Edges.size(); i != e; ++i) 173 LoopHeaders.insert(const_cast<BasicBlock *>(Edges[i].second)); 174 175 while (LocalChange) { 176 LocalChange = false; 177 178 // Loop over all of the basic blocks and remove them if they are unneeded. 179 for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) { 180 if (simplifyCFG(&*BBIt++, TTI, Options, &LoopHeaders)) { 181 LocalChange = true; 182 ++NumSimpl; 183 } 184 } 185 Changed |= LocalChange; 186 } 187 return Changed; 188 } 189 190 static bool simplifyFunctionCFG(Function &F, const TargetTransformInfo &TTI, 191 const SimplifyCFGOptions &Options) { 192 bool EverChanged = removeUnreachableBlocks(F); 193 EverChanged |= mergeEmptyReturnBlocks(F); 194 EverChanged |= iterativelySimplifyCFG(F, TTI, Options); 195 196 // If neither pass changed anything, we're done. 197 if (!EverChanged) return false; 198 199 // iterativelySimplifyCFG can (rarely) make some loops dead. If this happens, 200 // removeUnreachableBlocks is needed to nuke them, which means we should 201 // iterate between the two optimizations. We structure the code like this to 202 // avoid rerunning iterativelySimplifyCFG if the second pass of 203 // removeUnreachableBlocks doesn't do anything. 204 if (!removeUnreachableBlocks(F)) 205 return true; 206 207 do { 208 EverChanged = iterativelySimplifyCFG(F, TTI, Options); 209 EverChanged |= removeUnreachableBlocks(F); 210 } while (EverChanged); 211 212 return true; 213 } 214 215 // Command-line settings override compile-time settings. 216 static void applyCommandLineOverridesToOptions(SimplifyCFGOptions &Options) { 217 if (UserBonusInstThreshold.getNumOccurrences()) 218 Options.BonusInstThreshold = UserBonusInstThreshold; 219 if (UserForwardSwitchCond.getNumOccurrences()) 220 Options.ForwardSwitchCondToPhi = UserForwardSwitchCond; 221 if (UserSwitchToLookup.getNumOccurrences()) 222 Options.ConvertSwitchToLookupTable = UserSwitchToLookup; 223 if (UserKeepLoops.getNumOccurrences()) 224 Options.NeedCanonicalLoop = UserKeepLoops; 225 if (UserSinkCommonInsts.getNumOccurrences()) 226 Options.SinkCommonInsts = UserSinkCommonInsts; 227 } 228 229 SimplifyCFGPass::SimplifyCFGPass(const SimplifyCFGOptions &Opts) 230 : Options(Opts) { 231 applyCommandLineOverridesToOptions(Options); 232 } 233 234 PreservedAnalyses SimplifyCFGPass::run(Function &F, 235 FunctionAnalysisManager &AM) { 236 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 237 Options.AC = &AM.getResult<AssumptionAnalysis>(F); 238 if (!simplifyFunctionCFG(F, TTI, Options)) 239 return PreservedAnalyses::all(); 240 PreservedAnalyses PA; 241 PA.preserve<GlobalsAA>(); 242 return PA; 243 } 244 245 namespace { 246 struct CFGSimplifyPass : public FunctionPass { 247 static char ID; 248 SimplifyCFGOptions Options; 249 std::function<bool(const Function &)> PredicateFtor; 250 251 CFGSimplifyPass(SimplifyCFGOptions Options_ = SimplifyCFGOptions(), 252 std::function<bool(const Function &)> Ftor = nullptr) 253 : FunctionPass(ID), Options(Options_), PredicateFtor(std::move(Ftor)) { 254 255 initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry()); 256 257 // Check for command-line overrides of options for debug/customization. 258 applyCommandLineOverridesToOptions(Options); 259 } 260 261 bool runOnFunction(Function &F) override { 262 if (skipFunction(F) || (PredicateFtor && !PredicateFtor(F))) 263 return false; 264 265 Options.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 266 if (F.hasFnAttribute(Attribute::OptForFuzzing)) { 267 Options.setSimplifyCondBranch(false) 268 .setFoldTwoEntryPHINode(false); 269 } else { 270 Options.setSimplifyCondBranch(true) 271 .setFoldTwoEntryPHINode(true); 272 } 273 274 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 275 return simplifyFunctionCFG(F, TTI, Options); 276 } 277 void getAnalysisUsage(AnalysisUsage &AU) const override { 278 AU.addRequired<AssumptionCacheTracker>(); 279 AU.addRequired<TargetTransformInfoWrapperPass>(); 280 AU.addPreserved<GlobalsAAWrapperPass>(); 281 } 282 }; 283 } 284 285 char CFGSimplifyPass::ID = 0; 286 INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false, 287 false) 288 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 289 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 290 INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false, 291 false) 292 293 // Public interface to the CFGSimplification pass 294 FunctionPass * 295 llvm::createCFGSimplificationPass(SimplifyCFGOptions Options, 296 std::function<bool(const Function &)> Ftor) { 297 return new CFGSimplifyPass(Options, std::move(Ftor)); 298 } 299