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 DenseMapKeyInfo<Expression> {
149 static inline Expression getEmptyKey() { return Expression(Expression::EMPTY); }
150 static inline Expression getTombstoneKey() { return Expression(Expression::TOMBSTONE); }
152 static unsigned getHashValue(const Expression e) {
153 unsigned hash = e.opcode;
155 hash = e.firstVN + hash * 37;
156 hash = e.secondVN + hash * 37;
157 hash = e.thirdVN + hash * 37;
159 hash = (unsigned)((uintptr_t)e.type >> 4) ^
160 (unsigned)((uintptr_t)e.type >> 9) +
163 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(), E = e.varargs.end();
165 hash = *I + hash * 37;
169 static bool isPod() { return true; }
173 //===----------------------------------------------------------------------===//
174 // ValueTable Internal Functions
175 //===----------------------------------------------------------------------===//
176 Expression::ExpressionOpcode
177 ValueTable::getOpcode(BinaryOperator* BO) {
178 switch(BO->getOpcode()) {
179 case Instruction::Add:
180 return Expression::ADD;
181 case Instruction::Sub:
182 return Expression::SUB;
183 case Instruction::Mul:
184 return Expression::MUL;
185 case Instruction::UDiv:
186 return Expression::UDIV;
187 case Instruction::SDiv:
188 return Expression::SDIV;
189 case Instruction::FDiv:
190 return Expression::FDIV;
191 case Instruction::URem:
192 return Expression::UREM;
193 case Instruction::SRem:
194 return Expression::SREM;
195 case Instruction::FRem:
196 return Expression::FREM;
197 case Instruction::Shl:
198 return Expression::SHL;
199 case Instruction::LShr:
200 return Expression::LSHR;
201 case Instruction::AShr:
202 return Expression::ASHR;
203 case Instruction::And:
204 return Expression::AND;
205 case Instruction::Or:
206 return Expression::OR;
207 case Instruction::Xor:
208 return Expression::XOR;
210 // THIS SHOULD NEVER HAPPEN
212 assert(0 && "Binary operator with unknown opcode?");
213 return Expression::ADD;
217 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
218 if (C->getOpcode() == Instruction::ICmp) {
219 switch (C->getPredicate()) {
220 case ICmpInst::ICMP_EQ:
221 return Expression::ICMPEQ;
222 case ICmpInst::ICMP_NE:
223 return Expression::ICMPNE;
224 case ICmpInst::ICMP_UGT:
225 return Expression::ICMPUGT;
226 case ICmpInst::ICMP_UGE:
227 return Expression::ICMPUGE;
228 case ICmpInst::ICMP_ULT:
229 return Expression::ICMPULT;
230 case ICmpInst::ICMP_ULE:
231 return Expression::ICMPULE;
232 case ICmpInst::ICMP_SGT:
233 return Expression::ICMPSGT;
234 case ICmpInst::ICMP_SGE:
235 return Expression::ICMPSGE;
236 case ICmpInst::ICMP_SLT:
237 return Expression::ICMPSLT;
238 case ICmpInst::ICMP_SLE:
239 return Expression::ICMPSLE;
241 // THIS SHOULD NEVER HAPPEN
243 assert(0 && "Comparison with unknown predicate?");
244 return Expression::ICMPEQ;
247 switch (C->getPredicate()) {
248 case FCmpInst::FCMP_OEQ:
249 return Expression::FCMPOEQ;
250 case FCmpInst::FCMP_OGT:
251 return Expression::FCMPOGT;
252 case FCmpInst::FCMP_OGE:
253 return Expression::FCMPOGE;
254 case FCmpInst::FCMP_OLT:
255 return Expression::FCMPOLT;
256 case FCmpInst::FCMP_OLE:
257 return Expression::FCMPOLE;
258 case FCmpInst::FCMP_ONE:
259 return Expression::FCMPONE;
260 case FCmpInst::FCMP_ORD:
261 return Expression::FCMPORD;
262 case FCmpInst::FCMP_UNO:
263 return Expression::FCMPUNO;
264 case FCmpInst::FCMP_UEQ:
265 return Expression::FCMPUEQ;
266 case FCmpInst::FCMP_UGT:
267 return Expression::FCMPUGT;
268 case FCmpInst::FCMP_UGE:
269 return Expression::FCMPUGE;
270 case FCmpInst::FCMP_ULT:
271 return Expression::FCMPULT;
272 case FCmpInst::FCMP_ULE:
273 return Expression::FCMPULE;
274 case FCmpInst::FCMP_UNE:
275 return Expression::FCMPUNE;
277 // THIS SHOULD NEVER HAPPEN
279 assert(0 && "Comparison with unknown predicate?");
280 return Expression::FCMPOEQ;
285 Expression::ExpressionOpcode
286 ValueTable::getOpcode(CastInst* C) {
287 switch(C->getOpcode()) {
288 case Instruction::Trunc:
289 return Expression::TRUNC;
290 case Instruction::ZExt:
291 return Expression::ZEXT;
292 case Instruction::SExt:
293 return Expression::SEXT;
294 case Instruction::FPToUI:
295 return Expression::FPTOUI;
296 case Instruction::FPToSI:
297 return Expression::FPTOSI;
298 case Instruction::UIToFP:
299 return Expression::UITOFP;
300 case Instruction::SIToFP:
301 return Expression::SITOFP;
302 case Instruction::FPTrunc:
303 return Expression::FPTRUNC;
304 case Instruction::FPExt:
305 return Expression::FPEXT;
306 case Instruction::PtrToInt:
307 return Expression::PTRTOINT;
308 case Instruction::IntToPtr:
309 return Expression::INTTOPTR;
310 case Instruction::BitCast:
311 return Expression::BITCAST;
313 // THIS SHOULD NEVER HAPPEN
315 assert(0 && "Cast operator with unknown opcode?");
316 return Expression::BITCAST;
320 Expression ValueTable::create_expression(BinaryOperator* BO) {
323 e.firstVN = lookup_or_add(BO->getOperand(0));
324 e.secondVN = lookup_or_add(BO->getOperand(1));
326 e.type = BO->getType();
327 e.opcode = getOpcode(BO);
332 Expression ValueTable::create_expression(CmpInst* C) {
335 e.firstVN = lookup_or_add(C->getOperand(0));
336 e.secondVN = lookup_or_add(C->getOperand(1));
338 e.type = C->getType();
339 e.opcode = getOpcode(C);
344 Expression ValueTable::create_expression(CastInst* C) {
347 e.firstVN = lookup_or_add(C->getOperand(0));
350 e.type = C->getType();
351 e.opcode = getOpcode(C);
356 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
359 e.firstVN = lookup_or_add(S->getOperand(0));
360 e.secondVN = lookup_or_add(S->getOperand(1));
361 e.thirdVN = lookup_or_add(S->getOperand(2));
362 e.type = S->getType();
363 e.opcode = Expression::SHUFFLE;
368 Expression ValueTable::create_expression(ExtractElementInst* E) {
371 e.firstVN = lookup_or_add(E->getOperand(0));
372 e.secondVN = lookup_or_add(E->getOperand(1));
374 e.type = E->getType();
375 e.opcode = Expression::EXTRACT;
380 Expression ValueTable::create_expression(InsertElementInst* I) {
383 e.firstVN = lookup_or_add(I->getOperand(0));
384 e.secondVN = lookup_or_add(I->getOperand(1));
385 e.thirdVN = lookup_or_add(I->getOperand(2));
386 e.type = I->getType();
387 e.opcode = Expression::INSERT;
392 Expression ValueTable::create_expression(SelectInst* I) {
395 e.firstVN = lookup_or_add(I->getCondition());
396 e.secondVN = lookup_or_add(I->getTrueValue());
397 e.thirdVN = lookup_or_add(I->getFalseValue());
398 e.type = I->getType();
399 e.opcode = Expression::SELECT;
404 Expression ValueTable::create_expression(GetElementPtrInst* G) {
407 e.firstVN = lookup_or_add(G->getPointerOperand());
410 e.type = G->getType();
411 e.opcode = Expression::GEP;
413 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
415 e.varargs.push_back(lookup_or_add(*I));
420 //===----------------------------------------------------------------------===//
421 // ValueTable External Functions
422 //===----------------------------------------------------------------------===//
424 /// lookup_or_add - Returns the value number for the specified value, assigning
425 /// it a new number if it did not have one before.
426 uint32_t ValueTable::lookup_or_add(Value* V) {
427 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
428 if (VI != valueNumbering.end())
432 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
433 Expression e = create_expression(BO);
435 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
436 if (EI != expressionNumbering.end()) {
437 valueNumbering.insert(std::make_pair(V, EI->second));
440 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
441 valueNumbering.insert(std::make_pair(V, nextValueNumber));
443 return nextValueNumber++;
445 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
446 Expression e = create_expression(C);
448 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
449 if (EI != expressionNumbering.end()) {
450 valueNumbering.insert(std::make_pair(V, EI->second));
453 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
454 valueNumbering.insert(std::make_pair(V, nextValueNumber));
456 return nextValueNumber++;
458 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
459 Expression e = create_expression(U);
461 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
462 if (EI != expressionNumbering.end()) {
463 valueNumbering.insert(std::make_pair(V, EI->second));
466 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
467 valueNumbering.insert(std::make_pair(V, nextValueNumber));
469 return nextValueNumber++;
471 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
472 Expression e = create_expression(U);
474 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
475 if (EI != expressionNumbering.end()) {
476 valueNumbering.insert(std::make_pair(V, EI->second));
479 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
480 valueNumbering.insert(std::make_pair(V, nextValueNumber));
482 return nextValueNumber++;
484 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
485 Expression e = create_expression(U);
487 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
488 if (EI != expressionNumbering.end()) {
489 valueNumbering.insert(std::make_pair(V, EI->second));
492 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
493 valueNumbering.insert(std::make_pair(V, nextValueNumber));
495 return nextValueNumber++;
497 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
498 Expression e = create_expression(U);
500 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
501 if (EI != expressionNumbering.end()) {
502 valueNumbering.insert(std::make_pair(V, EI->second));
505 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
506 valueNumbering.insert(std::make_pair(V, nextValueNumber));
508 return nextValueNumber++;
510 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
511 Expression e = create_expression(U);
513 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
514 if (EI != expressionNumbering.end()) {
515 valueNumbering.insert(std::make_pair(V, EI->second));
518 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
519 valueNumbering.insert(std::make_pair(V, nextValueNumber));
521 return nextValueNumber++;
523 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
524 Expression e = create_expression(U);
526 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
527 if (EI != expressionNumbering.end()) {
528 valueNumbering.insert(std::make_pair(V, EI->second));
531 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
532 valueNumbering.insert(std::make_pair(V, nextValueNumber));
534 return nextValueNumber++;
537 valueNumbering.insert(std::make_pair(V, nextValueNumber));
538 return nextValueNumber++;
542 /// lookup - Returns the value number of the specified value. Fails if
543 /// the value has not yet been numbered.
544 uint32_t ValueTable::lookup(Value* V) const {
545 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
546 if (VI != valueNumbering.end())
549 assert(0 && "Value not numbered?");
554 /// clear - Remove all entries from the ValueTable
555 void ValueTable::clear() {
556 valueNumbering.clear();
557 expressionNumbering.clear();
561 //===----------------------------------------------------------------------===//
562 // ValueNumberedSet Class
563 //===----------------------------------------------------------------------===//
565 class ValueNumberedSet {
567 SmallPtrSet<Value*, 8> contents;
570 ValueNumberedSet() { numbers.resize(1); }
571 ValueNumberedSet(const ValueNumberedSet& other) {
572 numbers = other.numbers;
573 contents = other.contents;
576 typedef SmallPtrSet<Value*, 8>::iterator iterator;
578 iterator begin() { return contents.begin(); }
579 iterator end() { return contents.end(); }
581 bool insert(Value* v) { return contents.insert(v); }
582 void insert(iterator I, iterator E) { contents.insert(I, E); }
583 void erase(Value* v) { contents.erase(v); }
584 unsigned count(Value* v) { return contents.count(v); }
585 size_t size() { return contents.size(); }
587 void set(unsigned i) {
588 if (i >= numbers.size())
594 void operator=(const ValueNumberedSet& other) {
595 contents = other.contents;
596 numbers = other.numbers;
599 void reset(unsigned i) {
600 if (i < numbers.size())
604 bool test(unsigned i) {
605 if (i >= numbers.size())
608 return numbers.test(i);
618 //===----------------------------------------------------------------------===//
620 //===----------------------------------------------------------------------===//
624 class VISIBILITY_HIDDEN GVN : public FunctionPass {
625 bool runOnFunction(Function &F);
627 static char ID; // Pass identification, replacement for typeid
628 GVN() : FunctionPass((intptr_t)&ID) { }
633 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
635 // This transformation requires dominator postdominator info
636 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
637 AU.setPreservesCFG();
638 AU.addRequired<DominatorTree>();
639 AU.addRequired<MemoryDependenceAnalysis>();
640 AU.addPreserved<MemoryDependenceAnalysis>();
644 // FIXME: eliminate or document these better
645 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
646 void val_insert(ValueNumberedSet& s, Value* v);
647 bool processLoad(LoadInst* L,
648 DenseMap<Value*, LoadInst*>& lastLoad,
649 SmallVector<Instruction*, 4>& toErase);
650 bool processInstruction(Instruction* I,
651 ValueNumberedSet& currAvail,
652 DenseMap<Value*, LoadInst*>& lastSeenLoad,
653 SmallVector<Instruction*, 4>& toErase);
654 bool processNonLocalLoad(LoadInst* L, SmallVector<Instruction*, 4>& toErase);
655 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
656 DenseMap<BasicBlock*, Value*> &Phis);
657 void dump(DenseMap<BasicBlock*, Value*>& d);
664 // createGVNPass - The public interface to this file...
665 FunctionPass *llvm::createGVNPass() { return new GVN(); }
667 static RegisterPass<GVN> X("gvn",
668 "Global Value Numbering");
670 STATISTIC(NumGVNInstr, "Number of instructions deleted");
671 STATISTIC(NumGVNLoad, "Number of loads deleted");
673 /// find_leader - Given a set and a value number, return the first
674 /// element of the set with that value number, or 0 if no such element
676 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
680 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
682 if (v == VN.lookup(*I))
685 assert(0 && "No leader found, but present bit is set?");
689 /// val_insert - Insert a value into a set only if there is not a value
690 /// with the same value number already in the set
691 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
692 uint32_t num = VN.lookup(v);
697 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
699 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
700 E = d.end(); I != E; ++I) {
701 if (I->second == MemoryDependenceAnalysis::None)
710 /// GetValueForBlock - Get the value to use within the specified basic block.
711 /// available values are in Phis.
712 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
713 DenseMap<BasicBlock*, Value*> &Phis) {
714 DominatorTree &DT = getAnalysis<DominatorTree>();
716 // If we have already computed this value, return the previously computed val.
717 Value *&V = Phis[BB];
720 DomTreeNode *IDom = DT.getNode(BB)->getIDom();
722 if (IDom && Phis.count(IDom->getBlock())) {
723 return V = GetValueForBlock(IDom->getBlock(), orig, Phis);
726 if (std::distance(pred_begin(BB), pred_end(BB)) == 1)
727 return V = GetValueForBlock(IDom->getBlock(), orig, Phis);
729 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
730 // now, then get values to fill in the incoming values for the PHI.
731 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
733 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
736 // Fill in the incoming values for the block.
737 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
738 PN->addIncoming(GetValueForBlock(*PI, orig, Phis), *PI);
742 bool GVN::processNonLocalLoad(LoadInst* L, SmallVector<Instruction*, 4>& toErase) {
743 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
745 DenseMap<BasicBlock*, Value*> deps;
746 bool ret = MD.getNonLocalDependency(L, deps);
750 DenseMap<BasicBlock*, Value*> repl;
751 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
753 if (I->second == MemoryDependenceAnalysis::None) {
755 } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
757 }else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
758 if (S->getPointerOperand() == L->getPointerOperand())
759 repl.insert(std::make_pair(I->first, S->getOperand(0)));
762 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
763 if (LD->getPointerOperand() == L->getPointerOperand())
764 repl.insert(std::make_pair(I->first, LD));
771 SmallPtrSet<BasicBlock*, 4> visited;
772 Value* v = GetValueForBlock(L->getParent(), L, repl);
774 MD.removeInstruction(L);
775 L->replaceAllUsesWith(v);
776 toErase.push_back(L);
781 bool GVN::processLoad(LoadInst* L,
782 DenseMap<Value*, LoadInst*>& lastLoad,
783 SmallVector<Instruction*, 4>& toErase) {
784 if (L->isVolatile()) {
785 lastLoad[L->getPointerOperand()] = L;
789 Value* pointer = L->getPointerOperand();
790 LoadInst*& last = lastLoad[pointer];
792 // ... to a pointer that has been loaded from before...
793 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
794 Instruction* dep = MD.getDependency(L);
795 if (dep == MemoryDependenceAnalysis::NonLocal &&
796 L->getParent() != &L->getParent()->getParent()->getEntryBlock())
797 processNonLocalLoad(L, toErase);
798 bool deletedLoad = false;
800 while (dep != MemoryDependenceAnalysis::None &&
801 dep != MemoryDependenceAnalysis::NonLocal &&
802 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
803 // ... that depends on a store ...
804 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
805 if (S->getPointerOperand() == pointer) {
807 MD.removeInstruction(L);
809 L->replaceAllUsesWith(S->getOperand(0));
810 toErase.push_back(L);
815 // Whether we removed it or not, we can't
819 // If we don't depend on a store, and we haven't
820 // been loaded before, bail.
822 } else if (dep == last) {
824 MD.removeInstruction(L);
826 L->replaceAllUsesWith(last);
827 toErase.push_back(L);
833 dep = MD.getDependency(L, dep);
843 /// buildsets_availout - When calculating availability, handle an instruction
844 /// by inserting it into the appropriate sets
845 bool GVN::processInstruction(Instruction* I,
846 ValueNumberedSet& currAvail,
847 DenseMap<Value*, LoadInst*>& lastSeenLoad,
848 SmallVector<Instruction*, 4>& toErase) {
849 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
850 return processLoad(L, lastSeenLoad, toErase);
853 unsigned num = VN.lookup_or_add(I);
855 if (currAvail.test(num)) {
856 Value* repl = find_leader(currAvail, num);
858 I->replaceAllUsesWith(repl);
859 toErase.push_back(I);
861 } else if (!I->isTerminator()) {
869 // GVN::runOnFunction - This is the main transformation entry point for a
872 bool GVN::runOnFunction(Function &F) {
873 // Clean out global sets from any previous functions
875 availableOut.clear();
877 bool changed_function = false;
879 DominatorTree &DT = getAnalysis<DominatorTree>();
881 SmallVector<Instruction*, 4> toErase;
883 // Top-down walk of the dominator tree
884 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
885 E = df_end(DT.getRootNode()); DI != E; ++DI) {
887 // Get the set to update for this block
888 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
889 DenseMap<Value*, LoadInst*> lastSeenLoad;
891 BasicBlock* BB = DI->getBlock();
893 // A block inherits AVAIL_OUT from its dominator
894 if (DI->getIDom() != 0)
895 currAvail = availableOut[DI->getIDom()->getBlock()];
897 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
899 changed_function |= processInstruction(BI, currAvail, lastSeenLoad, toErase);
901 NumGVNInstr += toErase.size();
903 // Avoid iterator invalidation
906 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
907 E = toErase.end(); I != E; ++I)
908 (*I)->eraseFromParent();
914 return changed_function;