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/SparseBitVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
40 STATISTIC(NumGVNInstr, "Number of instructions deleted");
41 STATISTIC(NumGVNLoad, "Number of loads deleted");
43 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
47 /// This class holds the mapping between values and value numbers. It is used
48 /// as an efficient mechanism to determine the expression-wise equivalence of
51 struct VISIBILITY_HIDDEN Expression {
52 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
53 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
54 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
55 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
56 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
57 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
58 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
59 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
60 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
61 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
64 ExpressionOpcode opcode;
69 SmallVector<uint32_t, 4> varargs;
73 Expression(ExpressionOpcode o) : opcode(o) { }
75 bool operator==(const Expression &other) const {
76 if (opcode != other.opcode)
78 else if (opcode == EMPTY || opcode == TOMBSTONE)
80 else if (type != other.type)
82 else if (function != other.function)
84 else if (firstVN != other.firstVN)
86 else if (secondVN != other.secondVN)
88 else if (thirdVN != other.thirdVN)
91 if (varargs.size() != other.varargs.size())
94 for (size_t i = 0; i < varargs.size(); ++i)
95 if (varargs[i] != other.varargs[i])
102 bool operator!=(const Expression &other) const {
103 if (opcode != other.opcode)
105 else if (opcode == EMPTY || opcode == TOMBSTONE)
107 else if (type != other.type)
109 else if (function != other.function)
111 else if (firstVN != other.firstVN)
113 else if (secondVN != other.secondVN)
115 else if (thirdVN != other.thirdVN)
118 if (varargs.size() != other.varargs.size())
121 for (size_t i = 0; i < varargs.size(); ++i)
122 if (varargs[i] != other.varargs[i])
130 class VISIBILITY_HIDDEN ValueTable {
132 DenseMap<Value*, uint32_t> valueNumbering;
133 DenseMap<Expression, uint32_t> expressionNumbering;
135 MemoryDependenceAnalysis* MD;
138 uint32_t nextValueNumber;
140 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
141 Expression::ExpressionOpcode getOpcode(CmpInst* C);
142 Expression::ExpressionOpcode getOpcode(CastInst* C);
143 Expression create_expression(BinaryOperator* BO);
144 Expression create_expression(CmpInst* C);
145 Expression create_expression(ShuffleVectorInst* V);
146 Expression create_expression(ExtractElementInst* C);
147 Expression create_expression(InsertElementInst* V);
148 Expression create_expression(SelectInst* V);
149 Expression create_expression(CastInst* C);
150 Expression create_expression(GetElementPtrInst* G);
151 Expression create_expression(CallInst* C);
152 Expression create_expression(Constant* C);
154 ValueTable() : nextValueNumber(1) { }
155 uint32_t lookup_or_add(Value* V);
156 uint32_t lookup(Value* V) const;
157 void add(Value* V, uint32_t num);
159 void erase(Value* v);
161 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
162 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
163 void setDomTree(DominatorTree* D) { DT = D; }
168 template <> struct DenseMapInfo<Expression> {
169 static inline Expression getEmptyKey() {
170 return Expression(Expression::EMPTY);
173 static inline Expression getTombstoneKey() {
174 return Expression(Expression::TOMBSTONE);
177 static unsigned getHashValue(const Expression e) {
178 unsigned hash = e.opcode;
180 hash = e.firstVN + hash * 37;
181 hash = e.secondVN + hash * 37;
182 hash = e.thirdVN + hash * 37;
184 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
185 (unsigned)((uintptr_t)e.type >> 9)) +
188 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
189 E = e.varargs.end(); I != E; ++I)
190 hash = *I + hash * 37;
192 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
193 (unsigned)((uintptr_t)e.function >> 9)) +
198 static bool isEqual(const Expression &LHS, const Expression &RHS) {
201 static bool isPod() { return true; }
205 //===----------------------------------------------------------------------===//
206 // ValueTable Internal Functions
207 //===----------------------------------------------------------------------===//
208 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
209 switch(BO->getOpcode()) {
210 default: // THIS SHOULD NEVER HAPPEN
211 assert(0 && "Binary operator with unknown opcode?");
212 case Instruction::Add: return Expression::ADD;
213 case Instruction::Sub: return Expression::SUB;
214 case Instruction::Mul: return Expression::MUL;
215 case Instruction::UDiv: return Expression::UDIV;
216 case Instruction::SDiv: return Expression::SDIV;
217 case Instruction::FDiv: return Expression::FDIV;
218 case Instruction::URem: return Expression::UREM;
219 case Instruction::SRem: return Expression::SREM;
220 case Instruction::FRem: return Expression::FREM;
221 case Instruction::Shl: return Expression::SHL;
222 case Instruction::LShr: return Expression::LSHR;
223 case Instruction::AShr: return Expression::ASHR;
224 case Instruction::And: return Expression::AND;
225 case Instruction::Or: return Expression::OR;
226 case Instruction::Xor: return Expression::XOR;
230 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
231 if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
232 switch (C->getPredicate()) {
233 default: // THIS SHOULD NEVER HAPPEN
234 assert(0 && "Comparison with unknown predicate?");
235 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
236 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
237 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
238 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
239 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
240 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
241 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
242 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
243 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
244 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
247 assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
248 switch (C->getPredicate()) {
249 default: // THIS SHOULD NEVER HAPPEN
250 assert(0 && "Comparison with unknown predicate?");
251 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
252 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
253 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
254 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
255 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
256 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
257 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
258 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
259 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
260 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
261 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
262 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
263 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
264 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
268 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
269 switch(C->getOpcode()) {
270 default: // THIS SHOULD NEVER HAPPEN
271 assert(0 && "Cast operator with unknown opcode?");
272 case Instruction::Trunc: return Expression::TRUNC;
273 case Instruction::ZExt: return Expression::ZEXT;
274 case Instruction::SExt: return Expression::SEXT;
275 case Instruction::FPToUI: return Expression::FPTOUI;
276 case Instruction::FPToSI: return Expression::FPTOSI;
277 case Instruction::UIToFP: return Expression::UITOFP;
278 case Instruction::SIToFP: return Expression::SITOFP;
279 case Instruction::FPTrunc: return Expression::FPTRUNC;
280 case Instruction::FPExt: return Expression::FPEXT;
281 case Instruction::PtrToInt: return Expression::PTRTOINT;
282 case Instruction::IntToPtr: return Expression::INTTOPTR;
283 case Instruction::BitCast: return Expression::BITCAST;
287 Expression ValueTable::create_expression(CallInst* C) {
290 e.type = C->getType();
294 e.function = C->getCalledFunction();
295 e.opcode = Expression::CALL;
297 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
299 e.varargs.push_back(lookup_or_add(*I));
304 Expression ValueTable::create_expression(BinaryOperator* BO) {
307 e.firstVN = lookup_or_add(BO->getOperand(0));
308 e.secondVN = lookup_or_add(BO->getOperand(1));
311 e.type = BO->getType();
312 e.opcode = getOpcode(BO);
317 Expression ValueTable::create_expression(CmpInst* C) {
320 e.firstVN = lookup_or_add(C->getOperand(0));
321 e.secondVN = lookup_or_add(C->getOperand(1));
324 e.type = C->getType();
325 e.opcode = getOpcode(C);
330 Expression ValueTable::create_expression(CastInst* C) {
333 e.firstVN = lookup_or_add(C->getOperand(0));
337 e.type = C->getType();
338 e.opcode = getOpcode(C);
343 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
346 e.firstVN = lookup_or_add(S->getOperand(0));
347 e.secondVN = lookup_or_add(S->getOperand(1));
348 e.thirdVN = lookup_or_add(S->getOperand(2));
350 e.type = S->getType();
351 e.opcode = Expression::SHUFFLE;
356 Expression ValueTable::create_expression(ExtractElementInst* E) {
359 e.firstVN = lookup_or_add(E->getOperand(0));
360 e.secondVN = lookup_or_add(E->getOperand(1));
363 e.type = E->getType();
364 e.opcode = Expression::EXTRACT;
369 Expression ValueTable::create_expression(InsertElementInst* I) {
372 e.firstVN = lookup_or_add(I->getOperand(0));
373 e.secondVN = lookup_or_add(I->getOperand(1));
374 e.thirdVN = lookup_or_add(I->getOperand(2));
376 e.type = I->getType();
377 e.opcode = Expression::INSERT;
382 Expression ValueTable::create_expression(SelectInst* I) {
385 e.firstVN = lookup_or_add(I->getCondition());
386 e.secondVN = lookup_or_add(I->getTrueValue());
387 e.thirdVN = lookup_or_add(I->getFalseValue());
389 e.type = I->getType();
390 e.opcode = Expression::SELECT;
395 Expression ValueTable::create_expression(GetElementPtrInst* G) {
398 e.firstVN = lookup_or_add(G->getPointerOperand());
402 e.type = G->getType();
403 e.opcode = Expression::GEP;
405 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
407 e.varargs.push_back(lookup_or_add(*I));
412 //===----------------------------------------------------------------------===//
413 // ValueTable External Functions
414 //===----------------------------------------------------------------------===//
416 /// lookup_or_add - Returns the value number for the specified value, assigning
417 /// it a new number if it did not have one before.
418 uint32_t ValueTable::lookup_or_add(Value* V) {
419 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
420 if (VI != valueNumbering.end())
423 if (CallInst* C = dyn_cast<CallInst>(V)) {
424 if (AA->doesNotAccessMemory(C)) {
425 Expression e = create_expression(C);
427 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
428 if (EI != expressionNumbering.end()) {
429 valueNumbering.insert(std::make_pair(V, EI->second));
432 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
433 valueNumbering.insert(std::make_pair(V, nextValueNumber));
435 return nextValueNumber++;
437 } else if (AA->onlyReadsMemory(C)) {
438 Expression e = create_expression(C);
440 if (expressionNumbering.find(e) == expressionNumbering.end()) {
441 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
442 valueNumbering.insert(std::make_pair(V, nextValueNumber));
443 return nextValueNumber++;
446 Instruction* local_dep = MD->getDependency(C);
448 if (local_dep == MemoryDependenceAnalysis::None) {
449 valueNumbering.insert(std::make_pair(V, nextValueNumber));
450 return nextValueNumber++;
451 } else if (local_dep != MemoryDependenceAnalysis::NonLocal) {
452 if (!isa<CallInst>(local_dep)) {
453 valueNumbering.insert(std::make_pair(V, nextValueNumber));
454 return nextValueNumber++;
457 CallInst* local_cdep = cast<CallInst>(local_dep);
459 if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
460 local_cdep->getNumOperands() != C->getNumOperands()) {
461 valueNumbering.insert(std::make_pair(V, nextValueNumber));
462 return nextValueNumber++;
463 } else if (!C->getCalledFunction()) {
464 valueNumbering.insert(std::make_pair(V, nextValueNumber));
465 return nextValueNumber++;
467 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
468 uint32_t c_vn = lookup_or_add(C->getOperand(i));
469 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
471 valueNumbering.insert(std::make_pair(V, nextValueNumber));
472 return nextValueNumber++;
476 uint32_t v = lookup_or_add(local_cdep);
477 valueNumbering.insert(std::make_pair(V, v));
483 DenseMap<BasicBlock*, Value*> deps;
484 MD->getNonLocalDependency(C, deps);
487 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(),
488 E = deps.end(); I != E; ++I) {
489 if (I->second == MemoryDependenceAnalysis::None) {
490 valueNumbering.insert(std::make_pair(V, nextValueNumber));
492 return nextValueNumber++;
493 } else if (I->second != MemoryDependenceAnalysis::NonLocal) {
494 if (DT->dominates(I->first, C->getParent())) {
495 if (CallInst* CD = dyn_cast<CallInst>(I->second))
498 valueNumbering.insert(std::make_pair(V, nextValueNumber));
499 return nextValueNumber++;
502 valueNumbering.insert(std::make_pair(V, nextValueNumber));
503 return nextValueNumber++;
509 valueNumbering.insert(std::make_pair(V, nextValueNumber));
510 return nextValueNumber++;
513 if (cdep->getCalledFunction() != C->getCalledFunction() ||
514 cdep->getNumOperands() != C->getNumOperands()) {
515 valueNumbering.insert(std::make_pair(V, nextValueNumber));
516 return nextValueNumber++;
517 } else if (!C->getCalledFunction()) {
518 valueNumbering.insert(std::make_pair(V, nextValueNumber));
519 return nextValueNumber++;
521 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
522 uint32_t c_vn = lookup_or_add(C->getOperand(i));
523 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
525 valueNumbering.insert(std::make_pair(V, nextValueNumber));
526 return nextValueNumber++;
530 uint32_t v = lookup_or_add(cdep);
531 valueNumbering.insert(std::make_pair(V, v));
536 valueNumbering.insert(std::make_pair(V, nextValueNumber));
537 return nextValueNumber++;
539 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
540 Expression e = create_expression(BO);
542 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
543 if (EI != expressionNumbering.end()) {
544 valueNumbering.insert(std::make_pair(V, EI->second));
547 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
548 valueNumbering.insert(std::make_pair(V, nextValueNumber));
550 return nextValueNumber++;
552 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
553 Expression e = create_expression(C);
555 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
556 if (EI != expressionNumbering.end()) {
557 valueNumbering.insert(std::make_pair(V, EI->second));
560 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
561 valueNumbering.insert(std::make_pair(V, nextValueNumber));
563 return nextValueNumber++;
565 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
566 Expression e = create_expression(U);
568 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
569 if (EI != expressionNumbering.end()) {
570 valueNumbering.insert(std::make_pair(V, EI->second));
573 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
574 valueNumbering.insert(std::make_pair(V, nextValueNumber));
576 return nextValueNumber++;
578 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
579 Expression e = create_expression(U);
581 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
582 if (EI != expressionNumbering.end()) {
583 valueNumbering.insert(std::make_pair(V, EI->second));
586 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
587 valueNumbering.insert(std::make_pair(V, nextValueNumber));
589 return nextValueNumber++;
591 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
592 Expression e = create_expression(U);
594 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
595 if (EI != expressionNumbering.end()) {
596 valueNumbering.insert(std::make_pair(V, EI->second));
599 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
600 valueNumbering.insert(std::make_pair(V, nextValueNumber));
602 return nextValueNumber++;
604 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
605 Expression e = create_expression(U);
607 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
608 if (EI != expressionNumbering.end()) {
609 valueNumbering.insert(std::make_pair(V, EI->second));
612 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
613 valueNumbering.insert(std::make_pair(V, nextValueNumber));
615 return nextValueNumber++;
617 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
618 Expression e = create_expression(U);
620 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
621 if (EI != expressionNumbering.end()) {
622 valueNumbering.insert(std::make_pair(V, EI->second));
625 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
626 valueNumbering.insert(std::make_pair(V, nextValueNumber));
628 return nextValueNumber++;
630 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
631 Expression e = create_expression(U);
633 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
634 if (EI != expressionNumbering.end()) {
635 valueNumbering.insert(std::make_pair(V, EI->second));
638 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
639 valueNumbering.insert(std::make_pair(V, nextValueNumber));
641 return nextValueNumber++;
644 valueNumbering.insert(std::make_pair(V, nextValueNumber));
645 return nextValueNumber++;
649 /// lookup - Returns the value number of the specified value. Fails if
650 /// the value has not yet been numbered.
651 uint32_t ValueTable::lookup(Value* V) const {
652 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
653 assert(VI != valueNumbering.end() && "Value not numbered?");
657 /// clear - Remove all entries from the ValueTable
658 void ValueTable::clear() {
659 valueNumbering.clear();
660 expressionNumbering.clear();
664 /// erase - Remove a value from the value numbering
665 void ValueTable::erase(Value* V) {
666 valueNumbering.erase(V);
669 //===----------------------------------------------------------------------===//
670 // ValueNumberedSet Class
671 //===----------------------------------------------------------------------===//
673 class VISIBILITY_HIDDEN ValueNumberedSet {
675 SmallPtrSet<Value*, 8> contents;
676 SparseBitVector<64> numbers;
678 ValueNumberedSet() { }
679 ValueNumberedSet(const ValueNumberedSet& other) {
680 numbers = other.numbers;
681 contents = other.contents;
684 typedef SmallPtrSet<Value*, 8>::iterator iterator;
686 iterator begin() { return contents.begin(); }
687 iterator end() { return contents.end(); }
689 bool insert(Value* v) { return contents.insert(v); }
690 void insert(iterator I, iterator E) { contents.insert(I, E); }
691 void erase(Value* v) { contents.erase(v); }
692 unsigned count(Value* v) { return contents.count(v); }
693 size_t size() { return contents.size(); }
695 void set(unsigned i) {
699 void operator=(const ValueNumberedSet& other) {
700 contents = other.contents;
701 numbers = other.numbers;
704 void reset(unsigned i) {
708 bool test(unsigned i) {
709 return numbers.test(i);
714 //===----------------------------------------------------------------------===//
716 //===----------------------------------------------------------------------===//
720 class VISIBILITY_HIDDEN GVN : public FunctionPass {
721 bool runOnFunction(Function &F);
723 static char ID; // Pass identification, replacement for typeid
724 GVN() : FunctionPass((intptr_t)&ID) { }
729 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
731 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
735 // This transformation requires dominator postdominator info
736 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
737 AU.setPreservesCFG();
738 AU.addRequired<DominatorTree>();
739 AU.addRequired<MemoryDependenceAnalysis>();
740 AU.addRequired<AliasAnalysis>();
741 AU.addPreserved<AliasAnalysis>();
742 AU.addPreserved<MemoryDependenceAnalysis>();
746 // FIXME: eliminate or document these better
747 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
748 void val_insert(ValueNumberedSet& s, Value* v);
749 bool processLoad(LoadInst* L,
750 DenseMap<Value*, LoadInst*> &lastLoad,
751 SmallVectorImpl<Instruction*> &toErase);
752 bool processInstruction(Instruction* I,
753 ValueNumberedSet& currAvail,
754 DenseMap<Value*, LoadInst*>& lastSeenLoad,
755 SmallVectorImpl<Instruction*> &toErase);
756 bool processNonLocalLoad(LoadInst* L,
757 SmallVectorImpl<Instruction*> &toErase);
758 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
759 DenseMap<BasicBlock*, Value*> &Phis,
760 bool top_level = false);
761 void dump(DenseMap<BasicBlock*, Value*>& d);
762 bool iterateOnFunction(Function &F);
763 Value* CollapsePhi(PHINode* p);
764 bool isSafeReplacement(PHINode* p, Instruction* inst);
770 // createGVNPass - The public interface to this file...
771 FunctionPass *llvm::createGVNPass() { return new GVN(); }
773 static RegisterPass<GVN> X("gvn",
774 "Global Value Numbering");
776 /// find_leader - Given a set and a value number, return the first
777 /// element of the set with that value number, or 0 if no such element
779 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
783 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
785 if (v == VN.lookup(*I))
788 assert(0 && "No leader found, but present bit is set?");
792 /// val_insert - Insert a value into a set only if there is not a value
793 /// with the same value number already in the set
794 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
795 uint32_t num = VN.lookup(v);
800 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
802 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
803 E = d.end(); I != E; ++I) {
804 if (I->second == MemoryDependenceAnalysis::None)
812 Value* GVN::CollapsePhi(PHINode* p) {
813 DominatorTree &DT = getAnalysis<DominatorTree>();
814 Value* constVal = p->hasConstantValue();
816 if (!constVal) return 0;
818 Instruction* inst = dyn_cast<Instruction>(constVal);
822 if (DT.dominates(inst, p))
823 if (isSafeReplacement(p, inst))
828 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
829 if (!isa<PHINode>(inst))
832 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
834 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
835 if (use_phi->getParent() == inst->getParent())
841 /// GetValueForBlock - Get the value to use within the specified basic block.
842 /// available values are in Phis.
843 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
844 DenseMap<BasicBlock*, Value*> &Phis,
847 // If we have already computed this value, return the previously computed val.
848 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
849 if (V != Phis.end() && !top_level) return V->second;
851 BasicBlock* singlePred = BB->getSinglePredecessor();
853 Value *ret = GetValueForBlock(singlePred, orig, Phis);
858 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
859 // now, then get values to fill in the incoming values for the PHI.
860 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
862 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
864 if (Phis.count(BB) == 0)
865 Phis.insert(std::make_pair(BB, PN));
867 // Fill in the incoming values for the block.
868 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
869 Value* val = GetValueForBlock(*PI, orig, Phis);
870 PN->addIncoming(val, *PI);
873 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
874 AA.copyValue(orig, PN);
876 // Attempt to collapse PHI nodes that are trivially redundant
877 Value* v = CollapsePhi(PN);
879 // Cache our phi construction results
880 phiMap[orig->getPointerOperand()].insert(PN);
884 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
886 MD.removeInstruction(PN);
887 PN->replaceAllUsesWith(v);
889 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
890 E = Phis.end(); I != E; ++I)
894 PN->eraseFromParent();
900 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
901 /// non-local by performing PHI construction.
902 bool GVN::processNonLocalLoad(LoadInst* L,
903 SmallVectorImpl<Instruction*> &toErase) {
904 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
906 // Find the non-local dependencies of the load
907 DenseMap<BasicBlock*, Value*> deps;
908 MD.getNonLocalDependency(L, deps);
910 DenseMap<BasicBlock*, Value*> repl;
912 // Filter out useless results (non-locals, etc)
913 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
915 if (I->second == MemoryDependenceAnalysis::None)
918 if (I->second == MemoryDependenceAnalysis::NonLocal)
921 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
922 if (S->getPointerOperand() != L->getPointerOperand())
924 repl[I->first] = S->getOperand(0);
925 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
926 if (LD->getPointerOperand() != L->getPointerOperand())
934 // Use cached PHI construction information from previous runs
935 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
936 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
938 if ((*I)->getParent() == L->getParent()) {
939 MD.removeInstruction(L);
940 L->replaceAllUsesWith(*I);
941 toErase.push_back(L);
946 repl.insert(std::make_pair((*I)->getParent(), *I));
949 // Perform PHI construction
950 SmallPtrSet<BasicBlock*, 4> visited;
951 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
953 MD.removeInstruction(L);
954 L->replaceAllUsesWith(v);
955 toErase.push_back(L);
961 /// processLoad - Attempt to eliminate a load, first by eliminating it
962 /// locally, and then attempting non-local elimination if that fails.
963 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
964 SmallVectorImpl<Instruction*> &toErase) {
965 if (L->isVolatile()) {
966 lastLoad[L->getPointerOperand()] = L;
970 Value* pointer = L->getPointerOperand();
971 LoadInst*& last = lastLoad[pointer];
973 // ... to a pointer that has been loaded from before...
974 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
975 bool removedNonLocal = false;
976 Instruction* dep = MD.getDependency(L);
977 if (dep == MemoryDependenceAnalysis::NonLocal &&
978 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
979 removedNonLocal = processNonLocalLoad(L, toErase);
981 if (!removedNonLocal)
984 return removedNonLocal;
988 bool deletedLoad = false;
990 // Walk up the dependency chain until we either find
991 // a dependency we can use, or we can't walk any further
992 while (dep != MemoryDependenceAnalysis::None &&
993 dep != MemoryDependenceAnalysis::NonLocal &&
994 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
995 // ... that depends on a store ...
996 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
997 if (S->getPointerOperand() == pointer) {
999 MD.removeInstruction(L);
1001 L->replaceAllUsesWith(S->getOperand(0));
1002 toErase.push_back(L);
1007 // Whether we removed it or not, we can't
1011 // If we don't depend on a store, and we haven't
1012 // been loaded before, bail.
1014 } else if (dep == last) {
1016 MD.removeInstruction(L);
1018 L->replaceAllUsesWith(last);
1019 toErase.push_back(L);
1025 dep = MD.getDependency(L, dep);
1029 if (dep != MemoryDependenceAnalysis::None &&
1030 dep != MemoryDependenceAnalysis::NonLocal &&
1031 isa<AllocationInst>(dep)) {
1032 // Check that this load is actually from the
1033 // allocation we found
1034 Value* v = L->getOperand(0);
1036 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
1037 v = BC->getOperand(0);
1038 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
1039 v = GEP->getOperand(0);
1044 // If this load depends directly on an allocation, there isn't
1045 // anything stored there; therefore, we can optimize this load
1047 MD.removeInstruction(L);
1049 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1050 toErase.push_back(L);
1062 /// processInstruction - When calculating availability, handle an instruction
1063 /// by inserting it into the appropriate sets
1064 bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1065 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1066 SmallVectorImpl<Instruction*> &toErase) {
1067 if (LoadInst* L = dyn_cast<LoadInst>(I))
1068 return processLoad(L, lastSeenLoad, toErase);
1070 // Allocations are always uniquely numbered, so we can save time and memory
1071 // by fast failing them.
1072 if (isa<AllocationInst>(I))
1075 unsigned num = VN.lookup_or_add(I);
1077 // Collapse PHI nodes
1078 if (PHINode* p = dyn_cast<PHINode>(I)) {
1079 Value* constVal = CollapsePhi(p);
1082 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1084 if (PI->second.count(p))
1085 PI->second.erase(p);
1087 p->replaceAllUsesWith(constVal);
1088 toErase.push_back(p);
1090 // Perform value-number based elimination
1091 } else if (currAvail.test(num)) {
1092 Value* repl = find_leader(currAvail, num);
1095 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1096 MD.removeInstruction(I);
1099 I->replaceAllUsesWith(repl);
1100 toErase.push_back(I);
1102 } else if (!I->isTerminator()) {
1104 currAvail.insert(I);
1110 // GVN::runOnFunction - This is the main transformation entry point for a
1113 bool GVN::runOnFunction(Function& F) {
1114 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1115 VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1116 VN.setDomTree(&getAnalysis<DominatorTree>());
1118 bool changed = false;
1119 bool shouldContinue = true;
1121 while (shouldContinue) {
1122 shouldContinue = iterateOnFunction(F);
1123 changed |= shouldContinue;
1130 // GVN::iterateOnFunction - Executes one iteration of GVN
1131 bool GVN::iterateOnFunction(Function &F) {
1132 // Clean out global sets from any previous functions
1134 availableOut.clear();
1137 bool changed_function = false;
1139 DominatorTree &DT = getAnalysis<DominatorTree>();
1141 SmallVector<Instruction*, 8> toErase;
1142 DenseMap<Value*, LoadInst*> lastSeenLoad;
1143 DenseMap<DomTreeNode*, size_t> numChildrenVisited;
1145 // Top-down walk of the dominator tree
1146 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1147 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1149 // Get the set to update for this block
1150 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1151 lastSeenLoad.clear();
1153 BasicBlock* BB = DI->getBlock();
1155 // A block inherits AVAIL_OUT from its dominator
1156 if (DI->getIDom() != 0) {
1157 currAvail = availableOut[DI->getIDom()->getBlock()];
1159 numChildrenVisited[DI->getIDom()]++;
1161 if (numChildrenVisited[DI->getIDom()] == DI->getIDom()->getNumChildren()) {
1162 availableOut.erase(DI->getIDom()->getBlock());
1163 numChildrenVisited.erase(DI->getIDom());
1167 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1169 changed_function |= processInstruction(BI, currAvail,
1170 lastSeenLoad, toErase);
1171 if (toErase.empty()) {
1176 // If we need some instructions deleted, do it now.
1177 NumGVNInstr += toErase.size();
1179 // Avoid iterator invalidation.
1180 bool AtStart = BI == BB->begin();
1184 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1185 E = toErase.end(); I != E; ++I)
1186 (*I)->eraseFromParent();
1197 return changed_function;