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");
44 STATISTIC(NumGVNBlocks, "Number of blocks merged");
46 static cl::opt<bool> EnablePRE("enable-pre",
47 cl::init(false), cl::Hidden);
49 //===----------------------------------------------------------------------===//
51 //===----------------------------------------------------------------------===//
53 /// This class holds the mapping between values and value numbers. It is used
54 /// as an efficient mechanism to determine the expression-wise equivalence of
57 struct VISIBILITY_HIDDEN Expression {
58 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
59 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
60 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
61 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
62 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
63 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
64 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
65 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
66 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
67 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
70 ExpressionOpcode opcode;
75 SmallVector<uint32_t, 4> varargs;
79 Expression(ExpressionOpcode o) : opcode(o) { }
81 bool operator==(const Expression &other) const {
82 if (opcode != other.opcode)
84 else if (opcode == EMPTY || opcode == TOMBSTONE)
86 else if (type != other.type)
88 else if (function != other.function)
90 else if (firstVN != other.firstVN)
92 else if (secondVN != other.secondVN)
94 else if (thirdVN != other.thirdVN)
97 if (varargs.size() != other.varargs.size())
100 for (size_t i = 0; i < varargs.size(); ++i)
101 if (varargs[i] != other.varargs[i])
108 bool operator!=(const Expression &other) const {
109 if (opcode != other.opcode)
111 else if (opcode == EMPTY || opcode == TOMBSTONE)
113 else if (type != other.type)
115 else if (function != other.function)
117 else if (firstVN != other.firstVN)
119 else if (secondVN != other.secondVN)
121 else if (thirdVN != other.thirdVN)
124 if (varargs.size() != other.varargs.size())
127 for (size_t i = 0; i < varargs.size(); ++i)
128 if (varargs[i] != other.varargs[i])
136 class VISIBILITY_HIDDEN ValueTable {
138 DenseMap<Value*, uint32_t> valueNumbering;
139 DenseMap<Expression, uint32_t> expressionNumbering;
141 MemoryDependenceAnalysis* MD;
144 uint32_t nextValueNumber;
146 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
147 Expression::ExpressionOpcode getOpcode(CmpInst* C);
148 Expression::ExpressionOpcode getOpcode(CastInst* C);
149 Expression create_expression(BinaryOperator* BO);
150 Expression create_expression(CmpInst* C);
151 Expression create_expression(ShuffleVectorInst* V);
152 Expression create_expression(ExtractElementInst* C);
153 Expression create_expression(InsertElementInst* V);
154 Expression create_expression(SelectInst* V);
155 Expression create_expression(CastInst* C);
156 Expression create_expression(GetElementPtrInst* G);
157 Expression create_expression(CallInst* C);
158 Expression create_expression(Constant* C);
160 ValueTable() : nextValueNumber(1) { }
161 uint32_t lookup_or_add(Value* V);
162 uint32_t lookup(Value* V) const;
163 void add(Value* V, uint32_t num);
165 void erase(Value* v);
167 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
168 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
169 void setDomTree(DominatorTree* D) { DT = D; }
170 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
175 template <> struct DenseMapInfo<Expression> {
176 static inline Expression getEmptyKey() {
177 return Expression(Expression::EMPTY);
180 static inline Expression getTombstoneKey() {
181 return Expression(Expression::TOMBSTONE);
184 static unsigned getHashValue(const Expression e) {
185 unsigned hash = e.opcode;
187 hash = e.firstVN + hash * 37;
188 hash = e.secondVN + hash * 37;
189 hash = e.thirdVN + hash * 37;
191 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
192 (unsigned)((uintptr_t)e.type >> 9)) +
195 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
196 E = e.varargs.end(); I != E; ++I)
197 hash = *I + hash * 37;
199 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
200 (unsigned)((uintptr_t)e.function >> 9)) +
205 static bool isEqual(const Expression &LHS, const Expression &RHS) {
208 static bool isPod() { return true; }
212 //===----------------------------------------------------------------------===//
213 // ValueTable Internal Functions
214 //===----------------------------------------------------------------------===//
215 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
216 switch(BO->getOpcode()) {
217 default: // THIS SHOULD NEVER HAPPEN
218 assert(0 && "Binary operator with unknown opcode?");
219 case Instruction::Add: return Expression::ADD;
220 case Instruction::Sub: return Expression::SUB;
221 case Instruction::Mul: return Expression::MUL;
222 case Instruction::UDiv: return Expression::UDIV;
223 case Instruction::SDiv: return Expression::SDIV;
224 case Instruction::FDiv: return Expression::FDIV;
225 case Instruction::URem: return Expression::UREM;
226 case Instruction::SRem: return Expression::SREM;
227 case Instruction::FRem: return Expression::FREM;
228 case Instruction::Shl: return Expression::SHL;
229 case Instruction::LShr: return Expression::LSHR;
230 case Instruction::AShr: return Expression::ASHR;
231 case Instruction::And: return Expression::AND;
232 case Instruction::Or: return Expression::OR;
233 case Instruction::Xor: return Expression::XOR;
237 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
238 if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
239 switch (C->getPredicate()) {
240 default: // THIS SHOULD NEVER HAPPEN
241 assert(0 && "Comparison with unknown predicate?");
242 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
243 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
244 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
245 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
246 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
247 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
248 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
249 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
250 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
251 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
254 assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
255 switch (C->getPredicate()) {
256 default: // THIS SHOULD NEVER HAPPEN
257 assert(0 && "Comparison with unknown predicate?");
258 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
259 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
260 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
261 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
262 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
263 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
264 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
265 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
266 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
267 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
268 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
269 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
270 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
271 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
275 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
276 switch(C->getOpcode()) {
277 default: // THIS SHOULD NEVER HAPPEN
278 assert(0 && "Cast operator with unknown opcode?");
279 case Instruction::Trunc: return Expression::TRUNC;
280 case Instruction::ZExt: return Expression::ZEXT;
281 case Instruction::SExt: return Expression::SEXT;
282 case Instruction::FPToUI: return Expression::FPTOUI;
283 case Instruction::FPToSI: return Expression::FPTOSI;
284 case Instruction::UIToFP: return Expression::UITOFP;
285 case Instruction::SIToFP: return Expression::SITOFP;
286 case Instruction::FPTrunc: return Expression::FPTRUNC;
287 case Instruction::FPExt: return Expression::FPEXT;
288 case Instruction::PtrToInt: return Expression::PTRTOINT;
289 case Instruction::IntToPtr: return Expression::INTTOPTR;
290 case Instruction::BitCast: return Expression::BITCAST;
294 Expression ValueTable::create_expression(CallInst* C) {
297 e.type = C->getType();
301 e.function = C->getCalledFunction();
302 e.opcode = Expression::CALL;
304 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
306 e.varargs.push_back(lookup_or_add(*I));
311 Expression ValueTable::create_expression(BinaryOperator* BO) {
314 e.firstVN = lookup_or_add(BO->getOperand(0));
315 e.secondVN = lookup_or_add(BO->getOperand(1));
318 e.type = BO->getType();
319 e.opcode = getOpcode(BO);
324 Expression ValueTable::create_expression(CmpInst* C) {
327 e.firstVN = lookup_or_add(C->getOperand(0));
328 e.secondVN = lookup_or_add(C->getOperand(1));
331 e.type = C->getType();
332 e.opcode = getOpcode(C);
337 Expression ValueTable::create_expression(CastInst* C) {
340 e.firstVN = lookup_or_add(C->getOperand(0));
344 e.type = C->getType();
345 e.opcode = getOpcode(C);
350 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
353 e.firstVN = lookup_or_add(S->getOperand(0));
354 e.secondVN = lookup_or_add(S->getOperand(1));
355 e.thirdVN = lookup_or_add(S->getOperand(2));
357 e.type = S->getType();
358 e.opcode = Expression::SHUFFLE;
363 Expression ValueTable::create_expression(ExtractElementInst* E) {
366 e.firstVN = lookup_or_add(E->getOperand(0));
367 e.secondVN = lookup_or_add(E->getOperand(1));
370 e.type = E->getType();
371 e.opcode = Expression::EXTRACT;
376 Expression ValueTable::create_expression(InsertElementInst* I) {
379 e.firstVN = lookup_or_add(I->getOperand(0));
380 e.secondVN = lookup_or_add(I->getOperand(1));
381 e.thirdVN = lookup_or_add(I->getOperand(2));
383 e.type = I->getType();
384 e.opcode = Expression::INSERT;
389 Expression ValueTable::create_expression(SelectInst* I) {
392 e.firstVN = lookup_or_add(I->getCondition());
393 e.secondVN = lookup_or_add(I->getTrueValue());
394 e.thirdVN = lookup_or_add(I->getFalseValue());
396 e.type = I->getType();
397 e.opcode = Expression::SELECT;
402 Expression ValueTable::create_expression(GetElementPtrInst* G) {
405 e.firstVN = lookup_or_add(G->getPointerOperand());
409 e.type = G->getType();
410 e.opcode = Expression::GEP;
412 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
414 e.varargs.push_back(lookup_or_add(*I));
419 //===----------------------------------------------------------------------===//
420 // ValueTable External Functions
421 //===----------------------------------------------------------------------===//
423 /// add - Insert a value into the table with a specified value number.
424 void ValueTable::add(Value* V, uint32_t num) {
425 valueNumbering.insert(std::make_pair(V, num));
428 /// lookup_or_add - Returns the value number for the specified value, assigning
429 /// it a new number if it did not have one before.
430 uint32_t ValueTable::lookup_or_add(Value* V) {
431 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
432 if (VI != valueNumbering.end())
435 if (CallInst* C = dyn_cast<CallInst>(V)) {
436 if (AA->doesNotAccessMemory(C)) {
437 Expression e = create_expression(C);
439 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
440 if (EI != expressionNumbering.end()) {
441 valueNumbering.insert(std::make_pair(V, EI->second));
444 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
445 valueNumbering.insert(std::make_pair(V, nextValueNumber));
447 return nextValueNumber++;
449 } else if (AA->onlyReadsMemory(C)) {
450 Expression e = create_expression(C);
452 if (expressionNumbering.find(e) == expressionNumbering.end()) {
453 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
454 valueNumbering.insert(std::make_pair(V, nextValueNumber));
455 return nextValueNumber++;
458 Instruction* local_dep = MD->getDependency(C);
460 if (local_dep == MemoryDependenceAnalysis::None) {
461 valueNumbering.insert(std::make_pair(V, nextValueNumber));
462 return nextValueNumber++;
463 } else if (local_dep != MemoryDependenceAnalysis::NonLocal) {
464 if (!isa<CallInst>(local_dep)) {
465 valueNumbering.insert(std::make_pair(V, nextValueNumber));
466 return nextValueNumber++;
469 CallInst* local_cdep = cast<CallInst>(local_dep);
471 if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
472 local_cdep->getNumOperands() != C->getNumOperands()) {
473 valueNumbering.insert(std::make_pair(V, nextValueNumber));
474 return nextValueNumber++;
475 } else if (!C->getCalledFunction()) {
476 valueNumbering.insert(std::make_pair(V, nextValueNumber));
477 return nextValueNumber++;
479 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
480 uint32_t c_vn = lookup_or_add(C->getOperand(i));
481 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
483 valueNumbering.insert(std::make_pair(V, nextValueNumber));
484 return nextValueNumber++;
488 uint32_t v = lookup_or_add(local_cdep);
489 valueNumbering.insert(std::make_pair(V, v));
495 DenseMap<BasicBlock*, Value*> deps;
496 MD->getNonLocalDependency(C, deps);
499 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(),
500 E = deps.end(); I != E; ++I) {
501 if (I->second == MemoryDependenceAnalysis::None) {
502 valueNumbering.insert(std::make_pair(V, nextValueNumber));
504 return nextValueNumber++;
505 } else if (I->second != MemoryDependenceAnalysis::NonLocal) {
506 if (DT->properlyDominates(I->first, C->getParent())) {
507 if (CallInst* CD = dyn_cast<CallInst>(I->second))
510 valueNumbering.insert(std::make_pair(V, nextValueNumber));
511 return nextValueNumber++;
514 valueNumbering.insert(std::make_pair(V, nextValueNumber));
515 return nextValueNumber++;
521 valueNumbering.insert(std::make_pair(V, nextValueNumber));
522 return nextValueNumber++;
525 if (cdep->getCalledFunction() != C->getCalledFunction() ||
526 cdep->getNumOperands() != C->getNumOperands()) {
527 valueNumbering.insert(std::make_pair(V, nextValueNumber));
528 return nextValueNumber++;
529 } else if (!C->getCalledFunction()) {
530 valueNumbering.insert(std::make_pair(V, nextValueNumber));
531 return nextValueNumber++;
533 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
534 uint32_t c_vn = lookup_or_add(C->getOperand(i));
535 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
537 valueNumbering.insert(std::make_pair(V, nextValueNumber));
538 return nextValueNumber++;
542 uint32_t v = lookup_or_add(cdep);
543 valueNumbering.insert(std::make_pair(V, v));
548 valueNumbering.insert(std::make_pair(V, nextValueNumber));
549 return nextValueNumber++;
551 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
552 Expression e = create_expression(BO);
554 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
555 if (EI != expressionNumbering.end()) {
556 valueNumbering.insert(std::make_pair(V, EI->second));
559 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
560 valueNumbering.insert(std::make_pair(V, nextValueNumber));
562 return nextValueNumber++;
564 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
565 Expression e = create_expression(C);
567 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
568 if (EI != expressionNumbering.end()) {
569 valueNumbering.insert(std::make_pair(V, EI->second));
572 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
573 valueNumbering.insert(std::make_pair(V, nextValueNumber));
575 return nextValueNumber++;
577 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
578 Expression e = create_expression(U);
580 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
581 if (EI != expressionNumbering.end()) {
582 valueNumbering.insert(std::make_pair(V, EI->second));
585 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
586 valueNumbering.insert(std::make_pair(V, nextValueNumber));
588 return nextValueNumber++;
590 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
591 Expression e = create_expression(U);
593 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
594 if (EI != expressionNumbering.end()) {
595 valueNumbering.insert(std::make_pair(V, EI->second));
598 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
599 valueNumbering.insert(std::make_pair(V, nextValueNumber));
601 return nextValueNumber++;
603 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
604 Expression e = create_expression(U);
606 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
607 if (EI != expressionNumbering.end()) {
608 valueNumbering.insert(std::make_pair(V, EI->second));
611 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
612 valueNumbering.insert(std::make_pair(V, nextValueNumber));
614 return nextValueNumber++;
616 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
617 Expression e = create_expression(U);
619 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
620 if (EI != expressionNumbering.end()) {
621 valueNumbering.insert(std::make_pair(V, EI->second));
624 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
625 valueNumbering.insert(std::make_pair(V, nextValueNumber));
627 return nextValueNumber++;
629 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
630 Expression e = create_expression(U);
632 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
633 if (EI != expressionNumbering.end()) {
634 valueNumbering.insert(std::make_pair(V, EI->second));
637 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
638 valueNumbering.insert(std::make_pair(V, nextValueNumber));
640 return nextValueNumber++;
642 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
643 Expression e = create_expression(U);
645 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
646 if (EI != expressionNumbering.end()) {
647 valueNumbering.insert(std::make_pair(V, EI->second));
650 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
651 valueNumbering.insert(std::make_pair(V, nextValueNumber));
653 return nextValueNumber++;
656 valueNumbering.insert(std::make_pair(V, nextValueNumber));
657 return nextValueNumber++;
661 /// lookup - Returns the value number of the specified value. Fails if
662 /// the value has not yet been numbered.
663 uint32_t ValueTable::lookup(Value* V) const {
664 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
665 assert(VI != valueNumbering.end() && "Value not numbered?");
669 /// clear - Remove all entries from the ValueTable
670 void ValueTable::clear() {
671 valueNumbering.clear();
672 expressionNumbering.clear();
676 /// erase - Remove a value from the value numbering
677 void ValueTable::erase(Value* V) {
678 valueNumbering.erase(V);
681 //===----------------------------------------------------------------------===//
683 //===----------------------------------------------------------------------===//
686 template<> struct DenseMapInfo<uint32_t> {
687 static inline uint32_t getEmptyKey() { return ~0; }
688 static inline uint32_t getTombstoneKey() { return ~0 - 1; }
689 static unsigned getHashValue(const uint32_t& Val) { return Val * 37; }
690 static bool isPod() { return true; }
691 static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) {
698 struct VISIBILITY_HIDDEN ValueNumberScope {
699 ValueNumberScope* parent;
700 DenseMap<uint32_t, Value*> table;
702 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
708 class VISIBILITY_HIDDEN GVN : public FunctionPass {
709 bool runOnFunction(Function &F);
711 static char ID; // Pass identification, replacement for typeid
712 GVN() : FunctionPass((intptr_t)&ID) { }
716 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
718 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
722 // This transformation requires dominator postdominator info
723 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
724 AU.addRequired<DominatorTree>();
725 AU.addRequired<MemoryDependenceAnalysis>();
726 AU.addRequired<AliasAnalysis>();
728 AU.addPreserved<DominatorTree>();
729 AU.addPreserved<AliasAnalysis>();
730 AU.addPreserved<MemoryDependenceAnalysis>();
734 // FIXME: eliminate or document these better
735 bool processLoad(LoadInst* L,
736 DenseMap<Value*, LoadInst*> &lastLoad,
737 SmallVectorImpl<Instruction*> &toErase);
738 bool processInstruction(Instruction* I,
739 DenseMap<Value*, LoadInst*>& lastSeenLoad,
740 SmallVectorImpl<Instruction*> &toErase);
741 bool processNonLocalLoad(LoadInst* L,
742 SmallVectorImpl<Instruction*> &toErase);
743 bool processBlock(DomTreeNode* DTN);
744 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
745 DenseMap<BasicBlock*, Value*> &Phis,
746 bool top_level = false);
747 void dump(DenseMap<uint32_t, Value*>& d);
748 bool iterateOnFunction(Function &F);
749 Value* CollapsePhi(PHINode* p);
750 bool isSafeReplacement(PHINode* p, Instruction* inst);
751 bool performPRE(Function& F);
752 Value* lookupNumber(BasicBlock* BB, uint32_t num);
753 bool mergeBlockIntoPredecessor(BasicBlock* BB);
759 // createGVNPass - The public interface to this file...
760 FunctionPass *llvm::createGVNPass() { return new GVN(); }
762 static RegisterPass<GVN> X("gvn",
763 "Global Value Numbering");
765 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
767 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
768 E = d.end(); I != E; ++I) {
769 printf("%d\n", I->first);
775 Value* GVN::CollapsePhi(PHINode* p) {
776 DominatorTree &DT = getAnalysis<DominatorTree>();
777 Value* constVal = p->hasConstantValue();
779 if (!constVal) return 0;
781 Instruction* inst = dyn_cast<Instruction>(constVal);
785 if (DT.dominates(inst, p))
786 if (isSafeReplacement(p, inst))
791 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
792 if (!isa<PHINode>(inst))
795 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
797 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
798 if (use_phi->getParent() == inst->getParent())
804 /// GetValueForBlock - Get the value to use within the specified basic block.
805 /// available values are in Phis.
806 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
807 DenseMap<BasicBlock*, Value*> &Phis,
810 // If we have already computed this value, return the previously computed val.
811 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
812 if (V != Phis.end() && !top_level) return V->second;
814 // If the block is unreachable, just return undef, since this path
815 // can't actually occur at runtime.
816 if (!getAnalysis<DominatorTree>().isReachableFromEntry(BB))
817 return Phis[BB] = UndefValue::get(orig->getType());
819 BasicBlock* singlePred = BB->getSinglePredecessor();
821 Value *ret = GetValueForBlock(singlePred, orig, Phis);
826 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
827 // now, then get values to fill in the incoming values for the PHI.
828 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
830 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
832 if (Phis.count(BB) == 0)
833 Phis.insert(std::make_pair(BB, PN));
835 // Fill in the incoming values for the block.
836 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
837 Value* val = GetValueForBlock(*PI, orig, Phis);
838 PN->addIncoming(val, *PI);
841 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
842 AA.copyValue(orig, PN);
844 // Attempt to collapse PHI nodes that are trivially redundant
845 Value* v = CollapsePhi(PN);
847 // Cache our phi construction results
848 phiMap[orig->getPointerOperand()].insert(PN);
852 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
854 MD.removeInstruction(PN);
855 PN->replaceAllUsesWith(v);
857 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
858 E = Phis.end(); I != E; ++I)
862 PN->eraseFromParent();
868 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
869 /// non-local by performing PHI construction.
870 bool GVN::processNonLocalLoad(LoadInst* L,
871 SmallVectorImpl<Instruction*> &toErase) {
872 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
874 // Find the non-local dependencies of the load
875 DenseMap<BasicBlock*, Value*> deps;
876 MD.getNonLocalDependency(L, deps);
878 DenseMap<BasicBlock*, Value*> repl;
880 // Filter out useless results (non-locals, etc)
881 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
883 if (I->second == MemoryDependenceAnalysis::None)
886 if (I->second == MemoryDependenceAnalysis::NonLocal)
889 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
890 if (S->getPointerOperand() != L->getPointerOperand())
892 repl[I->first] = S->getOperand(0);
893 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
894 if (LD->getPointerOperand() != L->getPointerOperand())
902 // Use cached PHI construction information from previous runs
903 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
904 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
906 if ((*I)->getParent() == L->getParent()) {
907 MD.removeInstruction(L);
908 L->replaceAllUsesWith(*I);
909 toErase.push_back(L);
914 repl.insert(std::make_pair((*I)->getParent(), *I));
917 // Perform PHI construction
918 SmallPtrSet<BasicBlock*, 4> visited;
919 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
921 MD.removeInstruction(L);
922 L->replaceAllUsesWith(v);
923 toErase.push_back(L);
929 /// processLoad - Attempt to eliminate a load, first by eliminating it
930 /// locally, and then attempting non-local elimination if that fails.
931 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
932 SmallVectorImpl<Instruction*> &toErase) {
933 if (L->isVolatile()) {
934 lastLoad[L->getPointerOperand()] = L;
938 Value* pointer = L->getPointerOperand();
939 LoadInst*& last = lastLoad[pointer];
941 // ... to a pointer that has been loaded from before...
942 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
943 bool removedNonLocal = false;
944 Instruction* dep = MD.getDependency(L);
945 if (dep == MemoryDependenceAnalysis::NonLocal &&
946 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
947 removedNonLocal = processNonLocalLoad(L, toErase);
949 if (!removedNonLocal)
952 return removedNonLocal;
956 bool deletedLoad = false;
958 // Walk up the dependency chain until we either find
959 // a dependency we can use, or we can't walk any further
960 while (dep != MemoryDependenceAnalysis::None &&
961 dep != MemoryDependenceAnalysis::NonLocal &&
962 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
963 // ... that depends on a store ...
964 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
965 if (S->getPointerOperand() == pointer) {
967 MD.removeInstruction(L);
969 L->replaceAllUsesWith(S->getOperand(0));
970 toErase.push_back(L);
975 // Whether we removed it or not, we can't
979 // If we don't depend on a store, and we haven't
980 // been loaded before, bail.
982 } else if (dep == last) {
984 MD.removeInstruction(L);
986 L->replaceAllUsesWith(last);
987 toErase.push_back(L);
993 dep = MD.getDependency(L, dep);
997 if (dep != MemoryDependenceAnalysis::None &&
998 dep != MemoryDependenceAnalysis::NonLocal &&
999 isa<AllocationInst>(dep)) {
1000 // Check that this load is actually from the
1001 // allocation we found
1002 Value* v = L->getOperand(0);
1004 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
1005 v = BC->getOperand(0);
1006 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
1007 v = GEP->getOperand(0);
1012 // If this load depends directly on an allocation, there isn't
1013 // anything stored there; therefore, we can optimize this load
1015 MD.removeInstruction(L);
1017 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1018 toErase.push_back(L);
1030 Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) {
1031 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1032 if (I == localAvail.end())
1035 ValueNumberScope* locals = I->second;
1038 DenseMap<uint32_t, Value*>::iterator I = locals->table.find(num);
1039 if (I != locals->table.end())
1042 locals = locals->parent;
1048 /// processInstruction - When calculating availability, handle an instruction
1049 /// by inserting it into the appropriate sets
1050 bool GVN::processInstruction(Instruction *I,
1051 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1052 SmallVectorImpl<Instruction*> &toErase) {
1053 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1054 bool changed = processLoad(L, lastSeenLoad, toErase);
1057 unsigned num = VN.lookup_or_add(L);
1058 localAvail[I->getParent()]->table.insert(std::make_pair(num, L));
1064 uint32_t nextNum = VN.getNextUnusedValueNumber();
1065 unsigned num = VN.lookup_or_add(I);
1067 // Allocations are always uniquely numbered, so we can save time and memory
1068 // by fast failing them.
1069 if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
1070 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1074 // Collapse PHI nodes
1075 if (PHINode* p = dyn_cast<PHINode>(I)) {
1076 Value* constVal = CollapsePhi(p);
1079 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1081 if (PI->second.count(p))
1082 PI->second.erase(p);
1084 p->replaceAllUsesWith(constVal);
1085 toErase.push_back(p);
1087 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1090 // If the number we were assigned was a brand new VN, then we don't
1091 // need to do a lookup to see if the number already exists
1092 // somewhere in the domtree: it can't!
1093 } else if (num == nextNum) {
1094 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1096 // Perform value-number based elimination
1097 } else if (Value* repl = lookupNumber(I->getParent(), num)) {
1099 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1100 MD.removeInstruction(I);
1103 I->replaceAllUsesWith(repl);
1104 toErase.push_back(I);
1107 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1113 // GVN::runOnFunction - This is the main transformation entry point for a
1116 bool GVN::runOnFunction(Function& F) {
1117 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1118 VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1119 VN.setDomTree(&getAnalysis<DominatorTree>());
1121 bool changed = false;
1122 bool shouldContinue = true;
1124 while (shouldContinue) {
1125 shouldContinue = iterateOnFunction(F);
1126 changed |= shouldContinue;
1133 bool GVN::processBlock(DomTreeNode* DTN) {
1134 BasicBlock* BB = DTN->getBlock();
1136 SmallVector<Instruction*, 8> toErase;
1137 DenseMap<Value*, LoadInst*> lastSeenLoad;
1138 bool changed_function = false;
1142 new ValueNumberScope(localAvail[DTN->getIDom()->getBlock()]);
1144 localAvail[BB] = new ValueNumberScope(0);
1146 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1148 changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1149 if (toErase.empty()) {
1154 // If we need some instructions deleted, do it now.
1155 NumGVNInstr += toErase.size();
1157 // Avoid iterator invalidation.
1158 bool AtStart = BI == BB->begin();
1162 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1163 E = toErase.end(); I != E; ++I)
1164 (*I)->eraseFromParent();
1174 return changed_function;
1177 /// performPRE - Perform a purely local form of PRE that looks for diamond
1178 /// control flow patterns and attempts to perform simple PRE at the join point.
1179 bool GVN::performPRE(Function& F) {
1180 bool changed = false;
1181 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1182 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1183 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1184 BasicBlock* CurrentBlock = *DI;
1186 // Nothing to PRE in the entry block.
1187 if (CurrentBlock == &F.getEntryBlock()) continue;
1189 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1190 BE = CurrentBlock->end(); BI != BE; ) {
1191 if (isa<AllocationInst>(BI) || isa<TerminatorInst>(BI) ||
1192 isa<PHINode>(BI) || BI->mayReadFromMemory() ||
1193 BI->mayWriteToMemory()) {
1198 uint32_t valno = VN.lookup(BI);
1200 // Look for the predecessors for PRE opportunities. We're
1201 // only trying to solve the basic diamond case, where
1202 // a value is computed in the successor and one predecessor,
1203 // but not the other. We also explicitly disallow cases
1204 // where the successor is its own predecessor, because they're
1205 // more complicated to get right.
1206 unsigned numWith = 0;
1207 unsigned numWithout = 0;
1208 BasicBlock* PREPred = 0;
1209 DenseMap<BasicBlock*, Value*> predMap;
1210 for (pred_iterator PI = pred_begin(CurrentBlock),
1211 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1212 // We're not interested in PRE where the block is its
1213 // own predecessor, on in blocks with predecessors
1214 // that are not reachable.
1215 if (*PI == CurrentBlock) {
1218 } else if (!localAvail.count(*PI)) {
1223 DenseMap<uint32_t, Value*>::iterator predV =
1224 localAvail[*PI]->table.find(valno);
1225 if (predV == localAvail[*PI]->table.end()) {
1228 } else if (predV->second == BI) {
1231 predMap[*PI] = predV->second;
1236 // Don't do PRE when it might increase code size, i.e. when
1237 // we would need to insert instructions in more than one pred.
1238 if (numWithout != 1 || numWith == 0) {
1243 // We can't do PRE safely on a critical edge, so instead we schedule
1244 // the edge to be split and perform the PRE the next time we iterate
1246 unsigned succNum = 0;
1247 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1249 if (PREPred->getTerminator()->getSuccessor(i) == PREPred) {
1254 if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1255 toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1261 // Instantiate the expression the in predecessor that lacked it.
1262 // Because we are going top-down through the block, all value numbers
1263 // will be available in the predecessor by the time we need them. Any
1264 // that weren't original present will have been instantiated earlier
1266 Instruction* PREInstr = BI->clone();
1267 bool success = true;
1268 for (unsigned i = 0; i < BI->getNumOperands(); ++i) {
1269 Value* op = BI->getOperand(i);
1270 if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op))
1271 PREInstr->setOperand(i, op);
1273 Value* V = lookupNumber(PREPred, VN.lookup(op));
1278 PREInstr->setOperand(i, V);
1282 // Fail out if we encounter an operand that is not available in
1283 // the PRE predecessor. This is typically because of loads which
1284 // are not value numbered precisely.
1291 PREInstr->insertBefore(PREPred->getTerminator());
1292 PREInstr->setName(BI->getName() + ".pre");
1293 predMap[PREPred] = PREInstr;
1294 VN.add(PREInstr, valno);
1297 // Update the availability map to include the new instruction.
1298 localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr));
1300 // Create a PHI to make the value available in this block.
1301 PHINode* Phi = PHINode::Create(BI->getType(),
1302 BI->getName() + ".pre-phi",
1303 CurrentBlock->begin());
1304 for (pred_iterator PI = pred_begin(CurrentBlock),
1305 PE = pred_end(CurrentBlock); PI != PE; ++PI)
1306 Phi->addIncoming(predMap[*PI], *PI);
1309 localAvail[CurrentBlock]->table[valno] = Phi;
1311 BI->replaceAllUsesWith(Phi);
1314 Instruction* erase = BI;
1316 erase->eraseFromParent();
1322 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1323 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1324 SplitCriticalEdge(I->first, I->second, this);
1329 // mergeBlockIntoPredecessor - If this block is the only successor
1330 // of its predecessor, and the edge is non-critical,
1331 // fold it into that predecessor.
1332 bool GVN::mergeBlockIntoPredecessor(BasicBlock* BB) {
1333 // Can't merge the entry block.
1334 if (pred_begin(BB) == pred_end(BB)) return false;
1335 // Can't merge if there are multiple preds.
1336 if (++pred_begin(BB) != pred_end(BB)) return false;
1338 BasicBlock* PredBB = *pred_begin(BB);
1340 // Can't merge if the edge is critical.
1341 if (PredBB->getTerminator()->getNumSuccessors() != 1) return false;
1343 // Begin by getting rid of unneeded PHIs.
1344 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1345 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1346 BB->getInstList().pop_front(); // Delete the phi node...
1349 // Delete the unconditional branch from the predecessor...
1350 PredBB->getInstList().pop_back();
1352 // Move all definitions in the successor to the predecessor...
1353 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
1355 // Make all PHI nodes that referred to BB now refer to Pred as their
1357 BB->replaceAllUsesWith(PredBB);
1359 // Finally, erase the old block and update dominator info.
1360 DominatorTree& DT = getAnalysis<DominatorTree>();
1361 DomTreeNode* DTN = DT[BB];
1362 DomTreeNode* PredDTN = DT[PredBB];
1365 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
1366 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
1367 DE = Children.end(); DI != DE; ++DI)
1368 DT.changeImmediateDominator(*DI, PredDTN);
1373 BB->eraseFromParent();
1379 // iterateOnFunction - Executes one iteration of GVN
1380 bool GVN::iterateOnFunction(Function &F) {
1381 // Clean out global sets from any previous functions
1385 // Merge unconditional branches, allowing PRE to catch more
1386 // optimization opportunities.
1387 bool mergedBlocks = false;
1388 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1389 BasicBlock* BB = FI;
1391 mergedBlocks |= mergeBlockIntoPredecessor(BB);
1394 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1395 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1399 DominatorTree &DT = getAnalysis<DominatorTree>();
1401 // Top-down walk of the dominator tree
1402 bool changed = false;
1403 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1404 DE = df_end(DT.getRootNode()); DI != DE; ++DI)
1405 changed |= processBlock(*DI);
1408 changed |= performPRE(F);
1410 return changed || mergedBlocks;