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"
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
44 /// This class holds the mapping between values and value numbers.
47 class VISIBILITY_HIDDEN ValueTable {
50 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
51 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
52 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
53 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
54 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
55 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
56 FCMPULT, FCMPULE, FCMPUNE };
58 ExpressionOpcode opcode;
62 bool operator< (const Expression& other) const {
63 if (opcode < other.opcode)
65 else if (opcode > other.opcode)
67 else if (leftVN < other.leftVN)
69 else if (leftVN > other.leftVN)
71 else if (rightVN < other.rightVN)
73 else if (rightVN > other.rightVN)
81 std::map<Value*, uint32_t> valueNumbering;
82 std::map<Expression, uint32_t> expressionNumbering;
84 std::set<Expression> maximalExpressions;
85 std::set<Value*> maximalValues;
87 uint32_t nextValueNumber;
89 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
90 Expression::ExpressionOpcode getOpcode(CmpInst* C);
92 ValueTable() { nextValueNumber = 1; }
93 uint32_t lookup_or_add(Value* V);
94 uint32_t lookup(Value* V);
95 void add(Value* V, uint32_t num);
97 std::set<Expression>& getMaximalExpressions() {
98 return maximalExpressions;
101 std::set<Value*>& getMaximalValues() { return maximalValues; }
102 Expression create_expression(BinaryOperator* BO);
103 Expression create_expression(CmpInst* C);
107 ValueTable::Expression::ExpressionOpcode
108 ValueTable::getOpcode(BinaryOperator* BO) {
109 switch(BO->getOpcode()) {
110 case Instruction::Add:
111 return Expression::ADD;
112 case Instruction::Sub:
113 return Expression::SUB;
114 case Instruction::Mul:
115 return Expression::MUL;
116 case Instruction::UDiv:
117 return Expression::UDIV;
118 case Instruction::SDiv:
119 return Expression::SDIV;
120 case Instruction::FDiv:
121 return Expression::FDIV;
122 case Instruction::URem:
123 return Expression::UREM;
124 case Instruction::SRem:
125 return Expression::SREM;
126 case Instruction::FRem:
127 return Expression::FREM;
128 case Instruction::Shl:
129 return Expression::SHL;
130 case Instruction::LShr:
131 return Expression::LSHR;
132 case Instruction::AShr:
133 return Expression::ASHR;
134 case Instruction::And:
135 return Expression::AND;
136 case Instruction::Or:
137 return Expression::OR;
138 case Instruction::Xor:
139 return Expression::XOR;
141 // THIS SHOULD NEVER HAPPEN
143 assert(0 && "Binary operator with unknown opcode?");
144 return Expression::ADD;
148 ValueTable::Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
149 if (C->getOpcode() == Instruction::ICmp) {
150 switch (C->getPredicate()) {
151 case ICmpInst::ICMP_EQ:
152 return Expression::ICMPEQ;
153 case ICmpInst::ICMP_NE:
154 return Expression::ICMPNE;
155 case ICmpInst::ICMP_UGT:
156 return Expression::ICMPUGT;
157 case ICmpInst::ICMP_UGE:
158 return Expression::ICMPUGE;
159 case ICmpInst::ICMP_ULT:
160 return Expression::ICMPULT;
161 case ICmpInst::ICMP_ULE:
162 return Expression::ICMPULE;
163 case ICmpInst::ICMP_SGT:
164 return Expression::ICMPSGT;
165 case ICmpInst::ICMP_SGE:
166 return Expression::ICMPSGE;
167 case ICmpInst::ICMP_SLT:
168 return Expression::ICMPSLT;
169 case ICmpInst::ICMP_SLE:
170 return Expression::ICMPSLE;
172 // THIS SHOULD NEVER HAPPEN
174 assert(0 && "Comparison with unknown predicate?");
175 return Expression::ICMPEQ;
178 switch (C->getPredicate()) {
179 case FCmpInst::FCMP_OEQ:
180 return Expression::FCMPOEQ;
181 case FCmpInst::FCMP_OGT:
182 return Expression::FCMPOGT;
183 case FCmpInst::FCMP_OGE:
184 return Expression::FCMPOGE;
185 case FCmpInst::FCMP_OLT:
186 return Expression::FCMPOLT;
187 case FCmpInst::FCMP_OLE:
188 return Expression::FCMPOLE;
189 case FCmpInst::FCMP_ONE:
190 return Expression::FCMPONE;
191 case FCmpInst::FCMP_ORD:
192 return Expression::FCMPORD;
193 case FCmpInst::FCMP_UNO:
194 return Expression::FCMPUNO;
195 case FCmpInst::FCMP_UEQ:
196 return Expression::FCMPUEQ;
197 case FCmpInst::FCMP_UGT:
198 return Expression::FCMPUGT;
199 case FCmpInst::FCMP_UGE:
200 return Expression::FCMPUGE;
201 case FCmpInst::FCMP_ULT:
202 return Expression::FCMPULT;
203 case FCmpInst::FCMP_ULE:
204 return Expression::FCMPULE;
205 case FCmpInst::FCMP_UNE:
206 return Expression::FCMPUNE;
208 // THIS SHOULD NEVER HAPPEN
210 assert(0 && "Comparison with unknown predicate?");
211 return Expression::FCMPOEQ;
216 uint32_t ValueTable::lookup_or_add(Value* V) {
217 maximalValues.insert(V);
219 std::map<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
220 if (VI != valueNumbering.end())
224 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
225 Expression e = create_expression(BO);
227 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
228 if (EI != expressionNumbering.end()) {
229 valueNumbering.insert(std::make_pair(V, EI->second));
232 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
233 valueNumbering.insert(std::make_pair(V, nextValueNumber));
235 return nextValueNumber++;
237 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
238 Expression e = create_expression(C);
240 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
241 if (EI != expressionNumbering.end()) {
242 valueNumbering.insert(std::make_pair(V, EI->second));
245 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
246 valueNumbering.insert(std::make_pair(V, nextValueNumber));
248 return nextValueNumber++;
251 valueNumbering.insert(std::make_pair(V, nextValueNumber));
252 return nextValueNumber++;
256 uint32_t ValueTable::lookup(Value* V) {
257 std::map<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
258 if (VI != valueNumbering.end())
261 assert(0 && "Value not numbered?");
266 void ValueTable::add(Value* V, uint32_t num) {
267 std::map<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
268 if (VI != valueNumbering.end())
269 valueNumbering.erase(VI);
270 valueNumbering.insert(std::make_pair(V, num));
273 ValueTable::Expression ValueTable::create_expression(BinaryOperator* BO) {
276 e.leftVN = lookup_or_add(BO->getOperand(0));
277 e.rightVN = lookup_or_add(BO->getOperand(1));
278 e.opcode = getOpcode(BO);
280 maximalExpressions.insert(e);
285 ValueTable::Expression ValueTable::create_expression(CmpInst* C) {
288 e.leftVN = lookup_or_add(C->getOperand(0));
289 e.rightVN = lookup_or_add(C->getOperand(1));
290 e.opcode = getOpcode(C);
292 maximalExpressions.insert(e);
297 void ValueTable::clear() {
298 valueNumbering.clear();
299 expressionNumbering.clear();
300 maximalExpressions.clear();
301 maximalValues.clear();
307 class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
308 bool runOnFunction(Function &F);
310 static char ID; // Pass identification, replacement for typeid
311 GVNPRE() : FunctionPass((intptr_t)&ID) { }
315 std::vector<Instruction*> createdExpressions;
317 std::map<BasicBlock*, std::set<Value*> > availableOut;
318 std::map<BasicBlock*, std::set<Value*> > anticipatedIn;
319 std::map<User*, bool> invokeDep;
321 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
322 AU.setPreservesCFG();
323 AU.addRequired<DominatorTree>();
324 AU.addRequired<PostDominatorTree>();
328 // FIXME: eliminate or document these better
329 void dump(const std::set<Value*>& s) const;
330 void dump_unique(const std::set<Value*>& s) const;
331 void clean(std::set<Value*>& set);
332 Value* find_leader(std::set<Value*>& vals,
334 Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ);
335 void phi_translate_set(std::set<Value*>& anticIn, BasicBlock* pred,
336 BasicBlock* succ, std::set<Value*>& out);
338 void topo_sort(std::set<Value*>& set,
339 std::vector<Value*>& vec);
341 // For a given block, calculate the generated expressions, temporaries,
342 // and the AVAIL_OUT set
346 void val_insert(std::set<Value*>& s, Value* v);
347 void val_replace(std::set<Value*>& s, Value* v);
348 bool dependsOnInvoke(Value* V);
356 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
358 RegisterPass<GVNPRE> X("gvnpre",
359 "Global Value Numbering/Partial Redundancy Elimination");
362 STATISTIC(NumInsertedVals, "Number of values inserted");
363 STATISTIC(NumInsertedPhis, "Number of PHI nodes inserted");
364 STATISTIC(NumEliminated, "Number of redundant instructions eliminated");
366 Value* GVNPRE::find_leader(std::set<Value*>& vals, uint32_t v) {
367 for (std::set<Value*>::iterator I = vals.begin(), E = vals.end();
369 if (v == VN.lookup(*I))
375 void GVNPRE::val_insert(std::set<Value*>& s, Value* v) {
376 uint32_t num = VN.lookup(v);
377 Value* leader = find_leader(s, num);
382 void GVNPRE::val_replace(std::set<Value*>& s, Value* v) {
383 uint32_t num = VN.lookup(v);
384 Value* leader = find_leader(s, num);
385 while (leader != 0) {
387 leader = find_leader(s, num);
392 Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
396 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
398 if (isa<Instruction>(BO->getOperand(0)))
399 newOp1 = phi_translate(find_leader(anticipatedIn[succ],
400 VN.lookup(BO->getOperand(0))),
403 newOp1 = BO->getOperand(0);
409 if (isa<Instruction>(BO->getOperand(1)))
410 newOp2 = phi_translate(find_leader(anticipatedIn[succ],
411 VN.lookup(BO->getOperand(1))),
414 newOp2 = BO->getOperand(1);
419 if (newOp1 != BO->getOperand(0) || newOp2 != BO->getOperand(1)) {
420 Instruction* newVal = BinaryOperator::create(BO->getOpcode(),
422 BO->getName()+".gvnpre");
424 uint32_t v = VN.lookup_or_add(newVal);
426 Value* leader = find_leader(availableOut[pred], v);
428 createdExpressions.push_back(newVal);
435 } else if (PHINode* P = dyn_cast<PHINode>(V)) {
436 if (P->getParent() == succ)
437 return P->getIncomingValueForBlock(pred);
438 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
440 if (isa<Instruction>(C->getOperand(0)))
441 newOp1 = phi_translate(find_leader(anticipatedIn[succ],
442 VN.lookup(C->getOperand(0))),
445 newOp1 = C->getOperand(0);
451 if (isa<Instruction>(C->getOperand(1)))
452 newOp2 = phi_translate(find_leader(anticipatedIn[succ],
453 VN.lookup(C->getOperand(1))),
456 newOp2 = C->getOperand(1);
461 if (newOp1 != C->getOperand(0) || newOp2 != C->getOperand(1)) {
462 Instruction* newVal = CmpInst::create(C->getOpcode(),
465 C->getName()+".gvnpre");
467 uint32_t v = VN.lookup_or_add(newVal);
469 Value* leader = find_leader(availableOut[pred], v);
471 createdExpressions.push_back(newVal);
483 void GVNPRE::phi_translate_set(std::set<Value*>& anticIn,
484 BasicBlock* pred, BasicBlock* succ,
485 std::set<Value*>& out) {
486 for (std::set<Value*>::iterator I = anticIn.begin(),
487 E = anticIn.end(); I != E; ++I) {
488 Value* V = phi_translate(*I, pred, succ);
494 bool GVNPRE::dependsOnInvoke(Value* V) {
498 User* U = cast<User>(V);
499 std::map<User*, bool>::iterator I = invokeDep.find(U);
500 if (I != invokeDep.end())
503 std::vector<Value*> worklist(U->op_begin(), U->op_end());
504 std::set<Value*> visited;
506 while (!worklist.empty()) {
507 Value* current = worklist.back();
509 visited.insert(current);
511 if (!isa<User>(current))
513 else if (isa<InvokeInst>(current))
516 User* curr = cast<User>(current);
517 std::map<User*, bool>::iterator CI = invokeDep.find(curr);
518 if (CI != invokeDep.end()) {
522 for (unsigned i = 0; i < curr->getNumOperands(); ++i)
523 if (visited.find(curr->getOperand(i)) == visited.end())
524 worklist.push_back(curr->getOperand(i));
531 // Remove all expressions whose operands are not themselves in the set
532 void GVNPRE::clean(std::set<Value*>& set) {
533 std::vector<Value*> worklist;
534 topo_sort(set, worklist);
536 for (unsigned i = 0; i < worklist.size(); ++i) {
537 Value* v = worklist[i];
539 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(v)) {
540 bool lhsValid = !isa<Instruction>(BO->getOperand(0));
542 for (std::set<Value*>::iterator I = set.begin(), E = set.end();
544 if (VN.lookup(*I) == VN.lookup(BO->getOperand(0))) {
549 // Check for dependency on invoke insts
550 // NOTE: This check is expensive, so don't do it if we
553 lhsValid = !dependsOnInvoke(BO->getOperand(0));
555 bool rhsValid = !isa<Instruction>(BO->getOperand(1));
557 for (std::set<Value*>::iterator I = set.begin(), E = set.end();
559 if (VN.lookup(*I) == VN.lookup(BO->getOperand(1))) {
564 // Check for dependency on invoke insts
565 // NOTE: This check is expensive, so don't do it if we
568 rhsValid = !dependsOnInvoke(BO->getOperand(1));
570 if (!lhsValid || !rhsValid)
572 } else if (CmpInst* C = dyn_cast<CmpInst>(v)) {
573 bool lhsValid = !isa<Instruction>(C->getOperand(0));
575 for (std::set<Value*>::iterator I = set.begin(), E = set.end();
577 if (VN.lookup(*I) == VN.lookup(C->getOperand(0))) {
581 lhsValid &= !dependsOnInvoke(C->getOperand(0));
583 bool rhsValid = !isa<Instruction>(C->getOperand(1));
585 for (std::set<Value*>::iterator I = set.begin(), E = set.end();
587 if (VN.lookup(*I) == VN.lookup(C->getOperand(1))) {
591 rhsValid &= !dependsOnInvoke(C->getOperand(1));
593 if (!lhsValid || !rhsValid)
599 void GVNPRE::topo_sort(std::set<Value*>& set,
600 std::vector<Value*>& vec) {
601 std::set<Value*> toErase;
602 for (std::set<Value*>::iterator I = set.begin(), E = set.end();
604 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(*I))
605 for (std::set<Value*>::iterator SI = set.begin(); SI != E; ++SI) {
606 if (VN.lookup(BO->getOperand(0)) == VN.lookup(*SI) ||
607 VN.lookup(BO->getOperand(1)) == VN.lookup(*SI)) {
611 else if (CmpInst* C = dyn_cast<CmpInst>(*I))
612 for (std::set<Value*>::iterator SI = set.begin(); SI != E; ++SI) {
613 if (VN.lookup(C->getOperand(0)) == VN.lookup(*SI) ||
614 VN.lookup(C->getOperand(1)) == VN.lookup(*SI)) {
620 std::vector<Value*> Q;
621 for (std::set<Value*>::iterator I = set.begin(), E = set.end();
623 if (toErase.find(*I) == toErase.end())
627 std::set<Value*> visited;
631 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(e)) {
632 Value* l = find_leader(set, VN.lookup(BO->getOperand(0)));
633 Value* r = find_leader(set, VN.lookup(BO->getOperand(1)));
635 if (l != 0 && isa<Instruction>(l) &&
636 visited.find(l) == visited.end())
638 else if (r != 0 && isa<Instruction>(r) &&
639 visited.find(r) == visited.end())
646 } else if (CmpInst* C = dyn_cast<CmpInst>(e)) {
647 Value* l = find_leader(set, VN.lookup(C->getOperand(0)));
648 Value* r = find_leader(set, VN.lookup(C->getOperand(1)));
650 if (l != 0 && isa<Instruction>(l) &&
651 visited.find(l) == visited.end())
653 else if (r != 0 && isa<Instruction>(r) &&
654 visited.find(r) == visited.end())
670 void GVNPRE::dump(const std::set<Value*>& s) const {
672 for (std::set<Value*>::iterator I = s.begin(), E = s.end();
679 void GVNPRE::dump_unique(const std::set<Value*>& s) const {
681 for (std::set<Value*>::iterator I = s.begin(), E = s.end();
688 void GVNPRE::elimination() {
689 DOUT << "\n\nPhase 3: Elimination\n\n";
691 std::vector<std::pair<Instruction*, Value*> > replace;
692 std::vector<Instruction*> erase;
694 DominatorTree& DT = getAnalysis<DominatorTree>();
696 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
697 E = df_end(DT.getRootNode()); DI != E; ++DI) {
698 BasicBlock* BB = DI->getBlock();
700 DOUT << "Block: " << BB->getName() << "\n";
701 dump_unique(availableOut[BB]);
704 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
707 if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI)) {
708 Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
711 if (Instruction* Instr = dyn_cast<Instruction>(leader))
712 if (Instr->getParent() != 0 && Instr != BI) {
713 replace.push_back(std::make_pair(BI, leader));
721 while (!replace.empty()) {
722 std::pair<Instruction*, Value*> rep = replace.back();
724 rep.first->replaceAllUsesWith(rep.second);
727 for (std::vector<Instruction*>::iterator I = erase.begin(), E = erase.end();
729 (*I)->eraseFromParent();
733 void GVNPRE::cleanup() {
734 while (!createdExpressions.empty()) {
735 Instruction* I = createdExpressions.back();
736 createdExpressions.pop_back();
742 bool GVNPRE::runOnFunction(Function &F) {
744 createdExpressions.clear();
745 availableOut.clear();
746 anticipatedIn.clear();
749 std::map<BasicBlock*, std::set<Value*> > generatedExpressions;
750 std::map<BasicBlock*, std::set<PHINode*> > generatedPhis;
751 std::map<BasicBlock*, std::set<Value*> > generatedTemporaries;
754 DominatorTree &DT = getAnalysis<DominatorTree>();
756 // Phase 1: BuildSets
758 // Phase 1, Part 1: calculate AVAIL_OUT
760 // Top-down walk of the dominator tree
761 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
762 E = df_end(DT.getRootNode()); DI != E; ++DI) {
764 // Get the sets to update for this block
765 std::set<Value*>& currExps = generatedExpressions[DI->getBlock()];
766 std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()];
767 std::set<Value*>& currTemps = generatedTemporaries[DI->getBlock()];
768 std::set<Value*>& currAvail = availableOut[DI->getBlock()];
770 BasicBlock* BB = DI->getBlock();
772 // A block inherits AVAIL_OUT from its dominator
773 if (DI->getIDom() != 0)
774 currAvail.insert(availableOut[DI->getIDom()->getBlock()].begin(),
775 availableOut[DI->getIDom()->getBlock()].end());
778 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
781 // Handle PHI nodes...
782 if (PHINode* p = dyn_cast<PHINode>(BI)) {
786 // Handle binary ops...
787 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) {
788 Value* leftValue = BO->getOperand(0);
789 Value* rightValue = BO->getOperand(1);
791 VN.lookup_or_add(BO);
793 if (isa<Instruction>(leftValue))
794 val_insert(currExps, leftValue);
795 if (isa<Instruction>(rightValue))
796 val_insert(currExps, rightValue);
797 val_insert(currExps, BO);
800 } else if (CmpInst* C = dyn_cast<CmpInst>(BI)) {
801 Value* leftValue = C->getOperand(0);
802 Value* rightValue = C->getOperand(1);
806 if (isa<Instruction>(leftValue))
807 val_insert(currExps, leftValue);
808 if (isa<Instruction>(rightValue))
809 val_insert(currExps, rightValue);
810 val_insert(currExps, C);
812 // Handle unsupported ops
813 } else if (!BI->isTerminator()){
814 VN.lookup_or_add(BI);
815 currTemps.insert(BI);
818 if (!BI->isTerminator())
819 val_insert(currAvail, BI);
823 DOUT << "Maximal Set: ";
824 dump_unique(VN.getMaximalValues());
827 // If function has no exit blocks, only perform GVN
828 PostDominatorTree &PDT = getAnalysis<PostDominatorTree>();
829 if (PDT[&F.getEntryBlock()] == 0) {
837 // Phase 1, Part 2: calculate ANTIC_IN
839 std::set<BasicBlock*> visited;
842 unsigned iterations = 0;
845 std::set<Value*> anticOut;
847 // Top-down walk of the postdominator tree
848 for (df_iterator<DomTreeNode*> PDI =
849 df_begin(PDT.getRootNode()), E = df_end(PDT.getRootNode());
851 BasicBlock* BB = PDI->getBlock();
855 DOUT << "Block: " << BB->getName() << "\n";
857 dump(generatedTemporaries[BB]);
861 dump_unique(generatedExpressions[BB]);
864 std::set<Value*>& anticIn = anticipatedIn[BB];
865 std::set<Value*> old (anticIn.begin(), anticIn.end());
867 if (BB->getTerminator()->getNumSuccessors() == 1) {
868 if (visited.find(BB->getTerminator()->getSuccessor(0)) ==
870 phi_translate_set(VN.getMaximalValues(), BB,
871 BB->getTerminator()->getSuccessor(0),
874 phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
875 BB, BB->getTerminator()->getSuccessor(0),
877 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
878 BasicBlock* first = BB->getTerminator()->getSuccessor(0);
879 anticOut.insert(anticipatedIn[first].begin(),
880 anticipatedIn[first].end());
881 for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
882 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
883 std::set<Value*>& succAnticIn = anticipatedIn[currSucc];
885 std::set<Value*> temp;
886 std::insert_iterator<std::set<Value*> > temp_ins(temp,
888 std::set_intersection(anticOut.begin(), anticOut.end(),
889 succAnticIn.begin(), succAnticIn.end(),
893 anticOut.insert(temp.begin(), temp.end());
897 DOUT << "ANTIC_OUT: ";
898 dump_unique(anticOut);
902 std::insert_iterator<std::set<Value*> > s_ins(S, S.begin());
903 std::set_difference(anticOut.begin(), anticOut.end(),
904 generatedTemporaries[BB].begin(),
905 generatedTemporaries[BB].end(),
909 std::insert_iterator<std::set<Value*> > ai_ins(anticIn, anticIn.begin());
910 std::set_difference(generatedExpressions[BB].begin(),
911 generatedExpressions[BB].end(),
912 generatedTemporaries[BB].begin(),
913 generatedTemporaries[BB].end(),
916 for (std::set<Value*>::iterator I = S.begin(), E = S.end();
918 if (find_leader(anticIn, VN.lookup(*I)) == 0)
919 val_insert(anticIn, *I);
924 DOUT << "ANTIC_IN: ";
925 dump_unique(anticIn);
928 if (old.size() != anticIn.size())
937 DOUT << "Iterations: " << iterations << "\n";
939 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
940 DOUT << "Name: " << I->getName().c_str() << "\n";
943 dump(generatedTemporaries[I]);
947 dump_unique(generatedExpressions[I]);
950 DOUT << "ANTIC_IN: ";
951 dump_unique(anticipatedIn[I]);
954 DOUT << "AVAIL_OUT: ";
955 dump_unique(availableOut[I]);
960 DOUT<< "\nPhase 2: Insertion\n";
962 std::map<BasicBlock*, std::set<Value*> > new_sets;
963 unsigned i_iterations = 0;
964 bool new_stuff = true;
967 DOUT << "Iteration: " << i_iterations << "\n\n";
968 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
969 E = df_end(DT.getRootNode()); DI != E; ++DI) {
970 BasicBlock* BB = DI->getBlock();
975 std::set<Value*>& new_set = new_sets[BB];
976 std::set<Value*>& availOut = availableOut[BB];
977 std::set<Value*>& anticIn = anticipatedIn[BB];
981 // Replace leaders with leaders inherited from dominator
982 if (DI->getIDom() != 0) {
983 std::set<Value*>& dom_set = new_sets[DI->getIDom()->getBlock()];
984 for (std::set<Value*>::iterator I = dom_set.begin(),
985 E = dom_set.end(); I != E; ++I) {
987 val_replace(availOut, *I);
991 // If there is more than one predecessor...
992 if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
993 std::vector<Value*> workList;
994 topo_sort(anticIn, workList);
996 DOUT << "Merge Block: " << BB->getName() << "\n";
997 DOUT << "ANTIC_IN: ";
998 dump_unique(anticIn);
1001 for (unsigned i = 0; i < workList.size(); ++i) {
1002 Value* e = workList[i];
1004 if (isa<BinaryOperator>(e) || isa<CmpInst>(e)) {
1005 if (find_leader(availableOut[DI->getIDom()->getBlock()], VN.lookup(e)) != 0)
1008 std::map<BasicBlock*, Value*> avail;
1009 bool by_some = false;
1012 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1014 Value *e2 = phi_translate(e, *PI, BB);
1015 Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1018 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1019 if (av != avail.end())
1021 avail.insert(std::make_pair(*PI, e2));
1023 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1024 if (av != avail.end())
1026 avail.insert(std::make_pair(*PI, e3));
1034 num_avail < std::distance(pred_begin(BB), pred_end(BB))) {
1035 DOUT << "Processing Value: ";
1039 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1041 Value* e2 = avail[*PI];
1042 if (!find_leader(availableOut[*PI], VN.lookup(e2))) {
1043 User* U = cast<User>(e2);
1046 if (isa<BinaryOperator>(U->getOperand(0)) ||
1047 isa<CmpInst>(U->getOperand(0)))
1048 s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1050 s1 = U->getOperand(0);
1053 if (isa<BinaryOperator>(U->getOperand(1)) ||
1054 isa<CmpInst>(U->getOperand(1)))
1055 s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1057 s2 = U->getOperand(1);
1060 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1061 newVal = BinaryOperator::create(BO->getOpcode(),
1063 BO->getName()+".gvnpre",
1064 (*PI)->getTerminator());
1065 else if (CmpInst* C = dyn_cast<CmpInst>(U))
1066 newVal = CmpInst::create(C->getOpcode(),
1069 C->getName()+".gvnpre",
1070 (*PI)->getTerminator());
1072 VN.add(newVal, VN.lookup(U));
1074 std::set<Value*>& predAvail = availableOut[*PI];
1075 val_replace(predAvail, newVal);
1077 DOUT << "Creating value: " << std::hex << newVal << std::dec << "\n";
1079 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1080 if (av != avail.end())
1082 avail.insert(std::make_pair(*PI, newVal));
1090 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1093 p = new PHINode(avail[*PI]->getType(), "gvnpre-join",
1096 p->addIncoming(avail[*PI], *PI);
1099 VN.add(p, VN.lookup(e));
1100 DOUT << "Creating value: " << std::hex << p << std::dec << "\n";
1102 val_replace(availOut, p);
1107 DOUT << "Preds After Processing: ";
1108 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1110 DEBUG((*PI)->dump());
1113 DOUT << "Merge Block After Processing: ";
1128 // Phase 3: Eliminate