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 are 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/CFG.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/Debug.h"
41 bool operator()(Value* left, Value* right) {
42 if (!isa<BinaryOperator>(left) || !isa<BinaryOperator>(right))
45 BinaryOperator* BO1 = cast<BinaryOperator>(left);
46 BinaryOperator* BO2 = cast<BinaryOperator>(right);
48 if (BO1->getOpcode() != BO2->getOpcode())
49 return BO1->getOpcode() < BO2->getOpcode();
50 else if ((*this)(BO1->getOperand(0), BO2->getOperand(0)))
52 else if ((*this)(BO2->getOperand(0), BO1->getOperand(0)))
55 return (*this)(BO1->getOperand(1), BO2->getOperand(1));
61 class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
62 bool runOnFunction(Function &F);
64 static char ID; // Pass identification, replacement for typeid
65 GVNPRE() : FunctionPass((intptr_t)&ID) { nextValueNumber = 0; }
68 uint32_t nextValueNumber;
69 typedef std::map<Value*, uint32_t, ExprLT> ValueTable;
71 std::set<Value*, ExprLT> MS;
72 std::set<Instruction*> createdExpressions;
74 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addRequired<DominatorTree>();
77 AU.addRequired<PostDominatorTree>();
81 // FIXME: eliminate or document these better
82 void dump(const std::set<Value*>& s) const;
83 void dump_unique(const std::set<Value*, ExprLT>& s) const;
84 void clean(std::set<Value*, ExprLT>& set);
85 bool add(Value* V, uint32_t number);
86 Value* find_leader(std::set<Value*, ExprLT>& vals,
88 Value* phi_translate(std::set<Value*, ExprLT>& set,
89 Value* V, BasicBlock* pred);
90 void phi_translate_set(std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
91 std::set<Value*, ExprLT>& out);
93 void topo_sort(std::set<Value*, ExprLT>& set,
94 std::vector<Value*>& vec);
96 // For a given block, calculate the generated expressions, temporaries,
97 // and the AVAIL_OUT set
98 void CalculateAvailOut(DomTreeNode* DI,
99 std::set<Value*, ExprLT>& currExps,
100 std::set<PHINode*>& currPhis,
101 std::set<Value*>& currTemps,
102 std::set<Value*, ExprLT>& currAvail,
103 std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut);
111 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
113 RegisterPass<GVNPRE> X("gvnpre",
114 "Global Value Numbering/Partial Redundancy Elimination");
118 bool GVNPRE::add(Value* V, uint32_t number) {
119 std::pair<ValueTable::iterator, bool> ret = VN.insert(std::make_pair(V, number));
120 if (isa<BinaryOperator>(V) || isa<PHINode>(V))
125 Value* GVNPRE::find_leader(std::set<Value*, ExprLT>& vals, Value* v) {
126 for (std::set<Value*, ExprLT>::iterator I = vals.begin(), E = vals.end();
128 assert(VN.find(v) != VN.end() && "Value not numbered?");
129 assert(VN.find(*I) != VN.end() && "Value not numbered?");
137 Value* GVNPRE::phi_translate(std::set<Value*, ExprLT>& set,
138 Value* V, BasicBlock* pred) {
142 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
143 Value* newOp1 = isa<Instruction>(BO->getOperand(0))
145 find_leader(set, BO->getOperand(0)),
151 Value* newOp2 = isa<Instruction>(BO->getOperand(1))
153 find_leader(set, BO->getOperand(1)),
159 if (newOp1 != BO->getOperand(0) || newOp2 != BO->getOperand(1)) {
160 Instruction* newVal = BinaryOperator::create(BO->getOpcode(),
162 BO->getName()+".gvnpre");
164 if (add(newVal, nextValueNumber))
166 if (!find_leader(set, newVal)) {
167 DOUT << "Creating value: " << std::hex << newVal << std::dec << "\n";
168 createdExpressions.insert(newVal);
171 ValueTable::iterator I = VN.find(newVal);
172 if (I->first == newVal)
175 std::set<Value*, ExprLT>::iterator F = MS.find(newVal);
183 } else if (PHINode* P = dyn_cast<PHINode>(V)) {
184 if (P->getParent() == pred->getTerminator()->getSuccessor(0))
185 return P->getIncomingValueForBlock(pred);
191 void GVNPRE::phi_translate_set(std::set<Value*, ExprLT>& anticIn, BasicBlock* B,
192 std::set<Value*, ExprLT>& out) {
193 for (std::set<Value*, ExprLT>::iterator I = anticIn.begin(),
194 E = anticIn.end(); I != E; ++I) {
195 Value* V = phi_translate(anticIn, *I, B);
201 // Remove all expressions whose operands are not themselves in the set
202 void GVNPRE::clean(std::set<Value*, ExprLT>& set) {
203 std::vector<Value*> worklist;
204 topo_sort(set, worklist);
206 for (unsigned i = 0; i < worklist.size(); ++i) {
207 Value* v = worklist[i];
209 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(v)) {
210 bool lhsValid = !isa<Instruction>(BO->getOperand(0));
212 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
214 if (VN[*I] == VN[BO->getOperand(0)]) {
219 bool rhsValid = !isa<Instruction>(BO->getOperand(1));
221 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
223 if (VN[*I] == VN[BO->getOperand(1)]) {
228 if (!lhsValid || !rhsValid)
234 void GVNPRE::topo_sort(std::set<Value*, ExprLT>& set,
235 std::vector<Value*>& vec) {
236 std::set<Value*, ExprLT> toErase;
237 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
239 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(*I))
240 for (std::set<Value*, ExprLT>::iterator SI = set.begin(); SI != E; ++SI) {
241 if (VN[BO->getOperand(0)] == VN[*SI] ||
242 VN[BO->getOperand(1)] == VN[*SI]) {
248 std::vector<Value*> Q;
249 for (std::set<Value*, ExprLT>::iterator I = set.begin(), E = set.end();
251 if (toErase.find(*I) == toErase.end())
255 std::set<Value*> visited;
259 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(e)) {
260 Value* l = find_leader(set, BO->getOperand(0));
261 Value* r = find_leader(set, BO->getOperand(1));
263 if (l != 0 && isa<Instruction>(l) &&
264 visited.find(l) == visited.end())
266 else if (r != 0 && isa<Instruction>(r) &&
267 visited.find(r) == visited.end())
283 void GVNPRE::dump(const std::set<Value*>& s) const {
285 for (std::set<Value*>::iterator I = s.begin(), E = s.end();
292 void GVNPRE::dump_unique(const std::set<Value*, ExprLT>& s) const {
294 for (std::set<Value*>::iterator I = s.begin(), E = s.end();
301 void GVNPRE::CalculateAvailOut(DomTreeNode* DI,
302 std::set<Value*, ExprLT>& currExps,
303 std::set<PHINode*>& currPhis,
304 std::set<Value*>& currTemps,
305 std::set<Value*, ExprLT>& currAvail,
306 std::map<BasicBlock*, std::set<Value*, ExprLT> > availOut) {
308 BasicBlock* BB = DI->getBlock();
310 // A block inherits AVAIL_OUT from its dominator
311 if (DI->getIDom() != 0)
312 currAvail.insert(availOut[DI->getIDom()->getBlock()].begin(),
313 availOut[DI->getIDom()->getBlock()].end());
316 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
319 // Handle PHI nodes...
320 if (PHINode* p = dyn_cast<PHINode>(BI)) {
321 if (add(p, nextValueNumber))
325 // Handle binary ops...
326 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) {
327 Value* leftValue = BO->getOperand(0);
328 Value* rightValue = BO->getOperand(1);
330 if (add(BO, nextValueNumber))
333 if (isa<Instruction>(leftValue))
334 currExps.insert(leftValue);
335 if (isa<Instruction>(rightValue))
336 currExps.insert(rightValue);
339 // Handle unsupported ops
340 } else if (!BI->isTerminator()){
341 if (add(BI, nextValueNumber))
343 currTemps.insert(BI);
346 if (!BI->isTerminator())
347 currAvail.insert(BI);
351 bool GVNPRE::runOnFunction(Function &F) {
354 createdExpressions.clear();
356 std::map<BasicBlock*, std::set<Value*, ExprLT> > generatedExpressions;
357 std::map<BasicBlock*, std::set<PHINode*> > generatedPhis;
358 std::map<BasicBlock*, std::set<Value*> > generatedTemporaries;
359 std::map<BasicBlock*, std::set<Value*, ExprLT> > availableOut;
360 std::map<BasicBlock*, std::set<Value*, ExprLT> > anticipatedIn;
362 DominatorTree &DT = getAnalysis<DominatorTree>();
364 // Phase 1: BuildSets
366 // Phase 1, Part 1: calculate AVAIL_OUT
368 // Top-down walk of the dominator tree
369 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
370 E = df_end(DT.getRootNode()); DI != E; ++DI) {
372 // Get the sets to update for this block
373 std::set<Value*, ExprLT>& currExps = generatedExpressions[DI->getBlock()];
374 std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()];
375 std::set<Value*>& currTemps = generatedTemporaries[DI->getBlock()];
376 std::set<Value*, ExprLT>& currAvail = availableOut[DI->getBlock()];
378 CalculateAvailOut(*DI, currExps, currPhis,
379 currTemps, currAvail, availableOut);
382 DOUT << "Maximal Set: ";
386 PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
388 // Phase 1, Part 2: calculate ANTIC_IN
390 std::set<BasicBlock*> visited;
393 unsigned iterations = 0;
396 std::set<Value*, ExprLT> anticOut;
398 // Top-down walk of the postdominator tree
399 for (df_iterator<DomTreeNode*> PDI =
400 df_begin(PDT.getRootNode()), E = df_end(PDT.getRootNode());
402 BasicBlock* BB = PDI->getBlock();
403 DOUT << "Block: " << BB->getName() << "\n";
405 dump(generatedTemporaries[BB]);
409 dump_unique(generatedExpressions[BB]);
412 std::set<Value*, ExprLT>& anticIn = anticipatedIn[BB];
413 std::set<Value*, ExprLT> old (anticIn.begin(), anticIn.end());
415 if (BB->getTerminator()->getNumSuccessors() == 1) {
416 if (visited.find(BB->getTerminator()->getSuccessor(0)) ==
418 phi_translate_set(MS, BB, anticOut);
421 anticipatedIn[BB->getTerminator()->getSuccessor(0)], BB, anticOut);
422 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
423 BasicBlock* first = BB->getTerminator()->getSuccessor(0);
424 anticOut.insert(anticipatedIn[first].begin(),
425 anticipatedIn[first].end());
426 for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
427 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
428 std::set<Value*, ExprLT>& succAnticIn = anticipatedIn[currSucc];
430 std::set<Value*, ExprLT> temp;
431 std::insert_iterator<std::set<Value*, ExprLT> > temp_ins(temp,
433 std::set_intersection(anticOut.begin(), anticOut.end(),
434 succAnticIn.begin(), succAnticIn.end(),
438 anticOut.insert(temp.begin(), temp.end());
442 DOUT << "ANTIC_OUT: ";
443 dump_unique(anticOut);
446 std::set<Value*, ExprLT> S;
447 std::insert_iterator<std::set<Value*, ExprLT> > s_ins(S, S.begin());
448 std::set_union(anticOut.begin(), anticOut.end(),
449 generatedExpressions[BB].begin(),
450 generatedExpressions[BB].end(),
455 for (std::set<Value*, ExprLT>::iterator I = S.begin(), E = S.end();
457 if (generatedTemporaries[BB].find(*I) == generatedTemporaries[BB].end())
463 DOUT << "ANTIC_IN: ";
464 dump_unique(anticIn);
467 if (old.size() != anticIn.size())
476 DOUT << "Iterations: " << iterations << "\n";
478 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
479 DOUT << "Name: " << I->getName().c_str() << "\n";
482 dump(generatedTemporaries[I]);
486 dump_unique(generatedExpressions[I]);
489 DOUT << "ANTIC_IN: ";
490 dump_unique(anticipatedIn[I]);
493 DOUT << "AVAIL_OUT: ";
494 dump_unique(availableOut[I]);
500 DOUT<< "\nPhase 2: Insertion\n";
502 std::map<BasicBlock*, std::set<Value*, ExprLT> > new_sets;
503 unsigned i_iterations = 0;
504 bool new_stuff = true;
507 DOUT << "Iteration: " << i_iterations << "\n\n";
508 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
509 E = df_end(DT.getRootNode()); DI != E; ++DI) {
510 BasicBlock* BB = DI->getBlock();
512 std::set<Value*, ExprLT>& new_set = new_sets[BB];
513 std::set<Value*, ExprLT>& availOut = availableOut[BB];
514 std::set<Value*, ExprLT>& anticIn = anticipatedIn[BB];
518 // Replace leaders with leaders inherited from dominator
519 if (DI->getIDom() != 0) {
520 std::set<Value*, ExprLT>& dom_set = new_sets[DI->getIDom()->getBlock()];
521 for (std::set<Value*, ExprLT>::iterator I = dom_set.begin(),
522 E = dom_set.end(); I != E; ++I) {
525 Value* val = find_leader(availOut, *I);
528 val = find_leader(availOut, *I);
534 // If there is more than one predecessor...
535 if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
536 std::vector<Value*> workList;
537 topo_sort(anticIn, workList);
539 DOUT << "Merge Block: " << BB->getName() << "\n";
540 DOUT << "ANTIC_IN: ";
541 dump_unique(anticIn);
544 while (!workList.empty()) {
545 Value* e = workList.back();
548 if (isa<BinaryOperator>(e)) {
549 if (find_leader(availableOut[DI->getIDom()->getBlock()], e) != 0)
552 std::map<BasicBlock*, Value*> avail;
553 bool by_some = false;
556 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
558 Value *e2 = phi_translate(anticIn, e, *PI);
559 Value *e3 = find_leader(availableOut[*PI], e2);
562 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
563 if (av != avail.end())
565 avail.insert(std::make_pair(*PI, e2));
567 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
568 if (av != avail.end())
570 avail.insert(std::make_pair(*PI, e3));
578 num_avail < std::distance(pred_begin(BB), pred_end(BB))) {
579 DOUT << "Processing Value: ";
583 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
585 Value* e2 = avail[*PI];
586 if (!find_leader(availableOut[*PI], e2)) {
587 BinaryOperator* BO = cast<BinaryOperator>(e2);
590 if (isa<Instruction>(BO->getOperand(0)))
591 s1 = find_leader(availableOut[*PI], BO->getOperand(0));
593 s1 = BO->getOperand(0);
596 if (isa<Instruction>(BO->getOperand(1)))
597 s2 = find_leader(availableOut[*PI], BO->getOperand(1));
599 s2 = BO->getOperand(1);
601 Value* newVal = BinaryOperator::create(BO->getOpcode(),
603 BO->getName()+".gvnpre",
604 (*PI)->getTerminator());
607 std::set<Value*, ExprLT>& predAvail = availableOut[*PI];
608 Value* val = find_leader(predAvail, newVal);
610 predAvail.erase(val);
611 val = find_leader(predAvail, newVal);
613 predAvail.insert(newVal);
615 DOUT << "Creating value: " << std::hex << newVal << std::dec << "\n";
617 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
618 if (av != avail.end())
620 avail.insert(std::make_pair(*PI, newVal));
626 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
629 p = new PHINode(avail[*PI]->getType(), "gvnpre-join",
632 p->addIncoming(avail[*PI], *PI);
636 DOUT << "Creating value: " << std::hex << p << std::dec << "\n";
638 Value* val = find_leader(availOut, p);
641 val = find_leader(availOut, p);
647 DOUT << "Preds After Processing: ";
648 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
650 DEBUG((*PI)->dump());
653 DOUT << "Merge Block After Processing: ";
666 // Phase 3: Eliminate
667 DOUT << "\n\nPhase 3: Elimination\n\n";
669 std::vector<std::pair<Instruction*, Value*> > replace;
670 std::vector<Instruction*> erase;
672 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
673 E = df_end(DT.getRootNode()); DI != E; ++DI) {
674 BasicBlock* BB = DI->getBlock();
676 DOUT << "Block: " << BB->getName() << "\n";
677 dump_unique(availableOut[BB]);
680 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
683 if (isa<BinaryOperator>(BI)) {
684 Value *leader = find_leader(availableOut[BB], BI);
687 if (Instruction* Instr = dyn_cast<Instruction>(leader))
688 if (Instr->getParent() != 0 && Instr != BI) {
689 replace.push_back(std::make_pair(BI, leader));
696 while (!replace.empty()) {
697 std::pair<Instruction*, Value*> rep = replace.back();
700 rep.first->replaceAllUsesWith(rep.second);
703 for (std::vector<Instruction*>::iterator I = erase.begin(), E = erase.end();
705 (*I)->eraseFromParent();
708 for (std::set<Instruction*>::iterator I = createdExpressions.begin(),
709 E = createdExpressions.end(); I != E; ++I) {