1 //===- GVN.cpp - Eliminate redundant values and loads ------------===//
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 global value numbering to eliminate fully redundant
11 // instructions. It also performs simple dead load elimination.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "gvn"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Value.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Compiler.h"
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 /// This class holds the mapping between values and value numbers. It is used
41 /// as an efficient mechanism to determine the expression-wise equivalence of
44 struct VISIBILITY_HIDDEN Expression {
45 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
46 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
47 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
48 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
49 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
50 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
51 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
52 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
53 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
54 PTRTOINT, INTTOPTR, BITCAST, GEP, EMPTY,
57 ExpressionOpcode opcode;
62 SmallVector<uint32_t, 4> varargs;
65 Expression(ExpressionOpcode o) : opcode(o) { }
67 bool operator==(const Expression &other) const {
68 if (opcode != other.opcode)
70 else if (opcode == EMPTY || opcode == TOMBSTONE)
72 else if (type != other.type)
74 else if (firstVN != other.firstVN)
76 else if (secondVN != other.secondVN)
78 else if (thirdVN != other.thirdVN)
81 if (varargs.size() != other.varargs.size())
84 for (size_t i = 0; i < varargs.size(); ++i)
85 if (varargs[i] != other.varargs[i])
92 bool operator!=(const Expression &other) const {
93 if (opcode != other.opcode)
95 else if (opcode == EMPTY || opcode == TOMBSTONE)
97 else if (type != other.type)
99 else if (firstVN != other.firstVN)
101 else if (secondVN != other.secondVN)
103 else if (thirdVN != other.thirdVN)
106 if (varargs.size() != other.varargs.size())
109 for (size_t i = 0; i < varargs.size(); ++i)
110 if (varargs[i] != other.varargs[i])
118 class VISIBILITY_HIDDEN ValueTable {
120 DenseMap<Value*, uint32_t> valueNumbering;
121 DenseMap<Expression, uint32_t> expressionNumbering;
123 uint32_t nextValueNumber;
125 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
126 Expression::ExpressionOpcode getOpcode(CmpInst* C);
127 Expression::ExpressionOpcode getOpcode(CastInst* C);
128 Expression create_expression(BinaryOperator* BO);
129 Expression create_expression(CmpInst* C);
130 Expression create_expression(ShuffleVectorInst* V);
131 Expression create_expression(ExtractElementInst* C);
132 Expression create_expression(InsertElementInst* V);
133 Expression create_expression(SelectInst* V);
134 Expression create_expression(CastInst* C);
135 Expression create_expression(GetElementPtrInst* G);
137 ValueTable() { nextValueNumber = 1; }
138 uint32_t lookup_or_add(Value* V);
139 uint32_t lookup(Value* V) const;
140 void add(Value* V, uint32_t num);
142 void erase(Value* v);
148 template <> struct DenseMapInfo<Expression> {
149 static inline Expression getEmptyKey() {
150 return Expression(Expression::EMPTY);
153 static inline Expression getTombstoneKey() {
154 return Expression(Expression::TOMBSTONE);
157 static unsigned getHashValue(const Expression e) {
158 unsigned hash = e.opcode;
160 hash = e.firstVN + hash * 37;
161 hash = e.secondVN + hash * 37;
162 hash = e.thirdVN + hash * 37;
164 hash = (unsigned)((uintptr_t)e.type >> 4) ^
165 (unsigned)((uintptr_t)e.type >> 9) +
168 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
169 E = e.varargs.end(); I != E; ++I)
170 hash = *I + hash * 37;
174 static bool isEqual(const Expression &LHS, const Expression &RHS) {
177 static bool isPod() { return true; }
181 //===----------------------------------------------------------------------===//
182 // ValueTable Internal Functions
183 //===----------------------------------------------------------------------===//
184 Expression::ExpressionOpcode
185 ValueTable::getOpcode(BinaryOperator* BO) {
186 switch(BO->getOpcode()) {
187 case Instruction::Add:
188 return Expression::ADD;
189 case Instruction::Sub:
190 return Expression::SUB;
191 case Instruction::Mul:
192 return Expression::MUL;
193 case Instruction::UDiv:
194 return Expression::UDIV;
195 case Instruction::SDiv:
196 return Expression::SDIV;
197 case Instruction::FDiv:
198 return Expression::FDIV;
199 case Instruction::URem:
200 return Expression::UREM;
201 case Instruction::SRem:
202 return Expression::SREM;
203 case Instruction::FRem:
204 return Expression::FREM;
205 case Instruction::Shl:
206 return Expression::SHL;
207 case Instruction::LShr:
208 return Expression::LSHR;
209 case Instruction::AShr:
210 return Expression::ASHR;
211 case Instruction::And:
212 return Expression::AND;
213 case Instruction::Or:
214 return Expression::OR;
215 case Instruction::Xor:
216 return Expression::XOR;
218 // THIS SHOULD NEVER HAPPEN
220 assert(0 && "Binary operator with unknown opcode?");
221 return Expression::ADD;
225 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
226 if (C->getOpcode() == Instruction::ICmp) {
227 switch (C->getPredicate()) {
228 case ICmpInst::ICMP_EQ:
229 return Expression::ICMPEQ;
230 case ICmpInst::ICMP_NE:
231 return Expression::ICMPNE;
232 case ICmpInst::ICMP_UGT:
233 return Expression::ICMPUGT;
234 case ICmpInst::ICMP_UGE:
235 return Expression::ICMPUGE;
236 case ICmpInst::ICMP_ULT:
237 return Expression::ICMPULT;
238 case ICmpInst::ICMP_ULE:
239 return Expression::ICMPULE;
240 case ICmpInst::ICMP_SGT:
241 return Expression::ICMPSGT;
242 case ICmpInst::ICMP_SGE:
243 return Expression::ICMPSGE;
244 case ICmpInst::ICMP_SLT:
245 return Expression::ICMPSLT;
246 case ICmpInst::ICMP_SLE:
247 return Expression::ICMPSLE;
249 // THIS SHOULD NEVER HAPPEN
251 assert(0 && "Comparison with unknown predicate?");
252 return Expression::ICMPEQ;
255 switch (C->getPredicate()) {
256 case FCmpInst::FCMP_OEQ:
257 return Expression::FCMPOEQ;
258 case FCmpInst::FCMP_OGT:
259 return Expression::FCMPOGT;
260 case FCmpInst::FCMP_OGE:
261 return Expression::FCMPOGE;
262 case FCmpInst::FCMP_OLT:
263 return Expression::FCMPOLT;
264 case FCmpInst::FCMP_OLE:
265 return Expression::FCMPOLE;
266 case FCmpInst::FCMP_ONE:
267 return Expression::FCMPONE;
268 case FCmpInst::FCMP_ORD:
269 return Expression::FCMPORD;
270 case FCmpInst::FCMP_UNO:
271 return Expression::FCMPUNO;
272 case FCmpInst::FCMP_UEQ:
273 return Expression::FCMPUEQ;
274 case FCmpInst::FCMP_UGT:
275 return Expression::FCMPUGT;
276 case FCmpInst::FCMP_UGE:
277 return Expression::FCMPUGE;
278 case FCmpInst::FCMP_ULT:
279 return Expression::FCMPULT;
280 case FCmpInst::FCMP_ULE:
281 return Expression::FCMPULE;
282 case FCmpInst::FCMP_UNE:
283 return Expression::FCMPUNE;
285 // THIS SHOULD NEVER HAPPEN
287 assert(0 && "Comparison with unknown predicate?");
288 return Expression::FCMPOEQ;
293 Expression::ExpressionOpcode
294 ValueTable::getOpcode(CastInst* C) {
295 switch(C->getOpcode()) {
296 case Instruction::Trunc:
297 return Expression::TRUNC;
298 case Instruction::ZExt:
299 return Expression::ZEXT;
300 case Instruction::SExt:
301 return Expression::SEXT;
302 case Instruction::FPToUI:
303 return Expression::FPTOUI;
304 case Instruction::FPToSI:
305 return Expression::FPTOSI;
306 case Instruction::UIToFP:
307 return Expression::UITOFP;
308 case Instruction::SIToFP:
309 return Expression::SITOFP;
310 case Instruction::FPTrunc:
311 return Expression::FPTRUNC;
312 case Instruction::FPExt:
313 return Expression::FPEXT;
314 case Instruction::PtrToInt:
315 return Expression::PTRTOINT;
316 case Instruction::IntToPtr:
317 return Expression::INTTOPTR;
318 case Instruction::BitCast:
319 return Expression::BITCAST;
321 // THIS SHOULD NEVER HAPPEN
323 assert(0 && "Cast operator with unknown opcode?");
324 return Expression::BITCAST;
328 Expression ValueTable::create_expression(BinaryOperator* BO) {
331 e.firstVN = lookup_or_add(BO->getOperand(0));
332 e.secondVN = lookup_or_add(BO->getOperand(1));
334 e.type = BO->getType();
335 e.opcode = getOpcode(BO);
340 Expression ValueTable::create_expression(CmpInst* C) {
343 e.firstVN = lookup_or_add(C->getOperand(0));
344 e.secondVN = lookup_or_add(C->getOperand(1));
346 e.type = C->getType();
347 e.opcode = getOpcode(C);
352 Expression ValueTable::create_expression(CastInst* C) {
355 e.firstVN = lookup_or_add(C->getOperand(0));
358 e.type = C->getType();
359 e.opcode = getOpcode(C);
364 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
367 e.firstVN = lookup_or_add(S->getOperand(0));
368 e.secondVN = lookup_or_add(S->getOperand(1));
369 e.thirdVN = lookup_or_add(S->getOperand(2));
370 e.type = S->getType();
371 e.opcode = Expression::SHUFFLE;
376 Expression ValueTable::create_expression(ExtractElementInst* E) {
379 e.firstVN = lookup_or_add(E->getOperand(0));
380 e.secondVN = lookup_or_add(E->getOperand(1));
382 e.type = E->getType();
383 e.opcode = Expression::EXTRACT;
388 Expression ValueTable::create_expression(InsertElementInst* I) {
391 e.firstVN = lookup_or_add(I->getOperand(0));
392 e.secondVN = lookup_or_add(I->getOperand(1));
393 e.thirdVN = lookup_or_add(I->getOperand(2));
394 e.type = I->getType();
395 e.opcode = Expression::INSERT;
400 Expression ValueTable::create_expression(SelectInst* I) {
403 e.firstVN = lookup_or_add(I->getCondition());
404 e.secondVN = lookup_or_add(I->getTrueValue());
405 e.thirdVN = lookup_or_add(I->getFalseValue());
406 e.type = I->getType();
407 e.opcode = Expression::SELECT;
412 Expression ValueTable::create_expression(GetElementPtrInst* G) {
415 e.firstVN = lookup_or_add(G->getPointerOperand());
418 e.type = G->getType();
419 e.opcode = Expression::GEP;
421 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
423 e.varargs.push_back(lookup_or_add(*I));
428 //===----------------------------------------------------------------------===//
429 // ValueTable External Functions
430 //===----------------------------------------------------------------------===//
432 /// lookup_or_add - Returns the value number for the specified value, assigning
433 /// it a new number if it did not have one before.
434 uint32_t ValueTable::lookup_or_add(Value* V) {
435 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
436 if (VI != valueNumbering.end())
440 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
441 Expression e = create_expression(BO);
443 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
444 if (EI != expressionNumbering.end()) {
445 valueNumbering.insert(std::make_pair(V, EI->second));
448 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
449 valueNumbering.insert(std::make_pair(V, nextValueNumber));
451 return nextValueNumber++;
453 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
454 Expression e = create_expression(C);
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 (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
467 Expression e = create_expression(U);
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 (ExtractElementInst* U = dyn_cast<ExtractElementInst>(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 (InsertElementInst* U = dyn_cast<InsertElementInst>(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 (SelectInst* U = dyn_cast<SelectInst>(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 (CastInst* U = dyn_cast<CastInst>(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 (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(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++;
545 valueNumbering.insert(std::make_pair(V, nextValueNumber));
546 return nextValueNumber++;
550 /// lookup - Returns the value number of the specified value. Fails if
551 /// the value has not yet been numbered.
552 uint32_t ValueTable::lookup(Value* V) const {
553 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
554 if (VI != valueNumbering.end())
557 assert(0 && "Value not numbered?");
562 /// clear - Remove all entries from the ValueTable
563 void ValueTable::clear() {
564 valueNumbering.clear();
565 expressionNumbering.clear();
569 /// erase - Remove a value from the value numbering
570 void ValueTable::erase(Value* V) {
571 valueNumbering.erase(V);
574 //===----------------------------------------------------------------------===//
575 // ValueNumberedSet Class
576 //===----------------------------------------------------------------------===//
578 class ValueNumberedSet {
580 SmallPtrSet<Value*, 8> contents;
583 ValueNumberedSet() { numbers.resize(1); }
584 ValueNumberedSet(const ValueNumberedSet& other) {
585 numbers = other.numbers;
586 contents = other.contents;
589 typedef SmallPtrSet<Value*, 8>::iterator iterator;
591 iterator begin() { return contents.begin(); }
592 iterator end() { return contents.end(); }
594 bool insert(Value* v) { return contents.insert(v); }
595 void insert(iterator I, iterator E) { contents.insert(I, E); }
596 void erase(Value* v) { contents.erase(v); }
597 unsigned count(Value* v) { return contents.count(v); }
598 size_t size() { return contents.size(); }
600 void set(unsigned i) {
601 if (i >= numbers.size())
607 void operator=(const ValueNumberedSet& other) {
608 contents = other.contents;
609 numbers = other.numbers;
612 void reset(unsigned i) {
613 if (i < numbers.size())
617 bool test(unsigned i) {
618 if (i >= numbers.size())
621 return numbers.test(i);
631 //===----------------------------------------------------------------------===//
633 //===----------------------------------------------------------------------===//
637 class VISIBILITY_HIDDEN GVN : public FunctionPass {
638 bool runOnFunction(Function &F);
640 static char ID; // Pass identification, replacement for typeid
641 GVN() : FunctionPass((intptr_t)&ID) { }
646 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
648 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
652 // This transformation requires dominator postdominator info
653 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
654 AU.setPreservesCFG();
655 AU.addRequired<DominatorTree>();
656 AU.addRequired<MemoryDependenceAnalysis>();
657 AU.addPreserved<MemoryDependenceAnalysis>();
661 // FIXME: eliminate or document these better
662 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
663 void val_insert(ValueNumberedSet& s, Value* v);
664 bool processLoad(LoadInst* L,
665 DenseMap<Value*, LoadInst*>& lastLoad,
666 SmallVector<Instruction*, 4>& toErase);
667 bool processInstruction(Instruction* I,
668 ValueNumberedSet& currAvail,
669 DenseMap<Value*, LoadInst*>& lastSeenLoad,
670 SmallVector<Instruction*, 4>& toErase);
671 bool processNonLocalLoad(LoadInst* L,
672 SmallVector<Instruction*, 4>& toErase);
673 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
674 DenseMap<BasicBlock*, Value*> &Phis,
675 bool top_level = false);
676 void dump(DenseMap<BasicBlock*, Value*>& d);
677 bool iterateOnFunction(Function &F);
678 Value* CollapsePhi(PHINode* p);
679 bool isSafeReplacement(PHINode* p, Instruction* inst);
686 // createGVNPass - The public interface to this file...
687 FunctionPass *llvm::createGVNPass() { return new GVN(); }
689 static RegisterPass<GVN> X("gvn",
690 "Global Value Numbering");
692 STATISTIC(NumGVNInstr, "Number of instructions deleted");
693 STATISTIC(NumGVNLoad, "Number of loads deleted");
695 /// find_leader - Given a set and a value number, return the first
696 /// element of the set with that value number, or 0 if no such element
698 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
702 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
704 if (v == VN.lookup(*I))
707 assert(0 && "No leader found, but present bit is set?");
711 /// val_insert - Insert a value into a set only if there is not a value
712 /// with the same value number already in the set
713 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
714 uint32_t num = VN.lookup(v);
719 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
721 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
722 E = d.end(); I != E; ++I) {
723 if (I->second == MemoryDependenceAnalysis::None)
731 Value* GVN::CollapsePhi(PHINode* p) {
732 DominatorTree &DT = getAnalysis<DominatorTree>();
733 Value* constVal = p->hasConstantValue();
736 if (Instruction* inst = dyn_cast<Instruction>(constVal)) {
737 if (DT.dominates(inst, p))
738 if (isSafeReplacement(p, inst))
748 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
749 if (!isa<PHINode>(inst))
752 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
754 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
755 if (use_phi->getParent() == inst->getParent())
761 /// GetValueForBlock - Get the value to use within the specified basic block.
762 /// available values are in Phis.
763 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
764 DenseMap<BasicBlock*, Value*> &Phis,
767 // If we have already computed this value, return the previously computed val.
768 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
769 if (V != Phis.end() && !top_level) return V->second;
771 BasicBlock* singlePred = BB->getSinglePredecessor();
773 Value *ret = GetValueForBlock(singlePred, orig, Phis);
777 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
778 // now, then get values to fill in the incoming values for the PHI.
779 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
781 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
783 if (Phis.count(BB) == 0)
784 Phis.insert(std::make_pair(BB, PN));
786 // Fill in the incoming values for the block.
787 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
788 Value* val = GetValueForBlock(*PI, orig, Phis);
790 PN->addIncoming(val, *PI);
793 // Attempt to collapse PHI nodes that are trivially redundant
794 Value* v = CollapsePhi(PN);
796 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
798 MD.removeInstruction(PN);
799 PN->replaceAllUsesWith(v);
801 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
802 E = Phis.end(); I != E; ++I)
806 PN->eraseFromParent();
813 // Cache our phi construction results
814 phiMap[orig->getPointerOperand()].insert(PN);
818 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
819 /// non-local by performing PHI construction.
820 bool GVN::processNonLocalLoad(LoadInst* L,
821 SmallVector<Instruction*, 4>& toErase) {
822 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
824 // Find the non-local dependencies of the load
825 DenseMap<BasicBlock*, Value*> deps;
826 MD.getNonLocalDependency(L, deps);
828 DenseMap<BasicBlock*, Value*> repl;
830 // Filter out useless results (non-locals, etc)
831 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
833 if (I->second == MemoryDependenceAnalysis::None) {
835 } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
837 } else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
838 if (S->getPointerOperand() == L->getPointerOperand())
839 repl[I->first] = S->getOperand(0);
842 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
843 if (LD->getPointerOperand() == L->getPointerOperand())
851 // Use cached PHI construction information from previous runs
852 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
853 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
855 if ((*I)->getParent() == L->getParent()) {
856 MD.removeInstruction(L);
857 L->replaceAllUsesWith(*I);
858 toErase.push_back(L);
863 repl.insert(std::make_pair((*I)->getParent(), *I));
867 // Perform PHI construction
868 SmallPtrSet<BasicBlock*, 4> visited;
869 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
871 MD.removeInstruction(L);
872 L->replaceAllUsesWith(v);
873 toErase.push_back(L);
879 /// processLoad - Attempt to eliminate a load, first by eliminating it
880 /// locally, and then attempting non-local elimination if that fails.
881 bool GVN::processLoad(LoadInst* L,
882 DenseMap<Value*, LoadInst*>& lastLoad,
883 SmallVector<Instruction*, 4>& toErase) {
884 if (L->isVolatile()) {
885 lastLoad[L->getPointerOperand()] = L;
889 Value* pointer = L->getPointerOperand();
890 LoadInst*& last = lastLoad[pointer];
892 // ... to a pointer that has been loaded from before...
893 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
894 bool removedNonLocal = false;
895 Instruction* dep = MD.getDependency(L);
896 if (dep == MemoryDependenceAnalysis::NonLocal &&
897 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
898 removedNonLocal = processNonLocalLoad(L, toErase);
900 if (!removedNonLocal)
903 return removedNonLocal;
907 bool deletedLoad = false;
909 // Walk up the dependency chain until we either find
910 // a dependency we can use, or we can't walk any further
911 while (dep != MemoryDependenceAnalysis::None &&
912 dep != MemoryDependenceAnalysis::NonLocal &&
913 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
914 // ... that depends on a store ...
915 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
916 if (S->getPointerOperand() == pointer) {
918 MD.removeInstruction(L);
920 L->replaceAllUsesWith(S->getOperand(0));
921 toErase.push_back(L);
926 // Whether we removed it or not, we can't
930 // If we don't depend on a store, and we haven't
931 // been loaded before, bail.
933 } else if (dep == last) {
935 MD.removeInstruction(L);
937 L->replaceAllUsesWith(last);
938 toErase.push_back(L);
944 dep = MD.getDependency(L, dep);
954 /// processInstruction - When calculating availability, handle an instruction
955 /// by inserting it into the appropriate sets
956 bool GVN::processInstruction(Instruction* I,
957 ValueNumberedSet& currAvail,
958 DenseMap<Value*, LoadInst*>& lastSeenLoad,
959 SmallVector<Instruction*, 4>& toErase) {
960 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
961 return processLoad(L, lastSeenLoad, toErase);
964 unsigned num = VN.lookup_or_add(I);
966 // Collapse PHI nodes
967 if (PHINode* p = dyn_cast<PHINode>(I)) {
968 Value* constVal = CollapsePhi(p);
971 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
973 if (PI->second.count(p))
976 p->replaceAllUsesWith(constVal);
977 toErase.push_back(p);
979 // Perform value-number based elimination
980 } else if (currAvail.test(num)) {
981 Value* repl = find_leader(currAvail, num);
984 I->replaceAllUsesWith(repl);
985 toErase.push_back(I);
987 } else if (!I->isTerminator()) {
995 // GVN::runOnFunction - This is the main transformation entry point for a
998 bool GVN::runOnFunction(Function& F) {
999 bool changed = false;
1000 bool shouldContinue = true;
1002 while (shouldContinue) {
1003 shouldContinue = iterateOnFunction(F);
1004 changed |= shouldContinue;
1011 // GVN::iterateOnFunction - Executes one iteration of GVN
1012 bool GVN::iterateOnFunction(Function &F) {
1013 // Clean out global sets from any previous functions
1015 availableOut.clear();
1018 bool changed_function = false;
1020 DominatorTree &DT = getAnalysis<DominatorTree>();
1022 SmallVector<Instruction*, 4> toErase;
1024 // Top-down walk of the dominator tree
1025 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1026 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1028 // Get the set to update for this block
1029 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1030 DenseMap<Value*, LoadInst*> lastSeenLoad;
1032 BasicBlock* BB = DI->getBlock();
1034 // A block inherits AVAIL_OUT from its dominator
1035 if (DI->getIDom() != 0)
1036 currAvail = availableOut[DI->getIDom()->getBlock()];
1038 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1040 changed_function |= processInstruction(BI, currAvail,
1041 lastSeenLoad, toErase);
1043 NumGVNInstr += toErase.size();
1045 // Avoid iterator invalidation
1048 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1049 E = toErase.end(); I != E; ++I)
1050 (*I)->eraseFromParent();
1056 return changed_function;