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"
39 STATISTIC(NumGVNInstr, "Number of instructions deleted");
40 STATISTIC(NumGVNLoad, "Number of loads deleted");
41 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
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 /// add - Insert a value into the table with a specified value number.
417 void ValueTable::add(Value* V, uint32_t num) {
418 valueNumbering.insert(std::make_pair(V, num));
421 /// lookup_or_add - Returns the value number for the specified value, assigning
422 /// it a new number if it did not have one before.
423 uint32_t ValueTable::lookup_or_add(Value* V) {
424 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
425 if (VI != valueNumbering.end())
428 if (CallInst* C = dyn_cast<CallInst>(V)) {
429 if (AA->doesNotAccessMemory(C)) {
430 Expression e = create_expression(C);
432 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
433 if (EI != expressionNumbering.end()) {
434 valueNumbering.insert(std::make_pair(V, EI->second));
437 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
438 valueNumbering.insert(std::make_pair(V, nextValueNumber));
440 return nextValueNumber++;
442 } else if (AA->onlyReadsMemory(C)) {
443 Expression e = create_expression(C);
445 if (expressionNumbering.find(e) == expressionNumbering.end()) {
446 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
447 valueNumbering.insert(std::make_pair(V, nextValueNumber));
448 return nextValueNumber++;
451 Instruction* local_dep = MD->getDependency(C);
453 if (local_dep == MemoryDependenceAnalysis::None) {
454 valueNumbering.insert(std::make_pair(V, nextValueNumber));
455 return nextValueNumber++;
456 } else if (local_dep != MemoryDependenceAnalysis::NonLocal) {
457 if (!isa<CallInst>(local_dep)) {
458 valueNumbering.insert(std::make_pair(V, nextValueNumber));
459 return nextValueNumber++;
462 CallInst* local_cdep = cast<CallInst>(local_dep);
464 if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
465 local_cdep->getNumOperands() != C->getNumOperands()) {
466 valueNumbering.insert(std::make_pair(V, nextValueNumber));
467 return nextValueNumber++;
468 } else if (!C->getCalledFunction()) {
469 valueNumbering.insert(std::make_pair(V, nextValueNumber));
470 return nextValueNumber++;
472 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
473 uint32_t c_vn = lookup_or_add(C->getOperand(i));
474 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
476 valueNumbering.insert(std::make_pair(V, nextValueNumber));
477 return nextValueNumber++;
481 uint32_t v = lookup_or_add(local_cdep);
482 valueNumbering.insert(std::make_pair(V, v));
488 DenseMap<BasicBlock*, Value*> deps;
489 MD->getNonLocalDependency(C, deps);
492 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(),
493 E = deps.end(); I != E; ++I) {
494 if (I->second == MemoryDependenceAnalysis::None) {
495 valueNumbering.insert(std::make_pair(V, nextValueNumber));
497 return nextValueNumber++;
498 } else if (I->second != MemoryDependenceAnalysis::NonLocal) {
499 if (DT->properlyDominates(I->first, C->getParent())) {
500 if (CallInst* CD = dyn_cast<CallInst>(I->second))
503 valueNumbering.insert(std::make_pair(V, nextValueNumber));
504 return nextValueNumber++;
507 valueNumbering.insert(std::make_pair(V, nextValueNumber));
508 return nextValueNumber++;
514 valueNumbering.insert(std::make_pair(V, nextValueNumber));
515 return nextValueNumber++;
518 if (cdep->getCalledFunction() != C->getCalledFunction() ||
519 cdep->getNumOperands() != C->getNumOperands()) {
520 valueNumbering.insert(std::make_pair(V, nextValueNumber));
521 return nextValueNumber++;
522 } else if (!C->getCalledFunction()) {
523 valueNumbering.insert(std::make_pair(V, nextValueNumber));
524 return nextValueNumber++;
526 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
527 uint32_t c_vn = lookup_or_add(C->getOperand(i));
528 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
530 valueNumbering.insert(std::make_pair(V, nextValueNumber));
531 return nextValueNumber++;
535 uint32_t v = lookup_or_add(cdep);
536 valueNumbering.insert(std::make_pair(V, v));
541 valueNumbering.insert(std::make_pair(V, nextValueNumber));
542 return nextValueNumber++;
544 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
545 Expression e = create_expression(BO);
547 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
548 if (EI != expressionNumbering.end()) {
549 valueNumbering.insert(std::make_pair(V, EI->second));
552 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
553 valueNumbering.insert(std::make_pair(V, nextValueNumber));
555 return nextValueNumber++;
557 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
558 Expression e = create_expression(C);
560 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
561 if (EI != expressionNumbering.end()) {
562 valueNumbering.insert(std::make_pair(V, EI->second));
565 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
566 valueNumbering.insert(std::make_pair(V, nextValueNumber));
568 return nextValueNumber++;
570 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
571 Expression e = create_expression(U);
573 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
574 if (EI != expressionNumbering.end()) {
575 valueNumbering.insert(std::make_pair(V, EI->second));
578 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
579 valueNumbering.insert(std::make_pair(V, nextValueNumber));
581 return nextValueNumber++;
583 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
584 Expression e = create_expression(U);
586 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
587 if (EI != expressionNumbering.end()) {
588 valueNumbering.insert(std::make_pair(V, EI->second));
591 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
592 valueNumbering.insert(std::make_pair(V, nextValueNumber));
594 return nextValueNumber++;
596 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
597 Expression e = create_expression(U);
599 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
600 if (EI != expressionNumbering.end()) {
601 valueNumbering.insert(std::make_pair(V, EI->second));
604 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
605 valueNumbering.insert(std::make_pair(V, nextValueNumber));
607 return nextValueNumber++;
609 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
610 Expression e = create_expression(U);
612 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
613 if (EI != expressionNumbering.end()) {
614 valueNumbering.insert(std::make_pair(V, EI->second));
617 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
618 valueNumbering.insert(std::make_pair(V, nextValueNumber));
620 return nextValueNumber++;
622 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
623 Expression e = create_expression(U);
625 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
626 if (EI != expressionNumbering.end()) {
627 valueNumbering.insert(std::make_pair(V, EI->second));
630 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
631 valueNumbering.insert(std::make_pair(V, nextValueNumber));
633 return nextValueNumber++;
635 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
636 Expression e = create_expression(U);
638 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
639 if (EI != expressionNumbering.end()) {
640 valueNumbering.insert(std::make_pair(V, EI->second));
643 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
644 valueNumbering.insert(std::make_pair(V, nextValueNumber));
646 return nextValueNumber++;
649 valueNumbering.insert(std::make_pair(V, nextValueNumber));
650 return nextValueNumber++;
654 /// lookup - Returns the value number of the specified value. Fails if
655 /// the value has not yet been numbered.
656 uint32_t ValueTable::lookup(Value* V) const {
657 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
658 assert(VI != valueNumbering.end() && "Value not numbered?");
662 /// clear - Remove all entries from the ValueTable
663 void ValueTable::clear() {
664 valueNumbering.clear();
665 expressionNumbering.clear();
669 /// erase - Remove a value from the value numbering
670 void ValueTable::erase(Value* V) {
671 valueNumbering.erase(V);
674 //===----------------------------------------------------------------------===//
676 //===----------------------------------------------------------------------===//
679 template<> struct DenseMapInfo<uint32_t> {
680 static inline uint32_t getEmptyKey() { return ~0; }
681 static inline uint32_t getTombstoneKey() { return ~0 - 1; }
682 static unsigned getHashValue(const uint32_t& Val) { return Val * 37; }
683 static bool isPod() { return true; }
684 static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) {
692 class VISIBILITY_HIDDEN GVN : public FunctionPass {
693 bool runOnFunction(Function &F);
695 static char ID; // Pass identification, replacement for typeid
696 GVN() : FunctionPass((intptr_t)&ID) { }
700 DenseMap<BasicBlock*, DenseMap<uint32_t, Value*> > localAvail;
702 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
706 // This transformation requires dominator postdominator info
707 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
708 AU.setPreservesCFG();
709 AU.addRequired<DominatorTree>();
710 AU.addRequired<MemoryDependenceAnalysis>();
711 AU.addRequired<AliasAnalysis>();
712 AU.addPreserved<AliasAnalysis>();
713 AU.addPreserved<MemoryDependenceAnalysis>();
717 // FIXME: eliminate or document these better
718 bool processLoad(LoadInst* L,
719 DenseMap<Value*, LoadInst*> &lastLoad,
720 SmallVectorImpl<Instruction*> &toErase);
721 bool processInstruction(Instruction* I,
722 DenseMap<Value*, LoadInst*>& lastSeenLoad,
723 SmallVectorImpl<Instruction*> &toErase);
724 bool processNonLocalLoad(LoadInst* L,
725 SmallVectorImpl<Instruction*> &toErase);
726 bool processBlock(DomTreeNode* DTN);
727 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
728 DenseMap<BasicBlock*, Value*> &Phis,
729 bool top_level = false);
730 void dump(DenseMap<uint32_t, Value*>& d);
731 bool iterateOnFunction(Function &F);
732 Value* CollapsePhi(PHINode* p);
733 bool isSafeReplacement(PHINode* p, Instruction* inst);
734 bool performPRE(Function& F);
740 // createGVNPass - The public interface to this file...
741 FunctionPass *llvm::createGVNPass() { return new GVN(); }
743 static RegisterPass<GVN> X("gvn",
744 "Global Value Numbering");
746 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
748 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
749 E = d.end(); I != E; ++I) {
750 printf("%d\n", I->first);
756 Value* GVN::CollapsePhi(PHINode* p) {
757 DominatorTree &DT = getAnalysis<DominatorTree>();
758 Value* constVal = p->hasConstantValue();
760 if (!constVal) return 0;
762 Instruction* inst = dyn_cast<Instruction>(constVal);
766 if (DT.dominates(inst, p))
767 if (isSafeReplacement(p, inst))
772 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
773 if (!isa<PHINode>(inst))
776 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
778 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
779 if (use_phi->getParent() == inst->getParent())
785 /// GetValueForBlock - Get the value to use within the specified basic block.
786 /// available values are in Phis.
787 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
788 DenseMap<BasicBlock*, Value*> &Phis,
791 // If we have already computed this value, return the previously computed val.
792 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
793 if (V != Phis.end() && !top_level) return V->second;
795 BasicBlock* singlePred = BB->getSinglePredecessor();
797 Value *ret = GetValueForBlock(singlePred, orig, Phis);
802 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
803 // now, then get values to fill in the incoming values for the PHI.
804 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
806 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
808 if (Phis.count(BB) == 0)
809 Phis.insert(std::make_pair(BB, PN));
811 // Fill in the incoming values for the block.
812 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
813 Value* val = GetValueForBlock(*PI, orig, Phis);
814 PN->addIncoming(val, *PI);
817 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
818 AA.copyValue(orig, PN);
820 // Attempt to collapse PHI nodes that are trivially redundant
821 Value* v = CollapsePhi(PN);
823 // Cache our phi construction results
824 phiMap[orig->getPointerOperand()].insert(PN);
828 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
830 MD.removeInstruction(PN);
831 PN->replaceAllUsesWith(v);
833 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
834 E = Phis.end(); I != E; ++I)
838 PN->eraseFromParent();
844 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
845 /// non-local by performing PHI construction.
846 bool GVN::processNonLocalLoad(LoadInst* L,
847 SmallVectorImpl<Instruction*> &toErase) {
848 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
850 // Find the non-local dependencies of the load
851 DenseMap<BasicBlock*, Value*> deps;
852 MD.getNonLocalDependency(L, deps);
854 DenseMap<BasicBlock*, Value*> repl;
856 // Filter out useless results (non-locals, etc)
857 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
859 if (I->second == MemoryDependenceAnalysis::None)
862 if (I->second == MemoryDependenceAnalysis::NonLocal)
865 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
866 if (S->getPointerOperand() != L->getPointerOperand())
868 repl[I->first] = S->getOperand(0);
869 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
870 if (LD->getPointerOperand() != L->getPointerOperand())
878 // Use cached PHI construction information from previous runs
879 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
880 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
882 if ((*I)->getParent() == L->getParent()) {
883 MD.removeInstruction(L);
884 L->replaceAllUsesWith(*I);
885 toErase.push_back(L);
890 repl.insert(std::make_pair((*I)->getParent(), *I));
893 // Perform PHI construction
894 SmallPtrSet<BasicBlock*, 4> visited;
895 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
897 MD.removeInstruction(L);
898 L->replaceAllUsesWith(v);
899 toErase.push_back(L);
905 /// processLoad - Attempt to eliminate a load, first by eliminating it
906 /// locally, and then attempting non-local elimination if that fails.
907 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
908 SmallVectorImpl<Instruction*> &toErase) {
909 if (L->isVolatile()) {
910 lastLoad[L->getPointerOperand()] = L;
914 Value* pointer = L->getPointerOperand();
915 LoadInst*& last = lastLoad[pointer];
917 // ... to a pointer that has been loaded from before...
918 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
919 bool removedNonLocal = false;
920 Instruction* dep = MD.getDependency(L);
921 if (dep == MemoryDependenceAnalysis::NonLocal &&
922 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
923 removedNonLocal = processNonLocalLoad(L, toErase);
925 if (!removedNonLocal)
928 return removedNonLocal;
932 bool deletedLoad = false;
934 // Walk up the dependency chain until we either find
935 // a dependency we can use, or we can't walk any further
936 while (dep != MemoryDependenceAnalysis::None &&
937 dep != MemoryDependenceAnalysis::NonLocal &&
938 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
939 // ... that depends on a store ...
940 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
941 if (S->getPointerOperand() == pointer) {
943 MD.removeInstruction(L);
945 L->replaceAllUsesWith(S->getOperand(0));
946 toErase.push_back(L);
951 // Whether we removed it or not, we can't
955 // If we don't depend on a store, and we haven't
956 // been loaded before, bail.
958 } else if (dep == last) {
960 MD.removeInstruction(L);
962 L->replaceAllUsesWith(last);
963 toErase.push_back(L);
969 dep = MD.getDependency(L, dep);
973 if (dep != MemoryDependenceAnalysis::None &&
974 dep != MemoryDependenceAnalysis::NonLocal &&
975 isa<AllocationInst>(dep)) {
976 // Check that this load is actually from the
977 // allocation we found
978 Value* v = L->getOperand(0);
980 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
981 v = BC->getOperand(0);
982 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
983 v = GEP->getOperand(0);
988 // If this load depends directly on an allocation, there isn't
989 // anything stored there; therefore, we can optimize this load
991 MD.removeInstruction(L);
993 L->replaceAllUsesWith(UndefValue::get(L->getType()));
994 toErase.push_back(L);
1006 /// processInstruction - When calculating availability, handle an instruction
1007 /// by inserting it into the appropriate sets
1008 bool GVN::processInstruction(Instruction *I,
1009 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1010 SmallVectorImpl<Instruction*> &toErase) {
1011 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1012 bool changed = processLoad(L, lastSeenLoad, toErase);
1015 unsigned num = VN.lookup_or_add(L);
1016 localAvail[I->getParent()].insert(std::make_pair(num, L));
1022 unsigned num = VN.lookup_or_add(I);
1024 // Allocations are always uniquely numbered, so we can save time and memory
1025 // by fast failing them.
1026 if (isa<AllocationInst>(I)) {
1027 localAvail[I->getParent()].insert(std::make_pair(num, I));
1031 // Collapse PHI nodes
1032 if (PHINode* p = dyn_cast<PHINode>(I)) {
1033 Value* constVal = CollapsePhi(p);
1036 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1038 if (PI->second.count(p))
1039 PI->second.erase(p);
1041 p->replaceAllUsesWith(constVal);
1042 toErase.push_back(p);
1044 localAvail[I->getParent()].insert(std::make_pair(num, I));
1046 // Perform value-number based elimination
1047 } else if (localAvail[I->getParent()].count(num)) {
1048 Value* repl = localAvail[I->getParent()][num];
1051 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1052 MD.removeInstruction(I);
1055 I->replaceAllUsesWith(repl);
1056 toErase.push_back(I);
1058 } else if (!I->isTerminator()) {
1059 localAvail[I->getParent()].insert(std::make_pair(num, I));
1065 // GVN::runOnFunction - This is the main transformation entry point for a
1068 bool GVN::runOnFunction(Function& F) {
1069 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1070 VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1071 VN.setDomTree(&getAnalysis<DominatorTree>());
1073 bool changed = false;
1074 bool shouldContinue = true;
1076 while (shouldContinue) {
1077 shouldContinue = iterateOnFunction(F);
1078 changed |= shouldContinue;
1085 bool GVN::processBlock(DomTreeNode* DTN) {
1086 BasicBlock* BB = DTN->getBlock();
1088 SmallVector<Instruction*, 8> toErase;
1089 DenseMap<Value*, LoadInst*> lastSeenLoad;
1090 bool changed_function = false;
1093 localAvail.insert(std::make_pair(BB,
1094 localAvail[DTN->getIDom()->getBlock()]));
1096 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1098 changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1099 if (toErase.empty()) {
1104 // If we need some instructions deleted, do it now.
1105 NumGVNInstr += toErase.size();
1107 // Avoid iterator invalidation.
1108 bool AtStart = BI == BB->begin();
1112 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1113 E = toErase.end(); I != E; ++I)
1114 (*I)->eraseFromParent();
1124 return changed_function;
1127 /// performPRE - Perform a purely local form of PRE that looks for diamond
1128 /// control flow patterns and attempts to perform simple PRE at the join point.
1129 bool GVN::performPRE(Function& F) {
1130 bool changed = false;
1131 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1132 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1133 BasicBlock* CurrentBlock = *DI;
1135 // Nothing to PRE in the entry block.
1136 if (CurrentBlock == &F.getEntryBlock()) continue;
1138 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1139 BE = CurrentBlock->end(); BI != BE; ) {
1140 if (isa<AllocaInst>(BI) || isa<TerminatorInst>(BI) ||
1141 isa<LoadInst>(BI) || isa<StoreInst>(BI) ||
1142 isa<CallInst>(BI) || isa<PHINode>(BI)) {
1147 uint32_t valno = VN.lookup(BI);
1149 // Look for the predecessors for PRE opportunities. We're
1150 // only trying to solve the basic diamond case, where
1151 // a value is computed in the successor and one predecessor,
1152 // but not the other. We also explicitly disallow cases
1153 // where the successor is its own predecessor, because they're
1154 // more complicated to get right.
1155 unsigned numWith = 0;
1156 unsigned numWithout = 0;
1157 BasicBlock* PREPred = 0;
1158 for (pred_iterator PI = pred_begin(CurrentBlock),
1159 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1160 // We're not interested in PRE where the block is its
1162 if (*PI == CurrentBlock)
1165 if (!localAvail[*PI].count(valno)) {
1168 } else if (localAvail[*PI][valno] == BI) {
1175 // Don't do PRE when it might increase code size, i.e. when
1176 // we would need to insert instructions in more than one pred.
1177 if (numWithout != 1 || numWith == 0) {
1182 // Instantiate the expression the in predecessor that lacked it.
1183 // Because we are going top-down through the block, all value numbers
1184 // will be available in the predecessor by the time we need them. Any
1185 // that weren't original present will have been instantiated earlier
1187 Instruction* PREInstr = BI->clone();
1188 bool success = true;
1189 for (unsigned i = 0; i < BI->getNumOperands(); ++i) {
1190 Value* op = BI->getOperand(i);
1191 if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op))
1192 PREInstr->setOperand(i, op);
1193 else if (!localAvail[PREPred].count(VN.lookup(op))) {
1197 PREInstr->setOperand(i, localAvail[PREPred][VN.lookup(op)]);
1200 // Fail out if we encounter an operand that is not available in
1201 // the PRE predecessor. This is typically because of loads which
1202 // are not value numbered precisely.
1209 PREInstr->insertBefore(PREPred->getTerminator());
1210 PREInstr->setName(BI->getName() + ".pre");
1211 VN.add(PREInstr, valno);
1214 // Update the availability map to include the new instruction.
1215 localAvail[PREPred].insert(std::make_pair(valno, PREInstr));
1217 // Create a PHI to make the value available in this block.
1218 PHINode* Phi = PHINode::Create(BI->getType(),
1219 BI->getName() + ".pre-phi",
1220 CurrentBlock->begin());
1221 for (pred_iterator PI = pred_begin(CurrentBlock),
1222 PE = pred_end(CurrentBlock); PI != PE; ++PI)
1223 Phi->addIncoming(localAvail[*PI][valno], *PI);
1227 // The newly created PHI completely replaces the old instruction,
1228 // so we need to update the maps to reflect this.
1229 for (DenseMap<BasicBlock*, DenseMap<uint32_t, Value*> >::iterator
1230 UI = localAvail.begin(), UE = localAvail.end(); UI != UE; ++UI)
1231 for (DenseMap<uint32_t, Value*>::iterator UUI = UI->second.begin(),
1232 UUE = UI->second.end(); UUI != UUE; ++UUI)
1233 if (UUI->second == BI)
1236 BI->replaceAllUsesWith(Phi);
1239 Instruction* erase = BI;
1241 erase->eraseFromParent();
1250 // GVN::iterateOnFunction - Executes one iteration of GVN
1251 bool GVN::iterateOnFunction(Function &F) {
1252 // Clean out global sets from any previous functions
1257 DominatorTree &DT = getAnalysis<DominatorTree>();
1259 // Top-down walk of the dominator tree
1260 bool changed = false;
1261 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1262 DE = df_end(DT.getRootNode()); DI != DE; ++DI)
1263 changed |= processBlock(*DI);
1265 changed |= performPRE(F);