1 //===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the Owen Anderson and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs a hybrid of global value numbering and partial redundancy
11 // elimination, known as GVN-PRE. It performs partial redundancy elimination on
12 // values, rather than lexical expressions, allowing a more comprehensive view
13 // the optimization. It replaces redundant values with uses of earlier
14 // occurences of the same value. While this is beneficial in that it eliminates
15 // unneeded computation, it also increases register pressure by creating large
16 // live ranges, and should be used with caution on platforms that are very
17 // sensitive to register pressure.
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "gvnpre"
22 #include "llvm/Value.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Function.h"
26 #include "llvm/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/Statistic.h"
34 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 /// This class holds the mapping between values and value numbers. It is used
50 /// as an efficient mechanism to determine the expression-wise equivalence of
54 class VISIBILITY_HIDDEN ValueTable {
57 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
58 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
59 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
60 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
61 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
62 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
63 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
64 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
65 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
66 PTRTOINT, INTTOPTR, BITCAST, GEP};
68 ExpressionOpcode opcode;
73 std::vector<uint32_t> varargs;
75 bool operator< (const Expression& other) const {
76 if (opcode < other.opcode)
78 else if (opcode > other.opcode)
80 else if (type < other.type)
82 else if (type > other.type)
84 else if (firstVN < other.firstVN)
86 else if (firstVN > other.firstVN)
88 else if (secondVN < other.secondVN)
90 else if (secondVN > other.secondVN)
92 else if (thirdVN < other.thirdVN)
94 else if (thirdVN > other.thirdVN)
97 if (varargs.size() < other.varargs.size())
99 else if (varargs.size() > other.varargs.size())
102 for (size_t i = 0; i < varargs.size(); ++i)
103 if (varargs[i] < other.varargs[i])
105 else if (varargs[i] > other.varargs[i])
114 DenseMap<Value*, uint32_t> valueNumbering;
115 std::map<Expression, uint32_t> expressionNumbering;
117 uint32_t nextValueNumber;
119 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
120 Expression::ExpressionOpcode getOpcode(CmpInst* C);
121 Expression::ExpressionOpcode getOpcode(CastInst* C);
122 Expression create_expression(BinaryOperator* BO);
123 Expression create_expression(CmpInst* C);
124 Expression create_expression(ShuffleVectorInst* V);
125 Expression create_expression(ExtractElementInst* C);
126 Expression create_expression(InsertElementInst* V);
127 Expression create_expression(SelectInst* V);
128 Expression create_expression(CastInst* C);
129 Expression create_expression(GetElementPtrInst* G);
131 ValueTable() { nextValueNumber = 1; }
132 uint32_t lookup_or_add(Value* V);
133 uint32_t lookup(Value* V) const;
134 void add(Value* V, uint32_t num);
136 void erase(Value* v);
141 //===----------------------------------------------------------------------===//
142 // ValueTable Internal Functions
143 //===----------------------------------------------------------------------===//
144 ValueTable::Expression::ExpressionOpcode
145 ValueTable::getOpcode(BinaryOperator* BO) {
146 switch(BO->getOpcode()) {
147 case Instruction::Add:
148 return Expression::ADD;
149 case Instruction::Sub:
150 return Expression::SUB;
151 case Instruction::Mul:
152 return Expression::MUL;
153 case Instruction::UDiv:
154 return Expression::UDIV;
155 case Instruction::SDiv:
156 return Expression::SDIV;
157 case Instruction::FDiv:
158 return Expression::FDIV;
159 case Instruction::URem:
160 return Expression::UREM;
161 case Instruction::SRem:
162 return Expression::SREM;
163 case Instruction::FRem:
164 return Expression::FREM;
165 case Instruction::Shl:
166 return Expression::SHL;
167 case Instruction::LShr:
168 return Expression::LSHR;
169 case Instruction::AShr:
170 return Expression::ASHR;
171 case Instruction::And:
172 return Expression::AND;
173 case Instruction::Or:
174 return Expression::OR;
175 case Instruction::Xor:
176 return Expression::XOR;
178 // THIS SHOULD NEVER HAPPEN
180 assert(0 && "Binary operator with unknown opcode?");
181 return Expression::ADD;
185 ValueTable::Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
186 if (C->getOpcode() == Instruction::ICmp) {
187 switch (C->getPredicate()) {
188 case ICmpInst::ICMP_EQ:
189 return Expression::ICMPEQ;
190 case ICmpInst::ICMP_NE:
191 return Expression::ICMPNE;
192 case ICmpInst::ICMP_UGT:
193 return Expression::ICMPUGT;
194 case ICmpInst::ICMP_UGE:
195 return Expression::ICMPUGE;
196 case ICmpInst::ICMP_ULT:
197 return Expression::ICMPULT;
198 case ICmpInst::ICMP_ULE:
199 return Expression::ICMPULE;
200 case ICmpInst::ICMP_SGT:
201 return Expression::ICMPSGT;
202 case ICmpInst::ICMP_SGE:
203 return Expression::ICMPSGE;
204 case ICmpInst::ICMP_SLT:
205 return Expression::ICMPSLT;
206 case ICmpInst::ICMP_SLE:
207 return Expression::ICMPSLE;
209 // THIS SHOULD NEVER HAPPEN
211 assert(0 && "Comparison with unknown predicate?");
212 return Expression::ICMPEQ;
215 switch (C->getPredicate()) {
216 case FCmpInst::FCMP_OEQ:
217 return Expression::FCMPOEQ;
218 case FCmpInst::FCMP_OGT:
219 return Expression::FCMPOGT;
220 case FCmpInst::FCMP_OGE:
221 return Expression::FCMPOGE;
222 case FCmpInst::FCMP_OLT:
223 return Expression::FCMPOLT;
224 case FCmpInst::FCMP_OLE:
225 return Expression::FCMPOLE;
226 case FCmpInst::FCMP_ONE:
227 return Expression::FCMPONE;
228 case FCmpInst::FCMP_ORD:
229 return Expression::FCMPORD;
230 case FCmpInst::FCMP_UNO:
231 return Expression::FCMPUNO;
232 case FCmpInst::FCMP_UEQ:
233 return Expression::FCMPUEQ;
234 case FCmpInst::FCMP_UGT:
235 return Expression::FCMPUGT;
236 case FCmpInst::FCMP_UGE:
237 return Expression::FCMPUGE;
238 case FCmpInst::FCMP_ULT:
239 return Expression::FCMPULT;
240 case FCmpInst::FCMP_ULE:
241 return Expression::FCMPULE;
242 case FCmpInst::FCMP_UNE:
243 return Expression::FCMPUNE;
245 // THIS SHOULD NEVER HAPPEN
247 assert(0 && "Comparison with unknown predicate?");
248 return Expression::FCMPOEQ;
253 ValueTable::Expression::ExpressionOpcode
254 ValueTable::getOpcode(CastInst* C) {
255 switch(C->getOpcode()) {
256 case Instruction::Trunc:
257 return Expression::TRUNC;
258 case Instruction::ZExt:
259 return Expression::ZEXT;
260 case Instruction::SExt:
261 return Expression::SEXT;
262 case Instruction::FPToUI:
263 return Expression::FPTOUI;
264 case Instruction::FPToSI:
265 return Expression::FPTOSI;
266 case Instruction::UIToFP:
267 return Expression::UITOFP;
268 case Instruction::SIToFP:
269 return Expression::SITOFP;
270 case Instruction::FPTrunc:
271 return Expression::FPTRUNC;
272 case Instruction::FPExt:
273 return Expression::FPEXT;
274 case Instruction::PtrToInt:
275 return Expression::PTRTOINT;
276 case Instruction::IntToPtr:
277 return Expression::INTTOPTR;
278 case Instruction::BitCast:
279 return Expression::BITCAST;
281 // THIS SHOULD NEVER HAPPEN
283 assert(0 && "Cast operator with unknown opcode?");
284 return Expression::BITCAST;
288 ValueTable::Expression ValueTable::create_expression(BinaryOperator* BO) {
291 e.firstVN = lookup_or_add(BO->getOperand(0));
292 e.secondVN = lookup_or_add(BO->getOperand(1));
294 e.type = BO->getType();
295 e.opcode = getOpcode(BO);
300 ValueTable::Expression ValueTable::create_expression(CmpInst* C) {
303 e.firstVN = lookup_or_add(C->getOperand(0));
304 e.secondVN = lookup_or_add(C->getOperand(1));
306 e.type = C->getType();
307 e.opcode = getOpcode(C);
312 ValueTable::Expression ValueTable::create_expression(CastInst* C) {
315 e.firstVN = lookup_or_add(C->getOperand(0));
318 e.type = C->getType();
319 e.opcode = getOpcode(C);
324 ValueTable::Expression ValueTable::create_expression(ShuffleVectorInst* S) {
327 e.firstVN = lookup_or_add(S->getOperand(0));
328 e.secondVN = lookup_or_add(S->getOperand(1));
329 e.thirdVN = lookup_or_add(S->getOperand(2));
330 e.type = S->getType();
331 e.opcode = Expression::SHUFFLE;
336 ValueTable::Expression ValueTable::create_expression(ExtractElementInst* E) {
339 e.firstVN = lookup_or_add(E->getOperand(0));
340 e.secondVN = lookup_or_add(E->getOperand(1));
342 e.type = E->getType();
343 e.opcode = Expression::EXTRACT;
348 ValueTable::Expression ValueTable::create_expression(InsertElementInst* I) {
351 e.firstVN = lookup_or_add(I->getOperand(0));
352 e.secondVN = lookup_or_add(I->getOperand(1));
353 e.thirdVN = lookup_or_add(I->getOperand(2));
354 e.type = I->getType();
355 e.opcode = Expression::INSERT;
360 ValueTable::Expression ValueTable::create_expression(SelectInst* I) {
363 e.firstVN = lookup_or_add(I->getCondition());
364 e.secondVN = lookup_or_add(I->getTrueValue());
365 e.thirdVN = lookup_or_add(I->getFalseValue());
366 e.type = I->getType();
367 e.opcode = Expression::SELECT;
372 ValueTable::Expression ValueTable::create_expression(GetElementPtrInst* G) {
375 e.firstVN = lookup_or_add(G->getPointerOperand());
378 e.type = G->getType();
379 e.opcode = Expression::SELECT;
381 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
383 e.varargs.push_back(lookup_or_add(*I));
388 //===----------------------------------------------------------------------===//
389 // ValueTable External Functions
390 //===----------------------------------------------------------------------===//
392 /// lookup_or_add - Returns the value number for the specified value, assigning
393 /// it a new number if it did not have one before.
394 uint32_t ValueTable::lookup_or_add(Value* V) {
395 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
396 if (VI != valueNumbering.end())
400 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
401 Expression e = create_expression(BO);
403 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
404 if (EI != expressionNumbering.end()) {
405 valueNumbering.insert(std::make_pair(V, EI->second));
408 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
409 valueNumbering.insert(std::make_pair(V, nextValueNumber));
411 return nextValueNumber++;
413 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
414 Expression e = create_expression(C);
416 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
417 if (EI != expressionNumbering.end()) {
418 valueNumbering.insert(std::make_pair(V, EI->second));
421 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
422 valueNumbering.insert(std::make_pair(V, nextValueNumber));
424 return nextValueNumber++;
426 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
427 Expression e = create_expression(U);
429 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
430 if (EI != expressionNumbering.end()) {
431 valueNumbering.insert(std::make_pair(V, EI->second));
434 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
435 valueNumbering.insert(std::make_pair(V, nextValueNumber));
437 return nextValueNumber++;
439 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
440 Expression e = create_expression(U);
442 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
443 if (EI != expressionNumbering.end()) {
444 valueNumbering.insert(std::make_pair(V, EI->second));
447 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
448 valueNumbering.insert(std::make_pair(V, nextValueNumber));
450 return nextValueNumber++;
452 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
453 Expression e = create_expression(U);
455 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
456 if (EI != expressionNumbering.end()) {
457 valueNumbering.insert(std::make_pair(V, EI->second));
460 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
461 valueNumbering.insert(std::make_pair(V, nextValueNumber));
463 return nextValueNumber++;
465 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
466 Expression e = create_expression(U);
468 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
469 if (EI != expressionNumbering.end()) {
470 valueNumbering.insert(std::make_pair(V, EI->second));
473 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
474 valueNumbering.insert(std::make_pair(V, nextValueNumber));
476 return nextValueNumber++;
478 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
479 Expression e = create_expression(U);
481 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
482 if (EI != expressionNumbering.end()) {
483 valueNumbering.insert(std::make_pair(V, EI->second));
486 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
487 valueNumbering.insert(std::make_pair(V, nextValueNumber));
489 return nextValueNumber++;
491 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
492 Expression e = create_expression(U);
494 std::map<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
495 if (EI != expressionNumbering.end()) {
496 valueNumbering.insert(std::make_pair(V, EI->second));
499 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
500 valueNumbering.insert(std::make_pair(V, nextValueNumber));
502 return nextValueNumber++;
505 valueNumbering.insert(std::make_pair(V, nextValueNumber));
506 return nextValueNumber++;
510 /// lookup - Returns the value number of the specified value. Fails if
511 /// the value has not yet been numbered.
512 uint32_t ValueTable::lookup(Value* V) const {
513 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
514 if (VI != valueNumbering.end())
517 assert(0 && "Value not numbered?");
522 /// add - Add the specified value with the given value number, removing
523 /// its old number, if any
524 void ValueTable::add(Value* V, uint32_t num) {
525 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
526 if (VI != valueNumbering.end())
527 valueNumbering.erase(VI);
528 valueNumbering.insert(std::make_pair(V, num));
531 /// clear - Remove all entries from the ValueTable
532 void ValueTable::clear() {
533 valueNumbering.clear();
534 expressionNumbering.clear();
538 /// erase - Remove a value from the value numbering
539 void ValueTable::erase(Value* V) {
540 valueNumbering.erase(V);
543 /// size - Return the number of assigned value numbers
544 unsigned ValueTable::size() {
545 // NOTE: zero is never assigned
546 return nextValueNumber;
549 //===----------------------------------------------------------------------===//
550 // ValueNumberedSet Class
551 //===----------------------------------------------------------------------===//
553 class ValueNumberedSet {
555 SmallPtrSet<Value*, 8> contents;
558 ValueNumberedSet() { numbers.resize(1); }
560 typedef SmallPtrSet<Value*, 8>::iterator iterator;
562 iterator begin() { return contents.begin(); }
563 iterator end() { return contents.end(); }
565 bool insert(Value* v) { return contents.insert(v); }
566 void insert(iterator I, iterator E) { contents.insert(I, E); }
567 void erase(Value* v) { contents.erase(v); }
568 size_t size() { return contents.size(); }
570 void set(unsigned i) {
571 if (i >= numbers.size())
577 void operator=(const ValueNumberedSet& other) {
578 contents = other.contents;
579 numbers = other.numbers;
582 void reset(unsigned i) {
583 if (i < numbers.size())
587 bool test(unsigned i) {
588 if (i >= numbers.size())
591 return numbers.test(i);
600 //===----------------------------------------------------------------------===//
602 //===----------------------------------------------------------------------===//
606 class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
607 bool runOnFunction(Function &F);
609 static char ID; // Pass identification, replacement for typeid
610 GVNPRE() : FunctionPass((intptr_t)&ID) { }
614 std::vector<Instruction*> createdExpressions;
616 std::map<BasicBlock*, ValueNumberedSet> availableOut;
617 std::map<BasicBlock*, ValueNumberedSet> anticipatedIn;
618 std::map<BasicBlock*, ValueNumberedSet> generatedPhis;
620 // This transformation requires dominator postdominator info
621 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
622 AU.setPreservesCFG();
623 AU.addRequiredID(BreakCriticalEdgesID);
624 AU.addRequired<UnifyFunctionExitNodes>();
625 AU.addRequired<DominatorTree>();
629 // FIXME: eliminate or document these better
630 void dump(ValueNumberedSet& s) const ;
631 void clean(ValueNumberedSet& set) ;
632 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
633 Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) ;
634 void phi_translate_set(ValueNumberedSet& anticIn, BasicBlock* pred,
635 BasicBlock* succ, ValueNumberedSet& out) ;
637 void topo_sort(ValueNumberedSet& set,
638 std::vector<Value*>& vec) ;
643 void val_insert(ValueNumberedSet& s, Value* v) ;
644 void val_replace(ValueNumberedSet& s, Value* v) ;
645 bool dependsOnInvoke(Value* V) ;
646 void buildsets_availout(BasicBlock::iterator I,
647 ValueNumberedSet& currAvail,
648 ValueNumberedSet& currPhis,
649 ValueNumberedSet& currExps,
650 SmallPtrSet<Value*, 16>& currTemps) ;
651 bool buildsets_anticout(BasicBlock* BB,
652 ValueNumberedSet& anticOut,
653 std::set<BasicBlock*>& visited) ;
654 unsigned buildsets_anticin(BasicBlock* BB,
655 ValueNumberedSet& anticOut,
656 ValueNumberedSet& currExps,
657 SmallPtrSet<Value*, 16>& currTemps,
658 std::set<BasicBlock*>& visited) ;
659 void buildsets(Function& F) ;
661 void insertion_pre(Value* e, BasicBlock* BB,
662 std::map<BasicBlock*, Value*>& avail,
663 std::map<BasicBlock*,ValueNumberedSet>& new_set) ;
664 unsigned insertion_mergepoint(std::vector<Value*>& workList,
665 df_iterator<DomTreeNode*>& D,
666 std::map<BasicBlock*, ValueNumberedSet>& new_set) ;
667 bool insertion(Function& F) ;
675 // createGVNPREPass - The public interface to this file...
676 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
678 RegisterPass<GVNPRE> X("gvnpre",
679 "Global Value Numbering/Partial Redundancy Elimination");
682 STATISTIC(NumInsertedVals, "Number of values inserted");
683 STATISTIC(NumInsertedPhis, "Number of PHI nodes inserted");
684 STATISTIC(NumEliminated, "Number of redundant instructions eliminated");
686 /// find_leader - Given a set and a value number, return the first
687 /// element of the set with that value number, or 0 if no such element
689 Value* GVNPRE::find_leader(ValueNumberedSet& vals, uint32_t v) {
693 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
695 if (v == VN.lookup(*I))
698 assert(0 && "No leader found, but present bit is set?");
702 /// val_insert - Insert a value into a set only if there is not a value
703 /// with the same value number already in the set
704 void GVNPRE::val_insert(ValueNumberedSet& s, Value* v) {
705 uint32_t num = VN.lookup(v);
710 /// val_replace - Insert a value into a set, replacing any values already in
711 /// the set that have the same value number
712 void GVNPRE::val_replace(ValueNumberedSet& s, Value* v) {
713 uint32_t num = VN.lookup(v);
714 Value* leader = find_leader(s, num);
721 /// phi_translate - Given a value, its parent block, and a predecessor of its
722 /// parent, translate the value into legal for the predecessor block. This
723 /// means translating its operands (and recursively, their operands) through
724 /// any phi nodes in the parent into values available in the predecessor
725 Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
730 if (CastInst* U = dyn_cast<CastInst>(V)) {
732 if (isa<Instruction>(U->getOperand(0)))
733 newOp1 = phi_translate(U->getOperand(0), pred, succ);
735 newOp1 = U->getOperand(0);
740 if (newOp1 != U->getOperand(0)) {
741 Instruction* newVal = 0;
742 if (CastInst* C = dyn_cast<CastInst>(U))
743 newVal = CastInst::create(C->getOpcode(),
744 newOp1, C->getType(),
745 C->getName()+".expr");
747 uint32_t v = VN.lookup_or_add(newVal);
749 Value* leader = find_leader(availableOut[pred], v);
751 createdExpressions.push_back(newVal);
761 } if (isa<BinaryOperator>(V) || isa<CmpInst>(V) ||
762 isa<ExtractElementInst>(V)) {
763 User* U = cast<User>(V);
766 if (isa<Instruction>(U->getOperand(0)))
767 newOp1 = phi_translate(U->getOperand(0), pred, succ);
769 newOp1 = U->getOperand(0);
775 if (isa<Instruction>(U->getOperand(1)))
776 newOp2 = phi_translate(U->getOperand(1), pred, succ);
778 newOp2 = U->getOperand(1);
783 if (newOp1 != U->getOperand(0) || newOp2 != U->getOperand(1)) {
784 Instruction* newVal = 0;
785 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
786 newVal = BinaryOperator::create(BO->getOpcode(),
788 BO->getName()+".expr");
789 else if (CmpInst* C = dyn_cast<CmpInst>(U))
790 newVal = CmpInst::create(C->getOpcode(),
793 C->getName()+".expr");
794 else if (ExtractElementInst* E = dyn_cast<ExtractElementInst>(U))
795 newVal = new ExtractElementInst(newOp1, newOp2, E->getName()+".expr");
797 uint32_t v = VN.lookup_or_add(newVal);
799 Value* leader = find_leader(availableOut[pred], v);
801 createdExpressions.push_back(newVal);
810 // Ternary Operations
811 } else if (isa<ShuffleVectorInst>(V) || isa<InsertElementInst>(V) ||
812 isa<SelectInst>(V)) {
813 User* U = cast<User>(V);
816 if (isa<Instruction>(U->getOperand(0)))
817 newOp1 = phi_translate(U->getOperand(0), pred, succ);
819 newOp1 = U->getOperand(0);
825 if (isa<Instruction>(U->getOperand(1)))
826 newOp2 = phi_translate(U->getOperand(1), pred, succ);
828 newOp2 = U->getOperand(1);
834 if (isa<Instruction>(U->getOperand(2)))
835 newOp3 = phi_translate(U->getOperand(2), pred, succ);
837 newOp3 = U->getOperand(2);
842 if (newOp1 != U->getOperand(0) ||
843 newOp2 != U->getOperand(1) ||
844 newOp3 != U->getOperand(2)) {
845 Instruction* newVal = 0;
846 if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
847 newVal = new ShuffleVectorInst(newOp1, newOp2, newOp3,
848 S->getName()+".expr");
849 else if (InsertElementInst* I = dyn_cast<InsertElementInst>(U))
850 newVal = new InsertElementInst(newOp1, newOp2, newOp3,
851 I->getName()+".expr");
852 else if (SelectInst* I = dyn_cast<SelectInst>(U))
853 newVal = new SelectInst(newOp1, newOp2, newOp3, I->getName()+".expr");
855 uint32_t v = VN.lookup_or_add(newVal);
857 Value* leader = find_leader(availableOut[pred], v);
859 createdExpressions.push_back(newVal);
869 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
871 if (isa<Instruction>(U->getPointerOperand()))
872 newOp1 = phi_translate(U->getPointerOperand(), pred, succ);
874 newOp1 = U->getPointerOperand();
879 bool changed_idx = false;
880 std::vector<Value*> newIdx;
881 for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
883 if (isa<Instruction>(*I)) {
884 Value* newVal = phi_translate(*I, pred, succ);
885 newIdx.push_back(newVal);
889 newIdx.push_back(*I);
892 if (newOp1 != U->getPointerOperand() || changed_idx) {
893 Instruction* newVal = new GetElementPtrInst(newOp1,
894 &newIdx[0], newIdx.size(),
895 U->getName()+".expr");
897 uint32_t v = VN.lookup_or_add(newVal);
899 Value* leader = find_leader(availableOut[pred], v);
901 createdExpressions.push_back(newVal);
911 } else if (PHINode* P = dyn_cast<PHINode>(V)) {
912 if (P->getParent() == succ)
913 return P->getIncomingValueForBlock(pred);
919 /// phi_translate_set - Perform phi translation on every element of a set
920 void GVNPRE::phi_translate_set(ValueNumberedSet& anticIn,
921 BasicBlock* pred, BasicBlock* succ,
922 ValueNumberedSet& out) {
923 for (ValueNumberedSet::iterator I = anticIn.begin(),
924 E = anticIn.end(); I != E; ++I) {
925 Value* V = phi_translate(*I, pred, succ);
926 if (V != 0 && !out.test(VN.lookup_or_add(V))) {
928 out.set(VN.lookup(V));
933 /// dependsOnInvoke - Test if a value has an phi node as an operand, any of
934 /// whose inputs is an invoke instruction. If this is true, we cannot safely
935 /// PRE the instruction or anything that depends on it.
936 bool GVNPRE::dependsOnInvoke(Value* V) {
937 if (PHINode* p = dyn_cast<PHINode>(V)) {
938 for (PHINode::op_iterator I = p->op_begin(), E = p->op_end(); I != E; ++I)
939 if (isa<InvokeInst>(*I))
947 /// clean - Remove all non-opaque values from the set whose operands are not
948 /// themselves in the set, as well as all values that depend on invokes (see
950 void GVNPRE::clean(ValueNumberedSet& set) {
951 std::vector<Value*> worklist;
952 worklist.reserve(set.size());
953 topo_sort(set, worklist);
955 for (unsigned i = 0; i < worklist.size(); ++i) {
956 Value* v = worklist[i];
959 if (CastInst* U = dyn_cast<CastInst>(v)) {
960 bool lhsValid = !isa<Instruction>(U->getOperand(0));
961 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
963 lhsValid = !dependsOnInvoke(U->getOperand(0));
967 set.reset(VN.lookup(U));
971 } else if (isa<BinaryOperator>(v) || isa<CmpInst>(v) ||
972 isa<ExtractElementInst>(v)) {
973 User* U = cast<User>(v);
975 bool lhsValid = !isa<Instruction>(U->getOperand(0));
976 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
978 lhsValid = !dependsOnInvoke(U->getOperand(0));
980 bool rhsValid = !isa<Instruction>(U->getOperand(1));
981 rhsValid |= set.test(VN.lookup(U->getOperand(1)));
983 rhsValid = !dependsOnInvoke(U->getOperand(1));
985 if (!lhsValid || !rhsValid) {
987 set.reset(VN.lookup(U));
990 // Handle ternary ops
991 } else if (isa<ShuffleVectorInst>(v) || isa<InsertElementInst>(v) ||
992 isa<SelectInst>(v)) {
993 User* U = cast<User>(v);
995 bool lhsValid = !isa<Instruction>(U->getOperand(0));
996 lhsValid |= set.test(VN.lookup(U->getOperand(0)));
998 lhsValid = !dependsOnInvoke(U->getOperand(0));
1000 bool rhsValid = !isa<Instruction>(U->getOperand(1));
1001 rhsValid |= set.test(VN.lookup(U->getOperand(1)));
1003 rhsValid = !dependsOnInvoke(U->getOperand(1));
1005 bool thirdValid = !isa<Instruction>(U->getOperand(2));
1006 thirdValid |= set.test(VN.lookup(U->getOperand(2)));
1008 thirdValid = !dependsOnInvoke(U->getOperand(2));
1010 if (!lhsValid || !rhsValid || !thirdValid) {
1012 set.reset(VN.lookup(U));
1015 // Handle varargs ops
1016 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(v)) {
1017 bool ptrValid = !isa<Instruction>(U->getPointerOperand());
1018 ptrValid |= set.test(VN.lookup(U->getPointerOperand()));
1020 ptrValid = !dependsOnInvoke(U->getPointerOperand());
1022 bool varValid = true;
1023 for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
1026 varValid &= !isa<Instruction>(*I) || set.test(VN.lookup(*I));
1027 varValid &= !dependsOnInvoke(*I);
1030 if (!ptrValid || !varValid) {
1032 set.reset(VN.lookup(U));
1038 /// topo_sort - Given a set of values, sort them by topological
1039 /// order into the provided vector.
1040 void GVNPRE::topo_sort(ValueNumberedSet& set, std::vector<Value*>& vec) {
1041 SmallPtrSet<Value*, 16> visited;
1042 std::vector<Value*> stack;
1043 for (ValueNumberedSet::iterator I = set.begin(), E = set.end();
1045 if (visited.count(*I) == 0)
1046 stack.push_back(*I);
1048 while (!stack.empty()) {
1049 Value* e = stack.back();
1052 if (CastInst* U = dyn_cast<CastInst>(e)) {
1053 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1055 if (l != 0 && isa<Instruction>(l) &&
1056 visited.count(l) == 0)
1064 // Handle binary ops
1065 } else if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1066 isa<ExtractElementInst>(e)) {
1067 User* U = cast<User>(e);
1068 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1069 Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1071 if (l != 0 && isa<Instruction>(l) &&
1072 visited.count(l) == 0)
1074 else if (r != 0 && isa<Instruction>(r) &&
1075 visited.count(r) == 0)
1083 // Handle ternary ops
1084 } else if (isa<InsertElementInst>(e) || isa<ShuffleVectorInst>(e) ||
1085 isa<SelectInst>(e)) {
1086 User* U = cast<User>(e);
1087 Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1088 Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1089 Value* m = find_leader(set, VN.lookup(U->getOperand(2)));
1091 if (l != 0 && isa<Instruction>(l) &&
1092 visited.count(l) == 0)
1094 else if (r != 0 && isa<Instruction>(r) &&
1095 visited.count(r) == 0)
1097 else if (m != 0 && isa<Instruction>(m) &&
1098 visited.count(m) == 0)
1106 // Handle vararg ops
1107 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(e)) {
1108 Value* p = find_leader(set, VN.lookup(U->getPointerOperand()));
1110 if (p != 0 && isa<Instruction>(p) &&
1111 visited.count(p) == 0)
1114 bool push_va = false;
1115 for (GetElementPtrInst::op_iterator I = U->idx_begin(),
1116 E = U->idx_end(); I != E; ++I) {
1117 Value * v = find_leader(set, VN.lookup(*I));
1118 if (v != 0 && isa<Instruction>(v) && visited.count(v) == 0) {
1131 // Handle opaque ops
1143 /// dump - Dump a set of values to standard error
1144 void GVNPRE::dump(ValueNumberedSet& s) const {
1146 for (ValueNumberedSet::iterator I = s.begin(), E = s.end();
1148 DOUT << "" << VN.lookup(*I) << ": ";
1149 DEBUG((*I)->dump());
1154 /// elimination - Phase 3 of the main algorithm. Perform full redundancy
1155 /// elimination by walking the dominator tree and removing any instruction that
1156 /// is dominated by another instruction with the same value number.
1157 bool GVNPRE::elimination() {
1158 bool changed_function = false;
1160 std::vector<std::pair<Instruction*, Value*> > replace;
1161 std::vector<Instruction*> erase;
1163 DominatorTree& DT = getAnalysis<DominatorTree>();
1165 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1166 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1167 BasicBlock* BB = DI->getBlock();
1169 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1172 if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI) ||
1173 isa<ShuffleVectorInst>(BI) || isa<InsertElementInst>(BI) ||
1174 isa<ExtractElementInst>(BI) || isa<SelectInst>(BI) ||
1175 isa<CastInst>(BI) || isa<GetElementPtrInst>(BI)) {
1176 Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
1179 if (Instruction* Instr = dyn_cast<Instruction>(leader))
1180 if (Instr->getParent() != 0 && Instr != BI) {
1181 replace.push_back(std::make_pair(BI, leader));
1182 erase.push_back(BI);
1189 while (!replace.empty()) {
1190 std::pair<Instruction*, Value*> rep = replace.back();
1192 rep.first->replaceAllUsesWith(rep.second);
1193 changed_function = true;
1196 for (std::vector<Instruction*>::iterator I = erase.begin(), E = erase.end();
1198 (*I)->eraseFromParent();
1200 return changed_function;
1203 /// cleanup - Delete any extraneous values that were created to represent
1204 /// expressions without leaders.
1205 void GVNPRE::cleanup() {
1206 while (!createdExpressions.empty()) {
1207 Instruction* I = createdExpressions.back();
1208 createdExpressions.pop_back();
1214 /// buildsets_availout - When calculating availability, handle an instruction
1215 /// by inserting it into the appropriate sets
1216 void GVNPRE::buildsets_availout(BasicBlock::iterator I,
1217 ValueNumberedSet& currAvail,
1218 ValueNumberedSet& currPhis,
1219 ValueNumberedSet& currExps,
1220 SmallPtrSet<Value*, 16>& currTemps) {
1222 if (PHINode* p = dyn_cast<PHINode>(I)) {
1223 unsigned num = VN.lookup_or_add(p);
1229 } else if (CastInst* U = dyn_cast<CastInst>(I)) {
1230 Value* leftValue = U->getOperand(0);
1232 unsigned num = VN.lookup_or_add(U);
1234 if (isa<Instruction>(leftValue))
1235 if (!currExps.test(VN.lookup(leftValue))) {
1236 currExps.insert(leftValue);
1237 currExps.set(VN.lookup(leftValue));
1240 if (!currExps.test(num)) {
1245 // Handle binary ops
1246 } else if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1247 isa<ExtractElementInst>(I)) {
1248 User* U = cast<User>(I);
1249 Value* leftValue = U->getOperand(0);
1250 Value* rightValue = U->getOperand(1);
1252 unsigned num = VN.lookup_or_add(U);
1254 if (isa<Instruction>(leftValue))
1255 if (!currExps.test(VN.lookup(leftValue))) {
1256 currExps.insert(leftValue);
1257 currExps.set(VN.lookup(leftValue));
1260 if (isa<Instruction>(rightValue))
1261 if (!currExps.test(VN.lookup(rightValue))) {
1262 currExps.insert(rightValue);
1263 currExps.set(VN.lookup(rightValue));
1266 if (!currExps.test(num)) {
1271 // Handle ternary ops
1272 } else if (isa<InsertElementInst>(I) || isa<ShuffleVectorInst>(I) ||
1273 isa<SelectInst>(I)) {
1274 User* U = cast<User>(I);
1275 Value* leftValue = U->getOperand(0);
1276 Value* rightValue = U->getOperand(1);
1277 Value* thirdValue = U->getOperand(2);
1279 VN.lookup_or_add(U);
1281 unsigned num = VN.lookup_or_add(U);
1283 if (isa<Instruction>(leftValue))
1284 if (!currExps.test(VN.lookup(leftValue))) {
1285 currExps.insert(leftValue);
1286 currExps.set(VN.lookup(leftValue));
1288 if (isa<Instruction>(rightValue))
1289 if (!currExps.test(VN.lookup(rightValue))) {
1290 currExps.insert(rightValue);
1291 currExps.set(VN.lookup(rightValue));
1293 if (isa<Instruction>(thirdValue))
1294 if (!currExps.test(VN.lookup(thirdValue))) {
1295 currExps.insert(thirdValue);
1296 currExps.set(VN.lookup(thirdValue));
1299 if (!currExps.test(num)) {
1304 // Handle vararg ops
1305 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(I)) {
1306 Value* ptrValue = U->getPointerOperand();
1308 VN.lookup_or_add(U);
1310 unsigned num = VN.lookup_or_add(U);
1312 if (isa<Instruction>(ptrValue))
1313 if (!currExps.test(VN.lookup(ptrValue))) {
1314 currExps.insert(ptrValue);
1315 currExps.set(VN.lookup(ptrValue));
1318 for (GetElementPtrInst::op_iterator OI = U->idx_begin(), OE = U->idx_end();
1320 if (isa<Instruction>(*OI) && !currExps.test(VN.lookup(*OI))) {
1321 currExps.insert(*OI);
1322 currExps.set(VN.lookup(*OI));
1325 if (!currExps.test(VN.lookup(U))) {
1330 // Handle opaque ops
1331 } else if (!I->isTerminator()){
1332 VN.lookup_or_add(I);
1334 currTemps.insert(I);
1337 if (!I->isTerminator())
1338 if (!currAvail.test(VN.lookup(I))) {
1339 currAvail.insert(I);
1340 currAvail.set(VN.lookup(I));
1344 /// buildsets_anticout - When walking the postdom tree, calculate the ANTIC_OUT
1345 /// set as a function of the ANTIC_IN set of the block's predecessors
1346 bool GVNPRE::buildsets_anticout(BasicBlock* BB,
1347 ValueNumberedSet& anticOut,
1348 std::set<BasicBlock*>& visited) {
1349 if (BB->getTerminator()->getNumSuccessors() == 1) {
1350 if (BB->getTerminator()->getSuccessor(0) != BB &&
1351 visited.count(BB->getTerminator()->getSuccessor(0)) == 0) {
1355 phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
1356 BB, BB->getTerminator()->getSuccessor(0), anticOut);
1358 } else if (BB->getTerminator()->getNumSuccessors() > 1) {
1359 BasicBlock* first = BB->getTerminator()->getSuccessor(0);
1360 for (ValueNumberedSet::iterator I = anticipatedIn[first].begin(),
1361 E = anticipatedIn[first].end(); I != E; ++I) {
1362 anticOut.insert(*I);
1363 anticOut.set(VN.lookup(*I));
1366 for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
1367 BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
1368 ValueNumberedSet& succAnticIn = anticipatedIn[currSucc];
1370 std::vector<Value*> temp;
1372 for (ValueNumberedSet::iterator I = anticOut.begin(),
1373 E = anticOut.end(); I != E; ++I)
1374 if (!succAnticIn.test(VN.lookup(*I)))
1377 for (std::vector<Value*>::iterator I = temp.begin(), E = temp.end();
1380 anticOut.reset(VN.lookup(*I));
1388 /// buildsets_anticin - Walk the postdom tree, calculating ANTIC_OUT for
1389 /// each block. ANTIC_IN is then a function of ANTIC_OUT and the GEN
1390 /// sets populated in buildsets_availout
1391 unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
1392 ValueNumberedSet& anticOut,
1393 ValueNumberedSet& currExps,
1394 SmallPtrSet<Value*, 16>& currTemps,
1395 std::set<BasicBlock*>& visited) {
1396 ValueNumberedSet& anticIn = anticipatedIn[BB];
1397 unsigned old = anticIn.size();
1399 bool defer = buildsets_anticout(BB, anticOut, visited);
1405 for (ValueNumberedSet::iterator I = anticOut.begin(),
1406 E = anticOut.end(); I != E; ++I) {
1408 anticIn.set(VN.lookup(*I));
1410 for (ValueNumberedSet::iterator I = currExps.begin(),
1411 E = currExps.end(); I != E; ++I) {
1412 if (!anticIn.test(VN.lookup(*I))) {
1414 anticIn.set(VN.lookup(*I));
1418 for (SmallPtrSet<Value*, 16>::iterator I = currTemps.begin(),
1419 E = currTemps.end(); I != E; ++I) {
1421 anticIn.reset(VN.lookup(*I));
1427 if (old != anticIn.size())
1433 /// buildsets - Phase 1 of the main algorithm. Construct the AVAIL_OUT
1434 /// and the ANTIC_IN sets.
1435 void GVNPRE::buildsets(Function& F) {
1436 std::map<BasicBlock*, ValueNumberedSet> generatedExpressions;
1437 std::map<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
1439 DominatorTree &DT = getAnalysis<DominatorTree>();
1441 // Phase 1, Part 1: calculate AVAIL_OUT
1443 // Top-down walk of the dominator tree
1444 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1445 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1447 // Get the sets to update for this block
1448 ValueNumberedSet& currExps = generatedExpressions[DI->getBlock()];
1449 ValueNumberedSet& currPhis = generatedPhis[DI->getBlock()];
1450 SmallPtrSet<Value*, 16>& currTemps = generatedTemporaries[DI->getBlock()];
1451 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1453 BasicBlock* BB = DI->getBlock();
1455 // A block inherits AVAIL_OUT from its dominator
1456 if (DI->getIDom() != 0)
1457 currAvail = availableOut[DI->getIDom()->getBlock()];
1459 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1461 buildsets_availout(BI, currAvail, currPhis, currExps,
1466 // Phase 1, Part 2: calculate ANTIC_IN
1468 std::set<BasicBlock*> visited;
1469 SmallPtrSet<BasicBlock*, 4> block_changed;
1470 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1471 block_changed.insert(FI);
1473 bool changed = true;
1474 unsigned iterations = 0;
1478 ValueNumberedSet anticOut;
1480 // Postorder walk of the CFG
1481 for (po_iterator<BasicBlock*> BBI = po_begin(&F.getEntryBlock()),
1482 BBE = po_end(&F.getEntryBlock()); BBI != BBE; ++BBI) {
1483 BasicBlock* BB = *BBI;
1485 if (block_changed.count(BB) != 0) {
1486 unsigned ret = buildsets_anticin(BB, anticOut,generatedExpressions[BB],
1487 generatedTemporaries[BB], visited);
1496 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1498 block_changed.insert(*PI);
1501 block_changed.erase(BB);
1503 changed |= (ret == 2);
1512 /// insertion_pre - When a partial redundancy has been identified, eliminate it
1513 /// by inserting appropriate values into the predecessors and a phi node in
1515 void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
1516 std::map<BasicBlock*, Value*>& avail,
1517 std::map<BasicBlock*, ValueNumberedSet>& new_sets) {
1518 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1519 Value* e2 = avail[*PI];
1520 if (!availableOut[*PI].test(VN.lookup(e2))) {
1521 User* U = cast<User>(e2);
1524 if (isa<BinaryOperator>(U->getOperand(0)) ||
1525 isa<CmpInst>(U->getOperand(0)) ||
1526 isa<ShuffleVectorInst>(U->getOperand(0)) ||
1527 isa<ExtractElementInst>(U->getOperand(0)) ||
1528 isa<InsertElementInst>(U->getOperand(0)) ||
1529 isa<SelectInst>(U->getOperand(0)) ||
1530 isa<CastInst>(U->getOperand(0)) ||
1531 isa<GetElementPtrInst>(U->getOperand(0)))
1532 s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1534 s1 = U->getOperand(0);
1538 if (isa<BinaryOperator>(U) ||
1540 isa<ShuffleVectorInst>(U) ||
1541 isa<ExtractElementInst>(U) ||
1542 isa<InsertElementInst>(U) ||
1544 if (isa<BinaryOperator>(U->getOperand(1)) ||
1545 isa<CmpInst>(U->getOperand(1)) ||
1546 isa<ShuffleVectorInst>(U->getOperand(1)) ||
1547 isa<ExtractElementInst>(U->getOperand(1)) ||
1548 isa<InsertElementInst>(U->getOperand(1)) ||
1549 isa<SelectInst>(U->getOperand(1)) ||
1550 isa<CastInst>(U->getOperand(1)) ||
1551 isa<GetElementPtrInst>(U->getOperand(1))) {
1552 s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1554 s2 = U->getOperand(1);
1557 // Ternary Operators
1559 if (isa<ShuffleVectorInst>(U) ||
1560 isa<InsertElementInst>(U) ||
1562 if (isa<BinaryOperator>(U->getOperand(2)) ||
1563 isa<CmpInst>(U->getOperand(2)) ||
1564 isa<ShuffleVectorInst>(U->getOperand(2)) ||
1565 isa<ExtractElementInst>(U->getOperand(2)) ||
1566 isa<InsertElementInst>(U->getOperand(2)) ||
1567 isa<SelectInst>(U->getOperand(2)) ||
1568 isa<CastInst>(U->getOperand(2)) ||
1569 isa<GetElementPtrInst>(U->getOperand(2))) {
1570 s3 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(2)));
1572 s3 = U->getOperand(2);
1576 std::vector<Value*> sVarargs;
1577 if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U)) {
1578 for (GetElementPtrInst::op_iterator OI = G->idx_begin(),
1579 OE = G->idx_end(); OI != OE; ++OI) {
1580 if (isa<BinaryOperator>(*OI) ||
1581 isa<CmpInst>(*OI) ||
1582 isa<ShuffleVectorInst>(*OI) ||
1583 isa<ExtractElementInst>(*OI) ||
1584 isa<InsertElementInst>(*OI) ||
1585 isa<SelectInst>(*OI) ||
1586 isa<CastInst>(*OI) ||
1587 isa<GetElementPtrInst>(*OI)) {
1588 sVarargs.push_back(find_leader(availableOut[*PI],
1591 sVarargs.push_back(*OI);
1597 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1598 newVal = BinaryOperator::create(BO->getOpcode(), s1, s2,
1599 BO->getName()+".gvnpre",
1600 (*PI)->getTerminator());
1601 else if (CmpInst* C = dyn_cast<CmpInst>(U))
1602 newVal = CmpInst::create(C->getOpcode(), C->getPredicate(), s1, s2,
1603 C->getName()+".gvnpre",
1604 (*PI)->getTerminator());
1605 else if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
1606 newVal = new ShuffleVectorInst(s1, s2, s3, S->getName()+".gvnpre",
1607 (*PI)->getTerminator());
1608 else if (InsertElementInst* S = dyn_cast<InsertElementInst>(U))
1609 newVal = new InsertElementInst(s1, s2, s3, S->getName()+".gvnpre",
1610 (*PI)->getTerminator());
1611 else if (ExtractElementInst* S = dyn_cast<ExtractElementInst>(U))
1612 newVal = new ExtractElementInst(s1, s2, S->getName()+".gvnpre",
1613 (*PI)->getTerminator());
1614 else if (SelectInst* S = dyn_cast<SelectInst>(U))
1615 newVal = new SelectInst(s1, s2, s3, S->getName()+".gvnpre",
1616 (*PI)->getTerminator());
1617 else if (CastInst* C = dyn_cast<CastInst>(U))
1618 newVal = CastInst::create(C->getOpcode(), s1, C->getType(),
1619 C->getName()+".gvnpre",
1620 (*PI)->getTerminator());
1621 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U))
1622 newVal = new GetElementPtrInst(s1, &sVarargs[0], sVarargs.size(),
1623 G->getName()+".gvnpre",
1624 (*PI)->getTerminator());
1627 VN.add(newVal, VN.lookup(U));
1629 ValueNumberedSet& predAvail = availableOut[*PI];
1630 val_replace(predAvail, newVal);
1631 val_replace(new_sets[*PI], newVal);
1632 predAvail.set(VN.lookup(newVal));
1634 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1635 if (av != avail.end())
1637 avail.insert(std::make_pair(*PI, newVal));
1645 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1647 p = new PHINode(avail[*PI]->getType(), "gvnpre-join", BB->begin());
1649 p->addIncoming(avail[*PI], *PI);
1652 VN.add(p, VN.lookup(e));
1653 val_replace(availableOut[BB], p);
1654 availableOut[BB].set(VN.lookup(e));
1655 generatedPhis[BB].insert(p);
1656 generatedPhis[BB].set(VN.lookup(e));
1657 new_sets[BB].insert(p);
1658 new_sets[BB].set(VN.lookup(e));
1663 /// insertion_mergepoint - When walking the dom tree, check at each merge
1664 /// block for the possibility of a partial redundancy. If present, eliminate it
1665 unsigned GVNPRE::insertion_mergepoint(std::vector<Value*>& workList,
1666 df_iterator<DomTreeNode*>& D,
1667 std::map<BasicBlock*, ValueNumberedSet >& new_sets) {
1668 bool changed_function = false;
1669 bool new_stuff = false;
1671 BasicBlock* BB = D->getBlock();
1672 for (unsigned i = 0; i < workList.size(); ++i) {
1673 Value* e = workList[i];
1675 if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1676 isa<ExtractElementInst>(e) || isa<InsertElementInst>(e) ||
1677 isa<ShuffleVectorInst>(e) || isa<SelectInst>(e) || isa<CastInst>(e) ||
1678 isa<GetElementPtrInst>(e)) {
1679 if (availableOut[D->getIDom()->getBlock()].test(VN.lookup(e)))
1682 std::map<BasicBlock*, Value*> avail;
1683 bool by_some = false;
1684 bool all_same = true;
1685 Value * first_s = 0;
1687 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1689 Value *e2 = phi_translate(e, *PI, BB);
1690 Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1693 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1694 if (av != avail.end())
1696 avail.insert(std::make_pair(*PI, e2));
1699 std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1700 if (av != avail.end())
1702 avail.insert(std::make_pair(*PI, e3));
1707 else if (first_s != e3)
1712 if (by_some && !all_same &&
1713 !generatedPhis[BB].test(VN.lookup(e))) {
1714 insertion_pre(e, BB, avail, new_sets);
1716 changed_function = true;
1722 unsigned retval = 0;
1723 if (changed_function)
1731 /// insert - Phase 2 of the main algorithm. Walk the dominator tree looking for
1732 /// merge points. When one is found, check for a partial redundancy. If one is
1733 /// present, eliminate it. Repeat this walk until no changes are made.
1734 bool GVNPRE::insertion(Function& F) {
1735 bool changed_function = false;
1737 DominatorTree &DT = getAnalysis<DominatorTree>();
1739 std::map<BasicBlock*, ValueNumberedSet> new_sets;
1740 bool new_stuff = true;
1743 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1744 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1745 BasicBlock* BB = DI->getBlock();
1750 ValueNumberedSet& availOut = availableOut[BB];
1751 ValueNumberedSet& anticIn = anticipatedIn[BB];
1753 // Replace leaders with leaders inherited from dominator
1754 if (DI->getIDom() != 0) {
1755 ValueNumberedSet& dom_set = new_sets[DI->getIDom()->getBlock()];
1756 for (ValueNumberedSet::iterator I = dom_set.begin(),
1757 E = dom_set.end(); I != E; ++I) {
1758 val_replace(new_sets[BB], *I);
1759 val_replace(availOut, *I);
1763 // If there is more than one predecessor...
1764 if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
1765 std::vector<Value*> workList;
1766 workList.reserve(anticIn.size());
1767 topo_sort(anticIn, workList);
1769 unsigned result = insertion_mergepoint(workList, DI, new_sets);
1771 changed_function = true;
1778 return changed_function;
1781 // GVNPRE::runOnFunction - This is the main transformation entry point for a
1784 bool GVNPRE::runOnFunction(Function &F) {
1785 // Clean out global sets from any previous functions
1787 createdExpressions.clear();
1788 availableOut.clear();
1789 anticipatedIn.clear();
1790 generatedPhis.clear();
1792 bool changed_function = false;
1794 // Phase 1: BuildSets
1795 // This phase calculates the AVAIL_OUT and ANTIC_IN sets
1799 // This phase inserts values to make partially redundant values
1801 changed_function |= insertion(F);
1803 // Phase 3: Eliminate
1804 // This phase performs trivial full redundancy elimination
1805 changed_function |= elimination();
1808 // This phase cleans up values that were created solely
1809 // as leaders for expressions
1812 return changed_function;