LLVM API Documentation

GCSE.cpp

Go to the documentation of this file.
00001 //===-- GCSE.cpp - SSA-based Global Common Subexpression Elimination ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass is designed to be a very quick global transformation that
00011 // eliminates global common subexpressions from a function.  It does this by
00012 // using an existing value numbering implementation to identify the common
00013 // subexpressions, eliminating them when possible.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/Transforms/Scalar.h"
00018 #include "llvm/BasicBlock.h"
00019 #include "llvm/Constant.h"
00020 #include "llvm/Instructions.h"
00021 #include "llvm/Type.h"
00022 #include "llvm/Analysis/Dominators.h"
00023 #include "llvm/Analysis/ValueNumbering.h"
00024 #include "llvm/Transforms/Utils/Local.h"
00025 #include "llvm/ADT/DepthFirstIterator.h"
00026 #include "llvm/ADT/Statistic.h"
00027 #include <algorithm>
00028 using namespace llvm;
00029 
00030 namespace {
00031   Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
00032   Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
00033   Statistic<> NumCallRemoved("gcse", "Number of calls removed");
00034   Statistic<> NumNonInsts   ("gcse", "Number of instructions removed due "
00035                              "to non-instruction values");
00036   Statistic<> NumArgsRepl   ("gcse", "Number of function arguments replaced "
00037                              "with constant values");
00038 
00039   struct GCSE : public FunctionPass {
00040     virtual bool runOnFunction(Function &F);
00041 
00042   private:
00043     void ReplaceInstructionWith(Instruction *I, Value *V);
00044 
00045     // This transformation requires dominator and immediate dominator info
00046     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00047       AU.setPreservesCFG();
00048       AU.addRequired<ETForest>();
00049       AU.addRequired<DominatorTree>();
00050       AU.addRequired<ValueNumbering>();
00051     }
00052   };
00053 
00054   RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
00055 }
00056 
00057 // createGCSEPass - The public interface to this file...
00058 FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
00059 
00060 // GCSE::runOnFunction - This is the main transformation entry point for a
00061 // function.
00062 //
00063 bool GCSE::runOnFunction(Function &F) {
00064   bool Changed = false;
00065 
00066   // Get pointers to the analysis results that we will be using...
00067   ETForest &EF = getAnalysis<ETForest>();
00068   ValueNumbering &VN = getAnalysis<ValueNumbering>();
00069   DominatorTree &DT = getAnalysis<DominatorTree>();
00070 
00071   std::vector<Value*> EqualValues;
00072 
00073   // Check for value numbers of arguments.  If the value numbering
00074   // implementation can prove that an incoming argument is a constant or global
00075   // value address, substitute it, making the argument dead.
00076   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI)
00077     if (!AI->use_empty()) {
00078       VN.getEqualNumberNodes(AI, EqualValues);
00079       if (!EqualValues.empty()) {
00080         for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
00081           if (isa<Constant>(EqualValues[i])) {
00082             AI->replaceAllUsesWith(EqualValues[i]);
00083             ++NumArgsRepl;
00084             Changed = true;
00085             break;
00086           }
00087         EqualValues.clear();
00088       }
00089     }
00090 
00091   // Traverse the CFG of the function in dominator order, so that we see each
00092   // instruction after we see its operands.
00093   for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()),
00094          E = df_end(DT.getRootNode()); DI != E; ++DI) {
00095     BasicBlock *BB = DI->getBlock();
00096 
00097     // Remember which instructions we've seen in this basic block as we scan.
00098     std::set<Instruction*> BlockInsts;
00099 
00100     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
00101       Instruction *Inst = I++;
00102 
00103       if (Constant *C = ConstantFoldInstruction(Inst)) {
00104         ReplaceInstructionWith(Inst, C);
00105       } else if (Inst->getType() != Type::VoidTy) {
00106         // If this instruction computes a value, try to fold together common
00107         // instructions that compute it.
00108         //
00109         VN.getEqualNumberNodes(Inst, EqualValues);
00110 
00111         // If this instruction computes a value that is already computed
00112         // elsewhere, try to recycle the old value.
00113         if (!EqualValues.empty()) {
00114           if (Inst == &*BB->begin())
00115             I = BB->end();
00116           else {
00117             I = Inst; --I;
00118           }
00119 
00120           // First check to see if we were able to value number this instruction
00121           // to a non-instruction value.  If so, prefer that value over other
00122           // instructions which may compute the same thing.
00123           for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
00124             if (!isa<Instruction>(EqualValues[i])) {
00125               ++NumNonInsts;      // Keep track of # of insts repl with values
00126 
00127               // Change all users of Inst to use the replacement and remove it
00128               // from the program.
00129               ReplaceInstructionWith(Inst, EqualValues[i]);
00130               Inst = 0;
00131               EqualValues.clear();  // don't enter the next loop
00132               break;
00133             }
00134 
00135           // If there were no non-instruction values that this instruction
00136           // produces, find a dominating instruction that produces the same
00137           // value.  If we find one, use it's value instead of ours.
00138           for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) {
00139             Instruction *OtherI = cast<Instruction>(EqualValues[i]);
00140             bool Dominates = false;
00141             if (OtherI->getParent() == BB)
00142               Dominates = BlockInsts.count(OtherI);
00143             else
00144               Dominates = EF.dominates(OtherI->getParent(), BB);
00145 
00146             if (Dominates) {
00147               // Okay, we found an instruction with the same value as this one
00148               // and that dominates this one.  Replace this instruction with the
00149               // specified one.
00150               ReplaceInstructionWith(Inst, OtherI);
00151               Inst = 0;
00152               break;
00153             }
00154           }
00155 
00156           EqualValues.clear();
00157 
00158           if (Inst) {
00159             I = Inst; ++I;             // Deleted no instructions
00160           } else if (I == BB->end()) { // Deleted first instruction
00161             I = BB->begin();
00162           } else {                     // Deleted inst in middle of block.
00163             ++I;
00164           }
00165         }
00166 
00167         if (Inst)
00168           BlockInsts.insert(Inst);
00169       }
00170     }
00171   }
00172 
00173   // When the worklist is empty, return whether or not we changed anything...
00174   return Changed;
00175 }
00176 
00177 
00178 void GCSE::ReplaceInstructionWith(Instruction *I, Value *V) {
00179   if (isa<LoadInst>(I))
00180     ++NumLoadRemoved; // Keep track of loads eliminated
00181   if (isa<CallInst>(I))
00182     ++NumCallRemoved; // Keep track of calls eliminated
00183   ++NumInstRemoved;   // Keep track of number of insts eliminated
00184 
00185   // Update value numbering
00186   getAnalysis<ValueNumbering>().deleteValue(I);
00187 
00188   I->replaceAllUsesWith(V);
00189 
00190   if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
00191     // Removing an invoke instruction requires adding a branch to the normal
00192     // destination and removing PHI node entries in the exception destination.
00193     new BranchInst(II->getNormalDest(), II);
00194     II->getUnwindDest()->removePredecessor(II->getParent());
00195   }
00196 
00197   // Erase the instruction from the program.
00198   I->getParent()->getInstList().erase(I);
00199 }