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