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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "gvn"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/BasicBlock.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/ParameterAttributes.h"
24 #include "llvm/Value.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/DepthFirstIterator.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/SparseBitVector.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/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Target/TargetData.h"
43 STATISTIC(NumGVNInstr, "Number of instructions deleted");
44 STATISTIC(NumGVNLoad, "Number of loads deleted");
46 //===----------------------------------------------------------------------===//
48 //===----------------------------------------------------------------------===//
50 /// This class holds the mapping between values and value numbers. It is used
51 /// as an efficient mechanism to determine the expression-wise equivalence of
54 struct VISIBILITY_HIDDEN Expression {
55 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
56 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
57 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
58 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
59 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
60 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
61 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
62 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
63 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
64 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
67 ExpressionOpcode opcode;
72 SmallVector<uint32_t, 4> varargs;
76 Expression(ExpressionOpcode o) : opcode(o) { }
78 bool operator==(const Expression &other) const {
79 if (opcode != other.opcode)
81 else if (opcode == EMPTY || opcode == TOMBSTONE)
83 else if (type != other.type)
85 else if (function != other.function)
87 else if (firstVN != other.firstVN)
89 else if (secondVN != other.secondVN)
91 else if (thirdVN != other.thirdVN)
94 if (varargs.size() != other.varargs.size())
97 for (size_t i = 0; i < varargs.size(); ++i)
98 if (varargs[i] != other.varargs[i])
105 bool operator!=(const Expression &other) const {
106 if (opcode != other.opcode)
108 else if (opcode == EMPTY || opcode == TOMBSTONE)
110 else if (type != other.type)
112 else if (function != other.function)
114 else if (firstVN != other.firstVN)
116 else if (secondVN != other.secondVN)
118 else if (thirdVN != other.thirdVN)
121 if (varargs.size() != other.varargs.size())
124 for (size_t i = 0; i < varargs.size(); ++i)
125 if (varargs[i] != other.varargs[i])
133 class VISIBILITY_HIDDEN ValueTable {
135 DenseMap<Value*, uint32_t> valueNumbering;
136 DenseMap<Expression, uint32_t> expressionNumbering;
138 MemoryDependenceAnalysis* MD;
140 uint32_t nextValueNumber;
142 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
143 Expression::ExpressionOpcode getOpcode(CmpInst* C);
144 Expression::ExpressionOpcode getOpcode(CastInst* C);
145 Expression create_expression(BinaryOperator* BO);
146 Expression create_expression(CmpInst* C);
147 Expression create_expression(ShuffleVectorInst* V);
148 Expression create_expression(ExtractElementInst* C);
149 Expression create_expression(InsertElementInst* V);
150 Expression create_expression(SelectInst* V);
151 Expression create_expression(CastInst* C);
152 Expression create_expression(GetElementPtrInst* G);
153 Expression create_expression(CallInst* C);
155 ValueTable() : nextValueNumber(1) { }
156 uint32_t lookup_or_add(Value* V);
157 uint32_t lookup(Value* V) const;
158 void add(Value* V, uint32_t num);
160 void erase(Value* v);
162 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
163 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
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)) {
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) && "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 Instruction* dep = MD->getDependency(C);
442 if (dep == MemoryDependenceAnalysis::NonLocal ||
443 !isa<CallInst>(dep)) {
444 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
445 valueNumbering.insert(std::make_pair(V, nextValueNumber));
447 return nextValueNumber++;
450 CallInst* cdep = cast<CallInst>(dep);
451 Expression d_exp = create_expression(cdep);
454 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
455 valueNumbering.insert(std::make_pair(V, nextValueNumber));
457 return nextValueNumber++;
459 uint32_t v = expressionNumbering[d_exp];
460 valueNumbering.insert(std::make_pair(V, v));
465 valueNumbering.insert(std::make_pair(V, nextValueNumber));
466 return nextValueNumber++;
468 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
469 Expression e = create_expression(BO);
471 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
472 if (EI != expressionNumbering.end()) {
473 valueNumbering.insert(std::make_pair(V, EI->second));
476 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
477 valueNumbering.insert(std::make_pair(V, nextValueNumber));
479 return nextValueNumber++;
481 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
482 Expression e = create_expression(C);
484 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
485 if (EI != expressionNumbering.end()) {
486 valueNumbering.insert(std::make_pair(V, EI->second));
489 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
490 valueNumbering.insert(std::make_pair(V, nextValueNumber));
492 return nextValueNumber++;
494 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
495 Expression e = create_expression(U);
497 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
498 if (EI != expressionNumbering.end()) {
499 valueNumbering.insert(std::make_pair(V, EI->second));
502 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
503 valueNumbering.insert(std::make_pair(V, nextValueNumber));
505 return nextValueNumber++;
507 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
508 Expression e = create_expression(U);
510 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
511 if (EI != expressionNumbering.end()) {
512 valueNumbering.insert(std::make_pair(V, EI->second));
515 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
516 valueNumbering.insert(std::make_pair(V, nextValueNumber));
518 return nextValueNumber++;
520 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
521 Expression e = create_expression(U);
523 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
524 if (EI != expressionNumbering.end()) {
525 valueNumbering.insert(std::make_pair(V, EI->second));
528 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
529 valueNumbering.insert(std::make_pair(V, nextValueNumber));
531 return nextValueNumber++;
533 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
534 Expression e = create_expression(U);
536 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
537 if (EI != expressionNumbering.end()) {
538 valueNumbering.insert(std::make_pair(V, EI->second));
541 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
542 valueNumbering.insert(std::make_pair(V, nextValueNumber));
544 return nextValueNumber++;
546 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
547 Expression e = create_expression(U);
549 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
550 if (EI != expressionNumbering.end()) {
551 valueNumbering.insert(std::make_pair(V, EI->second));
554 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
555 valueNumbering.insert(std::make_pair(V, nextValueNumber));
557 return nextValueNumber++;
559 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
560 Expression e = create_expression(U);
562 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
563 if (EI != expressionNumbering.end()) {
564 valueNumbering.insert(std::make_pair(V, EI->second));
567 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
568 valueNumbering.insert(std::make_pair(V, nextValueNumber));
570 return nextValueNumber++;
573 valueNumbering.insert(std::make_pair(V, nextValueNumber));
574 return nextValueNumber++;
578 /// lookup - Returns the value number of the specified value. Fails if
579 /// the value has not yet been numbered.
580 uint32_t ValueTable::lookup(Value* V) const {
581 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
582 assert(VI != valueNumbering.end() && "Value not numbered?");
586 /// clear - Remove all entries from the ValueTable
587 void ValueTable::clear() {
588 valueNumbering.clear();
589 expressionNumbering.clear();
593 /// erase - Remove a value from the value numbering
594 void ValueTable::erase(Value* V) {
595 valueNumbering.erase(V);
598 //===----------------------------------------------------------------------===//
599 // ValueNumberedSet Class
600 //===----------------------------------------------------------------------===//
602 class VISIBILITY_HIDDEN ValueNumberedSet {
604 SmallPtrSet<Value*, 8> contents;
605 SparseBitVector<64> numbers;
607 ValueNumberedSet() { }
608 ValueNumberedSet(const ValueNumberedSet& other) {
609 numbers = other.numbers;
610 contents = other.contents;
613 typedef SmallPtrSet<Value*, 8>::iterator iterator;
615 iterator begin() { return contents.begin(); }
616 iterator end() { return contents.end(); }
618 bool insert(Value* v) { return contents.insert(v); }
619 void insert(iterator I, iterator E) { contents.insert(I, E); }
620 void erase(Value* v) { contents.erase(v); }
621 unsigned count(Value* v) { return contents.count(v); }
622 size_t size() { return contents.size(); }
624 void set(unsigned i) {
628 void operator=(const ValueNumberedSet& other) {
629 contents = other.contents;
630 numbers = other.numbers;
633 void reset(unsigned i) {
637 bool test(unsigned i) {
638 return numbers.test(i);
643 //===----------------------------------------------------------------------===//
645 //===----------------------------------------------------------------------===//
649 class VISIBILITY_HIDDEN GVN : public FunctionPass {
650 bool runOnFunction(Function &F);
652 static char ID; // Pass identification, replacement for typeid
653 GVN() : FunctionPass((intptr_t)&ID) { }
658 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
660 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
664 // This transformation requires dominator postdominator info
665 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
666 AU.setPreservesCFG();
667 AU.addRequired<DominatorTree>();
668 AU.addRequired<MemoryDependenceAnalysis>();
669 AU.addRequired<AliasAnalysis>();
670 AU.addRequired<TargetData>();
671 AU.addPreserved<AliasAnalysis>();
672 AU.addPreserved<MemoryDependenceAnalysis>();
673 AU.addPreserved<TargetData>();
677 // FIXME: eliminate or document these better
678 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
679 void val_insert(ValueNumberedSet& s, Value* v);
680 bool processLoad(LoadInst* L,
681 DenseMap<Value*, LoadInst*> &lastLoad,
682 SmallVectorImpl<Instruction*> &toErase);
683 bool processInstruction(Instruction* I,
684 ValueNumberedSet& currAvail,
685 DenseMap<Value*, LoadInst*>& lastSeenLoad,
686 SmallVectorImpl<Instruction*> &toErase);
687 bool processNonLocalLoad(LoadInst* L,
688 SmallVectorImpl<Instruction*> &toErase);
689 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
690 DenseMap<BasicBlock*, Value*> &Phis,
691 bool top_level = false);
692 void dump(DenseMap<BasicBlock*, Value*>& d);
693 bool iterateOnFunction(Function &F);
694 Value* CollapsePhi(PHINode* p);
695 bool isSafeReplacement(PHINode* p, Instruction* inst);
701 // createGVNPass - The public interface to this file...
702 FunctionPass *llvm::createGVNPass() { return new GVN(); }
704 static RegisterPass<GVN> X("gvn",
705 "Global Value Numbering");
707 /// find_leader - Given a set and a value number, return the first
708 /// element of the set with that value number, or 0 if no such element
710 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
714 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
716 if (v == VN.lookup(*I))
719 assert(0 && "No leader found, but present bit is set?");
723 /// val_insert - Insert a value into a set only if there is not a value
724 /// with the same value number already in the set
725 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
726 uint32_t num = VN.lookup(v);
731 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
733 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
734 E = d.end(); I != E; ++I) {
735 if (I->second == MemoryDependenceAnalysis::None)
743 Value* GVN::CollapsePhi(PHINode* p) {
744 DominatorTree &DT = getAnalysis<DominatorTree>();
745 Value* constVal = p->hasConstantValue();
747 if (!constVal) return 0;
749 Instruction* inst = dyn_cast<Instruction>(constVal);
753 if (DT.dominates(inst, p))
754 if (isSafeReplacement(p, inst))
759 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
760 if (!isa<PHINode>(inst))
763 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
765 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
766 if (use_phi->getParent() == inst->getParent())
772 /// GetValueForBlock - Get the value to use within the specified basic block.
773 /// available values are in Phis.
774 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
775 DenseMap<BasicBlock*, Value*> &Phis,
778 // If we have already computed this value, return the previously computed val.
779 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
780 if (V != Phis.end() && !top_level) return V->second;
782 BasicBlock* singlePred = BB->getSinglePredecessor();
784 Value *ret = GetValueForBlock(singlePred, orig, Phis);
789 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
790 // now, then get values to fill in the incoming values for the PHI.
791 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
793 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
795 if (Phis.count(BB) == 0)
796 Phis.insert(std::make_pair(BB, PN));
798 // Fill in the incoming values for the block.
799 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
800 Value* val = GetValueForBlock(*PI, orig, Phis);
801 PN->addIncoming(val, *PI);
804 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
805 AA.copyValue(orig, PN);
807 // Attempt to collapse PHI nodes that are trivially redundant
808 Value* v = CollapsePhi(PN);
810 // Cache our phi construction results
811 phiMap[orig->getPointerOperand()].insert(PN);
815 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
817 MD.removeInstruction(PN);
818 PN->replaceAllUsesWith(v);
820 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
821 E = Phis.end(); I != E; ++I)
825 PN->eraseFromParent();
831 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
832 /// non-local by performing PHI construction.
833 bool GVN::processNonLocalLoad(LoadInst* L,
834 SmallVectorImpl<Instruction*> &toErase) {
835 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
837 // Find the non-local dependencies of the load
838 DenseMap<BasicBlock*, Value*> deps;
839 MD.getNonLocalDependency(L, deps);
841 DenseMap<BasicBlock*, Value*> repl;
843 // Filter out useless results (non-locals, etc)
844 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
846 if (I->second == MemoryDependenceAnalysis::None)
849 if (I->second == MemoryDependenceAnalysis::NonLocal)
852 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
853 if (S->getPointerOperand() != L->getPointerOperand())
855 repl[I->first] = S->getOperand(0);
856 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
857 if (LD->getPointerOperand() != L->getPointerOperand())
865 // Use cached PHI construction information from previous runs
866 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
867 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
869 if ((*I)->getParent() == L->getParent()) {
870 MD.removeInstruction(L);
871 L->replaceAllUsesWith(*I);
872 toErase.push_back(L);
877 repl.insert(std::make_pair((*I)->getParent(), *I));
880 // Perform PHI construction
881 SmallPtrSet<BasicBlock*, 4> visited;
882 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
884 MD.removeInstruction(L);
885 L->replaceAllUsesWith(v);
886 toErase.push_back(L);
892 /// processLoad - Attempt to eliminate a load, first by eliminating it
893 /// locally, and then attempting non-local elimination if that fails.
894 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
895 SmallVectorImpl<Instruction*> &toErase) {
896 if (L->isVolatile()) {
897 lastLoad[L->getPointerOperand()] = L;
901 Value* pointer = L->getPointerOperand();
902 LoadInst*& last = lastLoad[pointer];
904 // ... to a pointer that has been loaded from before...
905 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
906 bool removedNonLocal = false;
907 Instruction* dep = MD.getDependency(L);
908 if (dep == MemoryDependenceAnalysis::NonLocal &&
909 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
910 removedNonLocal = processNonLocalLoad(L, toErase);
912 if (!removedNonLocal)
915 return removedNonLocal;
919 bool deletedLoad = false;
921 // Walk up the dependency chain until we either find
922 // a dependency we can use, or we can't walk any further
923 while (dep != MemoryDependenceAnalysis::None &&
924 dep != MemoryDependenceAnalysis::NonLocal &&
925 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
926 // ... that depends on a store ...
927 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
928 if (S->getPointerOperand() == pointer) {
930 MD.removeInstruction(L);
932 L->replaceAllUsesWith(S->getOperand(0));
933 toErase.push_back(L);
938 // Whether we removed it or not, we can't
942 // If we don't depend on a store, and we haven't
943 // been loaded before, bail.
945 } else if (dep == last) {
947 MD.removeInstruction(L);
949 L->replaceAllUsesWith(last);
950 toErase.push_back(L);
956 dep = MD.getDependency(L, dep);
960 if (dep != MemoryDependenceAnalysis::None &&
961 dep != MemoryDependenceAnalysis::NonLocal &&
962 isa<AllocationInst>(dep)) {
963 // Check that this load is actually from the
964 // allocation we found
965 Value* v = L->getOperand(0);
967 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
968 v = BC->getOperand(0);
969 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
970 v = GEP->getOperand(0);
975 // If this load depends directly on an allocation, there isn't
976 // anything stored there; therefore, we can optimize this load
978 MD.removeInstruction(L);
980 L->replaceAllUsesWith(UndefValue::get(L->getType()));
981 toErase.push_back(L);
993 /// processInstruction - When calculating availability, handle an instruction
994 /// by inserting it into the appropriate sets
995 bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
996 DenseMap<Value*, LoadInst*> &lastSeenLoad,
997 SmallVectorImpl<Instruction*> &toErase) {
998 if (LoadInst* L = dyn_cast<LoadInst>(I))
999 return processLoad(L, lastSeenLoad, toErase);
1001 // Allocations are always uniquely numbered, so we can save time and memory
1002 // by fast failing them.
1003 if (isa<AllocationInst>(I))
1006 unsigned num = VN.lookup_or_add(I);
1008 // Collapse PHI nodes
1009 if (PHINode* p = dyn_cast<PHINode>(I)) {
1010 Value* constVal = CollapsePhi(p);
1013 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1015 if (PI->second.count(p))
1016 PI->second.erase(p);
1018 p->replaceAllUsesWith(constVal);
1019 toErase.push_back(p);
1021 // Perform value-number based elimination
1022 } else if (currAvail.test(num)) {
1023 Value* repl = find_leader(currAvail, num);
1026 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1027 MD.removeInstruction(I);
1030 I->replaceAllUsesWith(repl);
1031 toErase.push_back(I);
1033 } else if (!I->isTerminator()) {
1035 currAvail.insert(I);
1041 // GVN::runOnFunction - This is the main transformation entry point for a
1044 bool GVN::runOnFunction(Function& F) {
1045 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1046 VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1048 bool changed = false;
1049 bool shouldContinue = true;
1051 while (shouldContinue) {
1052 shouldContinue = iterateOnFunction(F);
1053 changed |= shouldContinue;
1060 // GVN::iterateOnFunction - Executes one iteration of GVN
1061 bool GVN::iterateOnFunction(Function &F) {
1062 // Clean out global sets from any previous functions
1064 availableOut.clear();
1067 bool changed_function = false;
1069 DominatorTree &DT = getAnalysis<DominatorTree>();
1071 SmallVector<Instruction*, 8> toErase;
1072 DenseMap<Value*, LoadInst*> lastSeenLoad;
1073 DenseMap<DomTreeNode*, size_t> numChildrenVisited;
1075 // Top-down walk of the dominator tree
1076 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1077 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1079 // Get the set to update for this block
1080 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1081 lastSeenLoad.clear();
1083 BasicBlock* BB = DI->getBlock();
1085 // A block inherits AVAIL_OUT from its dominator
1086 if (DI->getIDom() != 0) {
1087 currAvail = availableOut[DI->getIDom()->getBlock()];
1089 numChildrenVisited[DI->getIDom()]++;
1091 if (numChildrenVisited[DI->getIDom()] == DI->getIDom()->getNumChildren()) {
1092 availableOut.erase(DI->getIDom()->getBlock());
1093 numChildrenVisited.erase(DI->getIDom());
1097 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1099 changed_function |= processInstruction(BI, currAvail,
1100 lastSeenLoad, toErase);
1101 if (toErase.empty()) {
1106 // If we need some instructions deleted, do it now.
1107 NumGVNInstr += toErase.size();
1109 // Avoid iterator invalidation.
1110 bool AtStart = BI == BB->begin();
1114 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1115 E = toErase.end(); I != E; ++I)
1116 (*I)->eraseFromParent();
1127 return changed_function;