1 //===- GVN.cpp - Eliminate redundant values and loads ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs global value numbering to eliminate fully redundant
11 // instructions. It also performs simple dead load elimination.
13 // Note that this pass does the value numbering itself, it does not use the
14 // ValueNumbering analysis passes.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "gvn"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Value.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/ScopedHashTable.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/SparseBitVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/Dominators.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
41 STATISTIC(NumGVNInstr, "Number of instructions deleted");
42 STATISTIC(NumGVNLoad, "Number of loads deleted");
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 /// This class holds the mapping between values and value numbers. It is used
49 /// as an efficient mechanism to determine the expression-wise equivalence of
52 struct VISIBILITY_HIDDEN Expression {
53 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
54 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
55 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
56 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
57 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
58 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
59 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
60 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
61 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
62 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
65 ExpressionOpcode opcode;
70 SmallVector<uint32_t, 4> varargs;
74 Expression(ExpressionOpcode o) : opcode(o) { }
76 bool operator==(const Expression &other) const {
77 if (opcode != other.opcode)
79 else if (opcode == EMPTY || opcode == TOMBSTONE)
81 else if (type != other.type)
83 else if (function != other.function)
85 else if (firstVN != other.firstVN)
87 else if (secondVN != other.secondVN)
89 else if (thirdVN != other.thirdVN)
92 if (varargs.size() != other.varargs.size())
95 for (size_t i = 0; i < varargs.size(); ++i)
96 if (varargs[i] != other.varargs[i])
103 bool operator!=(const Expression &other) const {
104 if (opcode != other.opcode)
106 else if (opcode == EMPTY || opcode == TOMBSTONE)
108 else if (type != other.type)
110 else if (function != other.function)
112 else if (firstVN != other.firstVN)
114 else if (secondVN != other.secondVN)
116 else if (thirdVN != other.thirdVN)
119 if (varargs.size() != other.varargs.size())
122 for (size_t i = 0; i < varargs.size(); ++i)
123 if (varargs[i] != other.varargs[i])
131 class VISIBILITY_HIDDEN ValueTable {
133 DenseMap<Value*, uint32_t> valueNumbering;
134 DenseMap<Expression, uint32_t> expressionNumbering;
136 MemoryDependenceAnalysis* MD;
139 uint32_t nextValueNumber;
141 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
142 Expression::ExpressionOpcode getOpcode(CmpInst* C);
143 Expression::ExpressionOpcode getOpcode(CastInst* C);
144 Expression create_expression(BinaryOperator* BO);
145 Expression create_expression(CmpInst* C);
146 Expression create_expression(ShuffleVectorInst* V);
147 Expression create_expression(ExtractElementInst* C);
148 Expression create_expression(InsertElementInst* V);
149 Expression create_expression(SelectInst* V);
150 Expression create_expression(CastInst* C);
151 Expression create_expression(GetElementPtrInst* G);
152 Expression create_expression(CallInst* C);
153 Expression create_expression(Constant* C);
155 ValueTable() : nextValueNumber(1) { }
156 uint32_t lookup_or_add(Value* V);
157 uint32_t lookup(Value* V) const;
158 void add(Value* V, uint32_t num);
160 void erase(Value* v);
162 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
163 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
164 void setDomTree(DominatorTree* D) { DT = D; }
169 template <> struct DenseMapInfo<Expression> {
170 static inline Expression getEmptyKey() {
171 return Expression(Expression::EMPTY);
174 static inline Expression getTombstoneKey() {
175 return Expression(Expression::TOMBSTONE);
178 static unsigned getHashValue(const Expression e) {
179 unsigned hash = e.opcode;
181 hash = e.firstVN + hash * 37;
182 hash = e.secondVN + hash * 37;
183 hash = e.thirdVN + hash * 37;
185 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
186 (unsigned)((uintptr_t)e.type >> 9)) +
189 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
190 E = e.varargs.end(); I != E; ++I)
191 hash = *I + hash * 37;
193 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
194 (unsigned)((uintptr_t)e.function >> 9)) +
199 static bool isEqual(const Expression &LHS, const Expression &RHS) {
202 static bool isPod() { return true; }
206 //===----------------------------------------------------------------------===//
207 // ValueTable Internal Functions
208 //===----------------------------------------------------------------------===//
209 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
210 switch(BO->getOpcode()) {
211 default: // THIS SHOULD NEVER HAPPEN
212 assert(0 && "Binary operator with unknown opcode?");
213 case Instruction::Add: return Expression::ADD;
214 case Instruction::Sub: return Expression::SUB;
215 case Instruction::Mul: return Expression::MUL;
216 case Instruction::UDiv: return Expression::UDIV;
217 case Instruction::SDiv: return Expression::SDIV;
218 case Instruction::FDiv: return Expression::FDIV;
219 case Instruction::URem: return Expression::UREM;
220 case Instruction::SRem: return Expression::SREM;
221 case Instruction::FRem: return Expression::FREM;
222 case Instruction::Shl: return Expression::SHL;
223 case Instruction::LShr: return Expression::LSHR;
224 case Instruction::AShr: return Expression::ASHR;
225 case Instruction::And: return Expression::AND;
226 case Instruction::Or: return Expression::OR;
227 case Instruction::Xor: return Expression::XOR;
231 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
232 if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
233 switch (C->getPredicate()) {
234 default: // THIS SHOULD NEVER HAPPEN
235 assert(0 && "Comparison with unknown predicate?");
236 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
237 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
238 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
239 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
240 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
241 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
242 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
243 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
244 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
245 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
248 assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
249 switch (C->getPredicate()) {
250 default: // THIS SHOULD NEVER HAPPEN
251 assert(0 && "Comparison with unknown predicate?");
252 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
253 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
254 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
255 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
256 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
257 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
258 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
259 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
260 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
261 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
262 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
263 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
264 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
265 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
269 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
270 switch(C->getOpcode()) {
271 default: // THIS SHOULD NEVER HAPPEN
272 assert(0 && "Cast operator with unknown opcode?");
273 case Instruction::Trunc: return Expression::TRUNC;
274 case Instruction::ZExt: return Expression::ZEXT;
275 case Instruction::SExt: return Expression::SEXT;
276 case Instruction::FPToUI: return Expression::FPTOUI;
277 case Instruction::FPToSI: return Expression::FPTOSI;
278 case Instruction::UIToFP: return Expression::UITOFP;
279 case Instruction::SIToFP: return Expression::SITOFP;
280 case Instruction::FPTrunc: return Expression::FPTRUNC;
281 case Instruction::FPExt: return Expression::FPEXT;
282 case Instruction::PtrToInt: return Expression::PTRTOINT;
283 case Instruction::IntToPtr: return Expression::INTTOPTR;
284 case Instruction::BitCast: return Expression::BITCAST;
288 Expression ValueTable::create_expression(CallInst* C) {
291 e.type = C->getType();
295 e.function = C->getCalledFunction();
296 e.opcode = Expression::CALL;
298 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
300 e.varargs.push_back(lookup_or_add(*I));
305 Expression ValueTable::create_expression(BinaryOperator* BO) {
308 e.firstVN = lookup_or_add(BO->getOperand(0));
309 e.secondVN = lookup_or_add(BO->getOperand(1));
312 e.type = BO->getType();
313 e.opcode = getOpcode(BO);
318 Expression ValueTable::create_expression(CmpInst* C) {
321 e.firstVN = lookup_or_add(C->getOperand(0));
322 e.secondVN = lookup_or_add(C->getOperand(1));
325 e.type = C->getType();
326 e.opcode = getOpcode(C);
331 Expression ValueTable::create_expression(CastInst* C) {
334 e.firstVN = lookup_or_add(C->getOperand(0));
338 e.type = C->getType();
339 e.opcode = getOpcode(C);
344 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
347 e.firstVN = lookup_or_add(S->getOperand(0));
348 e.secondVN = lookup_or_add(S->getOperand(1));
349 e.thirdVN = lookup_or_add(S->getOperand(2));
351 e.type = S->getType();
352 e.opcode = Expression::SHUFFLE;
357 Expression ValueTable::create_expression(ExtractElementInst* E) {
360 e.firstVN = lookup_or_add(E->getOperand(0));
361 e.secondVN = lookup_or_add(E->getOperand(1));
364 e.type = E->getType();
365 e.opcode = Expression::EXTRACT;
370 Expression ValueTable::create_expression(InsertElementInst* I) {
373 e.firstVN = lookup_or_add(I->getOperand(0));
374 e.secondVN = lookup_or_add(I->getOperand(1));
375 e.thirdVN = lookup_or_add(I->getOperand(2));
377 e.type = I->getType();
378 e.opcode = Expression::INSERT;
383 Expression ValueTable::create_expression(SelectInst* I) {
386 e.firstVN = lookup_or_add(I->getCondition());
387 e.secondVN = lookup_or_add(I->getTrueValue());
388 e.thirdVN = lookup_or_add(I->getFalseValue());
390 e.type = I->getType();
391 e.opcode = Expression::SELECT;
396 Expression ValueTable::create_expression(GetElementPtrInst* G) {
399 e.firstVN = lookup_or_add(G->getPointerOperand());
403 e.type = G->getType();
404 e.opcode = Expression::GEP;
406 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
408 e.varargs.push_back(lookup_or_add(*I));
413 //===----------------------------------------------------------------------===//
414 // ValueTable External Functions
415 //===----------------------------------------------------------------------===//
417 /// lookup_or_add - Returns the value number for the specified value, assigning
418 /// it a new number if it did not have one before.
419 uint32_t ValueTable::lookup_or_add(Value* V) {
420 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
421 if (VI != valueNumbering.end())
424 if (CallInst* C = dyn_cast<CallInst>(V)) {
425 if (AA->doesNotAccessMemory(C)) {
426 Expression e = create_expression(C);
428 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
429 if (EI != expressionNumbering.end()) {
430 valueNumbering.insert(std::make_pair(V, EI->second));
433 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
434 valueNumbering.insert(std::make_pair(V, nextValueNumber));
436 return nextValueNumber++;
438 } else if (AA->onlyReadsMemory(C)) {
439 Expression e = create_expression(C);
441 if (expressionNumbering.find(e) == expressionNumbering.end()) {
442 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
443 valueNumbering.insert(std::make_pair(V, nextValueNumber));
444 return nextValueNumber++;
447 Instruction* local_dep = MD->getDependency(C);
449 if (local_dep == MemoryDependenceAnalysis::None) {
450 valueNumbering.insert(std::make_pair(V, nextValueNumber));
451 return nextValueNumber++;
452 } else if (local_dep != MemoryDependenceAnalysis::NonLocal) {
453 if (!isa<CallInst>(local_dep)) {
454 valueNumbering.insert(std::make_pair(V, nextValueNumber));
455 return nextValueNumber++;
458 CallInst* local_cdep = cast<CallInst>(local_dep);
460 if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
461 local_cdep->getNumOperands() != C->getNumOperands()) {
462 valueNumbering.insert(std::make_pair(V, nextValueNumber));
463 return nextValueNumber++;
464 } else if (!C->getCalledFunction()) {
465 valueNumbering.insert(std::make_pair(V, nextValueNumber));
466 return nextValueNumber++;
468 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
469 uint32_t c_vn = lookup_or_add(C->getOperand(i));
470 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
472 valueNumbering.insert(std::make_pair(V, nextValueNumber));
473 return nextValueNumber++;
477 uint32_t v = lookup_or_add(local_cdep);
478 valueNumbering.insert(std::make_pair(V, v));
484 DenseMap<BasicBlock*, Value*> deps;
485 MD->getNonLocalDependency(C, deps);
488 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(),
489 E = deps.end(); I != E; ++I) {
490 if (I->second == MemoryDependenceAnalysis::None) {
491 valueNumbering.insert(std::make_pair(V, nextValueNumber));
493 return nextValueNumber++;
494 } else if (I->second != MemoryDependenceAnalysis::NonLocal) {
495 if (DT->properlyDominates(I->first, C->getParent())) {
496 if (CallInst* CD = dyn_cast<CallInst>(I->second))
499 valueNumbering.insert(std::make_pair(V, nextValueNumber));
500 return nextValueNumber++;
503 valueNumbering.insert(std::make_pair(V, nextValueNumber));
504 return nextValueNumber++;
510 valueNumbering.insert(std::make_pair(V, nextValueNumber));
511 return nextValueNumber++;
514 if (cdep->getCalledFunction() != C->getCalledFunction() ||
515 cdep->getNumOperands() != C->getNumOperands()) {
516 valueNumbering.insert(std::make_pair(V, nextValueNumber));
517 return nextValueNumber++;
518 } else if (!C->getCalledFunction()) {
519 valueNumbering.insert(std::make_pair(V, nextValueNumber));
520 return nextValueNumber++;
522 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
523 uint32_t c_vn = lookup_or_add(C->getOperand(i));
524 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
526 valueNumbering.insert(std::make_pair(V, nextValueNumber));
527 return nextValueNumber++;
531 uint32_t v = lookup_or_add(cdep);
532 valueNumbering.insert(std::make_pair(V, v));
537 valueNumbering.insert(std::make_pair(V, nextValueNumber));
538 return nextValueNumber++;
540 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
541 Expression e = create_expression(BO);
543 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
544 if (EI != expressionNumbering.end()) {
545 valueNumbering.insert(std::make_pair(V, EI->second));
548 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
549 valueNumbering.insert(std::make_pair(V, nextValueNumber));
551 return nextValueNumber++;
553 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
554 Expression e = create_expression(C);
556 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
557 if (EI != expressionNumbering.end()) {
558 valueNumbering.insert(std::make_pair(V, EI->second));
561 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
562 valueNumbering.insert(std::make_pair(V, nextValueNumber));
564 return nextValueNumber++;
566 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
567 Expression e = create_expression(U);
569 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
570 if (EI != expressionNumbering.end()) {
571 valueNumbering.insert(std::make_pair(V, EI->second));
574 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
575 valueNumbering.insert(std::make_pair(V, nextValueNumber));
577 return nextValueNumber++;
579 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
580 Expression e = create_expression(U);
582 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
583 if (EI != expressionNumbering.end()) {
584 valueNumbering.insert(std::make_pair(V, EI->second));
587 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
588 valueNumbering.insert(std::make_pair(V, nextValueNumber));
590 return nextValueNumber++;
592 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
593 Expression e = create_expression(U);
595 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
596 if (EI != expressionNumbering.end()) {
597 valueNumbering.insert(std::make_pair(V, EI->second));
600 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
601 valueNumbering.insert(std::make_pair(V, nextValueNumber));
603 return nextValueNumber++;
605 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
606 Expression e = create_expression(U);
608 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
609 if (EI != expressionNumbering.end()) {
610 valueNumbering.insert(std::make_pair(V, EI->second));
613 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
614 valueNumbering.insert(std::make_pair(V, nextValueNumber));
616 return nextValueNumber++;
618 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
619 Expression e = create_expression(U);
621 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
622 if (EI != expressionNumbering.end()) {
623 valueNumbering.insert(std::make_pair(V, EI->second));
626 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
627 valueNumbering.insert(std::make_pair(V, nextValueNumber));
629 return nextValueNumber++;
631 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
632 Expression e = create_expression(U);
634 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
635 if (EI != expressionNumbering.end()) {
636 valueNumbering.insert(std::make_pair(V, EI->second));
639 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
640 valueNumbering.insert(std::make_pair(V, nextValueNumber));
642 return nextValueNumber++;
645 valueNumbering.insert(std::make_pair(V, nextValueNumber));
646 return nextValueNumber++;
650 /// lookup - Returns the value number of the specified value. Fails if
651 /// the value has not yet been numbered.
652 uint32_t ValueTable::lookup(Value* V) const {
653 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
654 assert(VI != valueNumbering.end() && "Value not numbered?");
658 /// clear - Remove all entries from the ValueTable
659 void ValueTable::clear() {
660 valueNumbering.clear();
661 expressionNumbering.clear();
665 /// erase - Remove a value from the value numbering
666 void ValueTable::erase(Value* V) {
667 valueNumbering.erase(V);
670 //===----------------------------------------------------------------------===//
672 //===----------------------------------------------------------------------===//
675 template<> struct DenseMapInfo<uint32_t> {
676 static inline uint32_t getEmptyKey() { return ~0; }
677 static inline uint32_t getTombstoneKey() { return ~0 - 1; }
678 static unsigned getHashValue(const uint32_t& Val) { return Val; }
679 static bool isPod() { return true; }
680 static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) {
686 typedef ScopedHashTable<uint32_t, Value*> ValueNumberMap;
687 typedef ScopedHashTableScope<uint32_t, Value*> ValueNumberScope;
691 class VISIBILITY_HIDDEN GVN : public FunctionPass {
692 bool runOnFunction(Function &F);
694 static char ID; // Pass identification, replacement for typeid
695 GVN() : FunctionPass((intptr_t)&ID) { }
700 DenseMap<BasicBlock*, ValueNumberScope> availableOut;
701 ValueNumberMap BaseMap;
703 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
707 // This transformation requires dominator postdominator info
708 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
709 AU.setPreservesCFG();
710 AU.addRequired<DominatorTree>();
711 AU.addRequired<MemoryDependenceAnalysis>();
712 AU.addRequired<AliasAnalysis>();
713 AU.addPreserved<AliasAnalysis>();
714 AU.addPreserved<MemoryDependenceAnalysis>();
718 // FIXME: eliminate or document these better
719 bool processLoad(LoadInst* L,
720 DenseMap<Value*, LoadInst*> &lastLoad,
721 SmallVectorImpl<Instruction*> &toErase);
722 bool processInstruction(Instruction* I,
723 DenseMap<Value*, LoadInst*>& lastSeenLoad,
724 SmallVectorImpl<Instruction*> &toErase);
725 bool processNonLocalLoad(LoadInst* L,
726 SmallVectorImpl<Instruction*> &toErase);
727 bool processBlock(DomTreeNode* DTN);
728 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
729 DenseMap<BasicBlock*, Value*> &Phis,
730 bool top_level = false);
731 void dump(DenseMap<BasicBlock*, Value*>& d);
732 bool iterateOnFunction(Function &F);
733 Value* CollapsePhi(PHINode* p);
734 bool isSafeReplacement(PHINode* p, Instruction* inst);
740 // createGVNPass - The public interface to this file...
741 FunctionPass *llvm::createGVNPass() { return new GVN(); }
743 static RegisterPass<GVN> X("gvn",
744 "Global Value Numbering");
746 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
748 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
749 E = d.end(); I != E; ++I) {
750 if (I->second == MemoryDependenceAnalysis::None)
758 Value* GVN::CollapsePhi(PHINode* p) {
759 DominatorTree &DT = getAnalysis<DominatorTree>();
760 Value* constVal = p->hasConstantValue();
762 if (!constVal) return 0;
764 Instruction* inst = dyn_cast<Instruction>(constVal);
768 if (DT.dominates(inst, p))
769 if (isSafeReplacement(p, inst))
774 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
775 if (!isa<PHINode>(inst))
778 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
780 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
781 if (use_phi->getParent() == inst->getParent())
787 /// GetValueForBlock - Get the value to use within the specified basic block.
788 /// available values are in Phis.
789 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
790 DenseMap<BasicBlock*, Value*> &Phis,
793 // If we have already computed this value, return the previously computed val.
794 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
795 if (V != Phis.end() && !top_level) return V->second;
797 BasicBlock* singlePred = BB->getSinglePredecessor();
799 Value *ret = GetValueForBlock(singlePred, orig, Phis);
804 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
805 // now, then get values to fill in the incoming values for the PHI.
806 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
808 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
810 if (Phis.count(BB) == 0)
811 Phis.insert(std::make_pair(BB, PN));
813 // Fill in the incoming values for the block.
814 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
815 Value* val = GetValueForBlock(*PI, orig, Phis);
816 PN->addIncoming(val, *PI);
819 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
820 AA.copyValue(orig, PN);
822 // Attempt to collapse PHI nodes that are trivially redundant
823 Value* v = CollapsePhi(PN);
825 // Cache our phi construction results
826 phiMap[orig->getPointerOperand()].insert(PN);
830 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
832 MD.removeInstruction(PN);
833 PN->replaceAllUsesWith(v);
835 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
836 E = Phis.end(); I != E; ++I)
840 PN->eraseFromParent();
846 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
847 /// non-local by performing PHI construction.
848 bool GVN::processNonLocalLoad(LoadInst* L,
849 SmallVectorImpl<Instruction*> &toErase) {
850 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
852 // Find the non-local dependencies of the load
853 DenseMap<BasicBlock*, Value*> deps;
854 MD.getNonLocalDependency(L, deps);
856 DenseMap<BasicBlock*, Value*> repl;
858 // Filter out useless results (non-locals, etc)
859 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
861 if (I->second == MemoryDependenceAnalysis::None)
864 if (I->second == MemoryDependenceAnalysis::NonLocal)
867 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
868 if (S->getPointerOperand() != L->getPointerOperand())
870 repl[I->first] = S->getOperand(0);
871 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
872 if (LD->getPointerOperand() != L->getPointerOperand())
880 // Use cached PHI construction information from previous runs
881 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
882 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
884 if ((*I)->getParent() == L->getParent()) {
885 MD.removeInstruction(L);
886 L->replaceAllUsesWith(*I);
887 toErase.push_back(L);
892 repl.insert(std::make_pair((*I)->getParent(), *I));
895 // Perform PHI construction
896 SmallPtrSet<BasicBlock*, 4> visited;
897 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
899 MD.removeInstruction(L);
900 L->replaceAllUsesWith(v);
901 toErase.push_back(L);
907 /// processLoad - Attempt to eliminate a load, first by eliminating it
908 /// locally, and then attempting non-local elimination if that fails.
909 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
910 SmallVectorImpl<Instruction*> &toErase) {
911 if (L->isVolatile()) {
912 lastLoad[L->getPointerOperand()] = L;
916 Value* pointer = L->getPointerOperand();
917 LoadInst*& last = lastLoad[pointer];
919 // ... to a pointer that has been loaded from before...
920 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
921 bool removedNonLocal = false;
922 Instruction* dep = MD.getDependency(L);
923 if (dep == MemoryDependenceAnalysis::NonLocal &&
924 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
925 removedNonLocal = processNonLocalLoad(L, toErase);
927 if (!removedNonLocal)
930 return removedNonLocal;
934 bool deletedLoad = false;
936 // Walk up the dependency chain until we either find
937 // a dependency we can use, or we can't walk any further
938 while (dep != MemoryDependenceAnalysis::None &&
939 dep != MemoryDependenceAnalysis::NonLocal &&
940 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
941 // ... that depends on a store ...
942 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
943 if (S->getPointerOperand() == pointer) {
945 MD.removeInstruction(L);
947 L->replaceAllUsesWith(S->getOperand(0));
948 toErase.push_back(L);
953 // Whether we removed it or not, we can't
957 // If we don't depend on a store, and we haven't
958 // been loaded before, bail.
960 } else if (dep == last) {
962 MD.removeInstruction(L);
964 L->replaceAllUsesWith(last);
965 toErase.push_back(L);
971 dep = MD.getDependency(L, dep);
975 if (dep != MemoryDependenceAnalysis::None &&
976 dep != MemoryDependenceAnalysis::NonLocal &&
977 isa<AllocationInst>(dep)) {
978 // Check that this load is actually from the
979 // allocation we found
980 Value* v = L->getOperand(0);
982 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
983 v = BC->getOperand(0);
984 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
985 v = GEP->getOperand(0);
990 // If this load depends directly on an allocation, there isn't
991 // anything stored there; therefore, we can optimize this load
993 MD.removeInstruction(L);
995 L->replaceAllUsesWith(UndefValue::get(L->getType()));
996 toErase.push_back(L);
1008 /// processInstruction - When calculating availability, handle an instruction
1009 /// by inserting it into the appropriate sets
1010 bool GVN::processInstruction(Instruction *I,
1011 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1012 SmallVectorImpl<Instruction*> &toErase) {
1013 if (LoadInst* L = dyn_cast<LoadInst>(I))
1014 return processLoad(L, lastSeenLoad, toErase);
1016 // Allocations are always uniquely numbered, so we can save time and memory
1017 // by fast failing them.
1018 if (isa<AllocationInst>(I))
1021 unsigned num = VN.lookup_or_add(I);
1023 // Collapse PHI nodes
1024 if (PHINode* p = dyn_cast<PHINode>(I)) {
1025 Value* constVal = CollapsePhi(p);
1028 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1030 if (PI->second.count(p))
1031 PI->second.erase(p);
1033 p->replaceAllUsesWith(constVal);
1034 toErase.push_back(p);
1036 // Perform value-number based elimination
1037 } else if (BaseMap.begin(num) != BaseMap.end()) {
1038 Value* repl = *BaseMap.begin(num);
1041 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1042 MD.removeInstruction(I);
1045 I->replaceAllUsesWith(repl);
1046 toErase.push_back(I);
1048 } else if (!I->isTerminator()) {
1049 BaseMap.insert(num, I);
1055 // GVN::runOnFunction - This is the main transformation entry point for a
1058 bool GVN::runOnFunction(Function& F) {
1059 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1060 VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1061 VN.setDomTree(&getAnalysis<DominatorTree>());
1063 bool changed = false;
1064 bool shouldContinue = true;
1066 while (shouldContinue) {
1067 shouldContinue = iterateOnFunction(F);
1068 changed |= shouldContinue;
1075 bool GVN::processBlock(DomTreeNode* DTN) {
1076 BasicBlock* BB = DTN->getBlock();
1077 ValueNumberScope NewScope(BaseMap);
1079 SmallVector<Instruction*, 8> toErase;
1080 DenseMap<Value*, LoadInst*> lastSeenLoad;
1081 bool changed_function = false;
1083 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1085 changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1086 if (toErase.empty()) {
1091 // If we need some instructions deleted, do it now.
1092 NumGVNInstr += toErase.size();
1094 // Avoid iterator invalidation.
1095 bool AtStart = BI == BB->begin();
1099 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1100 E = toErase.end(); I != E; ++I)
1101 (*I)->eraseFromParent();
1111 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end(); I != E; ++I)
1112 changed_function |= processBlock(*I);
1114 return changed_function;
1117 // GVN::iterateOnFunction - Executes one iteration of GVN
1118 bool GVN::iterateOnFunction(Function &F) {
1119 // Clean out global sets from any previous functions
1121 availableOut.clear();
1124 DominatorTree &DT = getAnalysis<DominatorTree>();
1126 // Top-down walk of the dominator tree
1127 return processBlock(DT.getRootNode());