Remove attribution from file headers, per discussion on llvmdev.
[oota-llvm.git] / lib / Transforms / Scalar / GCSE.cpp
1 //===-- GCSE.cpp - SSA-based Global Common Subexpression Elimination ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16
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"
28 #include <algorithm>
29 using namespace llvm;
30
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");
38 namespace {
39   struct VISIBILITY_HIDDEN GCSE : public FunctionPass {
40     static char ID; // Pass identification, replacement for typeid
41     GCSE() : FunctionPass((intptr_t)&ID) {}
42
43     virtual bool runOnFunction(Function &F);
44
45   private:
46     void ReplaceInstructionWith(Instruction *I, Value *V);
47
48     // This transformation requires dominator and immediate dominator info
49     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50       AU.setPreservesCFG();
51       AU.addRequired<DominatorTree>();
52       AU.addRequired<ValueNumbering>();
53     }
54   };
55
56   char GCSE::ID = 0;
57   RegisterPass<GCSE> X("gcse", "Global Common Subexpression Elimination");
58 }
59
60 // createGCSEPass - The public interface to this file...
61 FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
62
63 // GCSE::runOnFunction - This is the main transformation entry point for a
64 // function.
65 //
66 bool GCSE::runOnFunction(Function &F) {
67   bool Changed = false;
68
69   // Get pointers to the analysis results that we will be using...
70   DominatorTree &DT = getAnalysis<DominatorTree>();
71   ValueNumbering &VN = getAnalysis<ValueNumbering>();
72
73   std::vector<Value*> EqualValues;
74
75   // Check for value numbers of arguments.  If the value numbering
76   // implementation can prove that an incoming argument is a constant or global
77   // value address, substitute it, making the argument dead.
78   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
79     if (!AI->use_empty()) {
80       VN.getEqualNumberNodes(AI, EqualValues);
81       if (!EqualValues.empty()) {
82         for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
83           if (isa<Constant>(EqualValues[i])) {
84             AI->replaceAllUsesWith(EqualValues[i]);
85             ++NumArgsRepl;
86             Changed = true;
87             break;
88           }
89         EqualValues.clear();
90       }
91     }
92
93   // Traverse the CFG of the function in dominator order, so that we see each
94   // instruction after we see its operands.
95   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
96          E = df_end(DT.getRootNode()); DI != E; ++DI) {
97     BasicBlock *BB = DI->getBlock();
98
99     // Remember which instructions we've seen in this basic block as we scan.
100     std::set<Instruction*> BlockInsts;
101
102     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
103       Instruction *Inst = I++;
104
105       if (Constant *C = ConstantFoldInstruction(Inst)) {
106         ReplaceInstructionWith(Inst, C);
107       } else if (Inst->getType() != Type::VoidTy) {
108         // If this instruction computes a value, try to fold together common
109         // instructions that compute it.
110         //
111         VN.getEqualNumberNodes(Inst, EqualValues);
112
113         // If this instruction computes a value that is already computed
114         // elsewhere, try to recycle the old value.
115         if (!EqualValues.empty()) {
116           if (Inst == &*BB->begin())
117             I = BB->end();
118           else {
119             I = Inst; --I;
120           }
121
122           // First check to see if we were able to value number this instruction
123           // to a non-instruction value.  If so, prefer that value over other
124           // instructions which may compute the same thing.
125           for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
126             if (!isa<Instruction>(EqualValues[i])) {
127               ++NumNonInsts;      // Keep track of # of insts repl with values
128
129               // Change all users of Inst to use the replacement and remove it
130               // from the program.
131               ReplaceInstructionWith(Inst, EqualValues[i]);
132               Inst = 0;
133               EqualValues.clear();  // don't enter the next loop
134               break;
135             }
136
137           // If there were no non-instruction values that this instruction
138           // produces, find a dominating instruction that produces the same
139           // value.  If we find one, use it's value instead of ours.
140           for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) {
141             Instruction *OtherI = cast<Instruction>(EqualValues[i]);
142             bool Dominates = false;
143             if (OtherI->getParent() == BB)
144               Dominates = BlockInsts.count(OtherI);
145             else
146               Dominates = DT.dominates(OtherI->getParent(), BB);
147
148             if (Dominates) {
149               // Okay, we found an instruction with the same value as this one
150               // and that dominates this one.  Replace this instruction with the
151               // specified one.
152               ReplaceInstructionWith(Inst, OtherI);
153               Inst = 0;
154               break;
155             }
156           }
157
158           EqualValues.clear();
159
160           if (Inst) {
161             I = Inst; ++I;             // Deleted no instructions
162           } else if (I == BB->end()) { // Deleted first instruction
163             I = BB->begin();
164           } else {                     // Deleted inst in middle of block.
165             ++I;
166           }
167         }
168
169         if (Inst)
170           BlockInsts.insert(Inst);
171       }
172     }
173   }
174
175   // When the worklist is empty, return whether or not we changed anything...
176   return Changed;
177 }
178
179
180 void GCSE::ReplaceInstructionWith(Instruction *I, Value *V) {
181   if (isa<LoadInst>(I))
182     ++NumLoadRemoved; // Keep track of loads eliminated
183   if (isa<CallInst>(I))
184     ++NumCallRemoved; // Keep track of calls eliminated
185   ++NumInstRemoved;   // Keep track of number of insts eliminated
186
187   // Update value numbering
188   getAnalysis<ValueNumbering>().deleteValue(I);
189
190   I->replaceAllUsesWith(V);
191
192   if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
193     // Removing an invoke instruction requires adding a branch to the normal
194     // destination and removing PHI node entries in the exception destination.
195     new BranchInst(II->getNormalDest(), II);
196     II->getUnwindDest()->removePredecessor(II->getParent());
197   }
198
199   // Erase the instruction from the program.
200   I->getParent()->getInstList().erase(I);
201 }