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 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);
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::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);
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 GVNPRE::ValueTable::iterator GVNPRE::lookup(ValueTable& VN, Value* V) {
124 Value* GVNPRE::find_leader(GVNPRE::ValueTable VN,
125 std::set<Value*, ExprLT>& vals,
127 for (std::set<Value*, ExprLT>::iterator I = vals.begin(), E = vals.end();
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);
141 for (std::set<Value*, ExprLT>::iterator I = anticIn.begin(), E = anticIn.end();
143 if (!isa<BinaryOperator>(*I)) {
144 if (PHINode* p = dyn_cast<PHINode>(*I)) {
145 if (p->getParent() == succ)
151 BinaryOperator* BO = cast<BinaryOperator>(*I);
152 Value* lhs = find_leader(VN, anticIn, VN[BO->getOperand(0)]);
156 if (PHINode* p = dyn_cast<PHINode>(lhs))
157 if (p->getParent() == succ) {
158 lhs = p->getIncomingValueForBlock(B);
162 Value* rhs = find_leader(VN, anticIn, VN[BO->getOperand(1)]);
166 if (PHINode* p = dyn_cast<PHINode>(rhs))
167 if (p->getParent() == succ) {
168 rhs = p->getIncomingValueForBlock(B);
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)
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);
190 while (!worklist.empty()) {
191 Value* v = worklist.back();
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();
198 if (VN[*I] == VN[BO->getOperand(0)]);
201 bool rhsValid = false;
202 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
204 if (VN[*I] == VN[BO->getOperand(1)]);
207 if (!lhsValid || !rhsValid)
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();
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]) {
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(),
233 std::set<Value*, ExprLT> visited;
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)]);
241 if (l != 0 && visited.find(l) == visited.end())
243 else if (r != 0 && visited.find(r) == visited.end())
258 void GVNPRE::dump(GVNPRE::ValueTable& VN, std::set<Value*, ExprLT>& s) {
259 std::vector<Value*> sorted;
260 topo_sort(VN, s, sorted);
262 for (std::vector<Value*>::iterator I = sorted.begin(), E = sorted.end();
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) {
277 BasicBlock* BB = DI->getBlock();
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());
285 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
288 // Handle PHI nodes...
289 if (PHINode* p = dyn_cast<PHINode>(BI)) {
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);
300 currExps.insert(leftValue);
301 currExps.insert(rightValue);
304 currTemps.insert(BO);
306 // Handle unsupported ops
307 } else if (!BI->isTerminator()){
309 currTemps.insert(BI);
312 if (!BI->isTerminator())
313 currAvail.insert(BI);
317 bool GVNPRE::runOnFunction(Function &F) {
319 std::set<Value*, ExprLT> maximalSet;
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;
327 DominatorTree &DT = getAnalysis<DominatorTree>();
329 // First Phase of BuildSets - calculate AVAIL_OUT
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) {
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()];
341 CalculateAvailOut(VN, maximalSet, *DI, currExps, currPhis,
342 currTemps, currAvail, availableOut);
345 PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
347 // Second Phase of BuildSets - calculate ANTIC_IN
349 std::set<BasicBlock*> visited;
352 unsigned iterations = 0;
355 std::set<Value*, ExprLT> anticOut;
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());
361 BasicBlock* BB = PDI->getBlock();
365 std::set<Value*, ExprLT>& anticIn = anticipatedIn[BB];
366 std::set<Value*, ExprLT> old (anticIn.begin(), anticIn.end());
368 if (BB->getTerminator()->getNumSuccessors() == 1) {
369 if (visited.find(BB) == visited.end())
370 phi_translate(VN, maximalSet, anticIn, BB, anticOut);
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());
380 temp.insert(anticIn.begin(), anticIn.end());
383 std::insert_iterator<std::set<Value*, ExprLT> > ai_ins(anticIn,
386 std::set_difference(anticipatedIn[currSucc].begin(),
387 anticipatedIn[currSucc].end(),
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(),
403 std::insert_iterator<std::set<Value*, ExprLT> > antic_ins(anticIn,
405 std::set_difference(S.begin(), S.end(),
406 generatedTemporaries[BB].begin(),
407 generatedTemporaries[BB].end(),
421 DOUT << "Iterations: " << iterations << "\n";
423 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
424 DOUT << "Name: " << I->getName().c_str() << "\n";
427 dump(VN, generatedTemporaries[I]);
431 dump(VN, generatedExpressions[I]);
434 DOUT << "ANTIC_IN: ";
435 dump(VN, anticipatedIn[I]);
438 DOUT << "AVAIL_OUT: ";
439 dump(VN, availableOut[I]);