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*, 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 Value* find_leader(ValueTable VN, std::set<Value*, ExprLT>& vals, uint32_t v);
80 void phi_translate(ValueTable& VN, std::set<Value*, ExprLT>& MS,
81 std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
82 std::set<Value*, ExprLT>& out);
84 void topo_sort(ValueTable& VN, std::set<Value*, ExprLT>& set,
85 std::vector<Value*>& vec);
87 // For a given block, calculate the generated expressions, temporaries,
88 // and the AVAIL_OUT set
89 void CalculateAvailOut(ValueTable& VN, std::set<Value*, ExprLT>& MS,
90 DominatorTree::Node* DI,
91 std::set<Value*, ExprLT>& currExps,
92 std::set<PHINode*>& currPhis,
93 std::set<Value*, ExprLT>& currTemps,
94 std::set<Value*, ExprLT>& currAvail,
95 std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut);
103 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
105 RegisterPass<GVNPRE> X("gvnpre",
106 "Global Value Numbering/Partial Redundancy Elimination");
110 bool GVNPRE::add(ValueTable& VN, std::set<Value*, ExprLT>& MS, Value* V) {
111 std::pair<ValueTable::iterator, bool> ret = VN.insert(std::make_pair(V, nextValueNumber));
114 if (isa<BinaryOperator>(V) || isa<PHINode>(V))
119 Value* GVNPRE::find_leader(GVNPRE::ValueTable VN,
120 std::set<Value*, ExprLT>& vals,
122 for (std::set<Value*, ExprLT>::iterator I = vals.begin(), E = vals.end();
130 void GVNPRE::phi_translate(GVNPRE::ValueTable& VN,
131 std::set<Value*, ExprLT>& MS,
132 std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
133 std::set<Value*, ExprLT>& out) {
134 BasicBlock* succ = B->getTerminator()->getSuccessor(0);
136 for (std::set<Value*, ExprLT>::iterator I = anticIn.begin(), E = anticIn.end();
138 if (!isa<BinaryOperator>(*I)) {
139 if (PHINode* p = dyn_cast<PHINode>(*I)) {
140 if (p->getParent() == succ)
146 BinaryOperator* BO = cast<BinaryOperator>(*I);
147 Value* lhs = find_leader(VN, anticIn, VN[BO->getOperand(0)]);
151 if (PHINode* p = dyn_cast<PHINode>(lhs))
152 if (p->getParent() == succ) {
153 lhs = p->getIncomingValueForBlock(B);
157 Value* rhs = find_leader(VN, anticIn, VN[BO->getOperand(1)]);
161 if (PHINode* p = dyn_cast<PHINode>(rhs))
162 if (p->getParent() == succ) {
163 rhs = p->getIncomingValueForBlock(B);
167 if (lhs != BO->getOperand(0) || rhs != BO->getOperand(1)) {
168 BO = BinaryOperator::create(BO->getOpcode(), lhs, rhs, BO->getName()+".gvnpre");
169 if (VN.insert(std::make_pair(BO, nextValueNumber)).second)
180 // Remove all expressions whose operands are not themselves in the set
181 void GVNPRE::clean(GVNPRE::ValueTable VN, std::set<Value*, ExprLT>& set) {
182 std::vector<Value*> worklist;
183 topo_sort(VN, set, worklist);
185 while (!worklist.empty()) {
186 Value* v = worklist.back();
189 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(v)) {
190 bool lhsValid = false;
191 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
193 if (VN[*I] == VN[BO->getOperand(0)]);
196 bool rhsValid = false;
197 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
199 if (VN[*I] == VN[BO->getOperand(1)]);
202 if (!lhsValid || !rhsValid)
208 void GVNPRE::topo_sort(GVNPRE::ValueTable& VN,
209 std::set<Value*, ExprLT>& set,
210 std::vector<Value*>& vec) {
211 std::set<Value*, ExprLT> toErase;
212 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
214 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(*I))
215 for (std::set<Value*, ExprLT>::iterator SI = set.begin(); SI != E; ++SI) {
216 if (VN[BO->getOperand(0)] == VN[*SI] || VN[BO->getOperand(1)] == VN[*SI]) {
222 std::vector<Value*> Q;
223 std::insert_iterator<std::vector<Value*> > q_ins(Q, Q.begin());
224 std::set_difference(set.begin(), set.end(),
225 toErase.begin(), toErase.end(),
228 std::set<Value*, ExprLT> visited;
232 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(e)) {
233 Value* l = find_leader(VN, set, VN[BO->getOperand(0)]);
234 Value* r = find_leader(VN, set, VN[BO->getOperand(1)]);
236 if (l != 0 && visited.find(l) == visited.end())
238 else if (r != 0 && visited.find(r) == visited.end())
253 void GVNPRE::dump(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& s) {
254 std::vector<Value*> sorted;
255 topo_sort(VN, s, sorted);
257 for (std::vector<Value*>::iterator I = sorted.begin(), E = sorted.end();
264 void GVNPRE::CalculateAvailOut(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& MS,
265 DominatorTree::Node* DI,
266 std::set<Value*, ExprLT>& currExps,
267 std::set<PHINode*>& currPhis,
268 std::set<Value*, ExprLT>& currTemps,
269 std::set<Value*, ExprLT>& currAvail,
270 std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut) {
272 BasicBlock* BB = DI->getBlock();
274 // A block inherits AVAIL_OUT from its dominator
275 if (DI->getIDom() != 0)
276 currAvail.insert(availOut[DI->getIDom()->getBlock()].begin(),
277 availOut[DI->getIDom()->getBlock()].end());
280 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
283 // Handle PHI nodes...
284 if (PHINode* p = dyn_cast<PHINode>(BI)) {
288 // Handle binary ops...
289 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) {
290 Value* leftValue = BO->getOperand(0);
291 Value* rightValue = BO->getOperand(1);
295 currExps.insert(leftValue);
296 currExps.insert(rightValue);
299 currTemps.insert(BO);
301 // Handle unsupported ops
302 } else if (!BI->isTerminator()){
304 currTemps.insert(BI);
307 if (!BI->isTerminator())
308 currAvail.insert(BI);
312 bool GVNPRE::runOnFunction(Function &F) {
314 std::set<Value*, ExprLT> maximalSet;
316 std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedExpressions;
317 std::map<BasicBlock*, std::set<PHINode*> > generatedPhis;
318 std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedTemporaries;
319 std::map<BasicBlock*, std::set<Value*, ExprLT> > availableOut;
320 std::map<BasicBlock*, std::set<Value*, ExprLT> > anticipatedIn;
322 DominatorTree &DT = getAnalysis<DominatorTree>();
324 // First Phase of BuildSets - calculate AVAIL_OUT
326 // Top-down walk of the dominator tree
327 for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()),
328 E = df_end(DT.getRootNode()); DI != E; ++DI) {
330 // Get the sets to update for this block
331 std::set<Value*, ExprLT>& currExps = generatedExpressions[DI->getBlock()];
332 std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()];
333 std::set<Value*, ExprLT>& currTemps = generatedTemporaries[DI->getBlock()];
334 std::set<Value*, ExprLT>& currAvail = availableOut[DI->getBlock()];
336 CalculateAvailOut(VN, maximalSet, *DI, currExps, currPhis,
337 currTemps, currAvail, availableOut);
340 PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
342 // Second Phase of BuildSets - calculate ANTIC_IN
344 std::set<BasicBlock*> visited;
347 unsigned iterations = 0;
350 std::set<Value*, ExprLT> anticOut;
352 // Top-down walk of the postdominator tree
353 for (df_iterator<PostDominatorTree::Node*> PDI =
354 df_begin(PDT.getRootNode()), E = df_end(DT.getRootNode());
356 BasicBlock* BB = PDI->getBlock();
360 std::set<Value*, ExprLT>& anticIn = anticipatedIn[BB];
361 std::set<Value*, ExprLT> old (anticIn.begin(), anticIn.end());
363 if (BB->getTerminator()->getNumSuccessors() == 1) {
364 if (visited.find(BB) == visited.end())
365 phi_translate(VN, maximalSet, anticIn, BB, anticOut);
367 phi_translate(VN, anticIn, anticIn, BB, anticOut);
368 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
369 for (unsigned i = 0; i < BB->getTerminator()->getNumSuccessors(); ++i) {
370 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
371 std::set<Value*, ExprLT> temp;
372 if (visited.find(currSucc) == visited.end())
373 temp.insert(maximalSet.begin(), maximalSet.end());
375 temp.insert(anticIn.begin(), anticIn.end());
378 std::insert_iterator<std::set<Value*, ExprLT> > ai_ins(anticIn,
381 std::set_difference(anticipatedIn[currSucc].begin(),
382 anticipatedIn[currSucc].end(),
390 std::set<Value*, ExprLT> S;
391 std::insert_iterator<std::set<Value*, ExprLT> > s_ins(S, S.begin());
392 std::set_union(anticOut.begin(), anticOut.end(),
393 generatedExpressions[BB].begin(),
394 generatedExpressions[BB].end(),
398 std::insert_iterator<std::set<Value*, ExprLT> > antic_ins(anticIn,
400 std::set_difference(S.begin(), S.end(),
401 generatedTemporaries[BB].begin(),
402 generatedTemporaries[BB].end(),
416 DOUT << "Iterations: " << iterations << "\n";
418 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
419 DOUT << "Name: " << I->getName().c_str() << "\n";
422 dump(VN, generatedTemporaries[I]);
426 dump(VN, generatedExpressions[I]);
429 DOUT << "ANTIC_IN: ";
430 dump(VN, anticipatedIn[I]);
433 DOUT << "AVAIL_OUT: ";
434 dump(VN, availableOut[I]);