LLVM API Documentation

SimplifyCFGPass.cpp
Go to the documentation of this file.
00001 //===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements dead code elimination and basic block merging, along
00011 // with a collection of other peephole control flow optimizations.  For example:
00012 //
00013 //   * Removes basic blocks with no predecessors.
00014 //   * Merges a basic block into its predecessor if there is only one and the
00015 //     predecessor only has one successor.
00016 //   * Eliminates PHI nodes for basic blocks with a single predecessor.
00017 //   * Eliminates a basic block that only contains an unconditional branch.
00018 //   * Changes invoke instructions to nounwind functions to be calls.
00019 //   * Change things like "if (x) if (y)" into "if (x&y)".
00020 //   * etc..
00021 //
00022 //===----------------------------------------------------------------------===//
00023 
00024 #define DEBUG_TYPE "simplifycfg"
00025 #include "llvm/Transforms/Scalar.h"
00026 #include "llvm/ADT/SmallPtrSet.h"
00027 #include "llvm/ADT/SmallVector.h"
00028 #include "llvm/ADT/Statistic.h"
00029 #include "llvm/Analysis/TargetTransformInfo.h"
00030 #include "llvm/IR/Attributes.h"
00031 #include "llvm/IR/CFG.h"
00032 #include "llvm/IR/Constants.h"
00033 #include "llvm/IR/DataLayout.h"
00034 #include "llvm/IR/Instructions.h"
00035 #include "llvm/IR/IntrinsicInst.h"
00036 #include "llvm/IR/Module.h"
00037 #include "llvm/Pass.h"
00038 #include "llvm/Transforms/Utils/Local.h"
00039 using namespace llvm;
00040 
00041 STATISTIC(NumSimpl, "Number of blocks simplified");
00042 
00043 namespace {
00044 struct CFGSimplifyPass : public FunctionPass {
00045   static char ID; // Pass identification, replacement for typeid
00046   CFGSimplifyPass() : FunctionPass(ID) {
00047     initializeCFGSimplifyPassPass(*PassRegistry::getPassRegistry());
00048   }
00049   bool runOnFunction(Function &F) override;
00050 
00051   void getAnalysisUsage(AnalysisUsage &AU) const override {
00052     AU.addRequired<TargetTransformInfo>();
00053   }
00054 };
00055 }
00056 
00057 char CFGSimplifyPass::ID = 0;
00058 INITIALIZE_PASS_BEGIN(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
00059                       false)
00060 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
00061 INITIALIZE_PASS_END(CFGSimplifyPass, "simplifycfg", "Simplify the CFG", false,
00062                     false)
00063 
00064 // Public interface to the CFGSimplification pass
00065 FunctionPass *llvm::createCFGSimplificationPass() {
00066   return new CFGSimplifyPass();
00067 }
00068 
00069 /// mergeEmptyReturnBlocks - If we have more than one empty (other than phi
00070 /// node) return blocks, merge them together to promote recursive block merging.
00071 static bool mergeEmptyReturnBlocks(Function &F) {
00072   bool Changed = false;
00073 
00074   BasicBlock *RetBlock = 0;
00075 
00076   // Scan all the blocks in the function, looking for empty return blocks.
00077   for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; ) {
00078     BasicBlock &BB = *BBI++;
00079 
00080     // Only look at return blocks.
00081     ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
00082     if (Ret == 0) continue;
00083 
00084     // Only look at the block if it is empty or the only other thing in it is a
00085     // single PHI node that is the operand to the return.
00086     if (Ret != &BB.front()) {
00087       // Check for something else in the block.
00088       BasicBlock::iterator I = Ret;
00089       --I;
00090       // Skip over debug info.
00091       while (isa<DbgInfoIntrinsic>(I) && I != BB.begin())
00092         --I;
00093       if (!isa<DbgInfoIntrinsic>(I) &&
00094           (!isa<PHINode>(I) || I != BB.begin() ||
00095            Ret->getNumOperands() == 0 ||
00096            Ret->getOperand(0) != I))
00097         continue;
00098     }
00099 
00100     // If this is the first returning block, remember it and keep going.
00101     if (RetBlock == 0) {
00102       RetBlock = &BB;
00103       continue;
00104     }
00105 
00106     // Otherwise, we found a duplicate return block.  Merge the two.
00107     Changed = true;
00108 
00109     // Case when there is no input to the return or when the returned values
00110     // agree is trivial.  Note that they can't agree if there are phis in the
00111     // blocks.
00112     if (Ret->getNumOperands() == 0 ||
00113         Ret->getOperand(0) ==
00114           cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0)) {
00115       BB.replaceAllUsesWith(RetBlock);
00116       BB.eraseFromParent();
00117       continue;
00118     }
00119 
00120     // If the canonical return block has no PHI node, create one now.
00121     PHINode *RetBlockPHI = dyn_cast<PHINode>(RetBlock->begin());
00122     if (RetBlockPHI == 0) {
00123       Value *InVal = cast<ReturnInst>(RetBlock->getTerminator())->getOperand(0);
00124       pred_iterator PB = pred_begin(RetBlock), PE = pred_end(RetBlock);
00125       RetBlockPHI = PHINode::Create(Ret->getOperand(0)->getType(),
00126                                     std::distance(PB, PE), "merge",
00127                                     &RetBlock->front());
00128 
00129       for (pred_iterator PI = PB; PI != PE; ++PI)
00130         RetBlockPHI->addIncoming(InVal, *PI);
00131       RetBlock->getTerminator()->setOperand(0, RetBlockPHI);
00132     }
00133 
00134     // Turn BB into a block that just unconditionally branches to the return
00135     // block.  This handles the case when the two return blocks have a common
00136     // predecessor but that return different things.
00137     RetBlockPHI->addIncoming(Ret->getOperand(0), &BB);
00138     BB.getTerminator()->eraseFromParent();
00139     BranchInst::Create(RetBlock, &BB);
00140   }
00141 
00142   return Changed;
00143 }
00144 
00145 /// iterativelySimplifyCFG - Call SimplifyCFG on all the blocks in the function,
00146 /// iterating until no more changes are made.
00147 static bool iterativelySimplifyCFG(Function &F, const TargetTransformInfo &TTI,
00148                                    const DataLayout *DL) {
00149   bool Changed = false;
00150   bool LocalChange = true;
00151   while (LocalChange) {
00152     LocalChange = false;
00153 
00154     // Loop over all of the basic blocks and remove them if they are unneeded...
00155     //
00156     for (Function::iterator BBIt = F.begin(); BBIt != F.end(); ) {
00157       if (SimplifyCFG(BBIt++, TTI, DL)) {
00158         LocalChange = true;
00159         ++NumSimpl;
00160       }
00161     }
00162     Changed |= LocalChange;
00163   }
00164   return Changed;
00165 }
00166 
00167 // It is possible that we may require multiple passes over the code to fully
00168 // simplify the CFG.
00169 //
00170 bool CFGSimplifyPass::runOnFunction(Function &F) {
00171   if (skipOptnoneFunction(F))
00172     return false;
00173 
00174   const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfo>();
00175   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
00176   const DataLayout *DL = DLP ? &DLP->getDataLayout() : 0;
00177   bool EverChanged = removeUnreachableBlocks(F);
00178   EverChanged |= mergeEmptyReturnBlocks(F);
00179   EverChanged |= iterativelySimplifyCFG(F, TTI, DL);
00180 
00181   // If neither pass changed anything, we're done.
00182   if (!EverChanged) return false;
00183 
00184   // iterativelySimplifyCFG can (rarely) make some loops dead.  If this happens,
00185   // removeUnreachableBlocks is needed to nuke them, which means we should
00186   // iterate between the two optimizations.  We structure the code like this to
00187   // avoid reruning iterativelySimplifyCFG if the second pass of
00188   // removeUnreachableBlocks doesn't do anything.
00189   if (!removeUnreachableBlocks(F))
00190     return true;
00191 
00192   do {
00193     EverChanged = iterativelySimplifyCFG(F, TTI, DL);
00194     EverChanged |= removeUnreachableBlocks(F);
00195   } while (EverChanged);
00196 
00197   return true;
00198 }