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