1 //===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/DerivedTypes.h"
27 #include "llvm/Analysis/Dominators.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/PostOrderIterator.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
50 /// This class holds the mapping between values and value numbers. It is used
51 /// as an efficient mechanism to determine the expression-wise equivalence of
55 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
56 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
57 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
58 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
59 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
60 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
61 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
62 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
63 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
64 PTRTOINT, INTTOPTR, BITCAST, GEP, EMPTY,
67 ExpressionOpcode opcode;
72 SmallVector<uint32_t, 4> varargs;
75 explicit Expression(ExpressionOpcode o) : opcode(o) { }
77 bool operator==(const Expression &other) const {
78 if (opcode != other.opcode)
80 else if (opcode == EMPTY || opcode == TOMBSTONE)
82 else if (type != other.type)
84 else if (firstVN != other.firstVN)
86 else if (secondVN != other.secondVN)
88 else if (thirdVN != other.thirdVN)
91 if (varargs.size() != other.varargs.size())
94 for (size_t i = 0; i < varargs.size(); ++i)
95 if (varargs[i] != other.varargs[i])
102 bool operator!=(const Expression &other) const {
103 if (opcode != other.opcode)
105 else if (opcode == EMPTY || opcode == TOMBSTONE)
107 else if (type != other.type)
109 else if (firstVN != other.firstVN)
111 else if (secondVN != other.secondVN)
113 else if (thirdVN != other.thirdVN)
116 if (varargs.size() != other.varargs.size())
119 for (size_t i = 0; i < varargs.size(); ++i)
120 if (varargs[i] != other.varargs[i])
131 class VISIBILITY_HIDDEN ValueTable {
133 DenseMap<Value*, uint32_t> valueNumbering;
134 DenseMap<Expression, uint32_t> expressionNumbering;
136 uint32_t nextValueNumber;
138 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
139 Expression::ExpressionOpcode getOpcode(CmpInst* C);
140 Expression::ExpressionOpcode getOpcode(CastInst* C);
141 Expression create_expression(BinaryOperator* BO);
142 Expression create_expression(CmpInst* C);
143 Expression create_expression(ShuffleVectorInst* V);
144 Expression create_expression(ExtractElementInst* C);
145 Expression create_expression(InsertElementInst* V);
146 Expression create_expression(SelectInst* V);
147 Expression create_expression(CastInst* C);
148 Expression create_expression(GetElementPtrInst* G);
150 ValueTable() { nextValueNumber = 1; }
151 uint32_t lookup_or_add(Value* V);
152 uint32_t lookup(Value* V) const;
153 void add(Value* V, uint32_t num);
155 void erase(Value* v);
161 template <> struct DenseMapInfo<Expression> {
162 static inline Expression getEmptyKey() {
163 return Expression(Expression::EMPTY);
166 static inline Expression getTombstoneKey() {
167 return Expression(Expression::TOMBSTONE);
170 static unsigned getHashValue(const Expression e) {
171 unsigned hash = e.opcode;
173 hash = e.firstVN + hash * 37;
174 hash = e.secondVN + hash * 37;
175 hash = e.thirdVN + hash * 37;
177 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
178 (unsigned)((uintptr_t)e.type >> 9)) +
181 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
182 E = e.varargs.end(); I != E; ++I)
183 hash = *I + hash * 37;
187 static bool isEqual(const Expression &LHS, const Expression &RHS) {
190 static bool isPod() { return true; }
194 //===----------------------------------------------------------------------===//
195 // ValueTable Internal Functions
196 //===----------------------------------------------------------------------===//
197 Expression::ExpressionOpcode
198 ValueTable::getOpcode(BinaryOperator* BO) {
199 switch(BO->getOpcode()) {
200 case Instruction::Add:
201 return Expression::ADD;
202 case Instruction::Sub:
203 return Expression::SUB;
204 case Instruction::Mul:
205 return Expression::MUL;
206 case Instruction::UDiv:
207 return Expression::UDIV;
208 case Instruction::SDiv:
209 return Expression::SDIV;
210 case Instruction::FDiv:
211 return Expression::FDIV;
212 case Instruction::URem:
213 return Expression::UREM;
214 case Instruction::SRem:
215 return Expression::SREM;
216 case Instruction::FRem:
217 return Expression::FREM;
218 case Instruction::Shl:
219 return Expression::SHL;
220 case Instruction::LShr:
221 return Expression::LSHR;
222 case Instruction::AShr:
223 return Expression::ASHR;
224 case Instruction::And:
225 return Expression::AND;
226 case Instruction::Or:
227 return Expression::OR;
228 case Instruction::Xor:
229 return Expression::XOR;
231 // THIS SHOULD NEVER HAPPEN
233 assert(0 && "Binary operator with unknown opcode?");
234 return Expression::ADD;
238 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
239 if (C->getOpcode() == Instruction::ICmp) {
240 switch (C->getPredicate()) {
241 case ICmpInst::ICMP_EQ:
242 return Expression::ICMPEQ;
243 case ICmpInst::ICMP_NE:
244 return Expression::ICMPNE;
245 case ICmpInst::ICMP_UGT:
246 return Expression::ICMPUGT;
247 case ICmpInst::ICMP_UGE:
248 return Expression::ICMPUGE;
249 case ICmpInst::ICMP_ULT:
250 return Expression::ICMPULT;
251 case ICmpInst::ICMP_ULE:
252 return Expression::ICMPULE;
253 case ICmpInst::ICMP_SGT:
254 return Expression::ICMPSGT;
255 case ICmpInst::ICMP_SGE:
256 return Expression::ICMPSGE;
257 case ICmpInst::ICMP_SLT:
258 return Expression::ICMPSLT;
259 case ICmpInst::ICMP_SLE:
260 return Expression::ICMPSLE;
262 // THIS SHOULD NEVER HAPPEN
264 assert(0 && "Comparison with unknown predicate?");
265 return Expression::ICMPEQ;
268 switch (C->getPredicate()) {
269 case FCmpInst::FCMP_OEQ:
270 return Expression::FCMPOEQ;
271 case FCmpInst::FCMP_OGT:
272 return Expression::FCMPOGT;
273 case FCmpInst::FCMP_OGE:
274 return Expression::FCMPOGE;
275 case FCmpInst::FCMP_OLT:
276 return Expression::FCMPOLT;
277 case FCmpInst::FCMP_OLE:
278 return Expression::FCMPOLE;
279 case FCmpInst::FCMP_ONE:
280 return Expression::FCMPONE;
281 case FCmpInst::FCMP_ORD:
282 return Expression::FCMPORD;
283 case FCmpInst::FCMP_UNO:
284 return Expression::FCMPUNO;
285 case FCmpInst::FCMP_UEQ:
286 return Expression::FCMPUEQ;
287 case FCmpInst::FCMP_UGT:
288 return Expression::FCMPUGT;
289 case FCmpInst::FCMP_UGE:
290 return Expression::FCMPUGE;
291 case FCmpInst::FCMP_ULT:
292 return Expression::FCMPULT;
293 case FCmpInst::FCMP_ULE:
294 return Expression::FCMPULE;
295 case FCmpInst::FCMP_UNE:
296 return Expression::FCMPUNE;
298 // THIS SHOULD NEVER HAPPEN
300 assert(0 && "Comparison with unknown predicate?");
301 return Expression::FCMPOEQ;
306 Expression::ExpressionOpcode
307 ValueTable::getOpcode(CastInst* C) {
308 switch(C->getOpcode()) {
309 case Instruction::Trunc:
310 return Expression::TRUNC;
311 case Instruction::ZExt:
312 return Expression::ZEXT;
313 case Instruction::SExt:
314 return Expression::SEXT;
315 case Instruction::FPToUI:
316 return Expression::FPTOUI;
317 case Instruction::FPToSI:
318 return Expression::FPTOSI;
319 case Instruction::UIToFP:
320 return Expression::UITOFP;
321 case Instruction::SIToFP:
322 return Expression::SITOFP;
323 case Instruction::FPTrunc:
324 return Expression::FPTRUNC;
325 case Instruction::FPExt:
326 return Expression::FPEXT;
327 case Instruction::PtrToInt:
328 return Expression::PTRTOINT;
329 case Instruction::IntToPtr:
330 return Expression::INTTOPTR;
331 case Instruction::BitCast:
332 return Expression::BITCAST;
334 // THIS SHOULD NEVER HAPPEN
336 assert(0 && "Cast operator with unknown opcode?");
337 return Expression::BITCAST;
341 Expression ValueTable::create_expression(BinaryOperator* BO) {
344 e.firstVN = lookup_or_add(BO->getOperand(0));
345 e.secondVN = lookup_or_add(BO->getOperand(1));
347 e.type = BO->getType();
348 e.opcode = getOpcode(BO);
353 Expression ValueTable::create_expression(CmpInst* C) {
356 e.firstVN = lookup_or_add(C->getOperand(0));
357 e.secondVN = lookup_or_add(C->getOperand(1));
359 e.type = C->getType();
360 e.opcode = getOpcode(C);
365 Expression ValueTable::create_expression(CastInst* C) {
368 e.firstVN = lookup_or_add(C->getOperand(0));
371 e.type = C->getType();
372 e.opcode = getOpcode(C);
377 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
380 e.firstVN = lookup_or_add(S->getOperand(0));
381 e.secondVN = lookup_or_add(S->getOperand(1));
382 e.thirdVN = lookup_or_add(S->getOperand(2));
383 e.type = S->getType();
384 e.opcode = Expression::SHUFFLE;
389 Expression ValueTable::create_expression(ExtractElementInst* E) {
392 e.firstVN = lookup_or_add(E->getOperand(0));
393 e.secondVN = lookup_or_add(E->getOperand(1));
395 e.type = E->getType();
396 e.opcode = Expression::EXTRACT;
401 Expression ValueTable::create_expression(InsertElementInst* I) {
404 e.firstVN = lookup_or_add(I->getOperand(0));
405 e.secondVN = lookup_or_add(I->getOperand(1));
406 e.thirdVN = lookup_or_add(I->getOperand(2));
407 e.type = I->getType();
408 e.opcode = Expression::INSERT;
413 Expression ValueTable::create_expression(SelectInst* I) {
416 e.firstVN = lookup_or_add(I->getCondition());
417 e.secondVN = lookup_or_add(I->getTrueValue());
418 e.thirdVN = lookup_or_add(I->getFalseValue());
419 e.type = I->getType();
420 e.opcode = Expression::SELECT;
425 Expression ValueTable::create_expression(GetElementPtrInst* G) {
428 e.firstVN = lookup_or_add(G->getPointerOperand());
431 e.type = G->getType();
432 e.opcode = Expression::GEP;
434 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
436 e.varargs.push_back(lookup_or_add(*I));
441 //===----------------------------------------------------------------------===//
442 // ValueTable External Functions
443 //===----------------------------------------------------------------------===//
445 /// lookup_or_add - Returns the value number for the specified value, assigning
446 /// it a new number if it did not have one before.
447 uint32_t ValueTable::lookup_or_add(Value* V) {
448 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
449 if (VI != valueNumbering.end())
453 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
454 Expression e = create_expression(BO);
456 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
457 if (EI != expressionNumbering.end()) {
458 valueNumbering.insert(std::make_pair(V, EI->second));
461 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
462 valueNumbering.insert(std::make_pair(V, nextValueNumber));
464 return nextValueNumber++;
466 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
467 Expression e = create_expression(C);
469 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
470 if (EI != expressionNumbering.end()) {
471 valueNumbering.insert(std::make_pair(V, EI->second));
474 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
475 valueNumbering.insert(std::make_pair(V, nextValueNumber));
477 return nextValueNumber++;
479 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
480 Expression e = create_expression(U);
482 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
483 if (EI != expressionNumbering.end()) {
484 valueNumbering.insert(std::make_pair(V, EI->second));
487 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
488 valueNumbering.insert(std::make_pair(V, nextValueNumber));
490 return nextValueNumber++;
492 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
493 Expression e = create_expression(U);
495 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
496 if (EI != expressionNumbering.end()) {
497 valueNumbering.insert(std::make_pair(V, EI->second));
500 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
501 valueNumbering.insert(std::make_pair(V, nextValueNumber));
503 return nextValueNumber++;
505 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
506 Expression e = create_expression(U);
508 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
509 if (EI != expressionNumbering.end()) {
510 valueNumbering.insert(std::make_pair(V, EI->second));
513 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
514 valueNumbering.insert(std::make_pair(V, nextValueNumber));
516 return nextValueNumber++;
518 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
519 Expression e = create_expression(U);
521 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
522 if (EI != expressionNumbering.end()) {
523 valueNumbering.insert(std::make_pair(V, EI->second));
526 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
527 valueNumbering.insert(std::make_pair(V, nextValueNumber));
529 return nextValueNumber++;
531 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
532 Expression e = create_expression(U);
534 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
535 if (EI != expressionNumbering.end()) {
536 valueNumbering.insert(std::make_pair(V, EI->second));
539 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
540 valueNumbering.insert(std::make_pair(V, nextValueNumber));
542 return nextValueNumber++;
544 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
545 Expression e = create_expression(U);
547 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
548 if (EI != expressionNumbering.end()) {
549 valueNumbering.insert(std::make_pair(V, EI->second));
552 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
553 valueNumbering.insert(std::make_pair(V, nextValueNumber));
555 return nextValueNumber++;
558 valueNumbering.insert(std::make_pair(V, nextValueNumber));
559 return nextValueNumber++;
563 /// lookup - Returns the value number of the specified value. Fails if
564 /// the value has not yet been numbered.
565 uint32_t ValueTable::lookup(Value* V) const {
566 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
567 if (VI != valueNumbering.end())
570 assert(0 && "Value not numbered?");
575 /// add - Add the specified value with the given value number, removing
576 /// its old number, if any
577 void ValueTable::add(Value* V, uint32_t num) {
578 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
579 if (VI != valueNumbering.end())
580 valueNumbering.erase(VI);
581 valueNumbering.insert(std::make_pair(V, num));
584 /// clear - Remove all entries from the ValueTable
585 void ValueTable::clear() {
586 valueNumbering.clear();
587 expressionNumbering.clear();
591 /// erase - Remove a value from the value numbering
592 void ValueTable::erase(Value* V) {
593 valueNumbering.erase(V);
596 /// size - Return the number of assigned value numbers
597 unsigned ValueTable::size() {
598 // NOTE: zero is never assigned
599 return nextValueNumber;
604 //===----------------------------------------------------------------------===//
605 // ValueNumberedSet Class
606 //===----------------------------------------------------------------------===//
608 class ValueNumberedSet {
610 SmallPtrSet<Value*, 8> contents;
613 ValueNumberedSet() { numbers.resize(1); }
614 ValueNumberedSet(const ValueNumberedSet& other) {
615 numbers = other.numbers;
616 contents = other.contents;
619 typedef SmallPtrSet<Value*, 8>::iterator iterator;
621 iterator begin() { return contents.begin(); }
622 iterator end() { return contents.end(); }
624 bool insert(Value* v) { return contents.insert(v); }
625 void insert(iterator I, iterator E) { contents.insert(I, E); }
626 void erase(Value* v) { contents.erase(v); }
627 unsigned count(Value* v) { return contents.count(v); }
628 size_t size() { return contents.size(); }
630 void set(unsigned i) {
631 if (i >= numbers.size())
637 void operator=(const ValueNumberedSet& other) {
638 contents = other.contents;
639 numbers = other.numbers;
642 void reset(unsigned i) {
643 if (i < numbers.size())
647 bool test(unsigned i) {
648 if (i >= numbers.size())
651 return numbers.test(i);
662 //===----------------------------------------------------------------------===//
664 //===----------------------------------------------------------------------===//
668 class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
669 bool runOnFunction(Function &F);
671 static char ID; // Pass identification, replacement for typeid
672 GVNPRE() : FunctionPass((intptr_t)&ID) { }
676 SmallVector<Instruction*, 8> createdExpressions;
678 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
679 DenseMap<BasicBlock*, ValueNumberedSet> anticipatedIn;
680 DenseMap<BasicBlock*, ValueNumberedSet> generatedPhis;
682 // This transformation requires dominator postdominator info
683 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
684 AU.setPreservesCFG();
685 AU.addRequiredID(BreakCriticalEdgesID);
686 AU.addRequired<UnifyFunctionExitNodes>();
687 AU.addRequired<DominatorTree>();
691 // FIXME: eliminate or document these better
692 void dump(ValueNumberedSet& s) const ;
693 void clean(ValueNumberedSet& set) ;
694 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
695 Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) ;
696 void phi_translate_set(ValueNumberedSet& anticIn, BasicBlock* pred,
697 BasicBlock* succ, ValueNumberedSet& out) ;
699 void topo_sort(ValueNumberedSet& set,
700 SmallVector<Value*, 8>& vec) ;
705 void val_insert(ValueNumberedSet& s, Value* v) ;
706 void val_replace(ValueNumberedSet& s, Value* v) ;
707 bool dependsOnInvoke(Value* V) ;
708 void buildsets_availout(BasicBlock::iterator I,
709 ValueNumberedSet& currAvail,
710 ValueNumberedSet& currPhis,
711 ValueNumberedSet& currExps,
712 SmallPtrSet<Value*, 16>& currTemps);
713 bool buildsets_anticout(BasicBlock* BB,
714 ValueNumberedSet& anticOut,
715 SmallPtrSet<BasicBlock*, 8>& visited);
716 unsigned buildsets_anticin(BasicBlock* BB,
717 ValueNumberedSet& anticOut,
718 ValueNumberedSet& currExps,
719 SmallPtrSet<Value*, 16>& currTemps,
720 SmallPtrSet<BasicBlock*, 8>& visited);
721 void buildsets(Function& F) ;
723 void insertion_pre(Value* e, BasicBlock* BB,
724 DenseMap<BasicBlock*, Value*>& avail,
725 std::map<BasicBlock*,ValueNumberedSet>& new_set);
726 unsigned insertion_mergepoint(SmallVector<Value*, 8>& workList,
727 df_iterator<DomTreeNode*>& D,
728 std::map<BasicBlock*, ValueNumberedSet>& new_set);
729 bool insertion(Function& F) ;
737 // createGVNPREPass - The public interface to this file...
738 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
740 static RegisterPass<GVNPRE> X("gvnpre",
741 "Global Value Numbering/Partial Redundancy Elimination");
744 STATISTIC(NumInsertedVals, "Number of values inserted");
745 STATISTIC(NumInsertedPhis, "Number of PHI nodes inserted");
746 STATISTIC(NumEliminated, "Number of redundant instructions eliminated");
748 /// find_leader - Given a set and a value number, return the first
749 /// element of the set with that value number, or 0 if no such element
751 Value* GVNPRE::find_leader(ValueNumberedSet& vals, uint32_t v) {
755 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
757 if (v == VN.lookup(*I))
760 assert(0 && "No leader found, but present bit is set?");
764 /// val_insert - Insert a value into a set only if there is not a value
765 /// with the same value number already in the set
766 void GVNPRE::val_insert(ValueNumberedSet& s, Value* v) {
767 uint32_t num = VN.lookup(v);
772 /// val_replace - Insert a value into a set, replacing any values already in
773 /// the set that have the same value number
774 void GVNPRE::val_replace(ValueNumberedSet& s, Value* v) {
775 if (s.count(v)) return;
777 uint32_t num = VN.lookup(v);
778 Value* leader = find_leader(s, num);
785 /// phi_translate - Given a value, its parent block, and a predecessor of its
786 /// parent, translate the value into legal for the predecessor block. This
787 /// means translating its operands (and recursively, their operands) through
788 /// any phi nodes in the parent into values available in the predecessor
789 Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
794 if (CastInst* U = dyn_cast<CastInst>(V)) {
796 if (isa<Instruction>(U->getOperand(0)))
797 newOp1 = phi_translate(U->getOperand(0), pred, succ);
799 newOp1 = U->getOperand(0);
804 if (newOp1 != U->getOperand(0)) {
805 Instruction* newVal = 0;
806 if (CastInst* C = dyn_cast<CastInst>(U))
807 newVal = CastInst::create(C->getOpcode(),
808 newOp1, C->getType(),
809 C->getName()+".expr");
811 uint32_t v = VN.lookup_or_add(newVal);
813 Value* leader = find_leader(availableOut[pred], v);
815 createdExpressions.push_back(newVal);
825 } if (isa<BinaryOperator>(V) || isa<CmpInst>(V) ||
826 isa<ExtractElementInst>(V)) {
827 User* U = cast<User>(V);
830 if (isa<Instruction>(U->getOperand(0)))
831 newOp1 = phi_translate(U->getOperand(0), pred, succ);
833 newOp1 = U->getOperand(0);
839 if (isa<Instruction>(U->getOperand(1)))
840 newOp2 = phi_translate(U->getOperand(1), pred, succ);
842 newOp2 = U->getOperand(1);
847 if (newOp1 != U->getOperand(0) || newOp2 != U->getOperand(1)) {
848 Instruction* newVal = 0;
849 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
850 newVal = BinaryOperator::create(BO->getOpcode(),
852 BO->getName()+".expr");
853 else if (CmpInst* C = dyn_cast<CmpInst>(U))
854 newVal = CmpInst::create(C->getOpcode(),
857 C->getName()+".expr");
858 else if (ExtractElementInst* E = dyn_cast<ExtractElementInst>(U))
859 newVal = new ExtractElementInst(newOp1, newOp2, E->getName()+".expr");
861 uint32_t v = VN.lookup_or_add(newVal);
863 Value* leader = find_leader(availableOut[pred], v);
865 createdExpressions.push_back(newVal);
874 // Ternary Operations
875 } else if (isa<ShuffleVectorInst>(V) || isa<InsertElementInst>(V) ||
876 isa<SelectInst>(V)) {
877 User* U = cast<User>(V);
880 if (isa<Instruction>(U->getOperand(0)))
881 newOp1 = phi_translate(U->getOperand(0), pred, succ);
883 newOp1 = U->getOperand(0);
889 if (isa<Instruction>(U->getOperand(1)))
890 newOp2 = phi_translate(U->getOperand(1), pred, succ);
892 newOp2 = U->getOperand(1);
898 if (isa<Instruction>(U->getOperand(2)))
899 newOp3 = phi_translate(U->getOperand(2), pred, succ);
901 newOp3 = U->getOperand(2);
906 if (newOp1 != U->getOperand(0) ||
907 newOp2 != U->getOperand(1) ||
908 newOp3 != U->getOperand(2)) {
909 Instruction* newVal = 0;
910 if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
911 newVal = new ShuffleVectorInst(newOp1, newOp2, newOp3,
912 S->getName()+".expr");
913 else if (InsertElementInst* I = dyn_cast<InsertElementInst>(U))
914 newVal = InsertElementInst::Create(newOp1, newOp2, newOp3,
915 I->getName()+".expr");
916 else if (SelectInst* I = dyn_cast<SelectInst>(U))
917 newVal = SelectInst::Create(newOp1, newOp2, newOp3, I->getName()+".expr");
919 uint32_t v = VN.lookup_or_add(newVal);
921 Value* leader = find_leader(availableOut[pred], v);
923 createdExpressions.push_back(newVal);
933 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
935 if (isa<Instruction>(U->getPointerOperand()))
936 newOp1 = phi_translate(U->getPointerOperand(), pred, succ);
938 newOp1 = U->getPointerOperand();
943 bool changed_idx = false;
944 SmallVector<Value*, 4> newIdx;
945 for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
947 if (isa<Instruction>(*I)) {
948 Value* newVal = phi_translate(*I, pred, succ);
949 newIdx.push_back(newVal);
953 newIdx.push_back(*I);
956 if (newOp1 != U->getPointerOperand() || changed_idx) {
957 Instruction* newVal =
958 GetElementPtrInst::Create(newOp1,
959 newIdx.begin(), newIdx.end(),
960 U->getName()+".expr");
962 uint32_t v = VN.lookup_or_add(newVal);
964 Value* leader = find_leader(availableOut[pred], v);
966 createdExpressions.push_back(newVal);
976 } else if (PHINode* P = dyn_cast<PHINode>(V)) {
977 if (P->getParent() == succ)
978 return P->getIncomingValueForBlock(pred);
984 /// phi_translate_set - Perform phi translation on every element of a set
985 void GVNPRE::phi_translate_set(ValueNumberedSet& anticIn,
986 BasicBlock* pred, BasicBlock* succ,
987 ValueNumberedSet& out) {
988 for (ValueNumberedSet::iterator I = anticIn.begin(),
989 E = anticIn.end(); I != E; ++I) {
990 Value* V = phi_translate(*I, pred, succ);
991 if (V != 0 && !out.test(VN.lookup_or_add(V))) {
993 out.set(VN.lookup(V));
998 /// dependsOnInvoke - Test if a value has an phi node as an operand, any of
999 /// whose inputs is an invoke instruction. If this is true, we cannot safely
1000 /// PRE the instruction or anything that depends on it.
1001 bool GVNPRE::dependsOnInvoke(Value* V) {
1002 if (PHINode* p = dyn_cast<PHINode>(V)) {
1003 for (PHINode::op_iterator I = p->op_begin(), E = p->op_end(); I != E; ++I)
1004 if (isa<InvokeInst>(*I))
1012 /// clean - Remove all non-opaque values from the set whose operands are not
1013 /// themselves in the set, as well as all values that depend on invokes (see
1015 void GVNPRE::clean(ValueNumberedSet& set) {
1016 SmallVector<Value*, 8> worklist;
1017 worklist.reserve(set.size());
1018 topo_sort(set, worklist);
1020 for (unsigned i = 0; i < worklist.size(); ++i) {
1021 Value* v = worklist[i];
1024 if (CastInst* U = dyn_cast<CastInst>(v)) {
1025 bool lhsValid = !isa<Instruction>(U->getOperand(0));
1026 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1028 lhsValid = !dependsOnInvoke(U->getOperand(0));
1032 set.reset(VN.lookup(U));
1035 // Handle binary ops
1036 } else if (isa<BinaryOperator>(v) || isa<CmpInst>(v) ||
1037 isa<ExtractElementInst>(v)) {
1038 User* U = cast<User>(v);
1040 bool lhsValid = !isa<Instruction>(U->getOperand(0));
1041 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1043 lhsValid = !dependsOnInvoke(U->getOperand(0));
1045 bool rhsValid = !isa<Instruction>(U->getOperand(1));
1046 rhsValid |= set.test(VN.lookup(U->getOperand(1)));
1048 rhsValid = !dependsOnInvoke(U->getOperand(1));
1050 if (!lhsValid || !rhsValid) {
1052 set.reset(VN.lookup(U));
1055 // Handle ternary ops
1056 } else if (isa<ShuffleVectorInst>(v) || isa<InsertElementInst>(v) ||
1057 isa<SelectInst>(v)) {
1058 User* U = cast<User>(v);
1060 bool lhsValid = !isa<Instruction>(U->getOperand(0));
1061 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1063 lhsValid = !dependsOnInvoke(U->getOperand(0));
1065 bool rhsValid = !isa<Instruction>(U->getOperand(1));
1066 rhsValid |= set.test(VN.lookup(U->getOperand(1)));
1068 rhsValid = !dependsOnInvoke(U->getOperand(1));
1070 bool thirdValid = !isa<Instruction>(U->getOperand(2));
1071 thirdValid |= set.test(VN.lookup(U->getOperand(2)));
1073 thirdValid = !dependsOnInvoke(U->getOperand(2));
1075 if (!lhsValid || !rhsValid || !thirdValid) {
1077 set.reset(VN.lookup(U));
1080 // Handle varargs ops
1081 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(v)) {
1082 bool ptrValid = !isa<Instruction>(U->getPointerOperand());
1083 ptrValid |= set.test(VN.lookup(U->getPointerOperand()));
1085 ptrValid = !dependsOnInvoke(U->getPointerOperand());
1087 bool varValid = true;
1088 for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
1091 varValid &= !isa<Instruction>(*I) || set.test(VN.lookup(*I));
1092 varValid &= !dependsOnInvoke(*I);
1095 if (!ptrValid || !varValid) {
1097 set.reset(VN.lookup(U));
1103 /// topo_sort - Given a set of values, sort them by topological
1104 /// order into the provided vector.
1105 void GVNPRE::topo_sort(ValueNumberedSet& set, SmallVector<Value*, 8>& vec) {
1106 SmallPtrSet<Value*, 16> visited;
1107 SmallVector<Value*, 8> stack;
1108 for (ValueNumberedSet::iterator I = set.begin(), E = set.end();
1110 if (visited.count(*I) == 0)
1111 stack.push_back(*I);
1113 while (!stack.empty()) {
1114 Value* e = stack.back();
1117 if (CastInst* U = dyn_cast<CastInst>(e)) {
1118 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1120 if (l != 0 && isa<Instruction>(l) &&
1121 visited.count(l) == 0)
1129 // Handle binary ops
1130 } else if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1131 isa<ExtractElementInst>(e)) {
1132 User* U = cast<User>(e);
1133 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1134 Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1136 if (l != 0 && isa<Instruction>(l) &&
1137 visited.count(l) == 0)
1139 else if (r != 0 && isa<Instruction>(r) &&
1140 visited.count(r) == 0)
1148 // Handle ternary ops
1149 } else if (isa<InsertElementInst>(e) || isa<ShuffleVectorInst>(e) ||
1150 isa<SelectInst>(e)) {
1151 User* U = cast<User>(e);
1152 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1153 Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1154 Value* m = find_leader(set, VN.lookup(U->getOperand(2)));
1156 if (l != 0 && isa<Instruction>(l) &&
1157 visited.count(l) == 0)
1159 else if (r != 0 && isa<Instruction>(r) &&
1160 visited.count(r) == 0)
1162 else if (m != 0 && isa<Instruction>(m) &&
1163 visited.count(m) == 0)
1171 // Handle vararg ops
1172 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(e)) {
1173 Value* p = find_leader(set, VN.lookup(U->getPointerOperand()));
1175 if (p != 0 && isa<Instruction>(p) &&
1176 visited.count(p) == 0)
1179 bool push_va = false;
1180 for (GetElementPtrInst::op_iterator I = U->idx_begin(),
1181 E = U->idx_end(); I != E; ++I) {
1182 Value * v = find_leader(set, VN.lookup(*I));
1183 if (v != 0 && isa<Instruction>(v) && visited.count(v) == 0) {
1196 // Handle opaque ops
1208 /// dump - Dump a set of values to standard error
1209 void GVNPRE::dump(ValueNumberedSet& s) const {
1211 for (ValueNumberedSet::iterator I = s.begin(), E = s.end();
1213 DOUT << "" << VN.lookup(*I) << ": ";
1214 DEBUG((*I)->dump());
1219 /// elimination - Phase 3 of the main algorithm. Perform full redundancy
1220 /// elimination by walking the dominator tree and removing any instruction that
1221 /// is dominated by another instruction with the same value number.
1222 bool GVNPRE::elimination() {
1223 bool changed_function = false;
1225 SmallVector<std::pair<Instruction*, Value*>, 8> replace;
1226 SmallVector<Instruction*, 8> erase;
1228 DominatorTree& DT = getAnalysis<DominatorTree>();
1230 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1231 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1232 BasicBlock* BB = DI->getBlock();
1234 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1237 if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI) ||
1238 isa<ShuffleVectorInst>(BI) || isa<InsertElementInst>(BI) ||
1239 isa<ExtractElementInst>(BI) || isa<SelectInst>(BI) ||
1240 isa<CastInst>(BI) || isa<GetElementPtrInst>(BI)) {
1242 if (availableOut[BB].test(VN.lookup(BI)) &&
1243 !availableOut[BB].count(BI)) {
1244 Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
1245 if (Instruction* Instr = dyn_cast<Instruction>(leader))
1246 if (Instr->getParent() != 0 && Instr != BI) {
1247 replace.push_back(std::make_pair(BI, leader));
1248 erase.push_back(BI);
1256 while (!replace.empty()) {
1257 std::pair<Instruction*, Value*> rep = replace.back();
1259 rep.first->replaceAllUsesWith(rep.second);
1260 changed_function = true;
1263 for (SmallVector<Instruction*, 8>::iterator I = erase.begin(),
1264 E = erase.end(); I != E; ++I)
1265 (*I)->eraseFromParent();
1267 return changed_function;
1270 /// cleanup - Delete any extraneous values that were created to represent
1271 /// expressions without leaders.
1272 void GVNPRE::cleanup() {
1273 while (!createdExpressions.empty()) {
1274 Instruction* I = createdExpressions.back();
1275 createdExpressions.pop_back();
1281 /// buildsets_availout - When calculating availability, handle an instruction
1282 /// by inserting it into the appropriate sets
1283 void GVNPRE::buildsets_availout(BasicBlock::iterator I,
1284 ValueNumberedSet& currAvail,
1285 ValueNumberedSet& currPhis,
1286 ValueNumberedSet& currExps,
1287 SmallPtrSet<Value*, 16>& currTemps) {
1289 if (PHINode* p = dyn_cast<PHINode>(I)) {
1290 unsigned num = VN.lookup_or_add(p);
1296 } else if (CastInst* U = dyn_cast<CastInst>(I)) {
1297 Value* leftValue = U->getOperand(0);
1299 unsigned num = VN.lookup_or_add(U);
1301 if (isa<Instruction>(leftValue))
1302 if (!currExps.test(VN.lookup(leftValue))) {
1303 currExps.insert(leftValue);
1304 currExps.set(VN.lookup(leftValue));
1307 if (!currExps.test(num)) {
1312 // Handle binary ops
1313 } else if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1314 isa<ExtractElementInst>(I)) {
1315 User* U = cast<User>(I);
1316 Value* leftValue = U->getOperand(0);
1317 Value* rightValue = U->getOperand(1);
1319 unsigned num = VN.lookup_or_add(U);
1321 if (isa<Instruction>(leftValue))
1322 if (!currExps.test(VN.lookup(leftValue))) {
1323 currExps.insert(leftValue);
1324 currExps.set(VN.lookup(leftValue));
1327 if (isa<Instruction>(rightValue))
1328 if (!currExps.test(VN.lookup(rightValue))) {
1329 currExps.insert(rightValue);
1330 currExps.set(VN.lookup(rightValue));
1333 if (!currExps.test(num)) {
1338 // Handle ternary ops
1339 } else if (isa<InsertElementInst>(I) || isa<ShuffleVectorInst>(I) ||
1340 isa<SelectInst>(I)) {
1341 User* U = cast<User>(I);
1342 Value* leftValue = U->getOperand(0);
1343 Value* rightValue = U->getOperand(1);
1344 Value* thirdValue = U->getOperand(2);
1346 VN.lookup_or_add(U);
1348 unsigned num = VN.lookup_or_add(U);
1350 if (isa<Instruction>(leftValue))
1351 if (!currExps.test(VN.lookup(leftValue))) {
1352 currExps.insert(leftValue);
1353 currExps.set(VN.lookup(leftValue));
1355 if (isa<Instruction>(rightValue))
1356 if (!currExps.test(VN.lookup(rightValue))) {
1357 currExps.insert(rightValue);
1358 currExps.set(VN.lookup(rightValue));
1360 if (isa<Instruction>(thirdValue))
1361 if (!currExps.test(VN.lookup(thirdValue))) {
1362 currExps.insert(thirdValue);
1363 currExps.set(VN.lookup(thirdValue));
1366 if (!currExps.test(num)) {
1371 // Handle vararg ops
1372 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(I)) {
1373 Value* ptrValue = U->getPointerOperand();
1375 VN.lookup_or_add(U);
1377 unsigned num = VN.lookup_or_add(U);
1379 if (isa<Instruction>(ptrValue))
1380 if (!currExps.test(VN.lookup(ptrValue))) {
1381 currExps.insert(ptrValue);
1382 currExps.set(VN.lookup(ptrValue));
1385 for (GetElementPtrInst::op_iterator OI = U->idx_begin(), OE = U->idx_end();
1387 if (isa<Instruction>(*OI) && !currExps.test(VN.lookup(*OI))) {
1388 currExps.insert(*OI);
1389 currExps.set(VN.lookup(*OI));
1392 if (!currExps.test(VN.lookup(U))) {
1397 // Handle opaque ops
1398 } else if (!I->isTerminator()){
1399 VN.lookup_or_add(I);
1401 currTemps.insert(I);
1404 if (!I->isTerminator())
1405 if (!currAvail.test(VN.lookup(I))) {
1406 currAvail.insert(I);
1407 currAvail.set(VN.lookup(I));
1411 /// buildsets_anticout - When walking the postdom tree, calculate the ANTIC_OUT
1412 /// set as a function of the ANTIC_IN set of the block's predecessors
1413 bool GVNPRE::buildsets_anticout(BasicBlock* BB,
1414 ValueNumberedSet& anticOut,
1415 SmallPtrSet<BasicBlock*, 8>& visited) {
1416 if (BB->getTerminator()->getNumSuccessors() == 1) {
1417 if (BB->getTerminator()->getSuccessor(0) != BB &&
1418 visited.count(BB->getTerminator()->getSuccessor(0)) == 0) {
1422 phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
1423 BB, BB->getTerminator()->getSuccessor(0), anticOut);
1425 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
1426 BasicBlock* first = BB->getTerminator()->getSuccessor(0);
1427 for (ValueNumberedSet::iterator I = anticipatedIn[first].begin(),
1428 E = anticipatedIn[first].end(); I != E; ++I) {
1429 anticOut.insert(*I);
1430 anticOut.set(VN.lookup(*I));
1433 for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
1434 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
1435 ValueNumberedSet& succAnticIn = anticipatedIn[currSucc];
1437 SmallVector<Value*, 16> temp;
1439 for (ValueNumberedSet::iterator I = anticOut.begin(),
1440 E = anticOut.end(); I != E; ++I)
1441 if (!succAnticIn.test(VN.lookup(*I)))
1444 for (SmallVector<Value*, 16>::iterator I = temp.begin(), E = temp.end();
1447 anticOut.reset(VN.lookup(*I));
1455 /// buildsets_anticin - Walk the postdom tree, calculating ANTIC_OUT for
1456 /// each block. ANTIC_IN is then a function of ANTIC_OUT and the GEN
1457 /// sets populated in buildsets_availout
1458 unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
1459 ValueNumberedSet& anticOut,
1460 ValueNumberedSet& currExps,
1461 SmallPtrSet<Value*, 16>& currTemps,
1462 SmallPtrSet<BasicBlock*, 8>& visited) {
1463 ValueNumberedSet& anticIn = anticipatedIn[BB];
1464 unsigned old = anticIn.size();
1466 bool defer = buildsets_anticout(BB, anticOut, visited);
1472 for (ValueNumberedSet::iterator I = anticOut.begin(),
1473 E = anticOut.end(); I != E; ++I) {
1475 anticIn.set(VN.lookup(*I));
1477 for (ValueNumberedSet::iterator I = currExps.begin(),
1478 E = currExps.end(); I != E; ++I) {
1479 if (!anticIn.test(VN.lookup(*I))) {
1481 anticIn.set(VN.lookup(*I));
1485 for (SmallPtrSet<Value*, 16>::iterator I = currTemps.begin(),
1486 E = currTemps.end(); I != E; ++I) {
1488 anticIn.reset(VN.lookup(*I));
1494 if (old != anticIn.size())
1500 /// buildsets - Phase 1 of the main algorithm. Construct the AVAIL_OUT
1501 /// and the ANTIC_IN sets.
1502 void GVNPRE::buildsets(Function& F) {
1503 DenseMap<BasicBlock*, ValueNumberedSet> generatedExpressions;
1504 DenseMap<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
1506 DominatorTree &DT = getAnalysis<DominatorTree>();
1508 // Phase 1, Part 1: calculate AVAIL_OUT
1510 // Top-down walk of the dominator tree
1511 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1512 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1514 // Get the sets to update for this block
1515 ValueNumberedSet& currExps = generatedExpressions[DI->getBlock()];
1516 ValueNumberedSet& currPhis = generatedPhis[DI->getBlock()];
1517 SmallPtrSet<Value*, 16>& currTemps = generatedTemporaries[DI->getBlock()];
1518 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1520 BasicBlock* BB = DI->getBlock();
1522 // A block inherits AVAIL_OUT from its dominator
1523 if (DI->getIDom() != 0)
1524 currAvail = availableOut[DI->getIDom()->getBlock()];
1526 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1528 buildsets_availout(BI, currAvail, currPhis, currExps,
1533 // Phase 1, Part 2: calculate ANTIC_IN
1535 SmallPtrSet<BasicBlock*, 8> visited;
1536 SmallPtrSet<BasicBlock*, 4> block_changed;
1537 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1538 block_changed.insert(FI);
1540 bool changed = true;
1541 unsigned iterations = 0;
1545 ValueNumberedSet anticOut;
1547 // Postorder walk of the CFG
1548 for (po_iterator<BasicBlock*> BBI = po_begin(&F.getEntryBlock()),
1549 BBE = po_end(&F.getEntryBlock()); BBI != BBE; ++BBI) {
1550 BasicBlock* BB = *BBI;
1552 if (block_changed.count(BB) != 0) {
1553 unsigned ret = buildsets_anticin(BB, anticOut,generatedExpressions[BB],
1554 generatedTemporaries[BB], visited);
1563 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1565 block_changed.insert(*PI);
1568 block_changed.erase(BB);
1570 changed |= (ret == 2);
1579 /// insertion_pre - When a partial redundancy has been identified, eliminate it
1580 /// by inserting appropriate values into the predecessors and a phi node in
1582 void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
1583 DenseMap<BasicBlock*, Value*>& avail,
1584 std::map<BasicBlock*, ValueNumberedSet>& new_sets) {
1585 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1586 Value* e2 = avail[*PI];
1587 if (!availableOut[*PI].test(VN.lookup(e2))) {
1588 User* U = cast<User>(e2);
1591 if (isa<BinaryOperator>(U->getOperand(0)) ||
1592 isa<CmpInst>(U->getOperand(0)) ||
1593 isa<ShuffleVectorInst>(U->getOperand(0)) ||
1594 isa<ExtractElementInst>(U->getOperand(0)) ||
1595 isa<InsertElementInst>(U->getOperand(0)) ||
1596 isa<SelectInst>(U->getOperand(0)) ||
1597 isa<CastInst>(U->getOperand(0)) ||
1598 isa<GetElementPtrInst>(U->getOperand(0)))
1599 s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1601 s1 = U->getOperand(0);
1605 if (isa<BinaryOperator>(U) ||
1607 isa<ShuffleVectorInst>(U) ||
1608 isa<ExtractElementInst>(U) ||
1609 isa<InsertElementInst>(U) ||
1610 isa<SelectInst>(U)) {
1611 if (isa<BinaryOperator>(U->getOperand(1)) ||
1612 isa<CmpInst>(U->getOperand(1)) ||
1613 isa<ShuffleVectorInst>(U->getOperand(1)) ||
1614 isa<ExtractElementInst>(U->getOperand(1)) ||
1615 isa<InsertElementInst>(U->getOperand(1)) ||
1616 isa<SelectInst>(U->getOperand(1)) ||
1617 isa<CastInst>(U->getOperand(1)) ||
1618 isa<GetElementPtrInst>(U->getOperand(1))) {
1619 s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1621 s2 = U->getOperand(1);
1625 // Ternary Operators
1627 if (isa<ShuffleVectorInst>(U) ||
1628 isa<InsertElementInst>(U) ||
1629 isa<SelectInst>(U)) {
1630 if (isa<BinaryOperator>(U->getOperand(2)) ||
1631 isa<CmpInst>(U->getOperand(2)) ||
1632 isa<ShuffleVectorInst>(U->getOperand(2)) ||
1633 isa<ExtractElementInst>(U->getOperand(2)) ||
1634 isa<InsertElementInst>(U->getOperand(2)) ||
1635 isa<SelectInst>(U->getOperand(2)) ||
1636 isa<CastInst>(U->getOperand(2)) ||
1637 isa<GetElementPtrInst>(U->getOperand(2))) {
1638 s3 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(2)));
1640 s3 = U->getOperand(2);
1645 SmallVector<Value*, 4> sVarargs;
1646 if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U)) {
1647 for (GetElementPtrInst::op_iterator OI = G->idx_begin(),
1648 OE = G->idx_end(); OI != OE; ++OI) {
1649 if (isa<BinaryOperator>(*OI) ||
1650 isa<CmpInst>(*OI) ||
1651 isa<ShuffleVectorInst>(*OI) ||
1652 isa<ExtractElementInst>(*OI) ||
1653 isa<InsertElementInst>(*OI) ||
1654 isa<SelectInst>(*OI) ||
1655 isa<CastInst>(*OI) ||
1656 isa<GetElementPtrInst>(*OI)) {
1657 sVarargs.push_back(find_leader(availableOut[*PI],
1660 sVarargs.push_back(*OI);
1666 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1667 newVal = BinaryOperator::create(BO->getOpcode(), s1, s2,
1668 BO->getName()+".gvnpre",
1669 (*PI)->getTerminator());
1670 else if (CmpInst* C = dyn_cast<CmpInst>(U))
1671 newVal = CmpInst::create(C->getOpcode(), C->getPredicate(), s1, s2,
1672 C->getName()+".gvnpre",
1673 (*PI)->getTerminator());
1674 else if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
1675 newVal = new ShuffleVectorInst(s1, s2, s3, S->getName()+".gvnpre",
1676 (*PI)->getTerminator());
1677 else if (InsertElementInst* S = dyn_cast<InsertElementInst>(U))
1678 newVal = InsertElementInst::Create(s1, s2, s3, S->getName()+".gvnpre",
1679 (*PI)->getTerminator());
1680 else if (ExtractElementInst* S = dyn_cast<ExtractElementInst>(U))
1681 newVal = new ExtractElementInst(s1, s2, S->getName()+".gvnpre",
1682 (*PI)->getTerminator());
1683 else if (SelectInst* S = dyn_cast<SelectInst>(U))
1684 newVal = SelectInst::Create(s1, s2, s3, S->getName()+".gvnpre",
1685 (*PI)->getTerminator());
1686 else if (CastInst* C = dyn_cast<CastInst>(U))
1687 newVal = CastInst::create(C->getOpcode(), s1, C->getType(),
1688 C->getName()+".gvnpre",
1689 (*PI)->getTerminator());
1690 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U))
1691 newVal = GetElementPtrInst::Create(s1, sVarargs.begin(), sVarargs.end(),
1692 G->getName()+".gvnpre",
1693 (*PI)->getTerminator());
1695 VN.add(newVal, VN.lookup(U));
1697 ValueNumberedSet& predAvail = availableOut[*PI];
1698 val_replace(predAvail, newVal);
1699 val_replace(new_sets[*PI], newVal);
1700 predAvail.set(VN.lookup(newVal));
1702 DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1703 if (av != avail.end())
1705 avail.insert(std::make_pair(*PI, newVal));
1713 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1715 p = PHINode::Create(avail[*PI]->getType(), "gvnpre-join", BB->begin());
1717 p->addIncoming(avail[*PI], *PI);
1720 VN.add(p, VN.lookup(e));
1721 val_replace(availableOut[BB], p);
1722 availableOut[BB].set(VN.lookup(e));
1723 generatedPhis[BB].insert(p);
1724 generatedPhis[BB].set(VN.lookup(e));
1725 new_sets[BB].insert(p);
1726 new_sets[BB].set(VN.lookup(e));
1731 /// insertion_mergepoint - When walking the dom tree, check at each merge
1732 /// block for the possibility of a partial redundancy. If present, eliminate it
1733 unsigned GVNPRE::insertion_mergepoint(SmallVector<Value*, 8>& workList,
1734 df_iterator<DomTreeNode*>& D,
1735 std::map<BasicBlock*, ValueNumberedSet >& new_sets) {
1736 bool changed_function = false;
1737 bool new_stuff = false;
1739 BasicBlock* BB = D->getBlock();
1740 for (unsigned i = 0; i < workList.size(); ++i) {
1741 Value* e = workList[i];
1743 if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1744 isa<ExtractElementInst>(e) || isa<InsertElementInst>(e) ||
1745 isa<ShuffleVectorInst>(e) || isa<SelectInst>(e) || isa<CastInst>(e) ||
1746 isa<GetElementPtrInst>(e)) {
1747 if (availableOut[D->getIDom()->getBlock()].test(VN.lookup(e)))
1750 DenseMap<BasicBlock*, Value*> avail;
1751 bool by_some = false;
1752 bool all_same = true;
1753 Value * first_s = 0;
1755 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1757 Value *e2 = phi_translate(e, *PI, BB);
1758 Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1761 DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1762 if (av != avail.end())
1764 avail.insert(std::make_pair(*PI, e2));
1767 DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1768 if (av != avail.end())
1770 avail.insert(std::make_pair(*PI, e3));
1775 else if (first_s != e3)
1780 if (by_some && !all_same &&
1781 !generatedPhis[BB].test(VN.lookup(e))) {
1782 insertion_pre(e, BB, avail, new_sets);
1784 changed_function = true;
1790 unsigned retval = 0;
1791 if (changed_function)
1799 /// insert - Phase 2 of the main algorithm. Walk the dominator tree looking for
1800 /// merge points. When one is found, check for a partial redundancy. If one is
1801 /// present, eliminate it. Repeat this walk until no changes are made.
1802 bool GVNPRE::insertion(Function& F) {
1803 bool changed_function = false;
1805 DominatorTree &DT = getAnalysis<DominatorTree>();
1807 std::map<BasicBlock*, ValueNumberedSet> new_sets;
1808 bool new_stuff = true;
1811 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1812 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1813 BasicBlock* BB = DI->getBlock();
1818 ValueNumberedSet& availOut = availableOut[BB];
1819 ValueNumberedSet& anticIn = anticipatedIn[BB];
1821 // Replace leaders with leaders inherited from dominator
1822 if (DI->getIDom() != 0) {
1823 ValueNumberedSet& dom_set = new_sets[DI->getIDom()->getBlock()];
1824 for (ValueNumberedSet::iterator I = dom_set.begin(),
1825 E = dom_set.end(); I != E; ++I) {
1826 val_replace(new_sets[BB], *I);
1827 val_replace(availOut, *I);
1831 // If there is more than one predecessor...
1832 if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
1833 SmallVector<Value*, 8> workList;
1834 workList.reserve(anticIn.size());
1835 topo_sort(anticIn, workList);
1837 unsigned result = insertion_mergepoint(workList, DI, new_sets);
1839 changed_function = true;
1846 return changed_function;
1849 // GVNPRE::runOnFunction - This is the main transformation entry point for a
1852 bool GVNPRE::runOnFunction(Function &F) {
1853 // Clean out global sets from any previous functions
1855 createdExpressions.clear();
1856 availableOut.clear();
1857 anticipatedIn.clear();
1858 generatedPhis.clear();
1860 bool changed_function = false;
1862 // Phase 1: BuildSets
1863 // This phase calculates the AVAIL_OUT and ANTIC_IN sets
1867 // This phase inserts values to make partially redundant values
1869 changed_function |= insertion(F);
1871 // Phase 3: Eliminate
1872 // This phase performs trivial full redundancy elimination
1873 changed_function |= elimination();
1876 // This phase cleans up values that were created solely
1877 // as leaders for expressions
1880 return changed_function;