1 //===-- GCSE.cpp - SSA-based Global Common Subexpression Elimination ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass is designed to be a very quick global transformation that
11 // eliminates global common subexpressions from a function. It does this by
12 // using an existing value numbering implementation to identify the common
13 // subexpressions, eliminating them when possible.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "gcse"
18 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Function.h"
21 #include "llvm/Type.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm/Analysis/ValueNumbering.h"
25 #include "llvm/ADT/DepthFirstIterator.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Compiler.h"
31 STATISTIC(NumInstRemoved, "Number of instructions removed");
32 STATISTIC(NumLoadRemoved, "Number of loads removed");
33 STATISTIC(NumCallRemoved, "Number of calls removed");
34 STATISTIC(NumNonInsts , "Number of instructions removed due "
35 "to non-instruction values");
36 STATISTIC(NumArgsRepl , "Number of function arguments replaced "
37 "with constant values");
39 struct VISIBILITY_HIDDEN GCSE : public FunctionPass {
40 static char ID; // Pass identifcation, replacement for typeid
41 GCSE() : FunctionPass((intptr_t)&ID) {}
43 virtual bool runOnFunction(Function &F);
46 void ReplaceInstructionWith(Instruction *I, Value *V);
48 // This transformation requires dominator and immediate dominator info
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addRequired<ETForest>();
52 AU.addRequired<DominatorTree>();
53 AU.addRequired<ValueNumbering>();
58 RegisterPass<GCSE> X("gcse", "Global Common Subexpression Elimination");
61 // createGCSEPass - The public interface to this file...
62 FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
64 // GCSE::runOnFunction - This is the main transformation entry point for a
67 bool GCSE::runOnFunction(Function &F) {
70 // Get pointers to the analysis results that we will be using...
71 ETForest &EF = getAnalysis<ETForest>();
72 ValueNumbering &VN = getAnalysis<ValueNumbering>();
73 DominatorTree &DT = getAnalysis<DominatorTree>();
75 std::vector<Value*> EqualValues;
77 // Check for value numbers of arguments. If the value numbering
78 // implementation can prove that an incoming argument is a constant or global
79 // value address, substitute it, making the argument dead.
80 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
81 if (!AI->use_empty()) {
82 VN.getEqualNumberNodes(AI, EqualValues);
83 if (!EqualValues.empty()) {
84 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
85 if (isa<Constant>(EqualValues[i])) {
86 AI->replaceAllUsesWith(EqualValues[i]);
95 // Traverse the CFG of the function in dominator order, so that we see each
96 // instruction after we see its operands.
97 for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()),
98 E = df_end(DT.getRootNode()); DI != E; ++DI) {
99 BasicBlock *BB = DI->getBlock();
101 // Remember which instructions we've seen in this basic block as we scan.
102 std::set<Instruction*> BlockInsts;
104 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
105 Instruction *Inst = I++;
107 if (Constant *C = ConstantFoldInstruction(Inst)) {
108 ReplaceInstructionWith(Inst, C);
109 } else if (Inst->getType() != Type::VoidTy) {
110 // If this instruction computes a value, try to fold together common
111 // instructions that compute it.
113 VN.getEqualNumberNodes(Inst, EqualValues);
115 // If this instruction computes a value that is already computed
116 // elsewhere, try to recycle the old value.
117 if (!EqualValues.empty()) {
118 if (Inst == &*BB->begin())
124 // First check to see if we were able to value number this instruction
125 // to a non-instruction value. If so, prefer that value over other
126 // instructions which may compute the same thing.
127 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
128 if (!isa<Instruction>(EqualValues[i])) {
129 ++NumNonInsts; // Keep track of # of insts repl with values
131 // Change all users of Inst to use the replacement and remove it
133 ReplaceInstructionWith(Inst, EqualValues[i]);
135 EqualValues.clear(); // don't enter the next loop
139 // If there were no non-instruction values that this instruction
140 // produces, find a dominating instruction that produces the same
141 // value. If we find one, use it's value instead of ours.
142 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) {
143 Instruction *OtherI = cast<Instruction>(EqualValues[i]);
144 bool Dominates = false;
145 if (OtherI->getParent() == BB)
146 Dominates = BlockInsts.count(OtherI);
148 Dominates = EF.dominates(OtherI->getParent(), BB);
151 // Okay, we found an instruction with the same value as this one
152 // and that dominates this one. Replace this instruction with the
154 ReplaceInstructionWith(Inst, OtherI);
163 I = Inst; ++I; // Deleted no instructions
164 } else if (I == BB->end()) { // Deleted first instruction
166 } else { // Deleted inst in middle of block.
172 BlockInsts.insert(Inst);
177 // When the worklist is empty, return whether or not we changed anything...
182 void GCSE::ReplaceInstructionWith(Instruction *I, Value *V) {
183 if (isa<LoadInst>(I))
184 ++NumLoadRemoved; // Keep track of loads eliminated
185 if (isa<CallInst>(I))
186 ++NumCallRemoved; // Keep track of calls eliminated
187 ++NumInstRemoved; // Keep track of number of insts eliminated
189 // Update value numbering
190 getAnalysis<ValueNumbering>().deleteValue(I);
192 I->replaceAllUsesWith(V);
194 if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
195 // Removing an invoke instruction requires adding a branch to the normal
196 // destination and removing PHI node entries in the exception destination.
197 new BranchInst(II->getNormalDest(), II);
198 II->getUnwindDest()->removePredecessor(II->getParent());
201 // Erase the instruction from the program.
202 I->getParent()->getInstList().erase(I);