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/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/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Target/TargetData.h"
41 STATISTIC(NumGVNInstr, "Number of instructions deleted");
42 STATISTIC(NumGVNLoad, "Number of loads deleted");
43 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
47 FormMemSet("form-memset-from-stores",
48 cl::desc("Transform straight-line stores to memsets"),
49 cl::init(false), cl::Hidden);
52 //===----------------------------------------------------------------------===//
54 //===----------------------------------------------------------------------===//
56 /// This class holds the mapping between values and value numbers. It is used
57 /// as an efficient mechanism to determine the expression-wise equivalence of
60 struct VISIBILITY_HIDDEN Expression {
61 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
62 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
63 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
64 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
65 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
66 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
67 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
68 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
69 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
70 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
73 ExpressionOpcode opcode;
78 SmallVector<uint32_t, 4> varargs;
82 Expression(ExpressionOpcode o) : opcode(o) { }
84 bool operator==(const Expression &other) const {
85 if (opcode != other.opcode)
87 else if (opcode == EMPTY || opcode == TOMBSTONE)
89 else if (type != other.type)
91 else if (function != other.function)
93 else if (firstVN != other.firstVN)
95 else if (secondVN != other.secondVN)
97 else if (thirdVN != other.thirdVN)
100 if (varargs.size() != other.varargs.size())
103 for (size_t i = 0; i < varargs.size(); ++i)
104 if (varargs[i] != other.varargs[i])
111 bool operator!=(const Expression &other) const {
112 if (opcode != other.opcode)
114 else if (opcode == EMPTY || opcode == TOMBSTONE)
116 else if (type != other.type)
118 else if (function != other.function)
120 else if (firstVN != other.firstVN)
122 else if (secondVN != other.secondVN)
124 else if (thirdVN != other.thirdVN)
127 if (varargs.size() != other.varargs.size())
130 for (size_t i = 0; i < varargs.size(); ++i)
131 if (varargs[i] != other.varargs[i])
139 class VISIBILITY_HIDDEN ValueTable {
141 DenseMap<Value*, uint32_t> valueNumbering;
142 DenseMap<Expression, uint32_t> expressionNumbering;
145 uint32_t nextValueNumber;
147 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
148 Expression::ExpressionOpcode getOpcode(CmpInst* C);
149 Expression::ExpressionOpcode getOpcode(CastInst* C);
150 Expression create_expression(BinaryOperator* BO);
151 Expression create_expression(CmpInst* C);
152 Expression create_expression(ShuffleVectorInst* V);
153 Expression create_expression(ExtractElementInst* C);
154 Expression create_expression(InsertElementInst* V);
155 Expression create_expression(SelectInst* V);
156 Expression create_expression(CastInst* C);
157 Expression create_expression(GetElementPtrInst* G);
158 Expression create_expression(CallInst* 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 uint32_t hash_operand(Value* v);
173 template <> struct DenseMapInfo<Expression> {
174 static inline Expression getEmptyKey() {
175 return Expression(Expression::EMPTY);
178 static inline Expression getTombstoneKey() {
179 return Expression(Expression::TOMBSTONE);
182 static unsigned getHashValue(const Expression e) {
183 unsigned hash = e.opcode;
185 hash = e.firstVN + hash * 37;
186 hash = e.secondVN + hash * 37;
187 hash = e.thirdVN + hash * 37;
189 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
190 (unsigned)((uintptr_t)e.type >> 9)) +
193 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
194 E = e.varargs.end(); I != E; ++I)
195 hash = *I + hash * 37;
197 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
198 (unsigned)((uintptr_t)e.function >> 9)) +
203 static bool isEqual(const Expression &LHS, const Expression &RHS) {
206 static bool isPod() { return true; }
210 //===----------------------------------------------------------------------===//
211 // ValueTable Internal Functions
212 //===----------------------------------------------------------------------===//
213 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
214 switch(BO->getOpcode()) {
215 default: // THIS SHOULD NEVER HAPPEN
216 assert(0 && "Binary operator with unknown opcode?");
217 case Instruction::Add: return Expression::ADD;
218 case Instruction::Sub: return Expression::SUB;
219 case Instruction::Mul: return Expression::MUL;
220 case Instruction::UDiv: return Expression::UDIV;
221 case Instruction::SDiv: return Expression::SDIV;
222 case Instruction::FDiv: return Expression::FDIV;
223 case Instruction::URem: return Expression::UREM;
224 case Instruction::SRem: return Expression::SREM;
225 case Instruction::FRem: return Expression::FREM;
226 case Instruction::Shl: return Expression::SHL;
227 case Instruction::LShr: return Expression::LSHR;
228 case Instruction::AShr: return Expression::ASHR;
229 case Instruction::And: return Expression::AND;
230 case Instruction::Or: return Expression::OR;
231 case Instruction::Xor: return Expression::XOR;
235 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
236 if (isa<ICmpInst>(C)) {
237 switch (C->getPredicate()) {
238 default: // THIS SHOULD NEVER HAPPEN
239 assert(0 && "Comparison with unknown predicate?");
240 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
241 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
242 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
243 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
244 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
245 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
246 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
247 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
248 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
249 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
252 assert(isa<FCmpInst>(C) && "Unknown compare");
253 switch (C->getPredicate()) {
254 default: // THIS SHOULD NEVER HAPPEN
255 assert(0 && "Comparison with unknown predicate?");
256 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
257 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
258 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
259 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
260 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
261 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
262 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
263 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
264 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
265 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
266 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
267 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
268 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
269 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
273 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
274 switch(C->getOpcode()) {
275 default: // THIS SHOULD NEVER HAPPEN
276 assert(0 && "Cast operator with unknown opcode?");
277 case Instruction::Trunc: return Expression::TRUNC;
278 case Instruction::ZExt: return Expression::ZEXT;
279 case Instruction::SExt: return Expression::SEXT;
280 case Instruction::FPToUI: return Expression::FPTOUI;
281 case Instruction::FPToSI: return Expression::FPTOSI;
282 case Instruction::UIToFP: return Expression::UITOFP;
283 case Instruction::SIToFP: return Expression::SITOFP;
284 case Instruction::FPTrunc: return Expression::FPTRUNC;
285 case Instruction::FPExt: return Expression::FPEXT;
286 case Instruction::PtrToInt: return Expression::PTRTOINT;
287 case Instruction::IntToPtr: return Expression::INTTOPTR;
288 case Instruction::BitCast: return Expression::BITCAST;
292 uint32_t ValueTable::hash_operand(Value* v) {
293 if (CallInst* CI = dyn_cast<CallInst>(v))
294 if (!AA->doesNotAccessMemory(CI))
295 return nextValueNumber++;
297 return lookup_or_add(v);
300 Expression ValueTable::create_expression(CallInst* C) {
303 e.type = C->getType();
307 e.function = C->getCalledFunction();
308 e.opcode = Expression::CALL;
310 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
312 e.varargs.push_back(hash_operand(*I));
317 Expression ValueTable::create_expression(BinaryOperator* BO) {
320 e.firstVN = hash_operand(BO->getOperand(0));
321 e.secondVN = hash_operand(BO->getOperand(1));
324 e.type = BO->getType();
325 e.opcode = getOpcode(BO);
330 Expression ValueTable::create_expression(CmpInst* C) {
333 e.firstVN = hash_operand(C->getOperand(0));
334 e.secondVN = hash_operand(C->getOperand(1));
337 e.type = C->getType();
338 e.opcode = getOpcode(C);
343 Expression ValueTable::create_expression(CastInst* C) {
346 e.firstVN = hash_operand(C->getOperand(0));
350 e.type = C->getType();
351 e.opcode = getOpcode(C);
356 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
359 e.firstVN = hash_operand(S->getOperand(0));
360 e.secondVN = hash_operand(S->getOperand(1));
361 e.thirdVN = hash_operand(S->getOperand(2));
363 e.type = S->getType();
364 e.opcode = Expression::SHUFFLE;
369 Expression ValueTable::create_expression(ExtractElementInst* E) {
372 e.firstVN = hash_operand(E->getOperand(0));
373 e.secondVN = hash_operand(E->getOperand(1));
376 e.type = E->getType();
377 e.opcode = Expression::EXTRACT;
382 Expression ValueTable::create_expression(InsertElementInst* I) {
385 e.firstVN = hash_operand(I->getOperand(0));
386 e.secondVN = hash_operand(I->getOperand(1));
387 e.thirdVN = hash_operand(I->getOperand(2));
389 e.type = I->getType();
390 e.opcode = Expression::INSERT;
395 Expression ValueTable::create_expression(SelectInst* I) {
398 e.firstVN = hash_operand(I->getCondition());
399 e.secondVN = hash_operand(I->getTrueValue());
400 e.thirdVN = hash_operand(I->getFalseValue());
402 e.type = I->getType();
403 e.opcode = Expression::SELECT;
408 Expression ValueTable::create_expression(GetElementPtrInst* G) {
411 e.firstVN = hash_operand(G->getPointerOperand());
415 e.type = G->getType();
416 e.opcode = Expression::GEP;
418 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
420 e.varargs.push_back(hash_operand(*I));
425 //===----------------------------------------------------------------------===//
426 // ValueTable External Functions
427 //===----------------------------------------------------------------------===//
429 /// lookup_or_add - Returns the value number for the specified value, assigning
430 /// it a new number if it did not have one before.
431 uint32_t ValueTable::lookup_or_add(Value* V) {
432 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
433 if (VI != valueNumbering.end())
436 if (CallInst* C = dyn_cast<CallInst>(V)) {
437 if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
438 Expression e = create_expression(C);
440 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
441 if (EI != expressionNumbering.end()) {
442 valueNumbering.insert(std::make_pair(V, EI->second));
445 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
446 valueNumbering.insert(std::make_pair(V, nextValueNumber));
448 return nextValueNumber++;
451 valueNumbering.insert(std::make_pair(V, nextValueNumber));
452 return nextValueNumber++;
454 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
455 Expression e = create_expression(BO);
457 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
458 if (EI != expressionNumbering.end()) {
459 valueNumbering.insert(std::make_pair(V, EI->second));
462 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
463 valueNumbering.insert(std::make_pair(V, nextValueNumber));
465 return nextValueNumber++;
467 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
468 Expression e = create_expression(C);
470 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
471 if (EI != expressionNumbering.end()) {
472 valueNumbering.insert(std::make_pair(V, EI->second));
475 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
476 valueNumbering.insert(std::make_pair(V, nextValueNumber));
478 return nextValueNumber++;
480 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
481 Expression e = create_expression(U);
483 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
484 if (EI != expressionNumbering.end()) {
485 valueNumbering.insert(std::make_pair(V, EI->second));
488 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
489 valueNumbering.insert(std::make_pair(V, nextValueNumber));
491 return nextValueNumber++;
493 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
494 Expression e = create_expression(U);
496 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
497 if (EI != expressionNumbering.end()) {
498 valueNumbering.insert(std::make_pair(V, EI->second));
501 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
502 valueNumbering.insert(std::make_pair(V, nextValueNumber));
504 return nextValueNumber++;
506 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
507 Expression e = create_expression(U);
509 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
510 if (EI != expressionNumbering.end()) {
511 valueNumbering.insert(std::make_pair(V, EI->second));
514 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
515 valueNumbering.insert(std::make_pair(V, nextValueNumber));
517 return nextValueNumber++;
519 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
520 Expression e = create_expression(U);
522 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
523 if (EI != expressionNumbering.end()) {
524 valueNumbering.insert(std::make_pair(V, EI->second));
527 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
528 valueNumbering.insert(std::make_pair(V, nextValueNumber));
530 return nextValueNumber++;
532 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
533 Expression e = create_expression(U);
535 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
536 if (EI != expressionNumbering.end()) {
537 valueNumbering.insert(std::make_pair(V, EI->second));
540 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
541 valueNumbering.insert(std::make_pair(V, nextValueNumber));
543 return nextValueNumber++;
545 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
546 Expression e = create_expression(U);
548 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
549 if (EI != expressionNumbering.end()) {
550 valueNumbering.insert(std::make_pair(V, EI->second));
553 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
554 valueNumbering.insert(std::make_pair(V, nextValueNumber));
556 return nextValueNumber++;
559 valueNumbering.insert(std::make_pair(V, nextValueNumber));
560 return nextValueNumber++;
564 /// lookup - Returns the value number of the specified value. Fails if
565 /// the value has not yet been numbered.
566 uint32_t ValueTable::lookup(Value* V) const {
567 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
568 assert(VI != valueNumbering.end() && "Value not numbered?");
572 /// clear - Remove all entries from the ValueTable
573 void ValueTable::clear() {
574 valueNumbering.clear();
575 expressionNumbering.clear();
579 /// erase - Remove a value from the value numbering
580 void ValueTable::erase(Value* V) {
581 valueNumbering.erase(V);
584 //===----------------------------------------------------------------------===//
585 // ValueNumberedSet Class
586 //===----------------------------------------------------------------------===//
588 class VISIBILITY_HIDDEN ValueNumberedSet {
590 SmallPtrSet<Value*, 8> contents;
593 ValueNumberedSet() { numbers.resize(1); }
594 ValueNumberedSet(const ValueNumberedSet& other) {
595 numbers = other.numbers;
596 contents = other.contents;
599 typedef SmallPtrSet<Value*, 8>::iterator iterator;
601 iterator begin() { return contents.begin(); }
602 iterator end() { return contents.end(); }
604 bool insert(Value* v) { return contents.insert(v); }
605 void insert(iterator I, iterator E) { contents.insert(I, E); }
606 void erase(Value* v) { contents.erase(v); }
607 unsigned count(Value* v) { return contents.count(v); }
608 size_t size() { return contents.size(); }
610 void set(unsigned i) {
611 if (i >= numbers.size())
617 void operator=(const ValueNumberedSet& other) {
618 contents = other.contents;
619 numbers = other.numbers;
622 void reset(unsigned i) {
623 if (i < numbers.size())
627 bool test(unsigned i) {
628 if (i >= numbers.size())
631 return numbers.test(i);
641 //===----------------------------------------------------------------------===//
643 //===----------------------------------------------------------------------===//
647 class VISIBILITY_HIDDEN GVN : public FunctionPass {
648 bool runOnFunction(Function &F);
650 static char ID; // Pass identification, replacement for typeid
651 GVN() : FunctionPass((intptr_t)&ID) { }
656 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
658 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
662 // This transformation requires dominator postdominator info
663 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
664 AU.setPreservesCFG();
665 AU.addRequired<DominatorTree>();
666 AU.addRequired<MemoryDependenceAnalysis>();
667 AU.addRequired<AliasAnalysis>();
668 AU.addRequired<TargetData>();
669 AU.addPreserved<AliasAnalysis>();
670 AU.addPreserved<MemoryDependenceAnalysis>();
671 AU.addPreserved<TargetData>();
675 // FIXME: eliminate or document these better
676 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
677 void val_insert(ValueNumberedSet& s, Value* v);
678 bool processLoad(LoadInst* L,
679 DenseMap<Value*, LoadInst*> &lastLoad,
680 SmallVectorImpl<Instruction*> &toErase);
681 bool processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase);
682 bool processInstruction(Instruction* I,
683 ValueNumberedSet& currAvail,
684 DenseMap<Value*, LoadInst*>& lastSeenLoad,
685 SmallVectorImpl<Instruction*> &toErase);
686 bool processNonLocalLoad(LoadInst* L,
687 SmallVectorImpl<Instruction*> &toErase);
688 bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
689 SmallVectorImpl<Instruction*> &toErase);
690 bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
691 SmallVectorImpl<Instruction*> &toErase);
692 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
693 DenseMap<BasicBlock*, Value*> &Phis,
694 bool top_level = false);
695 void dump(DenseMap<BasicBlock*, Value*>& d);
696 bool iterateOnFunction(Function &F);
697 Value* CollapsePhi(PHINode* p);
698 bool isSafeReplacement(PHINode* p, Instruction* inst);
704 // createGVNPass - The public interface to this file...
705 FunctionPass *llvm::createGVNPass() { return new GVN(); }
707 static RegisterPass<GVN> X("gvn",
708 "Global Value Numbering");
710 /// find_leader - Given a set and a value number, return the first
711 /// element of the set with that value number, or 0 if no such element
713 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
717 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
719 if (v == VN.lookup(*I))
722 assert(0 && "No leader found, but present bit is set?");
726 /// val_insert - Insert a value into a set only if there is not a value
727 /// with the same value number already in the set
728 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
729 uint32_t num = VN.lookup(v);
734 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
736 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
737 E = d.end(); I != E; ++I) {
738 if (I->second == MemoryDependenceAnalysis::None)
746 Value* GVN::CollapsePhi(PHINode* p) {
747 DominatorTree &DT = getAnalysis<DominatorTree>();
748 Value* constVal = p->hasConstantValue();
750 if (!constVal) return 0;
752 Instruction* inst = dyn_cast<Instruction>(constVal);
756 if (DT.dominates(inst, p))
757 if (isSafeReplacement(p, inst))
762 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
763 if (!isa<PHINode>(inst))
766 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
768 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
769 if (use_phi->getParent() == inst->getParent())
775 /// GetValueForBlock - Get the value to use within the specified basic block.
776 /// available values are in Phis.
777 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
778 DenseMap<BasicBlock*, Value*> &Phis,
781 // If we have already computed this value, return the previously computed val.
782 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
783 if (V != Phis.end() && !top_level) return V->second;
785 BasicBlock* singlePred = BB->getSinglePredecessor();
787 Value *ret = GetValueForBlock(singlePred, orig, Phis);
792 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
793 // now, then get values to fill in the incoming values for the PHI.
794 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
796 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
798 if (Phis.count(BB) == 0)
799 Phis.insert(std::make_pair(BB, PN));
801 // Fill in the incoming values for the block.
802 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
803 Value* val = GetValueForBlock(*PI, orig, Phis);
804 PN->addIncoming(val, *PI);
807 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
808 AA.copyValue(orig, PN);
810 // Attempt to collapse PHI nodes that are trivially redundant
811 Value* v = CollapsePhi(PN);
813 // Cache our phi construction results
814 phiMap[orig->getPointerOperand()].insert(PN);
818 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
820 MD.removeInstruction(PN);
821 PN->replaceAllUsesWith(v);
823 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
824 E = Phis.end(); I != E; ++I)
828 PN->eraseFromParent();
834 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
835 /// non-local by performing PHI construction.
836 bool GVN::processNonLocalLoad(LoadInst* L,
837 SmallVectorImpl<Instruction*> &toErase) {
838 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
840 // Find the non-local dependencies of the load
841 DenseMap<BasicBlock*, Value*> deps;
842 MD.getNonLocalDependency(L, deps);
844 DenseMap<BasicBlock*, Value*> repl;
846 // Filter out useless results (non-locals, etc)
847 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
849 if (I->second == MemoryDependenceAnalysis::None)
852 if (I->second == MemoryDependenceAnalysis::NonLocal)
855 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
856 if (S->getPointerOperand() != L->getPointerOperand())
858 repl[I->first] = S->getOperand(0);
859 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
860 if (LD->getPointerOperand() != L->getPointerOperand())
868 // Use cached PHI construction information from previous runs
869 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
870 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
872 if ((*I)->getParent() == L->getParent()) {
873 MD.removeInstruction(L);
874 L->replaceAllUsesWith(*I);
875 toErase.push_back(L);
880 repl.insert(std::make_pair((*I)->getParent(), *I));
883 // Perform PHI construction
884 SmallPtrSet<BasicBlock*, 4> visited;
885 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
887 MD.removeInstruction(L);
888 L->replaceAllUsesWith(v);
889 toErase.push_back(L);
895 /// processLoad - Attempt to eliminate a load, first by eliminating it
896 /// locally, and then attempting non-local elimination if that fails.
897 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
898 SmallVectorImpl<Instruction*> &toErase) {
899 if (L->isVolatile()) {
900 lastLoad[L->getPointerOperand()] = L;
904 Value* pointer = L->getPointerOperand();
905 LoadInst*& last = lastLoad[pointer];
907 // ... to a pointer that has been loaded from before...
908 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
909 bool removedNonLocal = false;
910 Instruction* dep = MD.getDependency(L);
911 if (dep == MemoryDependenceAnalysis::NonLocal &&
912 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
913 removedNonLocal = processNonLocalLoad(L, toErase);
915 if (!removedNonLocal)
918 return removedNonLocal;
922 bool deletedLoad = false;
924 // Walk up the dependency chain until we either find
925 // a dependency we can use, or we can't walk any further
926 while (dep != MemoryDependenceAnalysis::None &&
927 dep != MemoryDependenceAnalysis::NonLocal &&
928 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
929 // ... that depends on a store ...
930 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
931 if (S->getPointerOperand() == pointer) {
933 MD.removeInstruction(L);
935 L->replaceAllUsesWith(S->getOperand(0));
936 toErase.push_back(L);
941 // Whether we removed it or not, we can't
945 // If we don't depend on a store, and we haven't
946 // been loaded before, bail.
948 } else if (dep == last) {
950 MD.removeInstruction(L);
952 L->replaceAllUsesWith(last);
953 toErase.push_back(L);
959 dep = MD.getDependency(L, dep);
963 if (dep != MemoryDependenceAnalysis::None &&
964 dep != MemoryDependenceAnalysis::NonLocal &&
965 isa<AllocationInst>(dep)) {
966 // Check that this load is actually from the
967 // allocation we found
968 Value* v = L->getOperand(0);
970 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
971 v = BC->getOperand(0);
972 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
973 v = GEP->getOperand(0);
978 // If this load depends directly on an allocation, there isn't
979 // anything stored there; therefore, we can optimize this load
981 MD.removeInstruction(L);
983 L->replaceAllUsesWith(UndefValue::get(L->getType()));
984 toErase.push_back(L);
996 /// isBytewiseValue - If the specified value can be set by repeating the same
997 /// byte in memory, return the i8 value that it is represented with. This is
998 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
999 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1000 /// byte store (e.g. i16 0x1234), return null.
1001 static Value *isBytewiseValue(Value *V) {
1002 // All byte-wide stores are splatable, even of arbitrary variables.
1003 if (V->getType() == Type::Int8Ty) return V;
1005 // Constant float and double values can be handled as integer values if the
1006 // corresponding integer value is "byteable". An important case is 0.0.
1007 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1008 if (CFP->getType() == Type::FloatTy)
1009 V = ConstantExpr::getBitCast(CFP, Type::Int32Ty);
1010 if (CFP->getType() == Type::DoubleTy)
1011 V = ConstantExpr::getBitCast(CFP, Type::Int64Ty);
1012 // Don't handle long double formats, which have strange constraints.
1015 // We can handle constant integers that are power of two in size and a
1016 // multiple of 8 bits.
1017 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1018 unsigned Width = CI->getBitWidth();
1019 if (isPowerOf2_32(Width) && Width > 8) {
1020 // We can handle this value if the recursive binary decomposition is the
1021 // same at all levels.
1022 APInt Val = CI->getValue();
1024 while (Val.getBitWidth() != 8) {
1025 unsigned NextWidth = Val.getBitWidth()/2;
1026 Val2 = Val.lshr(NextWidth);
1027 Val2.trunc(Val.getBitWidth()/2);
1028 Val.trunc(Val.getBitWidth()/2);
1030 // If the top/bottom halves aren't the same, reject it.
1034 return ConstantInt::get(Val);
1038 // Conceptually, we could handle things like:
1039 // %a = zext i8 %X to i16
1040 // %b = shl i16 %a, 8
1041 // %c = or i16 %a, %b
1042 // but until there is an example that actually needs this, it doesn't seem
1043 // worth worrying about.
1047 static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
1048 bool &VariableIdxFound, TargetData &TD) {
1049 // Skip over the first indices.
1050 gep_type_iterator GTI = gep_type_begin(GEP);
1051 for (unsigned i = 1; i != Idx; ++i, ++GTI)
1054 // Compute the offset implied by the rest of the indices.
1056 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
1057 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
1059 return VariableIdxFound = true;
1060 if (OpC->isZero()) continue; // No offset.
1062 // Handle struct indices, which add their field offset to the pointer.
1063 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1064 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1068 // Otherwise, we have a sequential type like an array or vector. Multiply
1069 // the index by the ElementSize.
1070 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
1071 Offset += Size*OpC->getSExtValue();
1077 /// IsPointerAtOffset - Return true if Ptr1 is exactly provably equal to Ptr2
1078 /// plus the specified constant offset. For example, Ptr1 might be &A[42], and
1079 /// Ptr2 might be &A[40] and Offset might be 8.
1080 static bool IsPointerAtOffset(Value *Ptr1, Value *Ptr2, uint64_t Offset,
1082 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
1083 // base. After that base, they may have some number of common (and
1084 // potentially variable) indices. After that they handle some constant
1085 // offset, which determines their offset from each other. At this point, we
1086 // handle no other case.
1087 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
1088 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
1089 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
1092 // Skip any common indices and track the GEP types.
1094 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
1095 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
1098 bool VariableIdxFound = false;
1099 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
1100 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
1101 if (VariableIdxFound) return false;
1103 return Offset1 == Offset2+(int64_t)Offset;
1107 /// processStore - When GVN is scanning forward over instructions, we look for
1108 /// some other patterns to fold away. In particular, this looks for stores to
1109 /// neighboring locations of memory. If it sees enough consequtive ones
1110 /// (currently 4) it attempts to merge them together into a memcpy/memset.
1111 bool GVN::processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase) {
1112 if (!FormMemSet) return false;
1113 if (SI->isVolatile()) return false;
1115 // There are two cases that are interesting for this code to handle: memcpy
1116 // and memset. Right now we only handle memset.
1118 // Ensure that the value being stored is something that can be memset'able a
1119 // byte at a time like "0" or "-1" or any width, as well as things like
1120 // 0xA0A0A0A0 and 0.0.
1121 Value *ByteVal = isBytewiseValue(SI->getOperand(0));
1125 TargetData &TD = getAnalysis<TargetData>();
1126 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
1128 // Okay, so we now have a single store that can be splatable. Try to 'grow'
1129 // this store by looking for neighboring stores to the immediate left or right
1130 // of the store we have so far. While we could in theory handle stores in
1131 // this order: A[0], A[2], A[1]
1132 // in practice, right now we only worry about cases where stores are
1133 // consequtive in increasing or decreasing address order.
1134 uint64_t BytesSoFar = TD.getTypeStoreSize(SI->getOperand(0)->getType());
1135 uint64_t BytesFromSI = 0;
1136 unsigned StartAlign = SI->getAlignment();
1137 Value *StartPtr = SI->getPointerOperand();
1138 SmallVector<StoreInst*, 16> Stores;
1139 Stores.push_back(SI);
1141 BasicBlock::iterator BI = SI;
1142 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
1143 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
1144 // If the call is readnone, ignore it, otherwise bail out. We don't even
1145 // allow readonly here because we don't want something like:
1146 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
1147 if (AA.getModRefBehavior(CallSite::get(BI)) ==
1148 AliasAnalysis::DoesNotAccessMemory)
1151 // TODO: If this is a memset, try to join it in.
1154 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
1157 // If this is a non-store instruction it is fine, ignore it.
1158 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
1159 if (NextStore == 0) continue;
1161 // If this is a store, see if we can merge it in.
1162 if (NextStore->isVolatile()) break;
1164 // Check to see if this stored value is of the same byte-splattable value.
1165 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
1168 Value *ThisPointer = NextStore->getPointerOperand();
1169 unsigned AccessSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
1171 // If so, check to see if the store is before the current range or after it
1172 // in either case, extend the range, otherwise reject it.
1173 if (IsPointerAtOffset(ThisPointer, StartPtr, BytesSoFar, TD)) {
1174 // Okay, this extends the stored area on the end, just add to the bytes
1175 // so far and remember this store.
1176 BytesSoFar += AccessSize;
1177 Stores.push_back(NextStore);
1181 if (IsPointerAtOffset(StartPtr, ThisPointer, AccessSize, TD)) {
1182 // Okay, the store is before the current range. Reset our start pointer
1183 // and get new alignment info etc.
1184 BytesSoFar += AccessSize;
1185 BytesFromSI += AccessSize;
1186 Stores.push_back(NextStore);
1187 StartPtr = ThisPointer;
1188 StartAlign = NextStore->getAlignment();
1192 // Otherwise, this store wasn't contiguous with our current range, bail out.
1196 // If we found less than 4 stores to merge, bail out, it isn't worth losing
1197 // type information in llvm IR to do the transformation.
1198 if (Stores.size() < 4)
1201 // Otherwise, we do want to transform this! Create a new memset. We put the
1202 // memset right after the first store that we found in this block. This
1203 // ensures that the caller will increment the iterator to the memset before
1204 // it deletes all the stores.
1205 BasicBlock::iterator InsertPt = SI; ++InsertPt;
1207 Function *F = Intrinsic::getDeclaration(SI->getParent()->getParent()
1208 ->getParent(), Intrinsic::memset_i64);
1210 // StartPtr may not dominate the starting point. Instead of using it, base
1211 // the destination pointer off the input to the first store in the block.
1212 StartPtr = SI->getPointerOperand();
1214 // Cast the start ptr to be i8* as memset requires.
1215 const Type *i8Ptr = PointerType::getUnqual(Type::Int8Ty);
1216 if (StartPtr->getType() != i8Ptr)
1217 StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getNameStart(),
1220 // Offset the pointer if needed.
1222 StartPtr = new GetElementPtrInst(StartPtr, ConstantInt::get(Type::Int64Ty,
1224 "ptroffset", InsertPt);
1227 StartPtr, ByteVal, // Start, value
1228 ConstantInt::get(Type::Int64Ty, BytesSoFar), // size
1229 ConstantInt::get(Type::Int32Ty, StartAlign) // align
1231 new CallInst(F, Ops, Ops+4, "", InsertPt);
1233 // Zap all the stores.
1234 toErase.append(Stores.begin(), Stores.end());
1241 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
1242 /// and checks for the possibility of a call slot optimization by having
1243 /// the call write its result directly into the destination of the memcpy.
1244 bool GVN::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C,
1245 SmallVectorImpl<Instruction*> &toErase) {
1246 // The general transformation to keep in mind is
1248 // call @func(..., src, ...)
1249 // memcpy(dest, src, ...)
1253 // memcpy(dest, src, ...)
1254 // call @func(..., dest, ...)
1256 // Since moving the memcpy is technically awkward, we additionally check that
1257 // src only holds uninitialized values at the moment of the call, meaning that
1258 // the memcpy can be discarded rather than moved.
1260 // Deliberately get the source and destination with bitcasts stripped away,
1261 // because we'll need to do type comparisons based on the underlying type.
1262 Value* cpyDest = cpy->getDest();
1263 Value* cpySrc = cpy->getSource();
1264 CallSite CS = CallSite::get(C);
1266 // We need to be able to reason about the size of the memcpy, so we require
1267 // that it be a constant.
1268 ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1272 // Require that src be an alloca. This simplifies the reasoning considerably.
1273 AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1277 // Check that all of src is copied to dest.
1278 TargetData& TD = getAnalysis<TargetData>();
1280 ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1284 uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1285 srcArraySize->getZExtValue();
1287 if (cpyLength->getZExtValue() < srcSize)
1290 // Check that accessing the first srcSize bytes of dest will not cause a
1291 // trap. Otherwise the transform is invalid since it might cause a trap
1292 // to occur earlier than it otherwise would.
1293 if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1294 // The destination is an alloca. Check it is larger than srcSize.
1295 ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1299 uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1300 destArraySize->getZExtValue();
1302 if (destSize < srcSize)
1304 } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1305 // If the destination is an sret parameter then only accesses that are
1306 // outside of the returned struct type can trap.
1307 if (!A->hasStructRetAttr())
1310 const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1311 uint64_t destSize = TD.getABITypeSize(StructTy);
1313 if (destSize < srcSize)
1319 // Check that src is not accessed except via the call and the memcpy. This
1320 // guarantees that it holds only undefined values when passed in (so the final
1321 // memcpy can be dropped), that it is not read or written between the call and
1322 // the memcpy, and that writing beyond the end of it is undefined.
1323 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1324 srcAlloca->use_end());
1325 while (!srcUseList.empty()) {
1326 User* UI = srcUseList.back();
1327 srcUseList.pop_back();
1329 if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1330 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1332 srcUseList.push_back(*I);
1333 } else if (UI != C && UI != cpy) {
1338 // Since we're changing the parameter to the callsite, we need to make sure
1339 // that what would be the new parameter dominates the callsite.
1340 DominatorTree& DT = getAnalysis<DominatorTree>();
1341 if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1342 if (!DT.dominates(cpyDestInst, C))
1345 // In addition to knowing that the call does not access src in some
1346 // unexpected manner, for example via a global, which we deduce from
1347 // the use analysis, we also need to know that it does not sneakily
1348 // access dest. We rely on AA to figure this out for us.
1349 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1350 if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
1351 AliasAnalysis::NoModRef)
1354 // All the checks have passed, so do the transformation.
1355 for (unsigned i = 0; i < CS.arg_size(); ++i)
1356 if (CS.getArgument(i) == cpySrc) {
1357 if (cpySrc->getType() != cpyDest->getType())
1358 cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1359 cpyDest->getName(), C);
1360 CS.setArgument(i, cpyDest);
1363 // Drop any cached information about the call, because we may have changed
1364 // its dependence information by changing its parameter.
1365 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1366 MD.dropInstruction(C);
1368 // Remove the memcpy
1369 MD.removeInstruction(cpy);
1370 toErase.push_back(cpy);
1375 /// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
1376 /// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1377 /// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1378 /// This allows later passes to remove the first memcpy altogether.
1379 bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
1380 SmallVectorImpl<Instruction*> &toErase) {
1381 // We can only transforms memcpy's where the dest of one is the source of the
1383 if (M->getSource() != MDep->getDest())
1386 // Second, the length of the memcpy's must be the same, or the preceeding one
1387 // must be larger than the following one.
1388 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1389 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1393 uint64_t DepSize = C1->getValue().getZExtValue();
1394 uint64_t CpySize = C2->getValue().getZExtValue();
1396 if (DepSize < CpySize)
1399 // Finally, we have to make sure that the dest of the second does not
1400 // alias the source of the first
1401 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1402 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1403 AliasAnalysis::NoAlias)
1405 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1406 AliasAnalysis::NoAlias)
1408 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1409 != AliasAnalysis::NoAlias)
1412 // If all checks passed, then we can transform these memcpy's
1413 Function* MemCpyFun = Intrinsic::getDeclaration(
1414 M->getParent()->getParent()->getParent(),
1415 M->getIntrinsicID());
1417 std::vector<Value*> args;
1418 args.push_back(M->getRawDest());
1419 args.push_back(MDep->getRawSource());
1420 args.push_back(M->getLength());
1421 args.push_back(M->getAlignment());
1423 CallInst* C = new CallInst(MemCpyFun, args.begin(), args.end(), "", M);
1425 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1426 if (MD.getDependency(C) == MDep) {
1427 MD.dropInstruction(M);
1428 toErase.push_back(M);
1432 MD.removeInstruction(C);
1433 toErase.push_back(C);
1437 /// processInstruction - When calculating availability, handle an instruction
1438 /// by inserting it into the appropriate sets
1439 bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1440 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1441 SmallVectorImpl<Instruction*> &toErase) {
1442 if (LoadInst* L = dyn_cast<LoadInst>(I))
1443 return processLoad(L, lastSeenLoad, toErase);
1445 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1446 return processStore(SI, toErase);
1448 if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1449 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1451 // The are two possible optimizations we can do for memcpy:
1452 // a) memcpy-memcpy xform which exposes redundance for DSE
1453 // b) call-memcpy xform for return slot optimization
1454 Instruction* dep = MD.getDependency(M);
1455 if (dep == MemoryDependenceAnalysis::None ||
1456 dep == MemoryDependenceAnalysis::NonLocal)
1458 if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1459 return processMemCpy(M, MemCpy, toErase);
1460 if (CallInst* C = dyn_cast<CallInst>(dep))
1461 return performCallSlotOptzn(M, C, toErase);
1465 unsigned num = VN.lookup_or_add(I);
1467 // Collapse PHI nodes
1468 if (PHINode* p = dyn_cast<PHINode>(I)) {
1469 Value* constVal = CollapsePhi(p);
1472 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1474 if (PI->second.count(p))
1475 PI->second.erase(p);
1477 p->replaceAllUsesWith(constVal);
1478 toErase.push_back(p);
1480 // Perform value-number based elimination
1481 } else if (currAvail.test(num)) {
1482 Value* repl = find_leader(currAvail, num);
1484 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1485 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1486 if (!AA.doesNotAccessMemory(CI)) {
1487 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1488 if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1489 MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1490 // There must be an intervening may-alias store, so nothing from
1491 // this point on will be able to be replaced with the preceding call
1492 currAvail.erase(repl);
1493 currAvail.insert(I);
1501 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1502 MD.removeInstruction(I);
1505 I->replaceAllUsesWith(repl);
1506 toErase.push_back(I);
1508 } else if (!I->isTerminator()) {
1510 currAvail.insert(I);
1516 // GVN::runOnFunction - This is the main transformation entry point for a
1519 bool GVN::runOnFunction(Function& F) {
1520 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1522 bool changed = false;
1523 bool shouldContinue = true;
1525 while (shouldContinue) {
1526 shouldContinue = iterateOnFunction(F);
1527 changed |= shouldContinue;
1534 // GVN::iterateOnFunction - Executes one iteration of GVN
1535 bool GVN::iterateOnFunction(Function &F) {
1536 // Clean out global sets from any previous functions
1538 availableOut.clear();
1541 bool changed_function = false;
1543 DominatorTree &DT = getAnalysis<DominatorTree>();
1545 SmallVector<Instruction*, 4> toErase;
1546 DenseMap<Value*, LoadInst*> lastSeenLoad;
1548 // Top-down walk of the dominator tree
1549 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1550 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1552 // Get the set to update for this block
1553 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1554 lastSeenLoad.clear();
1556 BasicBlock* BB = DI->getBlock();
1558 // A block inherits AVAIL_OUT from its dominator
1559 if (DI->getIDom() != 0)
1560 currAvail = availableOut[DI->getIDom()->getBlock()];
1562 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1564 changed_function |= processInstruction(BI, currAvail,
1565 lastSeenLoad, toErase);
1567 NumGVNInstr += toErase.size();
1569 // Avoid iterator invalidation
1572 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1573 E = toErase.end(); I != E; ++I)
1574 (*I)->eraseFromParent();
1580 return changed_function;