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,
918 I->getName() + ".expr");
920 uint32_t v = VN.lookup_or_add(newVal);
922 Value* leader = find_leader(availableOut[pred], v);
924 createdExpressions.push_back(newVal);
934 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
936 if (isa<Instruction>(U->getPointerOperand()))
937 newOp1 = phi_translate(U->getPointerOperand(), pred, succ);
939 newOp1 = U->getPointerOperand();
944 bool changed_idx = false;
945 SmallVector<Value*, 4> newIdx;
946 for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
948 if (isa<Instruction>(*I)) {
949 Value* newVal = phi_translate(*I, pred, succ);
950 newIdx.push_back(newVal);
954 newIdx.push_back(*I);
957 if (newOp1 != U->getPointerOperand() || changed_idx) {
958 Instruction* newVal =
959 GetElementPtrInst::Create(newOp1,
960 newIdx.begin(), newIdx.end(),
961 U->getName()+".expr");
963 uint32_t v = VN.lookup_or_add(newVal);
965 Value* leader = find_leader(availableOut[pred], v);
967 createdExpressions.push_back(newVal);
977 } else if (PHINode* P = dyn_cast<PHINode>(V)) {
978 if (P->getParent() == succ)
979 return P->getIncomingValueForBlock(pred);
985 /// phi_translate_set - Perform phi translation on every element of a set
986 void GVNPRE::phi_translate_set(ValueNumberedSet& anticIn,
987 BasicBlock* pred, BasicBlock* succ,
988 ValueNumberedSet& out) {
989 for (ValueNumberedSet::iterator I = anticIn.begin(),
990 E = anticIn.end(); I != E; ++I) {
991 Value* V = phi_translate(*I, pred, succ);
992 if (V != 0 && !out.test(VN.lookup_or_add(V))) {
994 out.set(VN.lookup(V));
999 /// dependsOnInvoke - Test if a value has an phi node as an operand, any of
1000 /// whose inputs is an invoke instruction. If this is true, we cannot safely
1001 /// PRE the instruction or anything that depends on it.
1002 bool GVNPRE::dependsOnInvoke(Value* V) {
1003 if (PHINode* p = dyn_cast<PHINode>(V)) {
1004 for (PHINode::op_iterator I = p->op_begin(), E = p->op_end(); I != E; ++I)
1005 if (isa<InvokeInst>(*I))
1013 /// clean - Remove all non-opaque values from the set whose operands are not
1014 /// themselves in the set, as well as all values that depend on invokes (see
1016 void GVNPRE::clean(ValueNumberedSet& set) {
1017 SmallVector<Value*, 8> worklist;
1018 worklist.reserve(set.size());
1019 topo_sort(set, worklist);
1021 for (unsigned i = 0; i < worklist.size(); ++i) {
1022 Value* v = worklist[i];
1025 if (CastInst* U = dyn_cast<CastInst>(v)) {
1026 bool lhsValid = !isa<Instruction>(U->getOperand(0));
1027 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1029 lhsValid = !dependsOnInvoke(U->getOperand(0));
1033 set.reset(VN.lookup(U));
1036 // Handle binary ops
1037 } else if (isa<BinaryOperator>(v) || isa<CmpInst>(v) ||
1038 isa<ExtractElementInst>(v)) {
1039 User* U = cast<User>(v);
1041 bool lhsValid = !isa<Instruction>(U->getOperand(0));
1042 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1044 lhsValid = !dependsOnInvoke(U->getOperand(0));
1046 bool rhsValid = !isa<Instruction>(U->getOperand(1));
1047 rhsValid |= set.test(VN.lookup(U->getOperand(1)));
1049 rhsValid = !dependsOnInvoke(U->getOperand(1));
1051 if (!lhsValid || !rhsValid) {
1053 set.reset(VN.lookup(U));
1056 // Handle ternary ops
1057 } else if (isa<ShuffleVectorInst>(v) || isa<InsertElementInst>(v) ||
1058 isa<SelectInst>(v)) {
1059 User* U = cast<User>(v);
1061 bool lhsValid = !isa<Instruction>(U->getOperand(0));
1062 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1064 lhsValid = !dependsOnInvoke(U->getOperand(0));
1066 bool rhsValid = !isa<Instruction>(U->getOperand(1));
1067 rhsValid |= set.test(VN.lookup(U->getOperand(1)));
1069 rhsValid = !dependsOnInvoke(U->getOperand(1));
1071 bool thirdValid = !isa<Instruction>(U->getOperand(2));
1072 thirdValid |= set.test(VN.lookup(U->getOperand(2)));
1074 thirdValid = !dependsOnInvoke(U->getOperand(2));
1076 if (!lhsValid || !rhsValid || !thirdValid) {
1078 set.reset(VN.lookup(U));
1081 // Handle varargs ops
1082 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(v)) {
1083 bool ptrValid = !isa<Instruction>(U->getPointerOperand());
1084 ptrValid |= set.test(VN.lookup(U->getPointerOperand()));
1086 ptrValid = !dependsOnInvoke(U->getPointerOperand());
1088 bool varValid = true;
1089 for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
1092 varValid &= !isa<Instruction>(*I) || set.test(VN.lookup(*I));
1093 varValid &= !dependsOnInvoke(*I);
1096 if (!ptrValid || !varValid) {
1098 set.reset(VN.lookup(U));
1104 /// topo_sort - Given a set of values, sort them by topological
1105 /// order into the provided vector.
1106 void GVNPRE::topo_sort(ValueNumberedSet& set, SmallVector<Value*, 8>& vec) {
1107 SmallPtrSet<Value*, 16> visited;
1108 SmallVector<Value*, 8> stack;
1109 for (ValueNumberedSet::iterator I = set.begin(), E = set.end();
1111 if (visited.count(*I) == 0)
1112 stack.push_back(*I);
1114 while (!stack.empty()) {
1115 Value* e = stack.back();
1118 if (CastInst* U = dyn_cast<CastInst>(e)) {
1119 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1121 if (l != 0 && isa<Instruction>(l) &&
1122 visited.count(l) == 0)
1130 // Handle binary ops
1131 } else if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1132 isa<ExtractElementInst>(e)) {
1133 User* U = cast<User>(e);
1134 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1135 Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1137 if (l != 0 && isa<Instruction>(l) &&
1138 visited.count(l) == 0)
1140 else if (r != 0 && isa<Instruction>(r) &&
1141 visited.count(r) == 0)
1149 // Handle ternary ops
1150 } else if (isa<InsertElementInst>(e) || isa<ShuffleVectorInst>(e) ||
1151 isa<SelectInst>(e)) {
1152 User* U = cast<User>(e);
1153 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1154 Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1155 Value* m = find_leader(set, VN.lookup(U->getOperand(2)));
1157 if (l != 0 && isa<Instruction>(l) &&
1158 visited.count(l) == 0)
1160 else if (r != 0 && isa<Instruction>(r) &&
1161 visited.count(r) == 0)
1163 else if (m != 0 && isa<Instruction>(m) &&
1164 visited.count(m) == 0)
1172 // Handle vararg ops
1173 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(e)) {
1174 Value* p = find_leader(set, VN.lookup(U->getPointerOperand()));
1176 if (p != 0 && isa<Instruction>(p) &&
1177 visited.count(p) == 0)
1180 bool push_va = false;
1181 for (GetElementPtrInst::op_iterator I = U->idx_begin(),
1182 E = U->idx_end(); I != E; ++I) {
1183 Value * v = find_leader(set, VN.lookup(*I));
1184 if (v != 0 && isa<Instruction>(v) && visited.count(v) == 0) {
1197 // Handle opaque ops
1209 /// dump - Dump a set of values to standard error
1210 void GVNPRE::dump(ValueNumberedSet& s) const {
1212 for (ValueNumberedSet::iterator I = s.begin(), E = s.end();
1214 DOUT << "" << VN.lookup(*I) << ": ";
1215 DEBUG((*I)->dump());
1220 /// elimination - Phase 3 of the main algorithm. Perform full redundancy
1221 /// elimination by walking the dominator tree and removing any instruction that
1222 /// is dominated by another instruction with the same value number.
1223 bool GVNPRE::elimination() {
1224 bool changed_function = false;
1226 SmallVector<std::pair<Instruction*, Value*>, 8> replace;
1227 SmallVector<Instruction*, 8> erase;
1229 DominatorTree& DT = getAnalysis<DominatorTree>();
1231 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1232 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1233 BasicBlock* BB = DI->getBlock();
1235 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1238 if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI) ||
1239 isa<ShuffleVectorInst>(BI) || isa<InsertElementInst>(BI) ||
1240 isa<ExtractElementInst>(BI) || isa<SelectInst>(BI) ||
1241 isa<CastInst>(BI) || isa<GetElementPtrInst>(BI)) {
1243 if (availableOut[BB].test(VN.lookup(BI)) &&
1244 !availableOut[BB].count(BI)) {
1245 Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
1246 if (Instruction* Instr = dyn_cast<Instruction>(leader))
1247 if (Instr->getParent() != 0 && Instr != BI) {
1248 replace.push_back(std::make_pair(BI, leader));
1249 erase.push_back(BI);
1257 while (!replace.empty()) {
1258 std::pair<Instruction*, Value*> rep = replace.back();
1260 rep.first->replaceAllUsesWith(rep.second);
1261 changed_function = true;
1264 for (SmallVector<Instruction*, 8>::iterator I = erase.begin(),
1265 E = erase.end(); I != E; ++I)
1266 (*I)->eraseFromParent();
1268 return changed_function;
1271 /// cleanup - Delete any extraneous values that were created to represent
1272 /// expressions without leaders.
1273 void GVNPRE::cleanup() {
1274 while (!createdExpressions.empty()) {
1275 Instruction* I = createdExpressions.back();
1276 createdExpressions.pop_back();
1282 /// buildsets_availout - When calculating availability, handle an instruction
1283 /// by inserting it into the appropriate sets
1284 void GVNPRE::buildsets_availout(BasicBlock::iterator I,
1285 ValueNumberedSet& currAvail,
1286 ValueNumberedSet& currPhis,
1287 ValueNumberedSet& currExps,
1288 SmallPtrSet<Value*, 16>& currTemps) {
1290 if (PHINode* p = dyn_cast<PHINode>(I)) {
1291 unsigned num = VN.lookup_or_add(p);
1297 } else if (CastInst* U = dyn_cast<CastInst>(I)) {
1298 Value* leftValue = U->getOperand(0);
1300 unsigned num = VN.lookup_or_add(U);
1302 if (isa<Instruction>(leftValue))
1303 if (!currExps.test(VN.lookup(leftValue))) {
1304 currExps.insert(leftValue);
1305 currExps.set(VN.lookup(leftValue));
1308 if (!currExps.test(num)) {
1313 // Handle binary ops
1314 } else if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1315 isa<ExtractElementInst>(I)) {
1316 User* U = cast<User>(I);
1317 Value* leftValue = U->getOperand(0);
1318 Value* rightValue = U->getOperand(1);
1320 unsigned num = VN.lookup_or_add(U);
1322 if (isa<Instruction>(leftValue))
1323 if (!currExps.test(VN.lookup(leftValue))) {
1324 currExps.insert(leftValue);
1325 currExps.set(VN.lookup(leftValue));
1328 if (isa<Instruction>(rightValue))
1329 if (!currExps.test(VN.lookup(rightValue))) {
1330 currExps.insert(rightValue);
1331 currExps.set(VN.lookup(rightValue));
1334 if (!currExps.test(num)) {
1339 // Handle ternary ops
1340 } else if (isa<InsertElementInst>(I) || isa<ShuffleVectorInst>(I) ||
1341 isa<SelectInst>(I)) {
1342 User* U = cast<User>(I);
1343 Value* leftValue = U->getOperand(0);
1344 Value* rightValue = U->getOperand(1);
1345 Value* thirdValue = U->getOperand(2);
1347 VN.lookup_or_add(U);
1349 unsigned num = VN.lookup_or_add(U);
1351 if (isa<Instruction>(leftValue))
1352 if (!currExps.test(VN.lookup(leftValue))) {
1353 currExps.insert(leftValue);
1354 currExps.set(VN.lookup(leftValue));
1356 if (isa<Instruction>(rightValue))
1357 if (!currExps.test(VN.lookup(rightValue))) {
1358 currExps.insert(rightValue);
1359 currExps.set(VN.lookup(rightValue));
1361 if (isa<Instruction>(thirdValue))
1362 if (!currExps.test(VN.lookup(thirdValue))) {
1363 currExps.insert(thirdValue);
1364 currExps.set(VN.lookup(thirdValue));
1367 if (!currExps.test(num)) {
1372 // Handle vararg ops
1373 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(I)) {
1374 Value* ptrValue = U->getPointerOperand();
1376 VN.lookup_or_add(U);
1378 unsigned num = VN.lookup_or_add(U);
1380 if (isa<Instruction>(ptrValue))
1381 if (!currExps.test(VN.lookup(ptrValue))) {
1382 currExps.insert(ptrValue);
1383 currExps.set(VN.lookup(ptrValue));
1386 for (GetElementPtrInst::op_iterator OI = U->idx_begin(), OE = U->idx_end();
1388 if (isa<Instruction>(*OI) && !currExps.test(VN.lookup(*OI))) {
1389 currExps.insert(*OI);
1390 currExps.set(VN.lookup(*OI));
1393 if (!currExps.test(VN.lookup(U))) {
1398 // Handle opaque ops
1399 } else if (!I->isTerminator()){
1400 VN.lookup_or_add(I);
1402 currTemps.insert(I);
1405 if (!I->isTerminator())
1406 if (!currAvail.test(VN.lookup(I))) {
1407 currAvail.insert(I);
1408 currAvail.set(VN.lookup(I));
1412 /// buildsets_anticout - When walking the postdom tree, calculate the ANTIC_OUT
1413 /// set as a function of the ANTIC_IN set of the block's predecessors
1414 bool GVNPRE::buildsets_anticout(BasicBlock* BB,
1415 ValueNumberedSet& anticOut,
1416 SmallPtrSet<BasicBlock*, 8>& visited) {
1417 if (BB->getTerminator()->getNumSuccessors() == 1) {
1418 if (BB->getTerminator()->getSuccessor(0) != BB &&
1419 visited.count(BB->getTerminator()->getSuccessor(0)) == 0) {
1423 phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
1424 BB, BB->getTerminator()->getSuccessor(0), anticOut);
1426 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
1427 BasicBlock* first = BB->getTerminator()->getSuccessor(0);
1428 for (ValueNumberedSet::iterator I = anticipatedIn[first].begin(),
1429 E = anticipatedIn[first].end(); I != E; ++I) {
1430 anticOut.insert(*I);
1431 anticOut.set(VN.lookup(*I));
1434 for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
1435 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
1436 ValueNumberedSet& succAnticIn = anticipatedIn[currSucc];
1438 SmallVector<Value*, 16> temp;
1440 for (ValueNumberedSet::iterator I = anticOut.begin(),
1441 E = anticOut.end(); I != E; ++I)
1442 if (!succAnticIn.test(VN.lookup(*I)))
1445 for (SmallVector<Value*, 16>::iterator I = temp.begin(), E = temp.end();
1448 anticOut.reset(VN.lookup(*I));
1456 /// buildsets_anticin - Walk the postdom tree, calculating ANTIC_OUT for
1457 /// each block. ANTIC_IN is then a function of ANTIC_OUT and the GEN
1458 /// sets populated in buildsets_availout
1459 unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
1460 ValueNumberedSet& anticOut,
1461 ValueNumberedSet& currExps,
1462 SmallPtrSet<Value*, 16>& currTemps,
1463 SmallPtrSet<BasicBlock*, 8>& visited) {
1464 ValueNumberedSet& anticIn = anticipatedIn[BB];
1465 unsigned old = anticIn.size();
1467 bool defer = buildsets_anticout(BB, anticOut, visited);
1473 for (ValueNumberedSet::iterator I = anticOut.begin(),
1474 E = anticOut.end(); I != E; ++I) {
1476 anticIn.set(VN.lookup(*I));
1478 for (ValueNumberedSet::iterator I = currExps.begin(),
1479 E = currExps.end(); I != E; ++I) {
1480 if (!anticIn.test(VN.lookup(*I))) {
1482 anticIn.set(VN.lookup(*I));
1486 for (SmallPtrSet<Value*, 16>::iterator I = currTemps.begin(),
1487 E = currTemps.end(); I != E; ++I) {
1489 anticIn.reset(VN.lookup(*I));
1495 if (old != anticIn.size())
1501 /// buildsets - Phase 1 of the main algorithm. Construct the AVAIL_OUT
1502 /// and the ANTIC_IN sets.
1503 void GVNPRE::buildsets(Function& F) {
1504 DenseMap<BasicBlock*, ValueNumberedSet> generatedExpressions;
1505 DenseMap<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
1507 DominatorTree &DT = getAnalysis<DominatorTree>();
1509 // Phase 1, Part 1: calculate AVAIL_OUT
1511 // Top-down walk of the dominator tree
1512 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1513 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1515 // Get the sets to update for this block
1516 ValueNumberedSet& currExps = generatedExpressions[DI->getBlock()];
1517 ValueNumberedSet& currPhis = generatedPhis[DI->getBlock()];
1518 SmallPtrSet<Value*, 16>& currTemps = generatedTemporaries[DI->getBlock()];
1519 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1521 BasicBlock* BB = DI->getBlock();
1523 // A block inherits AVAIL_OUT from its dominator
1524 if (DI->getIDom() != 0)
1525 currAvail = availableOut[DI->getIDom()->getBlock()];
1527 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1529 buildsets_availout(BI, currAvail, currPhis, currExps,
1534 // Phase 1, Part 2: calculate ANTIC_IN
1536 SmallPtrSet<BasicBlock*, 8> visited;
1537 SmallPtrSet<BasicBlock*, 4> block_changed;
1538 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1539 block_changed.insert(FI);
1541 bool changed = true;
1542 unsigned iterations = 0;
1546 ValueNumberedSet anticOut;
1548 // Postorder walk of the CFG
1549 for (po_iterator<BasicBlock*> BBI = po_begin(&F.getEntryBlock()),
1550 BBE = po_end(&F.getEntryBlock()); BBI != BBE; ++BBI) {
1551 BasicBlock* BB = *BBI;
1553 if (block_changed.count(BB) != 0) {
1554 unsigned ret = buildsets_anticin(BB, anticOut,generatedExpressions[BB],
1555 generatedTemporaries[BB], visited);
1564 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1566 block_changed.insert(*PI);
1569 block_changed.erase(BB);
1571 changed |= (ret == 2);
1580 /// insertion_pre - When a partial redundancy has been identified, eliminate it
1581 /// by inserting appropriate values into the predecessors and a phi node in
1583 void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
1584 DenseMap<BasicBlock*, Value*>& avail,
1585 std::map<BasicBlock*, ValueNumberedSet>& new_sets) {
1586 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1587 Value* e2 = avail[*PI];
1588 if (!availableOut[*PI].test(VN.lookup(e2))) {
1589 User* U = cast<User>(e2);
1592 if (isa<BinaryOperator>(U->getOperand(0)) ||
1593 isa<CmpInst>(U->getOperand(0)) ||
1594 isa<ShuffleVectorInst>(U->getOperand(0)) ||
1595 isa<ExtractElementInst>(U->getOperand(0)) ||
1596 isa<InsertElementInst>(U->getOperand(0)) ||
1597 isa<SelectInst>(U->getOperand(0)) ||
1598 isa<CastInst>(U->getOperand(0)) ||
1599 isa<GetElementPtrInst>(U->getOperand(0)))
1600 s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1602 s1 = U->getOperand(0);
1606 if (isa<BinaryOperator>(U) ||
1608 isa<ShuffleVectorInst>(U) ||
1609 isa<ExtractElementInst>(U) ||
1610 isa<InsertElementInst>(U) ||
1611 isa<SelectInst>(U)) {
1612 if (isa<BinaryOperator>(U->getOperand(1)) ||
1613 isa<CmpInst>(U->getOperand(1)) ||
1614 isa<ShuffleVectorInst>(U->getOperand(1)) ||
1615 isa<ExtractElementInst>(U->getOperand(1)) ||
1616 isa<InsertElementInst>(U->getOperand(1)) ||
1617 isa<SelectInst>(U->getOperand(1)) ||
1618 isa<CastInst>(U->getOperand(1)) ||
1619 isa<GetElementPtrInst>(U->getOperand(1))) {
1620 s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1622 s2 = U->getOperand(1);
1626 // Ternary Operators
1628 if (isa<ShuffleVectorInst>(U) ||
1629 isa<InsertElementInst>(U) ||
1630 isa<SelectInst>(U)) {
1631 if (isa<BinaryOperator>(U->getOperand(2)) ||
1632 isa<CmpInst>(U->getOperand(2)) ||
1633 isa<ShuffleVectorInst>(U->getOperand(2)) ||
1634 isa<ExtractElementInst>(U->getOperand(2)) ||
1635 isa<InsertElementInst>(U->getOperand(2)) ||
1636 isa<SelectInst>(U->getOperand(2)) ||
1637 isa<CastInst>(U->getOperand(2)) ||
1638 isa<GetElementPtrInst>(U->getOperand(2))) {
1639 s3 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(2)));
1641 s3 = U->getOperand(2);
1646 SmallVector<Value*, 4> sVarargs;
1647 if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U)) {
1648 for (GetElementPtrInst::op_iterator OI = G->idx_begin(),
1649 OE = G->idx_end(); OI != OE; ++OI) {
1650 if (isa<BinaryOperator>(*OI) ||
1651 isa<CmpInst>(*OI) ||
1652 isa<ShuffleVectorInst>(*OI) ||
1653 isa<ExtractElementInst>(*OI) ||
1654 isa<InsertElementInst>(*OI) ||
1655 isa<SelectInst>(*OI) ||
1656 isa<CastInst>(*OI) ||
1657 isa<GetElementPtrInst>(*OI)) {
1658 sVarargs.push_back(find_leader(availableOut[*PI],
1661 sVarargs.push_back(*OI);
1667 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1668 newVal = BinaryOperator::Create(BO->getOpcode(), s1, s2,
1669 BO->getName()+".gvnpre",
1670 (*PI)->getTerminator());
1671 else if (CmpInst* C = dyn_cast<CmpInst>(U))
1672 newVal = CmpInst::Create(C->getOpcode(), C->getPredicate(), s1, s2,
1673 C->getName()+".gvnpre",
1674 (*PI)->getTerminator());
1675 else if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
1676 newVal = new ShuffleVectorInst(s1, s2, s3, S->getName()+".gvnpre",
1677 (*PI)->getTerminator());
1678 else if (InsertElementInst* S = dyn_cast<InsertElementInst>(U))
1679 newVal = InsertElementInst::Create(s1, s2, s3, S->getName()+".gvnpre",
1680 (*PI)->getTerminator());
1681 else if (ExtractElementInst* S = dyn_cast<ExtractElementInst>(U))
1682 newVal = new ExtractElementInst(s1, s2, S->getName()+".gvnpre",
1683 (*PI)->getTerminator());
1684 else if (SelectInst* S = dyn_cast<SelectInst>(U))
1685 newVal = SelectInst::Create(s1, s2, s3, S->getName()+".gvnpre",
1686 (*PI)->getTerminator());
1687 else if (CastInst* C = dyn_cast<CastInst>(U))
1688 newVal = CastInst::Create(C->getOpcode(), s1, C->getType(),
1689 C->getName()+".gvnpre",
1690 (*PI)->getTerminator());
1691 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U))
1692 newVal = GetElementPtrInst::Create(s1, sVarargs.begin(), sVarargs.end(),
1693 G->getName()+".gvnpre",
1694 (*PI)->getTerminator());
1696 VN.add(newVal, VN.lookup(U));
1698 ValueNumberedSet& predAvail = availableOut[*PI];
1699 val_replace(predAvail, newVal);
1700 val_replace(new_sets[*PI], newVal);
1701 predAvail.set(VN.lookup(newVal));
1703 DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1704 if (av != avail.end())
1706 avail.insert(std::make_pair(*PI, newVal));
1714 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1716 p = PHINode::Create(avail[*PI]->getType(), "gvnpre-join", BB->begin());
1718 p->addIncoming(avail[*PI], *PI);
1721 VN.add(p, VN.lookup(e));
1722 val_replace(availableOut[BB], p);
1723 availableOut[BB].set(VN.lookup(e));
1724 generatedPhis[BB].insert(p);
1725 generatedPhis[BB].set(VN.lookup(e));
1726 new_sets[BB].insert(p);
1727 new_sets[BB].set(VN.lookup(e));
1732 /// insertion_mergepoint - When walking the dom tree, check at each merge
1733 /// block for the possibility of a partial redundancy. If present, eliminate it
1734 unsigned GVNPRE::insertion_mergepoint(SmallVector<Value*, 8>& workList,
1735 df_iterator<DomTreeNode*>& D,
1736 std::map<BasicBlock*, ValueNumberedSet >& new_sets) {
1737 bool changed_function = false;
1738 bool new_stuff = false;
1740 BasicBlock* BB = D->getBlock();
1741 for (unsigned i = 0; i < workList.size(); ++i) {
1742 Value* e = workList[i];
1744 if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1745 isa<ExtractElementInst>(e) || isa<InsertElementInst>(e) ||
1746 isa<ShuffleVectorInst>(e) || isa<SelectInst>(e) || isa<CastInst>(e) ||
1747 isa<GetElementPtrInst>(e)) {
1748 if (availableOut[D->getIDom()->getBlock()].test(VN.lookup(e)))
1751 DenseMap<BasicBlock*, Value*> avail;
1752 bool by_some = false;
1753 bool all_same = true;
1754 Value * first_s = 0;
1756 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1758 Value *e2 = phi_translate(e, *PI, BB);
1759 Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1762 DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1763 if (av != avail.end())
1765 avail.insert(std::make_pair(*PI, e2));
1768 DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1769 if (av != avail.end())
1771 avail.insert(std::make_pair(*PI, e3));
1776 else if (first_s != e3)
1781 if (by_some && !all_same &&
1782 !generatedPhis[BB].test(VN.lookup(e))) {
1783 insertion_pre(e, BB, avail, new_sets);
1785 changed_function = true;
1791 unsigned retval = 0;
1792 if (changed_function)
1800 /// insert - Phase 2 of the main algorithm. Walk the dominator tree looking for
1801 /// merge points. When one is found, check for a partial redundancy. If one is
1802 /// present, eliminate it. Repeat this walk until no changes are made.
1803 bool GVNPRE::insertion(Function& F) {
1804 bool changed_function = false;
1806 DominatorTree &DT = getAnalysis<DominatorTree>();
1808 std::map<BasicBlock*, ValueNumberedSet> new_sets;
1809 bool new_stuff = true;
1812 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1813 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1814 BasicBlock* BB = DI->getBlock();
1819 ValueNumberedSet& availOut = availableOut[BB];
1820 ValueNumberedSet& anticIn = anticipatedIn[BB];
1822 // Replace leaders with leaders inherited from dominator
1823 if (DI->getIDom() != 0) {
1824 ValueNumberedSet& dom_set = new_sets[DI->getIDom()->getBlock()];
1825 for (ValueNumberedSet::iterator I = dom_set.begin(),
1826 E = dom_set.end(); I != E; ++I) {
1827 val_replace(new_sets[BB], *I);
1828 val_replace(availOut, *I);
1832 // If there is more than one predecessor...
1833 if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
1834 SmallVector<Value*, 8> workList;
1835 workList.reserve(anticIn.size());
1836 topo_sort(anticIn, workList);
1838 unsigned result = insertion_mergepoint(workList, DI, new_sets);
1840 changed_function = true;
1847 return changed_function;
1850 // GVNPRE::runOnFunction - This is the main transformation entry point for a
1853 bool GVNPRE::runOnFunction(Function &F) {
1854 // Clean out global sets from any previous functions
1856 createdExpressions.clear();
1857 availableOut.clear();
1858 anticipatedIn.clear();
1859 generatedPhis.clear();
1861 bool changed_function = false;
1863 // Phase 1: BuildSets
1864 // This phase calculates the AVAIL_OUT and ANTIC_IN sets
1868 // This phase inserts values to make partially redundant values
1870 changed_function |= insertion(F);
1872 // Phase 3: Eliminate
1873 // This phase performs trivial full redundancy elimination
1874 changed_function |= elimination();
1877 // This phase cleans up values that were created solely
1878 // as leaders for expressions
1881 return changed_function;