There's no need to have an Expression class... Value works just as well! This simpli...
[oota-llvm.git] / lib / Transforms / Scalar / GVNPRE.cpp
1 //===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the Owen Anderson and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs a hybrid of global value numbering and partial redundancy
11 // elimination, known as GVN-PRE.  It performs partial redundancy elimination on
12 // values, rather than lexical expressions, allowing a more comprehensive view 
13 // the optimization.  It replaces redundant values with uses of earlier 
14 // occurences of the same value.  While this is beneficial in that it eliminates
15 // unneeded computation, it also increases register pressure by creating large
16 // live ranges, and should be used with caution on platforms that a very 
17 // sensitive to register pressure.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "gvnpre"
22 #include "llvm/Value.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Function.h"
26 #include "llvm/Analysis/Dominators.h"
27 #include "llvm/Analysis/PostDominators.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Debug.h"
32 #include <algorithm>
33 #include <deque>
34 #include <map>
35 #include <vector>
36 #include <set>
37 using namespace llvm;
38
39 struct ExprLT {
40   bool operator()(Value* left, Value* right) {
41     if (!isa<BinaryOperator>(left) || !isa<BinaryOperator>(right))
42       return left < right;
43     
44     BinaryOperator* BO1 = cast<BinaryOperator>(left);
45     BinaryOperator* BO2 = cast<BinaryOperator>(right);
46     
47     if ((*this)(BO1->getOperand(0), BO2->getOperand(0)))
48       return true;
49     else if ((*this)(BO2->getOperand(0), BO1->getOperand(0)))
50       return false;
51     else
52       return (*this)(BO1->getOperand(1), BO2->getOperand(1));
53   }
54 };
55
56 namespace {
57
58   class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
59     bool runOnFunction(Function &F);
60   public:
61     static char ID; // Pass identification, replacement for typeid
62     GVNPRE() : FunctionPass((intptr_t)&ID) { nextValueNumber = 0; }
63
64   private:
65     uint32_t nextValueNumber;
66     typedef std::map<Value*, uint32_t, ExprLT> ValueTable;
67     
68     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69       AU.setPreservesCFG();
70       AU.addRequired<DominatorTree>();
71       AU.addRequired<PostDominatorTree>();
72     }
73   
74     // Helper fuctions
75     // FIXME: eliminate or document these better
76     void dump(ValueTable& VN, std::set<Value*, ExprLT>& s);
77     void clean(ValueTable VN, std::set<Value*, ExprLT>& set);
78     bool add(ValueTable& VN, std::set<Value*, ExprLT>& MS, Value* V);
79     ValueTable::iterator lookup(ValueTable& VN, Value* V);
80     Value* find_leader(ValueTable VN, std::set<Value*, ExprLT>& vals, uint32_t v);
81     void phi_translate(ValueTable& VN, std::set<Value*, ExprLT>& MS,
82                        std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
83                        std::set<Value*, ExprLT>& out);
84     
85     void topo_sort(ValueTable& VN, std::set<Value*, ExprLT>& set,
86                    std::vector<Value*>& vec);
87     
88     // For a given block, calculate the generated expressions, temporaries,
89     // and the AVAIL_OUT set
90     void CalculateAvailOut(ValueTable& VN, std::set<Value*, ExprLT>& MS,
91                        DominatorTree::Node* DI,
92                        std::set<Value*, ExprLT>& currExps,
93                        std::set<PHINode*>& currPhis,
94                        std::set<Value*, ExprLT>& currTemps,
95                        std::set<Value*, ExprLT>& currAvail,
96                        std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut);
97   
98   };
99   
100   char GVNPRE::ID = 0;
101   
102 }
103
104 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
105
106 RegisterPass<GVNPRE> X("gvnpre",
107                        "Global Value Numbering/Partial Redundancy Elimination");
108
109
110
111 bool GVNPRE::add(ValueTable& VN, std::set<Value*, ExprLT>& MS, Value* V) {
112   std::pair<ValueTable::iterator, bool> ret = VN.insert(std::make_pair(V, nextValueNumber));
113   if (ret.second)
114     nextValueNumber++;
115   if (isa<BinaryOperator>(V) || isa<PHINode>(V))
116     MS.insert(V);
117   return ret.second;
118 }
119
120 GVNPRE::ValueTable::iterator GVNPRE::lookup(ValueTable& VN, Value* V) {
121   return VN.find(V);
122 }
123
124 Value* GVNPRE::find_leader(GVNPRE::ValueTable VN,
125                            std::set<Value*, ExprLT>& vals,
126                            uint32_t v) {
127   for (std::set<Value*, ExprLT>::iterator I = vals.begin(), E = vals.end();
128        I != E; ++I)
129     if (VN[*I] == v)
130       return *I;
131   
132   return 0;
133 }
134
135 void GVNPRE::phi_translate(GVNPRE::ValueTable& VN,
136                            std::set<Value*, ExprLT>& MS,
137                            std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
138                            std::set<Value*, ExprLT>& out) {
139   BasicBlock* succ = B->getTerminator()->getSuccessor(0);
140   
141   for (std::set<Value*, ExprLT>::iterator I = anticIn.begin(), E = anticIn.end();
142        I != E; ++I) {
143     if (!isa<BinaryOperator>(*I)) {
144       if (PHINode* p = dyn_cast<PHINode>(*I)) {
145         if (p->getParent() == succ)
146           out.insert(p);
147       } else {
148         out.insert(*I);
149       }
150     } else {
151       BinaryOperator* BO = cast<BinaryOperator>(*I);
152       Value* lhs = find_leader(VN, anticIn, VN[BO->getOperand(0)]);
153       if (lhs == 0)
154         continue;
155       
156       if (PHINode* p = dyn_cast<PHINode>(lhs))
157         if (p->getParent() == succ) {
158           lhs = p->getIncomingValueForBlock(B);
159           out.insert(lhs);
160         }
161       
162       Value* rhs = find_leader(VN, anticIn, VN[BO->getOperand(1)]);
163       if (rhs == 0)
164         continue;
165       
166       if (PHINode* p = dyn_cast<PHINode>(rhs))
167         if (p->getParent() == succ) {
168           rhs = p->getIncomingValueForBlock(B);
169           out.insert(rhs);
170         }
171       
172       if (lhs != BO->getOperand(0) || rhs != BO->getOperand(1)) {
173         BO = BinaryOperator::create(BO->getOpcode(), lhs, rhs, BO->getName()+".gvnpre");
174         if (VN.insert(std::make_pair(BO, nextValueNumber)).second)
175           nextValueNumber++;
176         MS.insert(BO);
177       }
178       
179       out.insert(BO);
180       
181     }
182   }
183 }
184
185 // Remove all expressions whose operands are not themselves in the set
186 void GVNPRE::clean(GVNPRE::ValueTable VN, std::set<Value*, ExprLT>& set) {
187   std::vector<Value*> worklist;
188   topo_sort(VN, set, worklist);
189   
190   while (!worklist.empty()) {
191     Value* v = worklist.back();
192     worklist.pop_back();
193     
194     if (BinaryOperator* BO = dyn_cast<BinaryOperator>(v)) {   
195       bool lhsValid = false;
196       for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
197            I != E; ++I)
198         if (VN[*I] == VN[BO->getOperand(0)]);
199           lhsValid = true;
200     
201       bool rhsValid = false;
202       for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
203            I != E; ++I)
204         if (VN[*I] == VN[BO->getOperand(1)]);
205           rhsValid = true;
206       
207       if (!lhsValid || !rhsValid)
208         set.erase(BO);
209     }
210   }
211 }
212
213 void GVNPRE::topo_sort(GVNPRE::ValueTable& VN,
214                        std::set<Value*, ExprLT>& set,
215                        std::vector<Value*>& vec) {
216   std::set<Value*, ExprLT> toErase;               
217   for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
218        I != E; ++I) {
219     if (BinaryOperator* BO = dyn_cast<BinaryOperator>(*I))
220       for (std::set<Value*, ExprLT>::iterator SI = set.begin(); SI != E; ++SI) {
221         if (VN[BO->getOperand(0)] == VN[*SI] || VN[BO->getOperand(1)] == VN[*SI]) {
222           toErase.insert(BO);
223         }
224     }
225   }
226   
227   std::vector<Value*> Q;
228   std::insert_iterator<std::vector<Value*> > q_ins(Q, Q.begin());
229   std::set_difference(set.begin(), set.end(),
230                      toErase.begin(), toErase.end(),
231                      q_ins, ExprLT());
232   
233   std::set<Value*, ExprLT> visited;
234   while (!Q.empty()) {
235     Value* e = Q.back();
236   
237     if (BinaryOperator* BO = dyn_cast<BinaryOperator>(e)) {
238       Value* l = find_leader(VN, set, VN[BO->getOperand(0)]);
239       Value* r = find_leader(VN, set, VN[BO->getOperand(1)]);
240       
241       if (l != 0 && visited.find(l) == visited.end())
242         Q.push_back(l);
243       else if (r != 0 && visited.find(r) == visited.end())
244         Q.push_back(r);
245       else {
246         vec.push_back(e);
247         visited.insert(e);
248         Q.pop_back();
249       }
250     } else {
251       visited.insert(e);
252       vec.push_back(e);
253       Q.pop_back();
254     }
255   }
256 }
257
258 void GVNPRE::dump(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& s) {
259   std::vector<Value*> sorted;
260   topo_sort(VN, s, sorted);
261   DOUT << "{ ";
262   for (std::vector<Value*>::iterator I = sorted.begin(), E = sorted.end();
263        I != E; ++I) {
264     DEBUG((*I)->dump());
265   }
266   DOUT << "}\n\n";
267 }
268
269 void GVNPRE::CalculateAvailOut(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& MS,
270                        DominatorTree::Node* DI,
271                        std::set<Value*, ExprLT>& currExps,
272                        std::set<PHINode*>& currPhis,
273                        std::set<Value*, ExprLT>& currTemps,
274                        std::set<Value*, ExprLT>& currAvail,
275                        std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut) {
276   
277   BasicBlock* BB = DI->getBlock();
278   
279   // A block inherits AVAIL_OUT from its dominator
280   if (DI->getIDom() != 0)
281   currAvail.insert(availOut[DI->getIDom()->getBlock()].begin(),
282                    availOut[DI->getIDom()->getBlock()].end());
283     
284     
285  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
286       BI != BE; ++BI) {
287        
288     // Handle PHI nodes...
289     if (PHINode* p = dyn_cast<PHINode>(BI)) {
290       add(VN, MS, p);
291       currPhis.insert(p);
292     
293     // Handle binary ops...
294     } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) {
295       Value* leftValue = BO->getOperand(0);
296       Value* rightValue = BO->getOperand(1);
297       
298       add(VN, MS, BO);
299       
300       currExps.insert(leftValue);
301       currExps.insert(rightValue);
302       currExps.insert(BO);
303       
304       currTemps.insert(BO);
305         
306     // Handle unsupported ops
307     } else if (!BI->isTerminator()){
308       add(VN, MS, BI);
309       currTemps.insert(BI);
310     }
311     
312     if (!BI->isTerminator())
313       currAvail.insert(BI);
314   }
315 }
316
317 bool GVNPRE::runOnFunction(Function &F) {
318   ValueTable VN;
319   std::set<Value*, ExprLT> maximalSet;
320
321   std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedExpressions;
322   std::map<BasicBlock*, std::set<PHINode*> > generatedPhis;
323   std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedTemporaries;
324   std::map<BasicBlock*, std::set<Value*, ExprLT> > availableOut;
325   std::map<BasicBlock*, std::set<Value*, ExprLT> > anticipatedIn;
326   
327   DominatorTree &DT = getAnalysis<DominatorTree>();   
328   
329   // First Phase of BuildSets - calculate AVAIL_OUT
330   
331   // Top-down walk of the dominator tree
332   for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()),
333          E = df_end(DT.getRootNode()); DI != E; ++DI) {
334     
335     // Get the sets to update for this block
336     std::set<Value*, ExprLT>& currExps = generatedExpressions[DI->getBlock()];
337     std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()];
338     std::set<Value*, ExprLT>& currTemps = generatedTemporaries[DI->getBlock()];
339     std::set<Value*, ExprLT>& currAvail = availableOut[DI->getBlock()];     
340     
341     CalculateAvailOut(VN, maximalSet, *DI, currExps, currPhis,
342                       currTemps, currAvail, availableOut);
343   }
344   
345   PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
346   
347   // Second Phase of BuildSets - calculate ANTIC_IN
348   
349   std::set<BasicBlock*> visited;
350   
351   bool changed = true;
352   unsigned iterations = 0;
353   while (changed) {
354     changed = false;
355     std::set<Value*, ExprLT> anticOut;
356     
357     // Top-down walk of the postdominator tree
358     for (df_iterator<PostDominatorTree::Node*> PDI = 
359          df_begin(PDT.getRootNode()), E = df_end(DT.getRootNode());
360          PDI != E; ++PDI) {
361       BasicBlock* BB = PDI->getBlock();
362       
363       visited.insert(BB);
364       
365       std::set<Value*, ExprLT>& anticIn = anticipatedIn[BB];
366       std::set<Value*, ExprLT> old (anticIn.begin(), anticIn.end());
367       
368       if (BB->getTerminator()->getNumSuccessors() == 1) {
369          if (visited.find(BB) == visited.end())
370            phi_translate(VN, maximalSet, anticIn, BB, anticOut);
371          else
372            phi_translate(VN, anticIn, anticIn, BB, anticOut);
373       } else if (BB->getTerminator()->getNumSuccessors() > 1) {
374         for (unsigned i = 0; i < BB->getTerminator()->getNumSuccessors(); ++i) {
375           BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
376           std::set<Value*, ExprLT> temp;
377           if (visited.find(currSucc) == visited.end())
378             temp.insert(maximalSet.begin(), maximalSet.end());
379           else
380             temp.insert(anticIn.begin(), anticIn.end());
381        
382           anticIn.clear();
383           std::insert_iterator<std::set<Value*, ExprLT> >  ai_ins(anticIn,
384                                                        anticIn.begin());
385                                                        
386           std::set_difference(anticipatedIn[currSucc].begin(),
387                               anticipatedIn[currSucc].end(),
388                               temp.begin(),
389                               temp.end(),
390                               ai_ins,
391                               ExprLT());
392         }
393       }
394       
395       std::set<Value*, ExprLT> S;
396       std::insert_iterator<std::set<Value*, ExprLT> >  s_ins(S, S.begin());
397       std::set_union(anticOut.begin(), anticOut.end(),
398                      generatedExpressions[BB].begin(),
399                      generatedExpressions[BB].end(),
400                      s_ins, ExprLT());
401       
402       anticIn.clear();
403       std::insert_iterator<std::set<Value*, ExprLT> >  antic_ins(anticIn, 
404                                                              anticIn.begin());
405       std::set_difference(S.begin(), S.end(),
406                           generatedTemporaries[BB].begin(),
407                           generatedTemporaries[BB].end(),
408                           antic_ins,
409                           ExprLT());
410       
411       clean(VN, anticIn);
412       
413       if (old != anticIn)
414         changed = true;
415       
416       anticOut.clear();
417     }
418     iterations++;
419   }
420   
421   DOUT << "Iterations: " << iterations << "\n";
422   
423   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
424     DOUT << "Name: " << I->getName().c_str() << "\n";
425     
426     DOUT << "TMP_GEN: ";
427     dump(VN, generatedTemporaries[I]);
428     DOUT << "\n";
429     
430     DOUT << "EXP_GEN: ";
431     dump(VN, generatedExpressions[I]);
432     DOUT << "\n";
433     
434     DOUT << "ANTIC_IN: ";
435     dump(VN, anticipatedIn[I]);
436     DOUT << "\n";
437     
438     DOUT << "AVAIL_OUT: ";
439     dump(VN, availableOut[I]);
440     DOUT << "\n";
441   }
442   
443   return false;
444 }