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/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 STATISTIC(NumGVNInstr, "Number of instructions deleted");
41 STATISTIC(NumGVNLoad, "Number of loads deleted");
42 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
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 /// add - Insert a value into the table with a specified value number.
418 void ValueTable::add(Value* V, uint32_t num) {
419 valueNumbering.insert(std::make_pair(V, num));
422 /// lookup_or_add - Returns the value number for the specified value, assigning
423 /// it a new number if it did not have one before.
424 uint32_t ValueTable::lookup_or_add(Value* V) {
425 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
426 if (VI != valueNumbering.end())
429 if (CallInst* C = dyn_cast<CallInst>(V)) {
430 if (AA->doesNotAccessMemory(C)) {
431 Expression e = create_expression(C);
433 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
434 if (EI != expressionNumbering.end()) {
435 valueNumbering.insert(std::make_pair(V, EI->second));
438 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
439 valueNumbering.insert(std::make_pair(V, nextValueNumber));
441 return nextValueNumber++;
443 } else if (AA->onlyReadsMemory(C)) {
444 Expression e = create_expression(C);
446 if (expressionNumbering.find(e) == expressionNumbering.end()) {
447 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
448 valueNumbering.insert(std::make_pair(V, nextValueNumber));
449 return nextValueNumber++;
452 Instruction* local_dep = MD->getDependency(C);
454 if (local_dep == MemoryDependenceAnalysis::None) {
455 valueNumbering.insert(std::make_pair(V, nextValueNumber));
456 return nextValueNumber++;
457 } else if (local_dep != MemoryDependenceAnalysis::NonLocal) {
458 if (!isa<CallInst>(local_dep)) {
459 valueNumbering.insert(std::make_pair(V, nextValueNumber));
460 return nextValueNumber++;
463 CallInst* local_cdep = cast<CallInst>(local_dep);
465 if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
466 local_cdep->getNumOperands() != C->getNumOperands()) {
467 valueNumbering.insert(std::make_pair(V, nextValueNumber));
468 return nextValueNumber++;
469 } else if (!C->getCalledFunction()) {
470 valueNumbering.insert(std::make_pair(V, nextValueNumber));
471 return nextValueNumber++;
473 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
474 uint32_t c_vn = lookup_or_add(C->getOperand(i));
475 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
477 valueNumbering.insert(std::make_pair(V, nextValueNumber));
478 return nextValueNumber++;
482 uint32_t v = lookup_or_add(local_cdep);
483 valueNumbering.insert(std::make_pair(V, v));
489 DenseMap<BasicBlock*, Value*> deps;
490 MD->getNonLocalDependency(C, deps);
493 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(),
494 E = deps.end(); I != E; ++I) {
495 if (I->second == MemoryDependenceAnalysis::None) {
496 valueNumbering.insert(std::make_pair(V, nextValueNumber));
498 return nextValueNumber++;
499 } else if (I->second != MemoryDependenceAnalysis::NonLocal) {
500 if (DT->properlyDominates(I->first, C->getParent())) {
501 if (CallInst* CD = dyn_cast<CallInst>(I->second))
504 valueNumbering.insert(std::make_pair(V, nextValueNumber));
505 return nextValueNumber++;
508 valueNumbering.insert(std::make_pair(V, nextValueNumber));
509 return nextValueNumber++;
515 valueNumbering.insert(std::make_pair(V, nextValueNumber));
516 return nextValueNumber++;
519 if (cdep->getCalledFunction() != C->getCalledFunction() ||
520 cdep->getNumOperands() != C->getNumOperands()) {
521 valueNumbering.insert(std::make_pair(V, nextValueNumber));
522 return nextValueNumber++;
523 } else if (!C->getCalledFunction()) {
524 valueNumbering.insert(std::make_pair(V, nextValueNumber));
525 return nextValueNumber++;
527 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
528 uint32_t c_vn = lookup_or_add(C->getOperand(i));
529 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
531 valueNumbering.insert(std::make_pair(V, nextValueNumber));
532 return nextValueNumber++;
536 uint32_t v = lookup_or_add(cdep);
537 valueNumbering.insert(std::make_pair(V, v));
542 valueNumbering.insert(std::make_pair(V, nextValueNumber));
543 return nextValueNumber++;
545 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
546 Expression e = create_expression(BO);
548 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
549 if (EI != expressionNumbering.end()) {
550 valueNumbering.insert(std::make_pair(V, EI->second));
553 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
554 valueNumbering.insert(std::make_pair(V, nextValueNumber));
556 return nextValueNumber++;
558 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
559 Expression e = create_expression(C);
561 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
562 if (EI != expressionNumbering.end()) {
563 valueNumbering.insert(std::make_pair(V, EI->second));
566 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
567 valueNumbering.insert(std::make_pair(V, nextValueNumber));
569 return nextValueNumber++;
571 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
572 Expression e = create_expression(U);
574 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
575 if (EI != expressionNumbering.end()) {
576 valueNumbering.insert(std::make_pair(V, EI->second));
579 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
580 valueNumbering.insert(std::make_pair(V, nextValueNumber));
582 return nextValueNumber++;
584 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
585 Expression e = create_expression(U);
587 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
588 if (EI != expressionNumbering.end()) {
589 valueNumbering.insert(std::make_pair(V, EI->second));
592 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
593 valueNumbering.insert(std::make_pair(V, nextValueNumber));
595 return nextValueNumber++;
597 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
598 Expression e = create_expression(U);
600 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
601 if (EI != expressionNumbering.end()) {
602 valueNumbering.insert(std::make_pair(V, EI->second));
605 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
606 valueNumbering.insert(std::make_pair(V, nextValueNumber));
608 return nextValueNumber++;
610 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
611 Expression e = create_expression(U);
613 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
614 if (EI != expressionNumbering.end()) {
615 valueNumbering.insert(std::make_pair(V, EI->second));
618 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
619 valueNumbering.insert(std::make_pair(V, nextValueNumber));
621 return nextValueNumber++;
623 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
624 Expression e = create_expression(U);
626 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
627 if (EI != expressionNumbering.end()) {
628 valueNumbering.insert(std::make_pair(V, EI->second));
631 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
632 valueNumbering.insert(std::make_pair(V, nextValueNumber));
634 return nextValueNumber++;
636 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
637 Expression e = create_expression(U);
639 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
640 if (EI != expressionNumbering.end()) {
641 valueNumbering.insert(std::make_pair(V, EI->second));
644 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
645 valueNumbering.insert(std::make_pair(V, nextValueNumber));
647 return nextValueNumber++;
650 valueNumbering.insert(std::make_pair(V, nextValueNumber));
651 return nextValueNumber++;
655 /// lookup - Returns the value number of the specified value. Fails if
656 /// the value has not yet been numbered.
657 uint32_t ValueTable::lookup(Value* V) const {
658 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
659 assert(VI != valueNumbering.end() && "Value not numbered?");
663 /// clear - Remove all entries from the ValueTable
664 void ValueTable::clear() {
665 valueNumbering.clear();
666 expressionNumbering.clear();
670 /// erase - Remove a value from the value numbering
671 void ValueTable::erase(Value* V) {
672 valueNumbering.erase(V);
675 //===----------------------------------------------------------------------===//
677 //===----------------------------------------------------------------------===//
680 template<> struct DenseMapInfo<uint32_t> {
681 static inline uint32_t getEmptyKey() { return ~0; }
682 static inline uint32_t getTombstoneKey() { return ~0 - 1; }
683 static unsigned getHashValue(const uint32_t& Val) { return Val * 37; }
684 static bool isPod() { return true; }
685 static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) {
693 class VISIBILITY_HIDDEN GVN : public FunctionPass {
694 bool runOnFunction(Function &F);
696 static char ID; // Pass identification, replacement for typeid
697 GVN() : FunctionPass((intptr_t)&ID) { }
701 DenseMap<BasicBlock*, DenseMap<uint32_t, Value*> > localAvail;
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<uint32_t, Value*>& d);
732 bool iterateOnFunction(Function &F);
733 Value* CollapsePhi(PHINode* p);
734 bool isSafeReplacement(PHINode* p, Instruction* inst);
735 bool performPRE(Function& F);
741 // createGVNPass - The public interface to this file...
742 FunctionPass *llvm::createGVNPass() { return new GVN(); }
744 static RegisterPass<GVN> X("gvn",
745 "Global Value Numbering");
747 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
749 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
750 E = d.end(); I != E; ++I) {
751 printf("%d\n", I->first);
757 Value* GVN::CollapsePhi(PHINode* p) {
758 DominatorTree &DT = getAnalysis<DominatorTree>();
759 Value* constVal = p->hasConstantValue();
761 if (!constVal) return 0;
763 Instruction* inst = dyn_cast<Instruction>(constVal);
767 if (DT.dominates(inst, p))
768 if (isSafeReplacement(p, inst))
773 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
774 if (!isa<PHINode>(inst))
777 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
779 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
780 if (use_phi->getParent() == inst->getParent())
786 /// GetValueForBlock - Get the value to use within the specified basic block.
787 /// available values are in Phis.
788 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
789 DenseMap<BasicBlock*, Value*> &Phis,
792 // If we have already computed this value, return the previously computed val.
793 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
794 if (V != Phis.end() && !top_level) return V->second;
796 BasicBlock* singlePred = BB->getSinglePredecessor();
798 Value *ret = GetValueForBlock(singlePred, orig, Phis);
803 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
804 // now, then get values to fill in the incoming values for the PHI.
805 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
807 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
809 if (Phis.count(BB) == 0)
810 Phis.insert(std::make_pair(BB, PN));
812 // Fill in the incoming values for the block.
813 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
814 Value* val = GetValueForBlock(*PI, orig, Phis);
815 PN->addIncoming(val, *PI);
818 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
819 AA.copyValue(orig, PN);
821 // Attempt to collapse PHI nodes that are trivially redundant
822 Value* v = CollapsePhi(PN);
824 // Cache our phi construction results
825 phiMap[orig->getPointerOperand()].insert(PN);
829 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
831 MD.removeInstruction(PN);
832 PN->replaceAllUsesWith(v);
834 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
835 E = Phis.end(); I != E; ++I)
839 PN->eraseFromParent();
845 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
846 /// non-local by performing PHI construction.
847 bool GVN::processNonLocalLoad(LoadInst* L,
848 SmallVectorImpl<Instruction*> &toErase) {
849 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
851 // Find the non-local dependencies of the load
852 DenseMap<BasicBlock*, Value*> deps;
853 MD.getNonLocalDependency(L, deps);
855 DenseMap<BasicBlock*, Value*> repl;
857 // Filter out useless results (non-locals, etc)
858 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
860 if (I->second == MemoryDependenceAnalysis::None)
863 if (I->second == MemoryDependenceAnalysis::NonLocal)
866 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
867 if (S->getPointerOperand() != L->getPointerOperand())
869 repl[I->first] = S->getOperand(0);
870 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
871 if (LD->getPointerOperand() != L->getPointerOperand())
879 // Use cached PHI construction information from previous runs
880 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
881 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
883 if ((*I)->getParent() == L->getParent()) {
884 MD.removeInstruction(L);
885 L->replaceAllUsesWith(*I);
886 toErase.push_back(L);
891 repl.insert(std::make_pair((*I)->getParent(), *I));
894 // Perform PHI construction
895 SmallPtrSet<BasicBlock*, 4> visited;
896 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
898 MD.removeInstruction(L);
899 L->replaceAllUsesWith(v);
900 toErase.push_back(L);
906 /// processLoad - Attempt to eliminate a load, first by eliminating it
907 /// locally, and then attempting non-local elimination if that fails.
908 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
909 SmallVectorImpl<Instruction*> &toErase) {
910 if (L->isVolatile()) {
911 lastLoad[L->getPointerOperand()] = L;
915 Value* pointer = L->getPointerOperand();
916 LoadInst*& last = lastLoad[pointer];
918 // ... to a pointer that has been loaded from before...
919 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
920 bool removedNonLocal = false;
921 Instruction* dep = MD.getDependency(L);
922 if (dep == MemoryDependenceAnalysis::NonLocal &&
923 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
924 removedNonLocal = processNonLocalLoad(L, toErase);
926 if (!removedNonLocal)
929 return removedNonLocal;
933 bool deletedLoad = false;
935 // Walk up the dependency chain until we either find
936 // a dependency we can use, or we can't walk any further
937 while (dep != MemoryDependenceAnalysis::None &&
938 dep != MemoryDependenceAnalysis::NonLocal &&
939 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
940 // ... that depends on a store ...
941 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
942 if (S->getPointerOperand() == pointer) {
944 MD.removeInstruction(L);
946 L->replaceAllUsesWith(S->getOperand(0));
947 toErase.push_back(L);
952 // Whether we removed it or not, we can't
956 // If we don't depend on a store, and we haven't
957 // been loaded before, bail.
959 } else if (dep == last) {
961 MD.removeInstruction(L);
963 L->replaceAllUsesWith(last);
964 toErase.push_back(L);
970 dep = MD.getDependency(L, dep);
974 if (dep != MemoryDependenceAnalysis::None &&
975 dep != MemoryDependenceAnalysis::NonLocal &&
976 isa<AllocationInst>(dep)) {
977 // Check that this load is actually from the
978 // allocation we found
979 Value* v = L->getOperand(0);
981 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
982 v = BC->getOperand(0);
983 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
984 v = GEP->getOperand(0);
989 // If this load depends directly on an allocation, there isn't
990 // anything stored there; therefore, we can optimize this load
992 MD.removeInstruction(L);
994 L->replaceAllUsesWith(UndefValue::get(L->getType()));
995 toErase.push_back(L);
1007 /// processInstruction - When calculating availability, handle an instruction
1008 /// by inserting it into the appropriate sets
1009 bool GVN::processInstruction(Instruction *I,
1010 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1011 SmallVectorImpl<Instruction*> &toErase) {
1012 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1013 bool changed = processLoad(L, lastSeenLoad, toErase);
1016 unsigned num = VN.lookup_or_add(L);
1017 localAvail[I->getParent()].insert(std::make_pair(num, L));
1023 unsigned num = VN.lookup_or_add(I);
1025 // Allocations are always uniquely numbered, so we can save time and memory
1026 // by fast failing them.
1027 if (isa<AllocationInst>(I)) {
1028 localAvail[I->getParent()].insert(std::make_pair(num, I));
1032 // Collapse PHI nodes
1033 if (PHINode* p = dyn_cast<PHINode>(I)) {
1034 Value* constVal = CollapsePhi(p);
1037 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1039 if (PI->second.count(p))
1040 PI->second.erase(p);
1042 p->replaceAllUsesWith(constVal);
1043 toErase.push_back(p);
1045 localAvail[I->getParent()].insert(std::make_pair(num, I));
1047 // Perform value-number based elimination
1048 } else if (localAvail[I->getParent()].count(num)) {
1049 Value* repl = localAvail[I->getParent()][num];
1052 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1053 MD.removeInstruction(I);
1056 I->replaceAllUsesWith(repl);
1057 toErase.push_back(I);
1059 } else if (!I->isTerminator()) {
1060 localAvail[I->getParent()].insert(std::make_pair(num, I));
1066 // GVN::runOnFunction - This is the main transformation entry point for a
1069 bool GVN::runOnFunction(Function& F) {
1070 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1071 VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1072 VN.setDomTree(&getAnalysis<DominatorTree>());
1074 bool changed = false;
1075 bool shouldContinue = true;
1077 while (shouldContinue) {
1078 shouldContinue = iterateOnFunction(F);
1079 changed |= shouldContinue;
1086 bool GVN::processBlock(DomTreeNode* DTN) {
1087 BasicBlock* BB = DTN->getBlock();
1089 SmallVector<Instruction*, 8> toErase;
1090 DenseMap<Value*, LoadInst*> lastSeenLoad;
1091 bool changed_function = false;
1094 localAvail.insert(std::make_pair(BB,
1095 localAvail[DTN->getIDom()->getBlock()]));
1097 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1099 changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1100 if (toErase.empty()) {
1105 // If we need some instructions deleted, do it now.
1106 NumGVNInstr += toErase.size();
1108 // Avoid iterator invalidation.
1109 bool AtStart = BI == BB->begin();
1113 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1114 E = toErase.end(); I != E; ++I)
1115 (*I)->eraseFromParent();
1125 return changed_function;
1128 /// performPRE - Perform a purely local form of PRE that looks for diamond
1129 /// control flow patterns and attempts to perform simple PRE at the join point.
1130 bool GVN::performPRE(Function& F) {
1131 bool changed = false;
1132 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1133 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1134 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1135 BasicBlock* CurrentBlock = *DI;
1137 // Nothing to PRE in the entry block.
1138 if (CurrentBlock == &F.getEntryBlock()) continue;
1140 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1141 BE = CurrentBlock->end(); BI != BE; ) {
1142 if (isa<AllocaInst>(BI) || isa<TerminatorInst>(BI) ||
1143 isa<LoadInst>(BI) || isa<StoreInst>(BI) ||
1144 isa<CallInst>(BI) || isa<PHINode>(BI)) {
1149 uint32_t valno = VN.lookup(BI);
1151 // Look for the predecessors for PRE opportunities. We're
1152 // only trying to solve the basic diamond case, where
1153 // a value is computed in the successor and one predecessor,
1154 // but not the other. We also explicitly disallow cases
1155 // where the successor is its own predecessor, because they're
1156 // more complicated to get right.
1157 unsigned numWith = 0;
1158 unsigned numWithout = 0;
1159 BasicBlock* PREPred = 0;
1160 for (pred_iterator PI = pred_begin(CurrentBlock),
1161 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1162 // We're not interested in PRE where the block is its
1164 if (*PI == CurrentBlock)
1167 if (!localAvail[*PI].count(valno)) {
1170 } else if (localAvail[*PI][valno] == BI) {
1177 // Don't do PRE when it might increase code size, i.e. when
1178 // we would need to insert instructions in more than one pred.
1179 if (numWithout != 1 || numWith == 0) {
1184 // We can't do PRE safely on a critical edge, so instead we schedule
1185 // the edge to be split and perform the PRE the next time we iterate
1187 unsigned succNum = 0;
1188 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1190 if (PREPred->getTerminator()->getSuccessor(i) == PREPred) {
1195 if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1196 toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1202 // Instantiate the expression the in predecessor that lacked it.
1203 // Because we are going top-down through the block, all value numbers
1204 // will be available in the predecessor by the time we need them. Any
1205 // that weren't original present will have been instantiated earlier
1207 Instruction* PREInstr = BI->clone();
1208 bool success = true;
1209 for (unsigned i = 0; i < BI->getNumOperands(); ++i) {
1210 Value* op = BI->getOperand(i);
1211 if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op))
1212 PREInstr->setOperand(i, op);
1213 else if (!localAvail[PREPred].count(VN.lookup(op))) {
1217 PREInstr->setOperand(i, localAvail[PREPred][VN.lookup(op)]);
1220 // Fail out if we encounter an operand that is not available in
1221 // the PRE predecessor. This is typically because of loads which
1222 // are not value numbered precisely.
1229 PREInstr->insertBefore(PREPred->getTerminator());
1230 PREInstr->setName(BI->getName() + ".pre");
1231 VN.add(PREInstr, valno);
1234 // Update the availability map to include the new instruction.
1235 localAvail[PREPred].insert(std::make_pair(valno, PREInstr));
1237 // Create a PHI to make the value available in this block.
1238 PHINode* Phi = PHINode::Create(BI->getType(),
1239 BI->getName() + ".pre-phi",
1240 CurrentBlock->begin());
1241 for (pred_iterator PI = pred_begin(CurrentBlock),
1242 PE = pred_end(CurrentBlock); PI != PE; ++PI)
1243 Phi->addIncoming(localAvail[*PI][valno], *PI);
1247 // The newly created PHI completely replaces the old instruction,
1248 // so we need to update the maps to reflect this.
1249 for (DenseMap<BasicBlock*, DenseMap<uint32_t, Value*> >::iterator
1250 UI = localAvail.begin(), UE = localAvail.end(); UI != UE; ++UI)
1251 for (DenseMap<uint32_t, Value*>::iterator UUI = UI->second.begin(),
1252 UUE = UI->second.end(); UUI != UUE; ++UUI)
1253 if (UUI->second == BI)
1256 BI->replaceAllUsesWith(Phi);
1259 Instruction* erase = BI;
1261 erase->eraseFromParent();
1267 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1268 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1269 SplitCriticalEdge(I->first, I->second, this);
1274 // GVN::iterateOnFunction - Executes one iteration of GVN
1275 bool GVN::iterateOnFunction(Function &F) {
1276 // Clean out global sets from any previous functions
1281 DominatorTree &DT = getAnalysis<DominatorTree>();
1283 // Top-down walk of the dominator tree
1284 bool changed = false;
1285 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1286 DE = df_end(DT.getRootNode()); DI != DE; ++DI)
1287 changed |= processBlock(*DI);
1289 changed |= performPRE(F);