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/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 STATISTIC(NumGVNInstr, "Number of instructions deleted");
42 STATISTIC(NumGVNLoad, "Number of loads deleted");
43 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
45 static cl::opt<bool> EnablePRE("enable-pre",
46 cl::init(false), cl::Hidden);
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 /// This class holds the mapping between values and value numbers. It is used
53 /// as an efficient mechanism to determine the expression-wise equivalence of
56 struct VISIBILITY_HIDDEN Expression {
57 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
58 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
59 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
60 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
61 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
62 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
63 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
64 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
65 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
66 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
69 ExpressionOpcode opcode;
74 SmallVector<uint32_t, 4> varargs;
78 Expression(ExpressionOpcode o) : opcode(o) { }
80 bool operator==(const Expression &other) const {
81 if (opcode != other.opcode)
83 else if (opcode == EMPTY || opcode == TOMBSTONE)
85 else if (type != other.type)
87 else if (function != other.function)
89 else if (firstVN != other.firstVN)
91 else if (secondVN != other.secondVN)
93 else if (thirdVN != other.thirdVN)
96 if (varargs.size() != other.varargs.size())
99 for (size_t i = 0; i < varargs.size(); ++i)
100 if (varargs[i] != other.varargs[i])
107 bool operator!=(const Expression &other) const {
108 if (opcode != other.opcode)
110 else if (opcode == EMPTY || opcode == TOMBSTONE)
112 else if (type != other.type)
114 else if (function != other.function)
116 else if (firstVN != other.firstVN)
118 else if (secondVN != other.secondVN)
120 else if (thirdVN != other.thirdVN)
123 if (varargs.size() != other.varargs.size())
126 for (size_t i = 0; i < varargs.size(); ++i)
127 if (varargs[i] != other.varargs[i])
135 class VISIBILITY_HIDDEN ValueTable {
137 DenseMap<Value*, uint32_t> valueNumbering;
138 DenseMap<Expression, uint32_t> expressionNumbering;
140 MemoryDependenceAnalysis* MD;
143 uint32_t nextValueNumber;
145 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
146 Expression::ExpressionOpcode getOpcode(CmpInst* C);
147 Expression::ExpressionOpcode getOpcode(CastInst* C);
148 Expression create_expression(BinaryOperator* BO);
149 Expression create_expression(CmpInst* C);
150 Expression create_expression(ShuffleVectorInst* V);
151 Expression create_expression(ExtractElementInst* C);
152 Expression create_expression(InsertElementInst* V);
153 Expression create_expression(SelectInst* V);
154 Expression create_expression(CastInst* C);
155 Expression create_expression(GetElementPtrInst* G);
156 Expression create_expression(CallInst* C);
157 Expression create_expression(Constant* C);
159 ValueTable() : nextValueNumber(1) { }
160 uint32_t lookup_or_add(Value* V);
161 uint32_t lookup(Value* V) const;
162 void add(Value* V, uint32_t num);
164 void erase(Value* v);
166 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
167 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
168 void setDomTree(DominatorTree* D) { DT = D; }
169 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
174 template <> struct DenseMapInfo<Expression> {
175 static inline Expression getEmptyKey() {
176 return Expression(Expression::EMPTY);
179 static inline Expression getTombstoneKey() {
180 return Expression(Expression::TOMBSTONE);
183 static unsigned getHashValue(const Expression e) {
184 unsigned hash = e.opcode;
186 hash = e.firstVN + hash * 37;
187 hash = e.secondVN + hash * 37;
188 hash = e.thirdVN + hash * 37;
190 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
191 (unsigned)((uintptr_t)e.type >> 9)) +
194 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
195 E = e.varargs.end(); I != E; ++I)
196 hash = *I + hash * 37;
198 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
199 (unsigned)((uintptr_t)e.function >> 9)) +
204 static bool isEqual(const Expression &LHS, const Expression &RHS) {
207 static bool isPod() { return true; }
211 //===----------------------------------------------------------------------===//
212 // ValueTable Internal Functions
213 //===----------------------------------------------------------------------===//
214 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
215 switch(BO->getOpcode()) {
216 default: // THIS SHOULD NEVER HAPPEN
217 assert(0 && "Binary operator with unknown opcode?");
218 case Instruction::Add: return Expression::ADD;
219 case Instruction::Sub: return Expression::SUB;
220 case Instruction::Mul: return Expression::MUL;
221 case Instruction::UDiv: return Expression::UDIV;
222 case Instruction::SDiv: return Expression::SDIV;
223 case Instruction::FDiv: return Expression::FDIV;
224 case Instruction::URem: return Expression::UREM;
225 case Instruction::SRem: return Expression::SREM;
226 case Instruction::FRem: return Expression::FREM;
227 case Instruction::Shl: return Expression::SHL;
228 case Instruction::LShr: return Expression::LSHR;
229 case Instruction::AShr: return Expression::ASHR;
230 case Instruction::And: return Expression::AND;
231 case Instruction::Or: return Expression::OR;
232 case Instruction::Xor: return Expression::XOR;
236 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
237 if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
238 switch (C->getPredicate()) {
239 default: // THIS SHOULD NEVER HAPPEN
240 assert(0 && "Comparison with unknown predicate?");
241 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
242 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
243 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
244 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
245 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
246 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
247 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
248 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
249 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
250 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
253 assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
254 switch (C->getPredicate()) {
255 default: // THIS SHOULD NEVER HAPPEN
256 assert(0 && "Comparison with unknown predicate?");
257 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
258 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
259 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
260 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
261 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
262 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
263 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
264 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
265 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
266 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
267 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
268 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
269 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
270 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
274 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
275 switch(C->getOpcode()) {
276 default: // THIS SHOULD NEVER HAPPEN
277 assert(0 && "Cast operator with unknown opcode?");
278 case Instruction::Trunc: return Expression::TRUNC;
279 case Instruction::ZExt: return Expression::ZEXT;
280 case Instruction::SExt: return Expression::SEXT;
281 case Instruction::FPToUI: return Expression::FPTOUI;
282 case Instruction::FPToSI: return Expression::FPTOSI;
283 case Instruction::UIToFP: return Expression::UITOFP;
284 case Instruction::SIToFP: return Expression::SITOFP;
285 case Instruction::FPTrunc: return Expression::FPTRUNC;
286 case Instruction::FPExt: return Expression::FPEXT;
287 case Instruction::PtrToInt: return Expression::PTRTOINT;
288 case Instruction::IntToPtr: return Expression::INTTOPTR;
289 case Instruction::BitCast: return Expression::BITCAST;
293 Expression ValueTable::create_expression(CallInst* C) {
296 e.type = C->getType();
300 e.function = C->getCalledFunction();
301 e.opcode = Expression::CALL;
303 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
305 e.varargs.push_back(lookup_or_add(*I));
310 Expression ValueTable::create_expression(BinaryOperator* BO) {
313 e.firstVN = lookup_or_add(BO->getOperand(0));
314 e.secondVN = lookup_or_add(BO->getOperand(1));
317 e.type = BO->getType();
318 e.opcode = getOpcode(BO);
323 Expression ValueTable::create_expression(CmpInst* C) {
326 e.firstVN = lookup_or_add(C->getOperand(0));
327 e.secondVN = lookup_or_add(C->getOperand(1));
330 e.type = C->getType();
331 e.opcode = getOpcode(C);
336 Expression ValueTable::create_expression(CastInst* C) {
339 e.firstVN = lookup_or_add(C->getOperand(0));
343 e.type = C->getType();
344 e.opcode = getOpcode(C);
349 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
352 e.firstVN = lookup_or_add(S->getOperand(0));
353 e.secondVN = lookup_or_add(S->getOperand(1));
354 e.thirdVN = lookup_or_add(S->getOperand(2));
356 e.type = S->getType();
357 e.opcode = Expression::SHUFFLE;
362 Expression ValueTable::create_expression(ExtractElementInst* E) {
365 e.firstVN = lookup_or_add(E->getOperand(0));
366 e.secondVN = lookup_or_add(E->getOperand(1));
369 e.type = E->getType();
370 e.opcode = Expression::EXTRACT;
375 Expression ValueTable::create_expression(InsertElementInst* I) {
378 e.firstVN = lookup_or_add(I->getOperand(0));
379 e.secondVN = lookup_or_add(I->getOperand(1));
380 e.thirdVN = lookup_or_add(I->getOperand(2));
382 e.type = I->getType();
383 e.opcode = Expression::INSERT;
388 Expression ValueTable::create_expression(SelectInst* I) {
391 e.firstVN = lookup_or_add(I->getCondition());
392 e.secondVN = lookup_or_add(I->getTrueValue());
393 e.thirdVN = lookup_or_add(I->getFalseValue());
395 e.type = I->getType();
396 e.opcode = Expression::SELECT;
401 Expression ValueTable::create_expression(GetElementPtrInst* G) {
404 e.firstVN = lookup_or_add(G->getPointerOperand());
408 e.type = G->getType();
409 e.opcode = Expression::GEP;
411 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
413 e.varargs.push_back(lookup_or_add(*I));
418 //===----------------------------------------------------------------------===//
419 // ValueTable External Functions
420 //===----------------------------------------------------------------------===//
422 /// add - Insert a value into the table with a specified value number.
423 void ValueTable::add(Value* V, uint32_t num) {
424 valueNumbering.insert(std::make_pair(V, num));
427 /// lookup_or_add - Returns the value number for the specified value, assigning
428 /// it a new number if it did not have one before.
429 uint32_t ValueTable::lookup_or_add(Value* V) {
430 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
431 if (VI != valueNumbering.end())
434 if (CallInst* C = dyn_cast<CallInst>(V)) {
435 if (AA->doesNotAccessMemory(C)) {
436 Expression e = create_expression(C);
438 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
439 if (EI != expressionNumbering.end()) {
440 valueNumbering.insert(std::make_pair(V, EI->second));
443 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
444 valueNumbering.insert(std::make_pair(V, nextValueNumber));
446 return nextValueNumber++;
448 } else if (AA->onlyReadsMemory(C)) {
449 Expression e = create_expression(C);
451 if (expressionNumbering.find(e) == expressionNumbering.end()) {
452 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
453 valueNumbering.insert(std::make_pair(V, nextValueNumber));
454 return nextValueNumber++;
457 Instruction* local_dep = MD->getDependency(C);
459 if (local_dep == MemoryDependenceAnalysis::None) {
460 valueNumbering.insert(std::make_pair(V, nextValueNumber));
461 return nextValueNumber++;
462 } else if (local_dep != MemoryDependenceAnalysis::NonLocal) {
463 if (!isa<CallInst>(local_dep)) {
464 valueNumbering.insert(std::make_pair(V, nextValueNumber));
465 return nextValueNumber++;
468 CallInst* local_cdep = cast<CallInst>(local_dep);
470 if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
471 local_cdep->getNumOperands() != C->getNumOperands()) {
472 valueNumbering.insert(std::make_pair(V, nextValueNumber));
473 return nextValueNumber++;
474 } else if (!C->getCalledFunction()) {
475 valueNumbering.insert(std::make_pair(V, nextValueNumber));
476 return nextValueNumber++;
478 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
479 uint32_t c_vn = lookup_or_add(C->getOperand(i));
480 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
482 valueNumbering.insert(std::make_pair(V, nextValueNumber));
483 return nextValueNumber++;
487 uint32_t v = lookup_or_add(local_cdep);
488 valueNumbering.insert(std::make_pair(V, v));
494 DenseMap<BasicBlock*, Value*> deps;
495 MD->getNonLocalDependency(C, deps);
498 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(),
499 E = deps.end(); I != E; ++I) {
500 if (I->second == MemoryDependenceAnalysis::None) {
501 valueNumbering.insert(std::make_pair(V, nextValueNumber));
503 return nextValueNumber++;
504 } else if (I->second != MemoryDependenceAnalysis::NonLocal) {
505 if (DT->properlyDominates(I->first, C->getParent())) {
506 if (CallInst* CD = dyn_cast<CallInst>(I->second))
509 valueNumbering.insert(std::make_pair(V, nextValueNumber));
510 return nextValueNumber++;
513 valueNumbering.insert(std::make_pair(V, nextValueNumber));
514 return nextValueNumber++;
520 valueNumbering.insert(std::make_pair(V, nextValueNumber));
521 return nextValueNumber++;
524 if (cdep->getCalledFunction() != C->getCalledFunction() ||
525 cdep->getNumOperands() != C->getNumOperands()) {
526 valueNumbering.insert(std::make_pair(V, nextValueNumber));
527 return nextValueNumber++;
528 } else if (!C->getCalledFunction()) {
529 valueNumbering.insert(std::make_pair(V, nextValueNumber));
530 return nextValueNumber++;
532 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
533 uint32_t c_vn = lookup_or_add(C->getOperand(i));
534 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
536 valueNumbering.insert(std::make_pair(V, nextValueNumber));
537 return nextValueNumber++;
541 uint32_t v = lookup_or_add(cdep);
542 valueNumbering.insert(std::make_pair(V, v));
547 valueNumbering.insert(std::make_pair(V, nextValueNumber));
548 return nextValueNumber++;
550 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
551 Expression e = create_expression(BO);
553 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
554 if (EI != expressionNumbering.end()) {
555 valueNumbering.insert(std::make_pair(V, EI->second));
558 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
559 valueNumbering.insert(std::make_pair(V, nextValueNumber));
561 return nextValueNumber++;
563 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
564 Expression e = create_expression(C);
566 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
567 if (EI != expressionNumbering.end()) {
568 valueNumbering.insert(std::make_pair(V, EI->second));
571 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
572 valueNumbering.insert(std::make_pair(V, nextValueNumber));
574 return nextValueNumber++;
576 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
577 Expression e = create_expression(U);
579 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
580 if (EI != expressionNumbering.end()) {
581 valueNumbering.insert(std::make_pair(V, EI->second));
584 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
585 valueNumbering.insert(std::make_pair(V, nextValueNumber));
587 return nextValueNumber++;
589 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
590 Expression e = create_expression(U);
592 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
593 if (EI != expressionNumbering.end()) {
594 valueNumbering.insert(std::make_pair(V, EI->second));
597 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
598 valueNumbering.insert(std::make_pair(V, nextValueNumber));
600 return nextValueNumber++;
602 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
603 Expression e = create_expression(U);
605 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
606 if (EI != expressionNumbering.end()) {
607 valueNumbering.insert(std::make_pair(V, EI->second));
610 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
611 valueNumbering.insert(std::make_pair(V, nextValueNumber));
613 return nextValueNumber++;
615 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
616 Expression e = create_expression(U);
618 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
619 if (EI != expressionNumbering.end()) {
620 valueNumbering.insert(std::make_pair(V, EI->second));
623 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
624 valueNumbering.insert(std::make_pair(V, nextValueNumber));
626 return nextValueNumber++;
628 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
629 Expression e = create_expression(U);
631 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
632 if (EI != expressionNumbering.end()) {
633 valueNumbering.insert(std::make_pair(V, EI->second));
636 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
637 valueNumbering.insert(std::make_pair(V, nextValueNumber));
639 return nextValueNumber++;
641 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
642 Expression e = create_expression(U);
644 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
645 if (EI != expressionNumbering.end()) {
646 valueNumbering.insert(std::make_pair(V, EI->second));
649 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
650 valueNumbering.insert(std::make_pair(V, nextValueNumber));
652 return nextValueNumber++;
655 valueNumbering.insert(std::make_pair(V, nextValueNumber));
656 return nextValueNumber++;
660 /// lookup - Returns the value number of the specified value. Fails if
661 /// the value has not yet been numbered.
662 uint32_t ValueTable::lookup(Value* V) const {
663 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
664 assert(VI != valueNumbering.end() && "Value not numbered?");
668 /// clear - Remove all entries from the ValueTable
669 void ValueTable::clear() {
670 valueNumbering.clear();
671 expressionNumbering.clear();
675 /// erase - Remove a value from the value numbering
676 void ValueTable::erase(Value* V) {
677 valueNumbering.erase(V);
680 //===----------------------------------------------------------------------===//
682 //===----------------------------------------------------------------------===//
685 template<> struct DenseMapInfo<uint32_t> {
686 static inline uint32_t getEmptyKey() { return ~0; }
687 static inline uint32_t getTombstoneKey() { return ~0 - 1; }
688 static unsigned getHashValue(const uint32_t& Val) { return Val * 37; }
689 static bool isPod() { return true; }
690 static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) {
697 struct VISIBILITY_HIDDEN ValueNumberScope {
698 ValueNumberScope* parent;
699 DenseMap<uint32_t, Value*> table;
701 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
707 class VISIBILITY_HIDDEN GVN : public FunctionPass {
708 bool runOnFunction(Function &F);
710 static char ID; // Pass identification, replacement for typeid
711 GVN() : FunctionPass((intptr_t)&ID) { }
715 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
717 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
721 // This transformation requires dominator postdominator info
722 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
723 AU.addRequired<DominatorTree>();
724 AU.addRequired<MemoryDependenceAnalysis>();
725 AU.addRequired<AliasAnalysis>();
727 AU.addPreserved<DominatorTree>();
728 AU.addPreserved<AliasAnalysis>();
729 AU.addPreserved<MemoryDependenceAnalysis>();
733 // FIXME: eliminate or document these better
734 bool processLoad(LoadInst* L,
735 DenseMap<Value*, LoadInst*> &lastLoad,
736 SmallVectorImpl<Instruction*> &toErase);
737 bool processInstruction(Instruction* I,
738 DenseMap<Value*, LoadInst*>& lastSeenLoad,
739 SmallVectorImpl<Instruction*> &toErase);
740 bool processNonLocalLoad(LoadInst* L,
741 SmallVectorImpl<Instruction*> &toErase);
742 bool processBlock(DomTreeNode* DTN);
743 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
744 DenseMap<BasicBlock*, Value*> &Phis,
745 bool top_level = false);
746 void dump(DenseMap<uint32_t, Value*>& d);
747 bool iterateOnFunction(Function &F);
748 Value* CollapsePhi(PHINode* p);
749 bool isSafeReplacement(PHINode* p, Instruction* inst);
750 bool performPRE(Function& F);
751 Value* lookupNumber(BasicBlock* BB, uint32_t num);
757 // createGVNPass - The public interface to this file...
758 FunctionPass *llvm::createGVNPass() { return new GVN(); }
760 static RegisterPass<GVN> X("gvn",
761 "Global Value Numbering");
763 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
765 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
766 E = d.end(); I != E; ++I) {
767 printf("%d\n", I->first);
773 Value* GVN::CollapsePhi(PHINode* p) {
774 DominatorTree &DT = getAnalysis<DominatorTree>();
775 Value* constVal = p->hasConstantValue();
777 if (!constVal) return 0;
779 Instruction* inst = dyn_cast<Instruction>(constVal);
783 if (DT.dominates(inst, p))
784 if (isSafeReplacement(p, inst))
789 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
790 if (!isa<PHINode>(inst))
793 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
795 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
796 if (use_phi->getParent() == inst->getParent())
802 /// GetValueForBlock - Get the value to use within the specified basic block.
803 /// available values are in Phis.
804 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
805 DenseMap<BasicBlock*, Value*> &Phis,
808 // If we have already computed this value, return the previously computed val.
809 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
810 if (V != Phis.end() && !top_level) return V->second;
812 // If the block is unreachable, just return undef, since this path
813 // can't actually occur at runtime.
814 if (!getAnalysis<DominatorTree>().isReachableFromEntry(BB))
815 return Phis[BB] = UndefValue::get(orig->getType());
817 BasicBlock* singlePred = BB->getSinglePredecessor();
819 Value *ret = GetValueForBlock(singlePred, orig, Phis);
824 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
825 // now, then get values to fill in the incoming values for the PHI.
826 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
828 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
830 if (Phis.count(BB) == 0)
831 Phis.insert(std::make_pair(BB, PN));
833 // Fill in the incoming values for the block.
834 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
835 Value* val = GetValueForBlock(*PI, orig, Phis);
836 PN->addIncoming(val, *PI);
839 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
840 AA.copyValue(orig, PN);
842 // Attempt to collapse PHI nodes that are trivially redundant
843 Value* v = CollapsePhi(PN);
845 // Cache our phi construction results
846 phiMap[orig->getPointerOperand()].insert(PN);
850 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
852 MD.removeInstruction(PN);
853 PN->replaceAllUsesWith(v);
855 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
856 E = Phis.end(); I != E; ++I)
860 PN->eraseFromParent();
866 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
867 /// non-local by performing PHI construction.
868 bool GVN::processNonLocalLoad(LoadInst* L,
869 SmallVectorImpl<Instruction*> &toErase) {
870 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
872 // Find the non-local dependencies of the load
873 DenseMap<BasicBlock*, Value*> deps;
874 MD.getNonLocalDependency(L, deps);
876 DenseMap<BasicBlock*, Value*> repl;
878 // Filter out useless results (non-locals, etc)
879 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
881 if (I->second == MemoryDependenceAnalysis::None)
884 if (I->second == MemoryDependenceAnalysis::NonLocal)
887 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
888 if (S->getPointerOperand() != L->getPointerOperand())
890 repl[I->first] = S->getOperand(0);
891 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
892 if (LD->getPointerOperand() != L->getPointerOperand())
900 // Use cached PHI construction information from previous runs
901 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
902 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
904 if ((*I)->getParent() == L->getParent()) {
905 MD.removeInstruction(L);
906 L->replaceAllUsesWith(*I);
907 toErase.push_back(L);
912 repl.insert(std::make_pair((*I)->getParent(), *I));
915 // Perform PHI construction
916 SmallPtrSet<BasicBlock*, 4> visited;
917 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
919 MD.removeInstruction(L);
920 L->replaceAllUsesWith(v);
921 toErase.push_back(L);
927 /// processLoad - Attempt to eliminate a load, first by eliminating it
928 /// locally, and then attempting non-local elimination if that fails.
929 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
930 SmallVectorImpl<Instruction*> &toErase) {
931 if (L->isVolatile()) {
932 lastLoad[L->getPointerOperand()] = L;
936 Value* pointer = L->getPointerOperand();
937 LoadInst*& last = lastLoad[pointer];
939 // ... to a pointer that has been loaded from before...
940 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
941 bool removedNonLocal = false;
942 Instruction* dep = MD.getDependency(L);
943 if (dep == MemoryDependenceAnalysis::NonLocal &&
944 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
945 removedNonLocal = processNonLocalLoad(L, toErase);
947 if (!removedNonLocal)
950 return removedNonLocal;
954 bool deletedLoad = false;
956 // Walk up the dependency chain until we either find
957 // a dependency we can use, or we can't walk any further
958 while (dep != MemoryDependenceAnalysis::None &&
959 dep != MemoryDependenceAnalysis::NonLocal &&
960 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
961 // ... that depends on a store ...
962 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
963 if (S->getPointerOperand() == pointer) {
965 MD.removeInstruction(L);
967 L->replaceAllUsesWith(S->getOperand(0));
968 toErase.push_back(L);
973 // Whether we removed it or not, we can't
977 // If we don't depend on a store, and we haven't
978 // been loaded before, bail.
980 } else if (dep == last) {
982 MD.removeInstruction(L);
984 L->replaceAllUsesWith(last);
985 toErase.push_back(L);
991 dep = MD.getDependency(L, dep);
995 if (dep != MemoryDependenceAnalysis::None &&
996 dep != MemoryDependenceAnalysis::NonLocal &&
997 isa<AllocationInst>(dep)) {
998 // Check that this load is actually from the
999 // allocation we found
1000 Value* v = L->getOperand(0);
1002 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
1003 v = BC->getOperand(0);
1004 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
1005 v = GEP->getOperand(0);
1010 // If this load depends directly on an allocation, there isn't
1011 // anything stored there; therefore, we can optimize this load
1013 MD.removeInstruction(L);
1015 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1016 toErase.push_back(L);
1028 Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) {
1029 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1030 if (I == localAvail.end())
1033 ValueNumberScope* locals = I->second;
1036 DenseMap<uint32_t, Value*>::iterator I = locals->table.find(num);
1037 if (I != locals->table.end())
1040 locals = locals->parent;
1046 /// processInstruction - When calculating availability, handle an instruction
1047 /// by inserting it into the appropriate sets
1048 bool GVN::processInstruction(Instruction *I,
1049 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1050 SmallVectorImpl<Instruction*> &toErase) {
1051 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1052 bool changed = processLoad(L, lastSeenLoad, toErase);
1055 unsigned num = VN.lookup_or_add(L);
1056 localAvail[I->getParent()]->table.insert(std::make_pair(num, L));
1062 uint32_t nextNum = VN.getNextUnusedValueNumber();
1063 unsigned num = VN.lookup_or_add(I);
1065 // Allocations are always uniquely numbered, so we can save time and memory
1066 // by fast failing them.
1067 if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
1068 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1072 // Collapse PHI nodes
1073 if (PHINode* p = dyn_cast<PHINode>(I)) {
1074 Value* constVal = CollapsePhi(p);
1077 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1079 if (PI->second.count(p))
1080 PI->second.erase(p);
1082 p->replaceAllUsesWith(constVal);
1083 toErase.push_back(p);
1085 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1088 // If the number we were assigned was a brand new VN, then we don't
1089 // need to do a lookup to see if the number already exists
1090 // somewhere in the domtree: it can't!
1091 } else if (num == nextNum) {
1092 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1094 // Perform value-number based elimination
1095 } else if (Value* repl = lookupNumber(I->getParent(), num)) {
1097 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1098 MD.removeInstruction(I);
1101 I->replaceAllUsesWith(repl);
1102 toErase.push_back(I);
1105 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1111 // GVN::runOnFunction - This is the main transformation entry point for a
1114 bool GVN::runOnFunction(Function& F) {
1115 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1116 VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1117 VN.setDomTree(&getAnalysis<DominatorTree>());
1119 bool changed = false;
1120 bool shouldContinue = true;
1122 while (shouldContinue) {
1123 shouldContinue = iterateOnFunction(F);
1124 changed |= shouldContinue;
1131 bool GVN::processBlock(DomTreeNode* DTN) {
1132 BasicBlock* BB = DTN->getBlock();
1134 SmallVector<Instruction*, 8> toErase;
1135 DenseMap<Value*, LoadInst*> lastSeenLoad;
1136 bool changed_function = false;
1140 new ValueNumberScope(localAvail[DTN->getIDom()->getBlock()]);
1142 localAvail[BB] = new ValueNumberScope(0);
1144 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1146 changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1147 if (toErase.empty()) {
1152 // If we need some instructions deleted, do it now.
1153 NumGVNInstr += toErase.size();
1155 // Avoid iterator invalidation.
1156 bool AtStart = BI == BB->begin();
1160 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1161 E = toErase.end(); I != E; ++I)
1162 (*I)->eraseFromParent();
1172 return changed_function;
1175 /// performPRE - Perform a purely local form of PRE that looks for diamond
1176 /// control flow patterns and attempts to perform simple PRE at the join point.
1177 bool GVN::performPRE(Function& F) {
1178 bool changed = false;
1179 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1180 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1181 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1182 BasicBlock* CurrentBlock = *DI;
1184 // Nothing to PRE in the entry block.
1185 if (CurrentBlock == &F.getEntryBlock()) continue;
1187 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1188 BE = CurrentBlock->end(); BI != BE; ) {
1189 if (isa<AllocationInst>(BI) || isa<TerminatorInst>(BI) ||
1190 isa<PHINode>(BI) || BI->mayReadFromMemory() ||
1191 BI->mayWriteToMemory()) {
1196 uint32_t valno = VN.lookup(BI);
1198 // Look for the predecessors for PRE opportunities. We're
1199 // only trying to solve the basic diamond case, where
1200 // a value is computed in the successor and one predecessor,
1201 // but not the other. We also explicitly disallow cases
1202 // where the successor is its own predecessor, because they're
1203 // more complicated to get right.
1204 unsigned numWith = 0;
1205 unsigned numWithout = 0;
1206 BasicBlock* PREPred = 0;
1207 DenseMap<BasicBlock*, Value*> predMap;
1208 for (pred_iterator PI = pred_begin(CurrentBlock),
1209 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1210 // We're not interested in PRE where the block is its
1211 // own predecessor, on in blocks with predecessors
1212 // that are not reachable.
1213 if (*PI == CurrentBlock) {
1216 } else if (!localAvail.count(*PI)) {
1221 DenseMap<uint32_t, Value*>::iterator predV =
1222 localAvail[*PI]->table.find(valno);
1223 if (predV == localAvail[*PI]->table.end()) {
1226 } else if (predV->second == BI) {
1229 predMap[*PI] = predV->second;
1234 // Don't do PRE when it might increase code size, i.e. when
1235 // we would need to insert instructions in more than one pred.
1236 if (numWithout != 1 || numWith == 0) {
1241 // We can't do PRE safely on a critical edge, so instead we schedule
1242 // the edge to be split and perform the PRE the next time we iterate
1244 unsigned succNum = 0;
1245 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1247 if (PREPred->getTerminator()->getSuccessor(i) == PREPred) {
1252 if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1253 toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1259 // Instantiate the expression the in predecessor that lacked it.
1260 // Because we are going top-down through the block, all value numbers
1261 // will be available in the predecessor by the time we need them. Any
1262 // that weren't original present will have been instantiated earlier
1264 Instruction* PREInstr = BI->clone();
1265 bool success = true;
1266 for (unsigned i = 0; i < BI->getNumOperands(); ++i) {
1267 Value* op = BI->getOperand(i);
1268 if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op))
1269 PREInstr->setOperand(i, op);
1271 Value* V = lookupNumber(PREPred, VN.lookup(op));
1276 PREInstr->setOperand(i, V);
1280 // Fail out if we encounter an operand that is not available in
1281 // the PRE predecessor. This is typically because of loads which
1282 // are not value numbered precisely.
1289 PREInstr->insertBefore(PREPred->getTerminator());
1290 PREInstr->setName(BI->getName() + ".pre");
1291 predMap[PREPred] = PREInstr;
1292 VN.add(PREInstr, valno);
1295 // Update the availability map to include the new instruction.
1296 localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr));
1298 // Create a PHI to make the value available in this block.
1299 PHINode* Phi = PHINode::Create(BI->getType(),
1300 BI->getName() + ".pre-phi",
1301 CurrentBlock->begin());
1302 for (pred_iterator PI = pred_begin(CurrentBlock),
1303 PE = pred_end(CurrentBlock); PI != PE; ++PI)
1304 Phi->addIncoming(predMap[*PI], *PI);
1307 localAvail[CurrentBlock]->table[valno] = Phi;
1309 BI->replaceAllUsesWith(Phi);
1312 Instruction* erase = BI;
1314 erase->eraseFromParent();
1320 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1321 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1322 SplitCriticalEdge(I->first, I->second, this);
1327 // GVN::iterateOnFunction - Executes one iteration of GVN
1328 bool GVN::iterateOnFunction(Function &F) {
1329 // Clean out global sets from any previous functions
1333 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1334 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1338 DominatorTree &DT = getAnalysis<DominatorTree>();
1340 // Top-down walk of the dominator tree
1341 bool changed = false;
1342 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1343 DE = df_end(DT.getRootNode()); DI != DE; ++DI)
1344 changed |= processBlock(*DI);
1347 changed |= performPRE(F);