1 //===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
19 //===----------------------------------------------------------------------===//
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"
40 bool operator()(Value* left, Value* right) {
41 if (!isa<BinaryOperator>(left) || !isa<BinaryOperator>(right))
44 BinaryOperator* BO1 = cast<BinaryOperator>(left);
45 BinaryOperator* BO2 = cast<BinaryOperator>(right);
47 if ((*this)(BO1->getOperand(0), BO2->getOperand(0)))
49 else if ((*this)(BO2->getOperand(0), BO1->getOperand(0)))
52 return (*this)(BO1->getOperand(1), BO2->getOperand(1));
58 class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
59 bool runOnFunction(Function &F);
61 static char ID; // Pass identification, replacement for typeid
62 GVNPRE() : FunctionPass((intptr_t)&ID) { nextValueNumber = 0; }
65 uint32_t nextValueNumber;
66 typedef std::map<Value*, uint32_t, ExprLT> ValueTable;
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequired<DominatorTree>();
71 AU.addRequired<PostDominatorTree>();
75 // FIXME: eliminate or document these better
76 void dump(ValueTable& VN, std::set<Value*>& s);
77 void dump_unique(ValueTable& VN, std::set<Value*, ExprLT>& s);
78 void clean(ValueTable VN, std::set<Value*, ExprLT>& set);
79 bool add(ValueTable& VN, std::set<Value*, ExprLT>& MS, 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);
85 void topo_sort(ValueTable& VN, std::set<Value*, ExprLT>& set,
86 std::vector<Value*>& vec);
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::DomTreeNode* DI,
92 std::set<Value*, ExprLT>& currExps,
93 std::set<PHINode*>& currPhis,
94 std::set<Value*>& currTemps,
95 std::set<Value*, ExprLT>& currAvail,
96 std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut);
104 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
106 RegisterPass<GVNPRE> X("gvnpre",
107 "Global Value Numbering/Partial Redundancy Elimination");
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));
115 if (isa<BinaryOperator>(V) || isa<PHINode>(V))
120 Value* GVNPRE::find_leader(GVNPRE::ValueTable VN,
121 std::set<Value*, ExprLT>& vals,
123 for (std::set<Value*, ExprLT>::iterator I = vals.begin(), E = vals.end();
131 void GVNPRE::phi_translate(GVNPRE::ValueTable& VN,
132 std::set<Value*, ExprLT>& MS,
133 std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
134 std::set<Value*, ExprLT>& out) {
135 BasicBlock* succ = B->getTerminator()->getSuccessor(0);
137 for (std::set<Value*, ExprLT>::iterator I = anticIn.begin(), E = anticIn.end();
139 if (!isa<BinaryOperator>(*I)) {
140 if (PHINode* p = dyn_cast<PHINode>(*I)) {
141 if (p->getParent() == succ)
147 BinaryOperator* BO = cast<BinaryOperator>(*I);
148 Value* lhs = find_leader(VN, anticIn, VN[BO->getOperand(0)]);
152 if (PHINode* p = dyn_cast<PHINode>(lhs))
153 if (p->getParent() == succ) {
154 lhs = p->getIncomingValueForBlock(B);
158 Value* rhs = find_leader(VN, anticIn, VN[BO->getOperand(1)]);
162 if (PHINode* p = dyn_cast<PHINode>(rhs))
163 if (p->getParent() == succ) {
164 rhs = p->getIncomingValueForBlock(B);
168 if (lhs != BO->getOperand(0) || rhs != BO->getOperand(1)) {
169 BO = BinaryOperator::create(BO->getOpcode(), lhs, rhs, BO->getName()+".gvnpre");
170 if (VN.insert(std::make_pair(BO, nextValueNumber)).second)
181 // Remove all expressions whose operands are not themselves in the set
182 void GVNPRE::clean(GVNPRE::ValueTable VN, std::set<Value*, ExprLT>& set) {
183 std::vector<Value*> worklist;
184 topo_sort(VN, set, worklist);
186 while (!worklist.empty()) {
187 Value* v = worklist.back();
190 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(v)) {
191 bool lhsValid = false;
192 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
194 if (VN[*I] == VN[BO->getOperand(0)]);
197 bool rhsValid = false;
198 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
200 if (VN[*I] == VN[BO->getOperand(1)]);
203 if (!lhsValid || !rhsValid)
209 void GVNPRE::topo_sort(GVNPRE::ValueTable& VN,
210 std::set<Value*, ExprLT>& set,
211 std::vector<Value*>& vec) {
212 std::set<Value*, ExprLT> toErase;
213 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
215 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(*I))
216 for (std::set<Value*, ExprLT>::iterator SI = set.begin(); SI != E; ++SI) {
217 if (VN[BO->getOperand(0)] == VN[*SI] || VN[BO->getOperand(1)] == VN[*SI]) {
223 std::vector<Value*> Q;
224 std::insert_iterator<std::vector<Value*> > q_ins(Q, Q.begin());
225 std::set_difference(set.begin(), set.end(),
226 toErase.begin(), toErase.end(),
229 std::set<Value*, ExprLT> visited;
233 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(e)) {
234 Value* l = find_leader(VN, set, VN[BO->getOperand(0)]);
235 Value* r = find_leader(VN, set, VN[BO->getOperand(1)]);
237 if (l != 0 && visited.find(l) == visited.end())
239 else if (r != 0 && visited.find(r) == visited.end())
255 void GVNPRE::dump(GVNPRE::ValueTable& VN, std::set<Value*>& s) {
257 for (std::set<Value*>::iterator I = s.begin(), E = s.end();
264 void GVNPRE::dump_unique(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& s) {
266 for (std::set<Value*>::iterator I = s.begin(), E = s.end();
273 void GVNPRE::CalculateAvailOut(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& MS,
274 DominatorTree::DomTreeNode* DI,
275 std::set<Value*, ExprLT>& currExps,
276 std::set<PHINode*>& currPhis,
277 std::set<Value*>& currTemps,
278 std::set<Value*, ExprLT>& currAvail,
279 std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut) {
281 BasicBlock* BB = DI->getBlock();
283 // A block inherits AVAIL_OUT from its dominator
284 if (DI->getIDom() != 0)
285 currAvail.insert(availOut[DI->getIDom()->getBlock()].begin(),
286 availOut[DI->getIDom()->getBlock()].end());
289 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
292 // Handle PHI nodes...
293 if (PHINode* p = dyn_cast<PHINode>(BI)) {
297 // Handle binary ops...
298 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) {
299 Value* leftValue = BO->getOperand(0);
300 Value* rightValue = BO->getOperand(1);
304 currExps.insert(leftValue);
305 currExps.insert(rightValue);
308 currTemps.insert(BO);
310 // Handle unsupported ops
311 } else if (!BI->isTerminator()){
313 currTemps.insert(BI);
316 if (!BI->isTerminator())
317 currAvail.insert(BI);
321 bool GVNPRE::runOnFunction(Function &F) {
323 std::set<Value*, ExprLT> maximalSet;
325 std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedExpressions;
326 std::map<BasicBlock*, std::set<PHINode*> > generatedPhis;
327 std::map<BasicBlock*, std::set<Value*> > generatedTemporaries;
328 std::map<BasicBlock*, std::set<Value*, ExprLT> > availableOut;
329 std::map<BasicBlock*, std::set<Value*, ExprLT> > anticipatedIn;
331 DominatorTree &DT = getAnalysis<DominatorTree>();
333 // First Phase of BuildSets - calculate AVAIL_OUT
335 // Top-down walk of the dominator tree
336 for (df_iterator<DominatorTree::DomTreeNode*> DI = df_begin(DT.getRootNode()),
337 E = df_end(DT.getRootNode()); DI != E; ++DI) {
339 // Get the sets to update for this block
340 std::set<Value*, ExprLT>& currExps = generatedExpressions[DI->getBlock()];
341 std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()];
342 std::set<Value*>& currTemps = generatedTemporaries[DI->getBlock()];
343 std::set<Value*, ExprLT>& currAvail = availableOut[DI->getBlock()];
345 CalculateAvailOut(VN, maximalSet, *DI, currExps, currPhis,
346 currTemps, currAvail, availableOut);
349 PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
351 // Second Phase of BuildSets - calculate ANTIC_IN
353 std::set<BasicBlock*> visited;
356 unsigned iterations = 0;
359 std::set<Value*, ExprLT> anticOut;
361 // Top-down walk of the postdominator tree
362 for (df_iterator<PostDominatorTree::DomTreeNode*> PDI =
363 df_begin(PDT.getRootNode()), E = df_end(DT.getRootNode());
365 BasicBlock* BB = PDI->getBlock();
369 std::set<Value*, ExprLT>& anticIn = anticipatedIn[BB];
370 std::set<Value*, ExprLT> old (anticIn.begin(), anticIn.end());
372 if (BB->getTerminator()->getNumSuccessors() == 1) {
373 if (visited.find(BB) == visited.end())
374 phi_translate(VN, maximalSet, anticIn, BB, anticOut);
376 phi_translate(VN, anticIn, anticIn, BB, anticOut);
377 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
378 for (unsigned i = 0; i < BB->getTerminator()->getNumSuccessors(); ++i) {
379 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
380 std::set<Value*, ExprLT> temp;
381 if (visited.find(currSucc) == visited.end())
382 temp.insert(maximalSet.begin(), maximalSet.end());
384 temp.insert(anticIn.begin(), anticIn.end());
387 std::insert_iterator<std::set<Value*, ExprLT> > ai_ins(anticIn,
390 std::set_difference(anticipatedIn[currSucc].begin(),
391 anticipatedIn[currSucc].end(),
399 std::set<Value*, ExprLT> S;
400 std::insert_iterator<std::set<Value*, ExprLT> > s_ins(S, S.begin());
401 std::set_union(anticOut.begin(), anticOut.end(),
402 generatedExpressions[BB].begin(),
403 generatedExpressions[BB].end(),
407 std::insert_iterator<std::set<Value*, ExprLT> > antic_ins(anticIn,
409 std::set_difference(S.begin(), S.end(),
410 generatedTemporaries[BB].begin(),
411 generatedTemporaries[BB].end(),
425 DOUT << "Iterations: " << iterations << "\n";
427 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
428 DOUT << "Name: " << I->getName().c_str() << "\n";
431 dump(VN, generatedTemporaries[I]);
435 dump_unique(VN, generatedExpressions[I]);
438 DOUT << "ANTIC_IN: ";
439 dump_unique(VN, anticipatedIn[I]);
442 DOUT << "AVAIL_OUT: ";
443 dump_unique(VN, availableOut[I]);