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"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Value.h"
25 #include "llvm/ADT/BitVector.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"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 /// This class holds the mapping between values and value numbers. It is used
43 /// as an efficient mechanism to determine the expression-wise equivalence of
46 struct VISIBILITY_HIDDEN Expression {
47 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
48 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
49 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
50 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
51 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
52 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
53 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
54 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
55 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
56 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
59 ExpressionOpcode opcode;
64 SmallVector<uint32_t, 4> varargs;
68 Expression(ExpressionOpcode o) : opcode(o) { }
70 bool operator==(const Expression &other) const {
71 if (opcode != other.opcode)
73 else if (opcode == EMPTY || opcode == TOMBSTONE)
75 else if (type != other.type)
77 else if (function != other.function)
79 else if (firstVN != other.firstVN)
81 else if (secondVN != other.secondVN)
83 else if (thirdVN != other.thirdVN)
86 if (varargs.size() != other.varargs.size())
89 for (size_t i = 0; i < varargs.size(); ++i)
90 if (varargs[i] != other.varargs[i])
97 bool operator!=(const Expression &other) const {
98 if (opcode != other.opcode)
100 else if (opcode == EMPTY || opcode == TOMBSTONE)
102 else if (type != other.type)
104 else if (function != other.function)
106 else if (firstVN != other.firstVN)
108 else if (secondVN != other.secondVN)
110 else if (thirdVN != other.thirdVN)
113 if (varargs.size() != other.varargs.size())
116 for (size_t i = 0; i < varargs.size(); ++i)
117 if (varargs[i] != other.varargs[i])
125 class VISIBILITY_HIDDEN ValueTable {
127 DenseMap<Value*, uint32_t> valueNumbering;
128 DenseMap<Expression, uint32_t> expressionNumbering;
131 uint32_t nextValueNumber;
133 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
134 Expression::ExpressionOpcode getOpcode(CmpInst* C);
135 Expression::ExpressionOpcode getOpcode(CastInst* C);
136 Expression create_expression(BinaryOperator* BO);
137 Expression create_expression(CmpInst* C);
138 Expression create_expression(ShuffleVectorInst* V);
139 Expression create_expression(ExtractElementInst* C);
140 Expression create_expression(InsertElementInst* V);
141 Expression create_expression(SelectInst* V);
142 Expression create_expression(CastInst* C);
143 Expression create_expression(GetElementPtrInst* G);
144 Expression create_expression(CallInst* C);
146 ValueTable() : nextValueNumber(1) { }
147 uint32_t lookup_or_add(Value* V);
148 uint32_t lookup(Value* V) const;
149 void add(Value* V, uint32_t num);
151 void erase(Value* v);
153 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
154 uint32_t hash_operand(Value* v);
159 template <> struct DenseMapInfo<Expression> {
160 static inline Expression getEmptyKey() {
161 return Expression(Expression::EMPTY);
164 static inline Expression getTombstoneKey() {
165 return Expression(Expression::TOMBSTONE);
168 static unsigned getHashValue(const Expression e) {
169 unsigned hash = e.opcode;
171 hash = e.firstVN + hash * 37;
172 hash = e.secondVN + hash * 37;
173 hash = e.thirdVN + hash * 37;
175 hash = (unsigned)((uintptr_t)e.type >> 4) ^
176 (unsigned)((uintptr_t)e.type >> 9) +
179 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
180 E = e.varargs.end(); I != E; ++I)
181 hash = *I + hash * 37;
183 hash = (unsigned)((uintptr_t)e.function >> 4) ^
184 (unsigned)((uintptr_t)e.function >> 9) +
189 static bool isEqual(const Expression &LHS, const Expression &RHS) {
192 static bool isPod() { return true; }
196 //===----------------------------------------------------------------------===//
197 // ValueTable Internal Functions
198 //===----------------------------------------------------------------------===//
199 Expression::ExpressionOpcode
200 ValueTable::getOpcode(BinaryOperator* BO) {
201 switch(BO->getOpcode()) {
202 case Instruction::Add:
203 return Expression::ADD;
204 case Instruction::Sub:
205 return Expression::SUB;
206 case Instruction::Mul:
207 return Expression::MUL;
208 case Instruction::UDiv:
209 return Expression::UDIV;
210 case Instruction::SDiv:
211 return Expression::SDIV;
212 case Instruction::FDiv:
213 return Expression::FDIV;
214 case Instruction::URem:
215 return Expression::UREM;
216 case Instruction::SRem:
217 return Expression::SREM;
218 case Instruction::FRem:
219 return Expression::FREM;
220 case Instruction::Shl:
221 return Expression::SHL;
222 case Instruction::LShr:
223 return Expression::LSHR;
224 case Instruction::AShr:
225 return Expression::ASHR;
226 case Instruction::And:
227 return Expression::AND;
228 case Instruction::Or:
229 return Expression::OR;
230 case Instruction::Xor:
231 return Expression::XOR;
233 // THIS SHOULD NEVER HAPPEN
235 assert(0 && "Binary operator with unknown opcode?");
236 return Expression::ADD;
240 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
241 if (C->getOpcode() == Instruction::ICmp) {
242 switch (C->getPredicate()) {
243 case ICmpInst::ICMP_EQ:
244 return Expression::ICMPEQ;
245 case ICmpInst::ICMP_NE:
246 return Expression::ICMPNE;
247 case ICmpInst::ICMP_UGT:
248 return Expression::ICMPUGT;
249 case ICmpInst::ICMP_UGE:
250 return Expression::ICMPUGE;
251 case ICmpInst::ICMP_ULT:
252 return Expression::ICMPULT;
253 case ICmpInst::ICMP_ULE:
254 return Expression::ICMPULE;
255 case ICmpInst::ICMP_SGT:
256 return Expression::ICMPSGT;
257 case ICmpInst::ICMP_SGE:
258 return Expression::ICMPSGE;
259 case ICmpInst::ICMP_SLT:
260 return Expression::ICMPSLT;
261 case ICmpInst::ICMP_SLE:
262 return Expression::ICMPSLE;
264 // THIS SHOULD NEVER HAPPEN
266 assert(0 && "Comparison with unknown predicate?");
267 return Expression::ICMPEQ;
270 switch (C->getPredicate()) {
271 case FCmpInst::FCMP_OEQ:
272 return Expression::FCMPOEQ;
273 case FCmpInst::FCMP_OGT:
274 return Expression::FCMPOGT;
275 case FCmpInst::FCMP_OGE:
276 return Expression::FCMPOGE;
277 case FCmpInst::FCMP_OLT:
278 return Expression::FCMPOLT;
279 case FCmpInst::FCMP_OLE:
280 return Expression::FCMPOLE;
281 case FCmpInst::FCMP_ONE:
282 return Expression::FCMPONE;
283 case FCmpInst::FCMP_ORD:
284 return Expression::FCMPORD;
285 case FCmpInst::FCMP_UNO:
286 return Expression::FCMPUNO;
287 case FCmpInst::FCMP_UEQ:
288 return Expression::FCMPUEQ;
289 case FCmpInst::FCMP_UGT:
290 return Expression::FCMPUGT;
291 case FCmpInst::FCMP_UGE:
292 return Expression::FCMPUGE;
293 case FCmpInst::FCMP_ULT:
294 return Expression::FCMPULT;
295 case FCmpInst::FCMP_ULE:
296 return Expression::FCMPULE;
297 case FCmpInst::FCMP_UNE:
298 return Expression::FCMPUNE;
300 // THIS SHOULD NEVER HAPPEN
302 assert(0 && "Comparison with unknown predicate?");
303 return Expression::FCMPOEQ;
308 Expression::ExpressionOpcode
309 ValueTable::getOpcode(CastInst* C) {
310 switch(C->getOpcode()) {
311 case Instruction::Trunc:
312 return Expression::TRUNC;
313 case Instruction::ZExt:
314 return Expression::ZEXT;
315 case Instruction::SExt:
316 return Expression::SEXT;
317 case Instruction::FPToUI:
318 return Expression::FPTOUI;
319 case Instruction::FPToSI:
320 return Expression::FPTOSI;
321 case Instruction::UIToFP:
322 return Expression::UITOFP;
323 case Instruction::SIToFP:
324 return Expression::SITOFP;
325 case Instruction::FPTrunc:
326 return Expression::FPTRUNC;
327 case Instruction::FPExt:
328 return Expression::FPEXT;
329 case Instruction::PtrToInt:
330 return Expression::PTRTOINT;
331 case Instruction::IntToPtr:
332 return Expression::INTTOPTR;
333 case Instruction::BitCast:
334 return Expression::BITCAST;
336 // THIS SHOULD NEVER HAPPEN
338 assert(0 && "Cast operator with unknown opcode?");
339 return Expression::BITCAST;
343 uint32_t ValueTable::hash_operand(Value* v) {
344 if (CallInst* CI = dyn_cast<CallInst>(v))
345 if (!AA->doesNotAccessMemory(CI))
346 return nextValueNumber++;
348 return lookup_or_add(v);
351 Expression ValueTable::create_expression(CallInst* C) {
354 e.type = C->getType();
358 e.function = C->getCalledFunction();
359 e.opcode = Expression::CALL;
361 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
363 e.varargs.push_back(hash_operand(*I));
368 Expression ValueTable::create_expression(BinaryOperator* BO) {
371 e.firstVN = hash_operand(BO->getOperand(0));
372 e.secondVN = hash_operand(BO->getOperand(1));
375 e.type = BO->getType();
376 e.opcode = getOpcode(BO);
381 Expression ValueTable::create_expression(CmpInst* C) {
384 e.firstVN = hash_operand(C->getOperand(0));
385 e.secondVN = hash_operand(C->getOperand(1));
388 e.type = C->getType();
389 e.opcode = getOpcode(C);
394 Expression ValueTable::create_expression(CastInst* C) {
397 e.firstVN = hash_operand(C->getOperand(0));
401 e.type = C->getType();
402 e.opcode = getOpcode(C);
407 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
410 e.firstVN = hash_operand(S->getOperand(0));
411 e.secondVN = hash_operand(S->getOperand(1));
412 e.thirdVN = hash_operand(S->getOperand(2));
414 e.type = S->getType();
415 e.opcode = Expression::SHUFFLE;
420 Expression ValueTable::create_expression(ExtractElementInst* E) {
423 e.firstVN = hash_operand(E->getOperand(0));
424 e.secondVN = hash_operand(E->getOperand(1));
427 e.type = E->getType();
428 e.opcode = Expression::EXTRACT;
433 Expression ValueTable::create_expression(InsertElementInst* I) {
436 e.firstVN = hash_operand(I->getOperand(0));
437 e.secondVN = hash_operand(I->getOperand(1));
438 e.thirdVN = hash_operand(I->getOperand(2));
440 e.type = I->getType();
441 e.opcode = Expression::INSERT;
446 Expression ValueTable::create_expression(SelectInst* I) {
449 e.firstVN = hash_operand(I->getCondition());
450 e.secondVN = hash_operand(I->getTrueValue());
451 e.thirdVN = hash_operand(I->getFalseValue());
453 e.type = I->getType();
454 e.opcode = Expression::SELECT;
459 Expression ValueTable::create_expression(GetElementPtrInst* G) {
462 e.firstVN = hash_operand(G->getPointerOperand());
466 e.type = G->getType();
467 e.opcode = Expression::GEP;
469 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
471 e.varargs.push_back(hash_operand(*I));
476 //===----------------------------------------------------------------------===//
477 // ValueTable External Functions
478 //===----------------------------------------------------------------------===//
480 /// lookup_or_add - Returns the value number for the specified value, assigning
481 /// it a new number if it did not have one before.
482 uint32_t ValueTable::lookup_or_add(Value* V) {
483 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
484 if (VI != valueNumbering.end())
487 if (CallInst* C = dyn_cast<CallInst>(V)) {
488 if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
489 Expression e = create_expression(C);
491 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
492 if (EI != expressionNumbering.end()) {
493 valueNumbering.insert(std::make_pair(V, EI->second));
496 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
497 valueNumbering.insert(std::make_pair(V, nextValueNumber));
499 return nextValueNumber++;
502 valueNumbering.insert(std::make_pair(V, nextValueNumber));
503 return nextValueNumber++;
505 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
506 Expression e = create_expression(BO);
508 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
509 if (EI != expressionNumbering.end()) {
510 valueNumbering.insert(std::make_pair(V, EI->second));
513 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
514 valueNumbering.insert(std::make_pair(V, nextValueNumber));
516 return nextValueNumber++;
518 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
519 Expression e = create_expression(C);
521 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
522 if (EI != expressionNumbering.end()) {
523 valueNumbering.insert(std::make_pair(V, EI->second));
526 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
527 valueNumbering.insert(std::make_pair(V, nextValueNumber));
529 return nextValueNumber++;
531 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
532 Expression e = create_expression(U);
534 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
535 if (EI != expressionNumbering.end()) {
536 valueNumbering.insert(std::make_pair(V, EI->second));
539 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
540 valueNumbering.insert(std::make_pair(V, nextValueNumber));
542 return nextValueNumber++;
544 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
545 Expression e = create_expression(U);
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 (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
558 Expression e = create_expression(U);
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 (SelectInst* U = dyn_cast<SelectInst>(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 (CastInst* U = dyn_cast<CastInst>(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 (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(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++;
610 valueNumbering.insert(std::make_pair(V, nextValueNumber));
611 return nextValueNumber++;
615 /// lookup - Returns the value number of the specified value. Fails if
616 /// the value has not yet been numbered.
617 uint32_t ValueTable::lookup(Value* V) const {
618 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
619 if (VI != valueNumbering.end())
622 assert(0 && "Value not numbered?");
627 /// clear - Remove all entries from the ValueTable
628 void ValueTable::clear() {
629 valueNumbering.clear();
630 expressionNumbering.clear();
634 /// erase - Remove a value from the value numbering
635 void ValueTable::erase(Value* V) {
636 valueNumbering.erase(V);
639 //===----------------------------------------------------------------------===//
640 // ValueNumberedSet Class
641 //===----------------------------------------------------------------------===//
643 class ValueNumberedSet {
645 SmallPtrSet<Value*, 8> contents;
648 ValueNumberedSet() { numbers.resize(1); }
649 ValueNumberedSet(const ValueNumberedSet& other) {
650 numbers = other.numbers;
651 contents = other.contents;
654 typedef SmallPtrSet<Value*, 8>::iterator iterator;
656 iterator begin() { return contents.begin(); }
657 iterator end() { return contents.end(); }
659 bool insert(Value* v) { return contents.insert(v); }
660 void insert(iterator I, iterator E) { contents.insert(I, E); }
661 void erase(Value* v) { contents.erase(v); }
662 unsigned count(Value* v) { return contents.count(v); }
663 size_t size() { return contents.size(); }
665 void set(unsigned i) {
666 if (i >= numbers.size())
672 void operator=(const ValueNumberedSet& other) {
673 contents = other.contents;
674 numbers = other.numbers;
677 void reset(unsigned i) {
678 if (i < numbers.size())
682 bool test(unsigned i) {
683 if (i >= numbers.size())
686 return numbers.test(i);
696 //===----------------------------------------------------------------------===//
698 //===----------------------------------------------------------------------===//
702 class VISIBILITY_HIDDEN GVN : public FunctionPass {
703 bool runOnFunction(Function &F);
705 static char ID; // Pass identification, replacement for typeid
706 GVN() : FunctionPass((intptr_t)&ID) { }
711 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
713 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
717 // This transformation requires dominator postdominator info
718 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
719 AU.setPreservesCFG();
720 AU.addRequired<DominatorTree>();
721 AU.addRequired<MemoryDependenceAnalysis>();
722 AU.addRequired<AliasAnalysis>();
723 AU.addPreserved<AliasAnalysis>();
724 AU.addPreserved<MemoryDependenceAnalysis>();
728 // FIXME: eliminate or document these better
729 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
730 void val_insert(ValueNumberedSet& s, Value* v);
731 bool processLoad(LoadInst* L,
732 DenseMap<Value*, LoadInst*>& lastLoad,
733 SmallVector<Instruction*, 4>& toErase);
734 bool processInstruction(Instruction* I,
735 ValueNumberedSet& currAvail,
736 DenseMap<Value*, LoadInst*>& lastSeenLoad,
737 SmallVector<Instruction*, 4>& toErase);
738 bool processNonLocalLoad(LoadInst* L,
739 SmallVector<Instruction*, 4>& toErase);
740 bool processMemCpy(MemCpyInst* M, SmallVector<Instruction*, 4>& toErase);
741 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
742 DenseMap<BasicBlock*, Value*> &Phis,
743 bool top_level = false);
744 void dump(DenseMap<BasicBlock*, Value*>& d);
745 bool iterateOnFunction(Function &F);
746 Value* CollapsePhi(PHINode* p);
747 bool isSafeReplacement(PHINode* p, Instruction* inst);
754 // createGVNPass - The public interface to this file...
755 FunctionPass *llvm::createGVNPass() { return new GVN(); }
757 static RegisterPass<GVN> X("gvn",
758 "Global Value Numbering");
760 STATISTIC(NumGVNInstr, "Number of instructions deleted");
761 STATISTIC(NumGVNLoad, "Number of loads deleted");
763 /// find_leader - Given a set and a value number, return the first
764 /// element of the set with that value number, or 0 if no such element
766 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
770 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
772 if (v == VN.lookup(*I))
775 assert(0 && "No leader found, but present bit is set?");
779 /// val_insert - Insert a value into a set only if there is not a value
780 /// with the same value number already in the set
781 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
782 uint32_t num = VN.lookup(v);
787 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
789 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
790 E = d.end(); I != E; ++I) {
791 if (I->second == MemoryDependenceAnalysis::None)
799 Value* GVN::CollapsePhi(PHINode* p) {
800 DominatorTree &DT = getAnalysis<DominatorTree>();
801 Value* constVal = p->hasConstantValue();
804 if (Instruction* inst = dyn_cast<Instruction>(constVal)) {
805 if (DT.dominates(inst, p))
806 if (isSafeReplacement(p, inst))
816 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
817 if (!isa<PHINode>(inst))
820 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
822 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
823 if (use_phi->getParent() == inst->getParent())
829 /// GetValueForBlock - Get the value to use within the specified basic block.
830 /// available values are in Phis.
831 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
832 DenseMap<BasicBlock*, Value*> &Phis,
835 // If we have already computed this value, return the previously computed val.
836 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
837 if (V != Phis.end() && !top_level) return V->second;
839 BasicBlock* singlePred = BB->getSinglePredecessor();
841 Value *ret = GetValueForBlock(singlePred, orig, Phis);
845 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
846 // now, then get values to fill in the incoming values for the PHI.
847 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
849 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
851 if (Phis.count(BB) == 0)
852 Phis.insert(std::make_pair(BB, PN));
854 // Fill in the incoming values for the block.
855 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
856 Value* val = GetValueForBlock(*PI, orig, Phis);
858 PN->addIncoming(val, *PI);
861 // Attempt to collapse PHI nodes that are trivially redundant
862 Value* v = CollapsePhi(PN);
864 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
866 MD.removeInstruction(PN);
867 PN->replaceAllUsesWith(v);
869 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
870 E = Phis.end(); I != E; ++I)
874 PN->eraseFromParent();
881 // Cache our phi construction results
882 phiMap[orig->getPointerOperand()].insert(PN);
886 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
887 /// non-local by performing PHI construction.
888 bool GVN::processNonLocalLoad(LoadInst* L,
889 SmallVector<Instruction*, 4>& toErase) {
890 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
892 // Find the non-local dependencies of the load
893 DenseMap<BasicBlock*, Value*> deps;
894 MD.getNonLocalDependency(L, deps);
896 DenseMap<BasicBlock*, Value*> repl;
898 // Filter out useless results (non-locals, etc)
899 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
901 if (I->second == MemoryDependenceAnalysis::None) {
903 } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
905 } else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
906 if (S->getPointerOperand() == L->getPointerOperand())
907 repl[I->first] = S->getOperand(0);
910 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
911 if (LD->getPointerOperand() == L->getPointerOperand())
919 // Use cached PHI construction information from previous runs
920 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
921 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
923 if ((*I)->getParent() == L->getParent()) {
924 MD.removeInstruction(L);
925 L->replaceAllUsesWith(*I);
926 toErase.push_back(L);
931 repl.insert(std::make_pair((*I)->getParent(), *I));
935 // Perform PHI construction
936 SmallPtrSet<BasicBlock*, 4> visited;
937 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
939 MD.removeInstruction(L);
940 L->replaceAllUsesWith(v);
941 toErase.push_back(L);
947 /// processLoad - Attempt to eliminate a load, first by eliminating it
948 /// locally, and then attempting non-local elimination if that fails.
949 bool GVN::processLoad(LoadInst* L,
950 DenseMap<Value*, LoadInst*>& lastLoad,
951 SmallVector<Instruction*, 4>& toErase) {
952 if (L->isVolatile()) {
953 lastLoad[L->getPointerOperand()] = L;
957 Value* pointer = L->getPointerOperand();
958 LoadInst*& last = lastLoad[pointer];
960 // ... to a pointer that has been loaded from before...
961 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
962 bool removedNonLocal = false;
963 Instruction* dep = MD.getDependency(L);
964 if (dep == MemoryDependenceAnalysis::NonLocal &&
965 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
966 removedNonLocal = processNonLocalLoad(L, toErase);
968 if (!removedNonLocal)
971 return removedNonLocal;
975 bool deletedLoad = false;
977 // Walk up the dependency chain until we either find
978 // a dependency we can use, or we can't walk any further
979 while (dep != MemoryDependenceAnalysis::None &&
980 dep != MemoryDependenceAnalysis::NonLocal &&
981 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
982 // ... that depends on a store ...
983 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
984 if (S->getPointerOperand() == pointer) {
986 MD.removeInstruction(L);
988 L->replaceAllUsesWith(S->getOperand(0));
989 toErase.push_back(L);
994 // Whether we removed it or not, we can't
998 // If we don't depend on a store, and we haven't
999 // been loaded before, bail.
1001 } else if (dep == last) {
1003 MD.removeInstruction(L);
1005 L->replaceAllUsesWith(last);
1006 toErase.push_back(L);
1012 dep = MD.getDependency(L, dep);
1016 if (dep != MemoryDependenceAnalysis::None &&
1017 dep != MemoryDependenceAnalysis::NonLocal &&
1018 isa<AllocationInst>(dep)) {
1019 // Check that this load is actually from the
1020 // allocation we found
1021 Value* v = L->getOperand(0);
1023 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
1024 v = BC->getOperand(0);
1025 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
1026 v = GEP->getOperand(0);
1031 // If this load depends directly on an allocation, there isn't
1032 // anything stored there; therefore, we can optimize this load
1034 MD.removeInstruction(L);
1036 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1037 toErase.push_back(L);
1049 /// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
1050 /// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1051 /// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1052 /// This allows later passes to remove the first memcpy altogether.
1053 bool GVN::processMemCpy(MemCpyInst* M,
1054 SmallVector<Instruction*, 4>& toErase) {
1055 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1057 // First, we have to check that the dependency is another memcpy
1058 Instruction* dep = MD.getDependency(M);
1059 if (dep == MemoryDependenceAnalysis::None ||
1060 dep == MemoryDependenceAnalysis::NonLocal ||
1061 !isa<MemCpyInst>(dep))
1064 // We can only transforms memcpy's where the dest of one is the source of the
1066 MemCpyInst* MDep = cast<MemCpyInst>(dep);
1067 if (M->getSource() != MDep->getDest())
1070 // Second, the length of the memcpy's must be the same, or the preceeding one
1071 // must be larger than the following one.
1072 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1073 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1077 uint64_t CpySize = C1->getValue().getZExtValue();
1078 uint64_t DepSize = C2->getValue().getZExtValue();
1080 if (DepSize < CpySize)
1083 // Finally, we have to make sure that the dest of the second does not
1084 // alias the source of the first
1085 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1086 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1087 AliasAnalysis::NoAlias)
1089 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1090 AliasAnalysis::NoAlias)
1092 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1093 != AliasAnalysis::NoAlias)
1096 // If all checks passed, then we can transform these memcpy's
1097 bool is32bit = M->getIntrinsicID() == Intrinsic::memcpy_i32;
1098 Function* MemMoveFun = Intrinsic::getDeclaration(
1099 M->getParent()->getParent()->getParent(),
1100 is32bit ? Intrinsic::memcpy_i32 :
1101 Intrinsic::memcpy_i64);
1103 std::vector<Value*> args;
1104 args.push_back(M->getRawDest());
1105 args.push_back(MDep->getRawSource());
1106 args.push_back(M->getLength());
1107 args.push_back(M->getAlignment());
1109 CallInst* C = new CallInst(MemMoveFun, args.begin(), args.end(), "", M);
1111 if (MD.getDependency(C) == MDep) {
1112 MD.dropInstruction(M);
1113 toErase.push_back(M);
1116 MD.removeInstruction(C);
1117 toErase.push_back(C);
1122 /// processInstruction - When calculating availability, handle an instruction
1123 /// by inserting it into the appropriate sets
1124 bool GVN::processInstruction(Instruction* I,
1125 ValueNumberedSet& currAvail,
1126 DenseMap<Value*, LoadInst*>& lastSeenLoad,
1127 SmallVector<Instruction*, 4>& toErase) {
1128 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1129 return processLoad(L, lastSeenLoad, toErase);
1130 } else if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1131 return processMemCpy(M, toErase);
1134 unsigned num = VN.lookup_or_add(I);
1136 // Collapse PHI nodes
1137 if (PHINode* p = dyn_cast<PHINode>(I)) {
1138 Value* constVal = CollapsePhi(p);
1141 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1143 if (PI->second.count(p))
1144 PI->second.erase(p);
1146 p->replaceAllUsesWith(constVal);
1147 toErase.push_back(p);
1149 // Perform value-number based elimination
1150 } else if (currAvail.test(num)) {
1151 Value* repl = find_leader(currAvail, num);
1153 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1154 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1155 if (!AA.doesNotAccessMemory(CI)) {
1156 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1157 if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1158 MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1159 // There must be an intervening may-alias store, so nothing from
1160 // this point on will be able to be replaced with the preceding call
1161 currAvail.erase(repl);
1162 currAvail.insert(I);
1170 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1171 MD.removeInstruction(I);
1174 I->replaceAllUsesWith(repl);
1175 toErase.push_back(I);
1177 } else if (!I->isTerminator()) {
1179 currAvail.insert(I);
1185 // GVN::runOnFunction - This is the main transformation entry point for a
1188 bool GVN::runOnFunction(Function& F) {
1189 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1191 bool changed = false;
1192 bool shouldContinue = true;
1194 while (shouldContinue) {
1195 shouldContinue = iterateOnFunction(F);
1196 changed |= shouldContinue;
1203 // GVN::iterateOnFunction - Executes one iteration of GVN
1204 bool GVN::iterateOnFunction(Function &F) {
1205 // Clean out global sets from any previous functions
1207 availableOut.clear();
1210 bool changed_function = false;
1212 DominatorTree &DT = getAnalysis<DominatorTree>();
1214 SmallVector<Instruction*, 4> toErase;
1216 // Top-down walk of the dominator tree
1217 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1218 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1220 // Get the set to update for this block
1221 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1222 DenseMap<Value*, LoadInst*> lastSeenLoad;
1224 BasicBlock* BB = DI->getBlock();
1226 // A block inherits AVAIL_OUT from its dominator
1227 if (DI->getIDom() != 0)
1228 currAvail = availableOut[DI->getIDom()->getBlock()];
1230 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1232 changed_function |= processInstruction(BI, currAvail,
1233 lastSeenLoad, toErase);
1235 NumGVNInstr += toErase.size();
1237 // Avoid iterator invalidation
1240 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1241 E = toErase.end(); I != E; ++I) {
1242 (*I)->eraseFromParent();
1249 return changed_function;