1 //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs global value numbering to eliminate fully redundant
11 // instructions. It also performs simple dead load elimination.
13 // Note that this pass does the value numbering itself; it does not use the
14 // ValueNumbering analysis passes.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "gvn"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Value.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DepthFirstIterator.h"
30 #include "llvm/ADT/PostOrderIterator.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Analysis/Dominators.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/MallocHelper.h"
37 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
38 #include "llvm/Support/CFG.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/GetElementPtrTypeIterator.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
50 STATISTIC(NumGVNInstr, "Number of instructions deleted");
51 STATISTIC(NumGVNLoad, "Number of loads deleted");
52 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
53 STATISTIC(NumGVNBlocks, "Number of blocks merged");
54 STATISTIC(NumPRELoad, "Number of loads PRE'd");
56 static cl::opt<bool> EnablePRE("enable-pre",
57 cl::init(true), cl::Hidden);
58 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
60 //===----------------------------------------------------------------------===//
62 //===----------------------------------------------------------------------===//
64 /// This class holds the mapping between values and value numbers. It is used
65 /// as an efficient mechanism to determine the expression-wise equivalence of
69 enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
70 UDIV, SDIV, FDIV, UREM, SREM,
71 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
72 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
73 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
74 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
75 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
76 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
77 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
78 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
79 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
82 ExpressionOpcode opcode;
87 SmallVector<uint32_t, 4> varargs;
91 Expression(ExpressionOpcode o) : opcode(o) { }
93 bool operator==(const Expression &other) const {
94 if (opcode != other.opcode)
96 else if (opcode == EMPTY || opcode == TOMBSTONE)
98 else if (type != other.type)
100 else if (function != other.function)
102 else if (firstVN != other.firstVN)
104 else if (secondVN != other.secondVN)
106 else if (thirdVN != other.thirdVN)
109 if (varargs.size() != other.varargs.size())
112 for (size_t i = 0; i < varargs.size(); ++i)
113 if (varargs[i] != other.varargs[i])
120 bool operator!=(const Expression &other) const {
121 return !(*this == other);
127 DenseMap<Value*, uint32_t> valueNumbering;
128 DenseMap<Expression, uint32_t> expressionNumbering;
130 MemoryDependenceAnalysis* MD;
133 uint32_t nextValueNumber;
135 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
136 Expression::ExpressionOpcode getOpcode(CmpInst* C);
137 Expression::ExpressionOpcode getOpcode(CastInst* C);
138 Expression create_expression(BinaryOperator* BO);
139 Expression create_expression(CmpInst* C);
140 Expression create_expression(ShuffleVectorInst* V);
141 Expression create_expression(ExtractElementInst* C);
142 Expression create_expression(InsertElementInst* V);
143 Expression create_expression(SelectInst* V);
144 Expression create_expression(CastInst* C);
145 Expression create_expression(GetElementPtrInst* G);
146 Expression create_expression(CallInst* C);
147 Expression create_expression(Constant* C);
149 ValueTable() : nextValueNumber(1) { }
150 uint32_t lookup_or_add(Value *V);
151 uint32_t lookup(Value *V) const;
152 void add(Value *V, uint32_t num);
154 void erase(Value *v);
156 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
157 AliasAnalysis *getAliasAnalysis() const { return AA; }
158 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
159 void setDomTree(DominatorTree* D) { DT = D; }
160 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
161 void verifyRemoved(const Value *) const;
166 template <> struct DenseMapInfo<Expression> {
167 static inline Expression getEmptyKey() {
168 return Expression(Expression::EMPTY);
171 static inline Expression getTombstoneKey() {
172 return Expression(Expression::TOMBSTONE);
175 static unsigned getHashValue(const Expression e) {
176 unsigned hash = e.opcode;
178 hash = e.firstVN + hash * 37;
179 hash = e.secondVN + hash * 37;
180 hash = e.thirdVN + hash * 37;
182 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
183 (unsigned)((uintptr_t)e.type >> 9)) +
186 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
187 E = e.varargs.end(); I != E; ++I)
188 hash = *I + hash * 37;
190 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
191 (unsigned)((uintptr_t)e.function >> 9)) +
196 static bool isEqual(const Expression &LHS, const Expression &RHS) {
199 static bool isPod() { return true; }
203 //===----------------------------------------------------------------------===//
204 // ValueTable Internal Functions
205 //===----------------------------------------------------------------------===//
206 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
207 switch(BO->getOpcode()) {
208 default: // THIS SHOULD NEVER HAPPEN
209 llvm_unreachable("Binary operator with unknown opcode?");
210 case Instruction::Add: return Expression::ADD;
211 case Instruction::FAdd: return Expression::FADD;
212 case Instruction::Sub: return Expression::SUB;
213 case Instruction::FSub: return Expression::FSUB;
214 case Instruction::Mul: return Expression::MUL;
215 case Instruction::FMul: return Expression::FMUL;
216 case Instruction::UDiv: return Expression::UDIV;
217 case Instruction::SDiv: return Expression::SDIV;
218 case Instruction::FDiv: return Expression::FDIV;
219 case Instruction::URem: return Expression::UREM;
220 case Instruction::SRem: return Expression::SREM;
221 case Instruction::FRem: return Expression::FREM;
222 case Instruction::Shl: return Expression::SHL;
223 case Instruction::LShr: return Expression::LSHR;
224 case Instruction::AShr: return Expression::ASHR;
225 case Instruction::And: return Expression::AND;
226 case Instruction::Or: return Expression::OR;
227 case Instruction::Xor: return Expression::XOR;
231 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
232 if (isa<ICmpInst>(C)) {
233 switch (C->getPredicate()) {
234 default: // THIS SHOULD NEVER HAPPEN
235 llvm_unreachable("Comparison with unknown predicate?");
236 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
237 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
238 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
239 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
240 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
241 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
242 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
243 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
244 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
245 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
248 switch (C->getPredicate()) {
249 default: // THIS SHOULD NEVER HAPPEN
250 llvm_unreachable("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;
269 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
270 switch(C->getOpcode()) {
271 default: // THIS SHOULD NEVER HAPPEN
272 llvm_unreachable("Cast operator with unknown opcode?");
273 case Instruction::Trunc: return Expression::TRUNC;
274 case Instruction::ZExt: return Expression::ZEXT;
275 case Instruction::SExt: return Expression::SEXT;
276 case Instruction::FPToUI: return Expression::FPTOUI;
277 case Instruction::FPToSI: return Expression::FPTOSI;
278 case Instruction::UIToFP: return Expression::UITOFP;
279 case Instruction::SIToFP: return Expression::SITOFP;
280 case Instruction::FPTrunc: return Expression::FPTRUNC;
281 case Instruction::FPExt: return Expression::FPEXT;
282 case Instruction::PtrToInt: return Expression::PTRTOINT;
283 case Instruction::IntToPtr: return Expression::INTTOPTR;
284 case Instruction::BitCast: return Expression::BITCAST;
288 Expression ValueTable::create_expression(CallInst* C) {
291 e.type = C->getType();
295 e.function = C->getCalledFunction();
296 e.opcode = Expression::CALL;
298 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
300 e.varargs.push_back(lookup_or_add(*I));
305 Expression ValueTable::create_expression(BinaryOperator* BO) {
308 e.firstVN = lookup_or_add(BO->getOperand(0));
309 e.secondVN = lookup_or_add(BO->getOperand(1));
312 e.type = BO->getType();
313 e.opcode = getOpcode(BO);
318 Expression ValueTable::create_expression(CmpInst* C) {
321 e.firstVN = lookup_or_add(C->getOperand(0));
322 e.secondVN = lookup_or_add(C->getOperand(1));
325 e.type = C->getType();
326 e.opcode = getOpcode(C);
331 Expression ValueTable::create_expression(CastInst* C) {
334 e.firstVN = lookup_or_add(C->getOperand(0));
338 e.type = C->getType();
339 e.opcode = getOpcode(C);
344 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
347 e.firstVN = lookup_or_add(S->getOperand(0));
348 e.secondVN = lookup_or_add(S->getOperand(1));
349 e.thirdVN = lookup_or_add(S->getOperand(2));
351 e.type = S->getType();
352 e.opcode = Expression::SHUFFLE;
357 Expression ValueTable::create_expression(ExtractElementInst* E) {
360 e.firstVN = lookup_or_add(E->getOperand(0));
361 e.secondVN = lookup_or_add(E->getOperand(1));
364 e.type = E->getType();
365 e.opcode = Expression::EXTRACT;
370 Expression ValueTable::create_expression(InsertElementInst* I) {
373 e.firstVN = lookup_or_add(I->getOperand(0));
374 e.secondVN = lookup_or_add(I->getOperand(1));
375 e.thirdVN = lookup_or_add(I->getOperand(2));
377 e.type = I->getType();
378 e.opcode = Expression::INSERT;
383 Expression ValueTable::create_expression(SelectInst* I) {
386 e.firstVN = lookup_or_add(I->getCondition());
387 e.secondVN = lookup_or_add(I->getTrueValue());
388 e.thirdVN = lookup_or_add(I->getFalseValue());
390 e.type = I->getType();
391 e.opcode = Expression::SELECT;
396 Expression ValueTable::create_expression(GetElementPtrInst* G) {
399 e.firstVN = lookup_or_add(G->getPointerOperand());
403 e.type = G->getType();
404 e.opcode = Expression::GEP;
406 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
408 e.varargs.push_back(lookup_or_add(*I));
413 //===----------------------------------------------------------------------===//
414 // ValueTable External Functions
415 //===----------------------------------------------------------------------===//
417 /// add - Insert a value into the table with a specified value number.
418 void ValueTable::add(Value *V, uint32_t num) {
419 valueNumbering.insert(std::make_pair(V, num));
422 /// lookup_or_add - Returns the value number for the specified value, assigning
423 /// it a new number if it did not have one before.
424 uint32_t ValueTable::lookup_or_add(Value *V) {
425 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
426 if (VI != valueNumbering.end())
429 if (CallInst* C = dyn_cast<CallInst>(V)) {
430 if (AA->doesNotAccessMemory(C)) {
431 Expression e = create_expression(C);
433 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
434 if (EI != expressionNumbering.end()) {
435 valueNumbering.insert(std::make_pair(V, EI->second));
438 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
439 valueNumbering.insert(std::make_pair(V, nextValueNumber));
441 return nextValueNumber++;
443 } else if (AA->onlyReadsMemory(C)) {
444 Expression e = create_expression(C);
446 if (expressionNumbering.find(e) == expressionNumbering.end()) {
447 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
448 valueNumbering.insert(std::make_pair(V, nextValueNumber));
449 return nextValueNumber++;
452 MemDepResult local_dep = MD->getDependency(C);
454 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
455 valueNumbering.insert(std::make_pair(V, nextValueNumber));
456 return nextValueNumber++;
459 if (local_dep.isDef()) {
460 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
462 if (local_cdep->getNumOperands() != C->getNumOperands()) {
463 valueNumbering.insert(std::make_pair(V, nextValueNumber));
464 return nextValueNumber++;
467 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
468 uint32_t c_vn = lookup_or_add(C->getOperand(i));
469 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
471 valueNumbering.insert(std::make_pair(V, nextValueNumber));
472 return nextValueNumber++;
476 uint32_t v = lookup_or_add(local_cdep);
477 valueNumbering.insert(std::make_pair(V, v));
482 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
483 MD->getNonLocalCallDependency(CallSite(C));
484 // FIXME: call/call dependencies for readonly calls should return def, not
485 // clobber! Move the checking logic to MemDep!
488 // Check to see if we have a single dominating call instruction that is
490 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
491 const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
492 // Ignore non-local dependencies.
493 if (I->second.isNonLocal())
496 // We don't handle non-depedencies. If we already have a call, reject
497 // instruction dependencies.
498 if (I->second.isClobber() || cdep != 0) {
503 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
504 // FIXME: All duplicated with non-local case.
505 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
506 cdep = NonLocalDepCall;
515 valueNumbering.insert(std::make_pair(V, nextValueNumber));
516 return nextValueNumber++;
519 if (cdep->getNumOperands() != C->getNumOperands()) {
520 valueNumbering.insert(std::make_pair(V, nextValueNumber));
521 return nextValueNumber++;
523 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
524 uint32_t c_vn = lookup_or_add(C->getOperand(i));
525 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
527 valueNumbering.insert(std::make_pair(V, nextValueNumber));
528 return nextValueNumber++;
532 uint32_t v = lookup_or_add(cdep);
533 valueNumbering.insert(std::make_pair(V, v));
537 valueNumbering.insert(std::make_pair(V, nextValueNumber));
538 return nextValueNumber++;
540 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
541 Expression e = create_expression(BO);
543 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
544 if (EI != expressionNumbering.end()) {
545 valueNumbering.insert(std::make_pair(V, EI->second));
548 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
549 valueNumbering.insert(std::make_pair(V, nextValueNumber));
551 return nextValueNumber++;
553 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
554 Expression e = create_expression(C);
556 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
557 if (EI != expressionNumbering.end()) {
558 valueNumbering.insert(std::make_pair(V, EI->second));
561 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
562 valueNumbering.insert(std::make_pair(V, nextValueNumber));
564 return nextValueNumber++;
566 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
567 Expression e = create_expression(U);
569 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
570 if (EI != expressionNumbering.end()) {
571 valueNumbering.insert(std::make_pair(V, EI->second));
574 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
575 valueNumbering.insert(std::make_pair(V, nextValueNumber));
577 return nextValueNumber++;
579 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
580 Expression e = create_expression(U);
582 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
583 if (EI != expressionNumbering.end()) {
584 valueNumbering.insert(std::make_pair(V, EI->second));
587 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
588 valueNumbering.insert(std::make_pair(V, nextValueNumber));
590 return nextValueNumber++;
592 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
593 Expression e = create_expression(U);
595 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
596 if (EI != expressionNumbering.end()) {
597 valueNumbering.insert(std::make_pair(V, EI->second));
600 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
601 valueNumbering.insert(std::make_pair(V, nextValueNumber));
603 return nextValueNumber++;
605 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
606 Expression e = create_expression(U);
608 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
609 if (EI != expressionNumbering.end()) {
610 valueNumbering.insert(std::make_pair(V, EI->second));
613 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
614 valueNumbering.insert(std::make_pair(V, nextValueNumber));
616 return nextValueNumber++;
618 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
619 Expression e = create_expression(U);
621 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
622 if (EI != expressionNumbering.end()) {
623 valueNumbering.insert(std::make_pair(V, EI->second));
626 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
627 valueNumbering.insert(std::make_pair(V, nextValueNumber));
629 return nextValueNumber++;
631 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
632 Expression e = create_expression(U);
634 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
635 if (EI != expressionNumbering.end()) {
636 valueNumbering.insert(std::make_pair(V, EI->second));
639 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
640 valueNumbering.insert(std::make_pair(V, nextValueNumber));
642 return nextValueNumber++;
645 valueNumbering.insert(std::make_pair(V, nextValueNumber));
646 return nextValueNumber++;
650 /// lookup - Returns the value number of the specified value. Fails if
651 /// the value has not yet been numbered.
652 uint32_t ValueTable::lookup(Value *V) const {
653 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
654 assert(VI != valueNumbering.end() && "Value not numbered?");
658 /// clear - Remove all entries from the ValueTable
659 void ValueTable::clear() {
660 valueNumbering.clear();
661 expressionNumbering.clear();
665 /// erase - Remove a value from the value numbering
666 void ValueTable::erase(Value *V) {
667 valueNumbering.erase(V);
670 /// verifyRemoved - Verify that the value is removed from all internal data
672 void ValueTable::verifyRemoved(const Value *V) const {
673 for (DenseMap<Value*, uint32_t>::iterator
674 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
675 assert(I->first != V && "Inst still occurs in value numbering map!");
679 //===----------------------------------------------------------------------===//
681 //===----------------------------------------------------------------------===//
684 struct ValueNumberScope {
685 ValueNumberScope* parent;
686 DenseMap<uint32_t, Value*> table;
688 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
694 class GVN : public FunctionPass {
695 bool runOnFunction(Function &F);
697 static char ID; // Pass identification, replacement for typeid
698 GVN() : FunctionPass(&ID) { }
701 MemoryDependenceAnalysis *MD;
705 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
707 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
711 // This transformation requires dominator postdominator info
712 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
713 AU.addRequired<DominatorTree>();
714 AU.addRequired<MemoryDependenceAnalysis>();
715 AU.addRequired<AliasAnalysis>();
717 AU.addPreserved<DominatorTree>();
718 AU.addPreserved<AliasAnalysis>();
722 // FIXME: eliminate or document these better
723 bool processLoad(LoadInst* L,
724 SmallVectorImpl<Instruction*> &toErase);
725 bool processInstruction(Instruction *I,
726 SmallVectorImpl<Instruction*> &toErase);
727 bool processNonLocalLoad(LoadInst* L,
728 SmallVectorImpl<Instruction*> &toErase);
729 bool processBlock(BasicBlock *BB);
730 Value *GetValueForBlock(BasicBlock *BB, Instruction *orig,
731 DenseMap<BasicBlock*, Value*> &Phis,
732 bool top_level = false);
733 void dump(DenseMap<uint32_t, Value*>& d);
734 bool iterateOnFunction(Function &F);
735 Value *CollapsePhi(PHINode* p);
736 bool performPRE(Function& F);
737 Value *lookupNumber(BasicBlock *BB, uint32_t num);
738 Value *AttemptRedundancyElimination(Instruction *orig, unsigned valno);
739 void cleanupGlobalSets();
740 void verifyRemoved(const Instruction *I) const;
746 // createGVNPass - The public interface to this file...
747 FunctionPass *llvm::createGVNPass() { return new GVN(); }
749 static RegisterPass<GVN> X("gvn",
750 "Global Value Numbering");
752 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
754 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
755 E = d.end(); I != E; ++I) {
756 printf("%d\n", I->first);
762 static bool 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 Value *GVN::CollapsePhi(PHINode *PN) {
776 Value *ConstVal = PN->hasConstantValue(DT);
777 if (!ConstVal) return 0;
779 Instruction *Inst = dyn_cast<Instruction>(ConstVal);
783 if (DT->dominates(Inst, PN))
784 if (isSafeReplacement(PN, Inst))
789 /// GetValueForBlock - Get the value to use within the specified basic block.
790 /// available values are in Phis.
791 Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction *Orig,
792 DenseMap<BasicBlock*, Value*> &Phis,
795 // If we have already computed this value, return the previously computed val.
796 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
797 if (V != Phis.end() && !TopLevel) return V->second;
799 // If the block is unreachable, just return undef, since this path
800 // can't actually occur at runtime.
801 if (!DT->isReachableFromEntry(BB))
802 return Phis[BB] = UndefValue::get(Orig->getType());
804 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
805 Value *ret = GetValueForBlock(Pred, Orig, Phis);
810 // Get the number of predecessors of this block so we can reserve space later.
811 // If there is already a PHI in it, use the #preds from it, otherwise count.
812 // Getting it from the PHI is constant time.
814 if (PHINode *ExistingPN = dyn_cast<PHINode>(BB->begin()))
815 NumPreds = ExistingPN->getNumIncomingValues();
817 NumPreds = std::distance(pred_begin(BB), pred_end(BB));
819 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
820 // now, then get values to fill in the incoming values for the PHI.
821 PHINode *PN = PHINode::Create(Orig->getType(), Orig->getName()+".rle",
823 PN->reserveOperandSpace(NumPreds);
825 Phis.insert(std::make_pair(BB, PN));
827 // Fill in the incoming values for the block.
828 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
829 Value *val = GetValueForBlock(*PI, Orig, Phis);
830 PN->addIncoming(val, *PI);
833 VN.getAliasAnalysis()->copyValue(Orig, PN);
835 // Attempt to collapse PHI nodes that are trivially redundant
836 Value *v = CollapsePhi(PN);
838 // Cache our phi construction results
839 if (LoadInst* L = dyn_cast<LoadInst>(Orig))
840 phiMap[L->getPointerOperand()].insert(PN);
842 phiMap[Orig].insert(PN);
847 PN->replaceAllUsesWith(v);
848 if (isa<PointerType>(v->getType()))
849 MD->invalidateCachedPointerInfo(v);
851 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
852 E = Phis.end(); I != E; ++I)
856 DEBUG(errs() << "GVN removed: " << *PN << '\n');
857 MD->removeInstruction(PN);
858 PN->eraseFromParent();
859 DEBUG(verifyRemoved(PN));
865 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
866 /// we're analyzing is fully available in the specified block. As we go, keep
867 /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
868 /// map is actually a tri-state map with the following values:
869 /// 0) we know the block *is not* fully available.
870 /// 1) we know the block *is* fully available.
871 /// 2) we do not know whether the block is fully available or not, but we are
872 /// currently speculating that it will be.
873 /// 3) we are speculating for this block and have used that to speculate for
875 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
876 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
877 // Optimistically assume that the block is fully available and check to see
878 // if we already know about this block in one lookup.
879 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
880 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
882 // If the entry already existed for this block, return the precomputed value.
884 // If this is a speculative "available" value, mark it as being used for
885 // speculation of other blocks.
886 if (IV.first->second == 2)
887 IV.first->second = 3;
888 return IV.first->second != 0;
891 // Otherwise, see if it is fully available in all predecessors.
892 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
894 // If this block has no predecessors, it isn't live-in here.
896 goto SpeculationFailure;
898 for (; PI != PE; ++PI)
899 // If the value isn't fully available in one of our predecessors, then it
900 // isn't fully available in this block either. Undo our previous
901 // optimistic assumption and bail out.
902 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
903 goto SpeculationFailure;
907 // SpeculationFailure - If we get here, we found out that this is not, after
908 // all, a fully-available block. We have a problem if we speculated on this and
909 // used the speculation to mark other blocks as available.
911 char &BBVal = FullyAvailableBlocks[BB];
913 // If we didn't speculate on this, just return with it set to false.
919 // If we did speculate on this value, we could have blocks set to 1 that are
920 // incorrect. Walk the (transitive) successors of this block and mark them as
922 SmallVector<BasicBlock*, 32> BBWorklist;
923 BBWorklist.push_back(BB);
925 while (!BBWorklist.empty()) {
926 BasicBlock *Entry = BBWorklist.pop_back_val();
927 // Note that this sets blocks to 0 (unavailable) if they happen to not
928 // already be in FullyAvailableBlocks. This is safe.
929 char &EntryVal = FullyAvailableBlocks[Entry];
930 if (EntryVal == 0) continue; // Already unavailable.
932 // Mark as unavailable.
935 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
936 BBWorklist.push_back(*I);
943 /// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
944 /// then a load from a must-aliased pointer of a different type, try to coerce
945 /// the stored value. LoadedTy is the type of the load we want to replace and
946 /// InsertPt is the place to insert new instructions.
948 /// If we can't do it, return null.
949 static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
950 const Type *LoadedTy,
951 Instruction *InsertPt,
952 const TargetData &TD) {
953 const Type *StoredValTy = StoredVal->getType();
955 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
956 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
958 // If the store and reload are the same size, we can always reuse it.
959 if (StoreSize == LoadSize) {
960 if (isa<PointerType>(StoredValTy) && isa<PointerType>(LoadedTy)) {
961 // Pointer to Pointer -> use bitcast.
962 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
965 // Convert source pointers to integers, which can be bitcast.
966 if (isa<PointerType>(StoredValTy)) {
967 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
968 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
971 const Type *TypeToCastTo = LoadedTy;
972 if (isa<PointerType>(TypeToCastTo))
973 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
975 if (StoredValTy != TypeToCastTo)
976 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
978 // Cast to pointer if the load needs a pointer type.
979 if (isa<PointerType>(LoadedTy))
980 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
985 // If the loaded value is smaller than the available value, then we can
986 // extract out a piece from it. If the available value is too small, then we
987 // can't do anything.
988 if (StoreSize < LoadSize)
991 // Convert source pointers to integers, which can be manipulated.
992 if (isa<PointerType>(StoredValTy)) {
993 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
994 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
997 // Convert vectors and fp to integer, which can be manipulated.
998 if (!isa<IntegerType>(StoredValTy)) {
999 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
1000 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
1003 // If this is a big-endian system, we need to shift the value down to the low
1004 // bits so that a truncate will work.
1005 if (TD.isBigEndian()) {
1006 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
1007 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
1010 // Truncate the integer to the right size now.
1011 const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
1012 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
1014 if (LoadedTy == NewIntTy)
1017 // If the result is a pointer, inttoptr.
1018 if (isa<PointerType>(LoadedTy))
1019 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
1021 // Otherwise, bitcast.
1022 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
1026 GetAvailableBlockValues(DenseMap<BasicBlock*, Value*> &BlockReplValues,
1027 SmallVector<std::pair<BasicBlock*,
1028 Value*>, 16> &ValuesPerBlock,
1030 const TargetData *TD) {
1032 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1033 BasicBlock *BB = ValuesPerBlock[i].first;
1034 Value *AvailableVal = ValuesPerBlock[i].second;
1036 Value *&BlockEntry = BlockReplValues[BB];
1037 if (BlockEntry) continue;
1039 if (AvailableVal->getType() != LoadTy) {
1040 assert(TD && "Need target data to handle type mismatch case");
1041 AvailableVal = CoerceAvailableValueToLoadType(AvailableVal, LoadTy,
1042 BB->getTerminator(), *TD);
1043 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
1044 << *ValuesPerBlock[i].second << '\n'
1045 << *AvailableVal << '\n' << "\n\n\n");
1047 BlockEntry = AvailableVal;
1051 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1052 /// non-local by performing PHI construction.
1053 bool GVN::processNonLocalLoad(LoadInst *LI,
1054 SmallVectorImpl<Instruction*> &toErase) {
1055 // Find the non-local dependencies of the load.
1056 SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
1057 MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
1059 //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
1060 // << Deps.size() << *LI << '\n');
1062 // If we had to process more than one hundred blocks to find the
1063 // dependencies, this load isn't worth worrying about. Optimizing
1064 // it will be too expensive.
1065 if (Deps.size() > 100)
1068 // If we had a phi translation failure, we'll have a single entry which is a
1069 // clobber in the current block. Reject this early.
1070 if (Deps.size() == 1 && Deps[0].second.isClobber()) {
1072 errs() << "GVN: non-local load ";
1073 WriteAsOperand(errs(), LI);
1074 errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
1079 // Filter out useless results (non-locals, etc). Keep track of the blocks
1080 // where we have a value available in repl, also keep track of whether we see
1081 // dependencies that produce an unknown value for the load (such as a call
1082 // that could potentially clobber the load).
1083 SmallVector<std::pair<BasicBlock*, Value*>, 16> ValuesPerBlock;
1084 SmallVector<BasicBlock*, 16> UnavailableBlocks;
1086 const TargetData *TD = 0;
1088 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1089 BasicBlock *DepBB = Deps[i].first;
1090 MemDepResult DepInfo = Deps[i].second;
1092 if (DepInfo.isClobber()) {
1093 UnavailableBlocks.push_back(DepBB);
1097 Instruction *DepInst = DepInfo.getInst();
1099 // Loading the allocation -> undef.
1100 if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
1101 ValuesPerBlock.push_back(std::make_pair(DepBB,
1102 UndefValue::get(LI->getType())));
1106 if (StoreInst* S = dyn_cast<StoreInst>(DepInst)) {
1107 // Reject loads and stores that are to the same address but are of
1108 // different types if we have to.
1109 if (S->getOperand(0)->getType() != LI->getType()) {
1111 TD = getAnalysisIfAvailable<TargetData>();
1113 // If the stored value is larger or equal to the loaded value, we can
1116 TD->getTypeSizeInBits(S->getOperand(0)->getType()) <
1117 TD->getTypeSizeInBits(LI->getType())) {
1118 UnavailableBlocks.push_back(DepBB);
1123 ValuesPerBlock.push_back(std::make_pair(DepBB, S->getOperand(0)));
1125 } else if (LoadInst* LD = dyn_cast<LoadInst>(DepInst)) {
1126 // If the types mismatch and we can't handle it, reject reuse of the load.
1127 if (LD->getType() != LI->getType()) {
1129 TD = getAnalysisIfAvailable<TargetData>();
1131 // If the stored value is larger or equal to the loaded value, we can
1134 TD->getTypeSizeInBits(LD->getType()) <
1135 TD->getTypeSizeInBits(LI->getType())) {
1136 UnavailableBlocks.push_back(DepBB);
1140 ValuesPerBlock.push_back(std::make_pair(DepBB, LD));
1142 // FIXME: Handle memset/memcpy.
1143 UnavailableBlocks.push_back(DepBB);
1148 // If we have no predecessors that produce a known value for this load, exit
1150 if (ValuesPerBlock.empty()) return false;
1152 // If all of the instructions we depend on produce a known value for this
1153 // load, then it is fully redundant and we can use PHI insertion to compute
1154 // its value. Insert PHIs and remove the fully redundant value now.
1155 if (UnavailableBlocks.empty()) {
1156 // Use cached PHI construction information from previous runs
1157 SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1158 // FIXME: What does phiMap do? Are we positive it isn't getting invalidated?
1159 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1161 if ((*I)->getParent() == LI->getParent()) {
1162 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD #1: " << *LI << '\n');
1163 LI->replaceAllUsesWith(*I);
1164 if (isa<PointerType>((*I)->getType()))
1165 MD->invalidateCachedPointerInfo(*I);
1166 toErase.push_back(LI);
1171 ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I));
1174 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1176 // Convert the block information to a map, and insert coersions as needed.
1177 DenseMap<BasicBlock*, Value*> BlockReplValues;
1178 GetAvailableBlockValues(BlockReplValues, ValuesPerBlock, LI->getType(), TD);
1180 // Perform PHI construction.
1181 Value *V = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1182 LI->replaceAllUsesWith(V);
1184 if (isa<PHINode>(V))
1186 if (isa<PointerType>(V->getType()))
1187 MD->invalidateCachedPointerInfo(V);
1188 toErase.push_back(LI);
1193 if (!EnablePRE || !EnableLoadPRE)
1196 // Okay, we have *some* definitions of the value. This means that the value
1197 // is available in some of our (transitive) predecessors. Lets think about
1198 // doing PRE of this load. This will involve inserting a new load into the
1199 // predecessor when it's not available. We could do this in general, but
1200 // prefer to not increase code size. As such, we only do this when we know
1201 // that we only have to insert *one* load (which means we're basically moving
1202 // the load, not inserting a new one).
1204 SmallPtrSet<BasicBlock *, 4> Blockers;
1205 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1206 Blockers.insert(UnavailableBlocks[i]);
1208 // Lets find first basic block with more than one predecessor. Walk backwards
1209 // through predecessors if needed.
1210 BasicBlock *LoadBB = LI->getParent();
1211 BasicBlock *TmpBB = LoadBB;
1213 bool isSinglePred = false;
1214 bool allSingleSucc = true;
1215 while (TmpBB->getSinglePredecessor()) {
1216 isSinglePred = true;
1217 TmpBB = TmpBB->getSinglePredecessor();
1218 if (!TmpBB) // If haven't found any, bail now.
1220 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1222 if (Blockers.count(TmpBB))
1224 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1225 allSingleSucc = false;
1231 // If we have a repl set with LI itself in it, this means we have a loop where
1232 // at least one of the values is LI. Since this means that we won't be able
1233 // to eliminate LI even if we insert uses in the other predecessors, we will
1234 // end up increasing code size. Reject this by scanning for LI.
1235 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1236 if (ValuesPerBlock[i].second == LI)
1241 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1242 if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].second))
1243 // "Hot" Instruction is in some loop (because it dominates its dep.
1245 if (DT->dominates(LI, I)) {
1250 // We are interested only in "hot" instructions. We don't want to do any
1251 // mis-optimizations here.
1256 // Okay, we have some hope :). Check to see if the loaded value is fully
1257 // available in all but one predecessor.
1258 // FIXME: If we could restructure the CFG, we could make a common pred with
1259 // all the preds that don't have an available LI and insert a new load into
1261 BasicBlock *UnavailablePred = 0;
1263 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1264 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1265 FullyAvailableBlocks[ValuesPerBlock[i].first] = true;
1266 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1267 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1269 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1271 if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1274 // If this load is not available in multiple predecessors, reject it.
1275 if (UnavailablePred && UnavailablePred != *PI)
1277 UnavailablePred = *PI;
1280 assert(UnavailablePred != 0 &&
1281 "Fully available value should be eliminated above!");
1283 // If the loaded pointer is PHI node defined in this block, do PHI translation
1284 // to get its value in the predecessor.
1285 Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
1287 // Make sure the value is live in the predecessor. If it was defined by a
1288 // non-PHI instruction in this block, we don't know how to recompute it above.
1289 if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1290 if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
1291 DEBUG(errs() << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
1292 << *LPInst << '\n' << *LI << "\n");
1296 // We don't currently handle critical edges :(
1297 if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
1298 DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
1299 << UnavailablePred->getName() << "': " << *LI << '\n');
1303 // Make sure it is valid to move this load here. We have to watch out for:
1304 // @1 = getelementptr (i8* p, ...
1305 // test p and branch if == 0
1307 // It is valid to have the getelementptr before the test, even if p can be 0,
1308 // as getelementptr only does address arithmetic.
1309 // If we are not pushing the value through any multiple-successor blocks
1310 // we do not have this case. Otherwise, check that the load is safe to
1311 // put anywhere; this can be improved, but should be conservatively safe.
1312 if (!allSingleSucc &&
1313 !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1316 // Okay, we can eliminate this load by inserting a reload in the predecessor
1317 // and using PHI construction to get the value in the other predecessors, do
1319 DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1321 Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1323 UnavailablePred->getTerminator());
1325 SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1326 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1328 ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I));
1330 DenseMap<BasicBlock*, Value*> BlockReplValues;
1331 GetAvailableBlockValues(BlockReplValues, ValuesPerBlock, LI->getType(), TD);
1332 BlockReplValues[UnavailablePred] = NewLoad;
1334 // Perform PHI construction.
1335 Value *V = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1336 LI->replaceAllUsesWith(V);
1337 if (isa<PHINode>(V))
1339 if (isa<PointerType>(V->getType()))
1340 MD->invalidateCachedPointerInfo(V);
1341 toErase.push_back(LI);
1346 /// GetBaseWithConstantOffset - Analyze the specified pointer to see if it can
1347 /// be expressed as a base pointer plus a constant offset. Return the base and
1348 /// offset to the caller.
1349 static Value *GetBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1350 const TargetData *TD) {
1351 Operator *PtrOp = dyn_cast<Operator>(Ptr);
1352 if (PtrOp == 0) return Ptr;
1354 // Just look through bitcasts.
1355 if (PtrOp->getOpcode() == Instruction::BitCast)
1356 return GetBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1358 // If this is a GEP with constant indices, we can look through it.
1359 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1360 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1362 gep_type_iterator GTI = gep_type_begin(GEP);
1363 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1365 ConstantInt *OpC = cast<ConstantInt>(*I);
1366 if (OpC->isZero()) continue;
1368 // Handle a struct and array indices which add their offset to the pointer.
1369 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1370 Offset += TD->getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1372 uint64_t Size = TD->getTypeAllocSize(GTI.getIndexedType());
1373 Offset += OpC->getSExtValue()*Size;
1377 // Re-sign extend from the pointer size if needed to get overflow edge cases
1379 unsigned PtrSize = TD->getPointerSizeInBits();
1381 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1383 return GetBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1387 /// AnalyzeLoadFromClobberingStore - This function is called when we have a
1388 /// memdep query of a load that ends up being a clobbering store. This means
1389 /// that the store *may* provide bits used by the load but we can't be sure
1390 /// because the pointers don't mustalias. Check this case to see if there is
1391 /// anything more we can do before we give up. This returns -1 if we have to
1392 /// give up, or a byte number in the stored value of the piece that feeds the
1394 static int AnalyzeLoadFromClobberingStore(LoadInst *L, StoreInst *DepSI,
1395 const TargetData *TD) {
1396 int64_t StoreOffset = 0, LoadOffset = 0;
1398 GetBaseWithConstantOffset(DepSI->getPointerOperand(), StoreOffset, TD);
1400 GetBaseWithConstantOffset(L->getPointerOperand(), LoadOffset, TD);
1401 if (StoreBase != LoadBase)
1404 // If the load and store are to the exact same address, they should have been
1405 // a must alias. AA must have gotten confused.
1406 // FIXME: Study to see if/when this happens.
1407 if (LoadOffset == StoreOffset) {
1409 errs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
1410 << "Base = " << *StoreBase << "\n"
1411 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1412 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1413 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1414 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1415 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1421 // If the load and store don't overlap at all, the store doesn't provide
1422 // anything to the load. In this case, they really don't alias at all, AA
1423 // must have gotten confused.
1424 // FIXME: Investigate cases where this bails out, e.g. rdar://7238614. Then
1425 // remove this check, as it is duplicated with what we have below.
1426 uint64_t StoreSize = TD->getTypeSizeInBits(DepSI->getOperand(0)->getType());
1427 uint64_t LoadSize = TD->getTypeSizeInBits(L->getType());
1429 if ((StoreSize & 7) | (LoadSize & 7))
1431 StoreSize >>= 3; // Convert to bytes.
1435 bool isAAFailure = false;
1436 if (StoreOffset < LoadOffset) {
1437 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
1439 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
1443 errs() << "STORE LOAD DEP WITH COMMON BASE:\n"
1444 << "Base = " << *StoreBase << "\n"
1445 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1446 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1447 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1448 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1449 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1455 // If the Load isn't completely contained within the stored bits, we don't
1456 // have all the bits to feed it. We could do something crazy in the future
1457 // (issue a smaller load then merge the bits in) but this seems unlikely to be
1459 if (StoreOffset > LoadOffset ||
1460 StoreOffset+StoreSize < LoadOffset+LoadSize)
1463 // Okay, we can do this transformation. Return the number of bytes into the
1464 // store that the load is.
1465 return LoadOffset-StoreOffset;
1469 /// GetStoreValueForLoad - This function is called when we have a
1470 /// memdep query of a load that ends up being a clobbering store. This means
1471 /// that the store *may* provide bits used by the load but we can't be sure
1472 /// because the pointers don't mustalias. Check this case to see if there is
1473 /// anything more we can do before we give up.
1474 static Value *GetStoreValueForLoad(Value *SrcVal, int Offset,const Type *LoadTy,
1475 Instruction *InsertPt, const TargetData *TD){
1476 LLVMContext &Ctx = SrcVal->getType()->getContext();
1478 uint64_t StoreSize = TD->getTypeSizeInBits(SrcVal->getType())/8;
1479 uint64_t LoadSize = TD->getTypeSizeInBits(LoadTy)/8;
1482 // Compute which bits of the stored value are being used by the load. Convert
1483 // to an integer type to start with.
1484 if (isa<PointerType>(SrcVal->getType()))
1485 SrcVal = new PtrToIntInst(SrcVal, TD->getIntPtrType(Ctx), "tmp", InsertPt);
1486 if (!isa<IntegerType>(SrcVal->getType()))
1487 SrcVal = new BitCastInst(SrcVal, IntegerType::get(Ctx, StoreSize*8),
1490 // Shift the bits to the least significant depending on endianness.
1492 if (TD->isLittleEndian()) {
1493 ShiftAmt = Offset*8;
1495 ShiftAmt = StoreSize-LoadSize-Offset;
1498 SrcVal = BinaryOperator::CreateLShr(SrcVal,
1499 ConstantInt::get(SrcVal->getType(), ShiftAmt), "tmp", InsertPt);
1501 SrcVal = new TruncInst(SrcVal, IntegerType::get(Ctx, LoadSize*8),
1504 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, *TD);
1509 /// processLoad - Attempt to eliminate a load, first by eliminating it
1510 /// locally, and then attempting non-local elimination if that fails.
1511 bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1512 if (L->isVolatile())
1515 // ... to a pointer that has been loaded from before...
1516 MemDepResult Dep = MD->getDependency(L);
1518 // If the value isn't available, don't do anything!
1519 if (Dep.isClobber()) {
1520 // FIXME: We should handle memset/memcpy/memmove as dependent instructions
1521 // to forward the value if available.
1522 //if (isa<MemIntrinsic>(Dep.getInst()))
1523 //errs() << "LOAD DEPENDS ON MEM: " << *L << "\n" << *Dep.getInst()<<"\n\n";
1525 // Check to see if we have something like this:
1526 // store i32 123, i32* %P
1527 // %A = bitcast i32* %P to i8*
1528 // %B = gep i8* %A, i32 1
1531 // We could do that by recognizing if the clobber instructions are obviously
1532 // a common base + constant offset, and if the previous store (or memset)
1533 // completely covers this load. This sort of thing can happen in bitfield
1535 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst()))
1536 if (const TargetData *TD = getAnalysisIfAvailable<TargetData>()) {
1537 int Offset = AnalyzeLoadFromClobberingStore(L, DepSI, TD);
1539 Value *AvailVal = GetStoreValueForLoad(DepSI->getOperand(0), Offset,
1540 L->getType(), L, TD);
1541 DEBUG(errs() << "GVN COERCED STORE BITS:\n" << *DepSI << '\n'
1542 << *AvailVal << '\n' << *L << "\n\n\n");
1544 // Replace the load!
1545 L->replaceAllUsesWith(AvailVal);
1546 if (isa<PointerType>(AvailVal->getType()))
1547 MD->invalidateCachedPointerInfo(AvailVal);
1548 toErase.push_back(L);
1555 // fast print dep, using operator<< on instruction would be too slow
1556 errs() << "GVN: load ";
1557 WriteAsOperand(errs(), L);
1558 Instruction *I = Dep.getInst();
1559 errs() << " is clobbered by " << *I << '\n';
1564 // If it is defined in another block, try harder.
1565 if (Dep.isNonLocal())
1566 return processNonLocalLoad(L, toErase);
1568 Instruction *DepInst = Dep.getInst();
1569 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1570 Value *StoredVal = DepSI->getOperand(0);
1572 // The store and load are to a must-aliased pointer, but they may not
1573 // actually have the same type. See if we know how to reuse the stored
1574 // value (depending on its type).
1575 const TargetData *TD = 0;
1576 if (StoredVal->getType() != L->getType() &&
1577 (TD = getAnalysisIfAvailable<TargetData>())) {
1578 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(), L, *TD);
1582 DEBUG(errs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1583 << '\n' << *L << "\n\n\n");
1587 L->replaceAllUsesWith(StoredVal);
1588 if (isa<PointerType>(StoredVal->getType()))
1589 MD->invalidateCachedPointerInfo(StoredVal);
1590 toErase.push_back(L);
1595 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1596 Value *AvailableVal = DepLI;
1598 // The loads are of a must-aliased pointer, but they may not actually have
1599 // the same type. See if we know how to reuse the previously loaded value
1600 // (depending on its type).
1601 const TargetData *TD = 0;
1602 if (DepLI->getType() != L->getType() &&
1603 (TD = getAnalysisIfAvailable<TargetData>())) {
1604 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L, *TD);
1605 if (AvailableVal == 0)
1608 DEBUG(errs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1609 << "\n" << *L << "\n\n\n");
1613 L->replaceAllUsesWith(AvailableVal);
1614 if (isa<PointerType>(DepLI->getType()))
1615 MD->invalidateCachedPointerInfo(DepLI);
1616 toErase.push_back(L);
1621 // If this load really doesn't depend on anything, then we must be loading an
1622 // undef value. This can happen when loading for a fresh allocation with no
1623 // intervening stores, for example.
1624 if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
1625 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1626 toErase.push_back(L);
1634 Value *GVN::lookupNumber(BasicBlock *BB, uint32_t num) {
1635 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1636 if (I == localAvail.end())
1639 ValueNumberScope *Locals = I->second;
1641 DenseMap<uint32_t, Value*>::iterator I = Locals->table.find(num);
1642 if (I != Locals->table.end())
1644 Locals = Locals->parent;
1650 /// AttemptRedundancyElimination - If the "fast path" of redundancy elimination
1651 /// by inheritance from the dominator fails, see if we can perform phi
1652 /// construction to eliminate the redundancy.
1653 Value *GVN::AttemptRedundancyElimination(Instruction *orig, unsigned valno) {
1654 BasicBlock *BaseBlock = orig->getParent();
1656 SmallPtrSet<BasicBlock*, 4> Visited;
1657 SmallVector<BasicBlock*, 8> Stack;
1658 Stack.push_back(BaseBlock);
1660 DenseMap<BasicBlock*, Value*> Results;
1662 // Walk backwards through our predecessors, looking for instances of the
1663 // value number we're looking for. Instances are recorded in the Results
1664 // map, which is then used to perform phi construction.
1665 while (!Stack.empty()) {
1666 BasicBlock *Current = Stack.back();
1669 // If we've walked all the way to a proper dominator, then give up. Cases
1670 // where the instance is in the dominator will have been caught by the fast
1671 // path, and any cases that require phi construction further than this are
1672 // probably not worth it anyways. Note that this is a SIGNIFICANT compile
1673 // time improvement.
1674 if (DT->properlyDominates(Current, orig->getParent())) return 0;
1676 DenseMap<BasicBlock*, ValueNumberScope*>::iterator LA =
1677 localAvail.find(Current);
1678 if (LA == localAvail.end()) return 0;
1679 DenseMap<uint32_t, Value*>::iterator V = LA->second->table.find(valno);
1681 if (V != LA->second->table.end()) {
1682 // Found an instance, record it.
1683 Results.insert(std::make_pair(Current, V->second));
1687 // If we reach the beginning of the function, then give up.
1688 if (pred_begin(Current) == pred_end(Current))
1691 for (pred_iterator PI = pred_begin(Current), PE = pred_end(Current);
1693 if (Visited.insert(*PI))
1694 Stack.push_back(*PI);
1697 // If we didn't find instances, give up. Otherwise, perform phi construction.
1698 if (Results.size() == 0)
1701 return GetValueForBlock(BaseBlock, orig, Results, true);
1704 /// processInstruction - When calculating availability, handle an instruction
1705 /// by inserting it into the appropriate sets
1706 bool GVN::processInstruction(Instruction *I,
1707 SmallVectorImpl<Instruction*> &toErase) {
1708 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1709 bool Changed = processLoad(LI, toErase);
1712 unsigned Num = VN.lookup_or_add(LI);
1713 localAvail[I->getParent()]->table.insert(std::make_pair(Num, LI));
1719 uint32_t NextNum = VN.getNextUnusedValueNumber();
1720 unsigned Num = VN.lookup_or_add(I);
1722 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1723 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1725 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1728 Value *BranchCond = BI->getCondition();
1729 uint32_t CondVN = VN.lookup_or_add(BranchCond);
1731 BasicBlock *TrueSucc = BI->getSuccessor(0);
1732 BasicBlock *FalseSucc = BI->getSuccessor(1);
1734 if (TrueSucc->getSinglePredecessor())
1735 localAvail[TrueSucc]->table[CondVN] =
1736 ConstantInt::getTrue(TrueSucc->getContext());
1737 if (FalseSucc->getSinglePredecessor())
1738 localAvail[FalseSucc]->table[CondVN] =
1739 ConstantInt::getFalse(TrueSucc->getContext());
1743 // Allocations are always uniquely numbered, so we can save time and memory
1744 // by fast failing them.
1745 } else if (isa<AllocationInst>(I) || isMalloc(I) || isa<TerminatorInst>(I)) {
1746 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1750 // Collapse PHI nodes
1751 if (PHINode* p = dyn_cast<PHINode>(I)) {
1752 Value *constVal = CollapsePhi(p);
1755 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1757 PI->second.erase(p);
1759 p->replaceAllUsesWith(constVal);
1760 if (isa<PointerType>(constVal->getType()))
1761 MD->invalidateCachedPointerInfo(constVal);
1764 toErase.push_back(p);
1766 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1769 // If the number we were assigned was a brand new VN, then we don't
1770 // need to do a lookup to see if the number already exists
1771 // somewhere in the domtree: it can't!
1772 } else if (Num == NextNum) {
1773 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1775 // Perform fast-path value-number based elimination of values inherited from
1777 } else if (Value *repl = lookupNumber(I->getParent(), Num)) {
1780 I->replaceAllUsesWith(repl);
1781 if (isa<PointerType>(repl->getType()))
1782 MD->invalidateCachedPointerInfo(repl);
1783 toErase.push_back(I);
1787 // Perform slow-pathvalue-number based elimination with phi construction.
1788 } else if (Value *repl = AttemptRedundancyElimination(I, Num)) {
1791 I->replaceAllUsesWith(repl);
1792 if (isa<PointerType>(repl->getType()))
1793 MD->invalidateCachedPointerInfo(repl);
1794 toErase.push_back(I);
1798 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1804 /// runOnFunction - This is the main transformation entry point for a function.
1805 bool GVN::runOnFunction(Function& F) {
1806 MD = &getAnalysis<MemoryDependenceAnalysis>();
1807 DT = &getAnalysis<DominatorTree>();
1808 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1812 bool Changed = false;
1813 bool ShouldContinue = true;
1815 // Merge unconditional branches, allowing PRE to catch more
1816 // optimization opportunities.
1817 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1818 BasicBlock *BB = FI;
1820 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1821 if (removedBlock) NumGVNBlocks++;
1823 Changed |= removedBlock;
1826 unsigned Iteration = 0;
1828 while (ShouldContinue) {
1829 DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
1830 ShouldContinue = iterateOnFunction(F);
1831 Changed |= ShouldContinue;
1836 bool PREChanged = true;
1837 while (PREChanged) {
1838 PREChanged = performPRE(F);
1839 Changed |= PREChanged;
1842 // FIXME: Should perform GVN again after PRE does something. PRE can move
1843 // computations into blocks where they become fully redundant. Note that
1844 // we can't do this until PRE's critical edge splitting updates memdep.
1845 // Actually, when this happens, we should just fully integrate PRE into GVN.
1847 cleanupGlobalSets();
1853 bool GVN::processBlock(BasicBlock *BB) {
1854 // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1855 // incrementing BI before processing an instruction).
1856 SmallVector<Instruction*, 8> toErase;
1857 bool ChangedFunction = false;
1859 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1861 ChangedFunction |= processInstruction(BI, toErase);
1862 if (toErase.empty()) {
1867 // If we need some instructions deleted, do it now.
1868 NumGVNInstr += toErase.size();
1870 // Avoid iterator invalidation.
1871 bool AtStart = BI == BB->begin();
1875 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1876 E = toErase.end(); I != E; ++I) {
1877 DEBUG(errs() << "GVN removed: " << **I << '\n');
1878 MD->removeInstruction(*I);
1879 (*I)->eraseFromParent();
1880 DEBUG(verifyRemoved(*I));
1890 return ChangedFunction;
1893 /// performPRE - Perform a purely local form of PRE that looks for diamond
1894 /// control flow patterns and attempts to perform simple PRE at the join point.
1895 bool GVN::performPRE(Function& F) {
1896 bool Changed = false;
1897 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1898 DenseMap<BasicBlock*, Value*> predMap;
1899 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1900 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1901 BasicBlock *CurrentBlock = *DI;
1903 // Nothing to PRE in the entry block.
1904 if (CurrentBlock == &F.getEntryBlock()) continue;
1906 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1907 BE = CurrentBlock->end(); BI != BE; ) {
1908 Instruction *CurInst = BI++;
1910 if (isa<AllocationInst>(CurInst) || isMalloc(CurInst) ||
1911 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
1912 (CurInst->getType() == Type::getVoidTy(F.getContext())) ||
1913 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
1914 isa<DbgInfoIntrinsic>(CurInst))
1917 uint32_t ValNo = VN.lookup(CurInst);
1919 // Look for the predecessors for PRE opportunities. We're
1920 // only trying to solve the basic diamond case, where
1921 // a value is computed in the successor and one predecessor,
1922 // but not the other. We also explicitly disallow cases
1923 // where the successor is its own predecessor, because they're
1924 // more complicated to get right.
1925 unsigned NumWith = 0;
1926 unsigned NumWithout = 0;
1927 BasicBlock *PREPred = 0;
1930 for (pred_iterator PI = pred_begin(CurrentBlock),
1931 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1932 // We're not interested in PRE where the block is its
1933 // own predecessor, on in blocks with predecessors
1934 // that are not reachable.
1935 if (*PI == CurrentBlock) {
1938 } else if (!localAvail.count(*PI)) {
1943 DenseMap<uint32_t, Value*>::iterator predV =
1944 localAvail[*PI]->table.find(ValNo);
1945 if (predV == localAvail[*PI]->table.end()) {
1948 } else if (predV->second == CurInst) {
1951 predMap[*PI] = predV->second;
1956 // Don't do PRE when it might increase code size, i.e. when
1957 // we would need to insert instructions in more than one pred.
1958 if (NumWithout != 1 || NumWith == 0)
1961 // We can't do PRE safely on a critical edge, so instead we schedule
1962 // the edge to be split and perform the PRE the next time we iterate
1964 unsigned SuccNum = 0;
1965 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1967 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
1972 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
1973 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
1977 // Instantiate the expression the in predecessor that lacked it.
1978 // Because we are going top-down through the block, all value numbers
1979 // will be available in the predecessor by the time we need them. Any
1980 // that weren't original present will have been instantiated earlier
1982 Instruction *PREInstr = CurInst->clone(CurInst->getContext());
1983 bool success = true;
1984 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
1985 Value *Op = PREInstr->getOperand(i);
1986 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
1989 if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
1990 PREInstr->setOperand(i, V);
1997 // Fail out if we encounter an operand that is not available in
1998 // the PRE predecessor. This is typically because of loads which
1999 // are not value numbered precisely.
2002 DEBUG(verifyRemoved(PREInstr));
2006 PREInstr->insertBefore(PREPred->getTerminator());
2007 PREInstr->setName(CurInst->getName() + ".pre");
2008 predMap[PREPred] = PREInstr;
2009 VN.add(PREInstr, ValNo);
2012 // Update the availability map to include the new instruction.
2013 localAvail[PREPred]->table.insert(std::make_pair(ValNo, PREInstr));
2015 // Create a PHI to make the value available in this block.
2016 PHINode* Phi = PHINode::Create(CurInst->getType(),
2017 CurInst->getName() + ".pre-phi",
2018 CurrentBlock->begin());
2019 for (pred_iterator PI = pred_begin(CurrentBlock),
2020 PE = pred_end(CurrentBlock); PI != PE; ++PI)
2021 Phi->addIncoming(predMap[*PI], *PI);
2024 localAvail[CurrentBlock]->table[ValNo] = Phi;
2026 CurInst->replaceAllUsesWith(Phi);
2027 if (isa<PointerType>(Phi->getType()))
2028 MD->invalidateCachedPointerInfo(Phi);
2031 DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
2032 MD->removeInstruction(CurInst);
2033 CurInst->eraseFromParent();
2034 DEBUG(verifyRemoved(CurInst));
2039 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
2040 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
2041 SplitCriticalEdge(I->first, I->second, this);
2043 return Changed || toSplit.size();
2046 /// iterateOnFunction - Executes one iteration of GVN
2047 bool GVN::iterateOnFunction(Function &F) {
2048 cleanupGlobalSets();
2050 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2051 DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
2053 localAvail[DI->getBlock()] =
2054 new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
2056 localAvail[DI->getBlock()] = new ValueNumberScope(0);
2059 // Top-down walk of the dominator tree
2060 bool Changed = false;
2062 // Needed for value numbering with phi construction to work.
2063 ReversePostOrderTraversal<Function*> RPOT(&F);
2064 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2065 RE = RPOT.end(); RI != RE; ++RI)
2066 Changed |= processBlock(*RI);
2068 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2069 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
2070 Changed |= processBlock(DI->getBlock());
2076 void GVN::cleanupGlobalSets() {
2080 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2081 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
2086 /// verifyRemoved - Verify that the specified instruction does not occur in our
2087 /// internal data structures.
2088 void GVN::verifyRemoved(const Instruction *Inst) const {
2089 VN.verifyRemoved(Inst);
2091 // Walk through the PHI map to make sure the instruction isn't hiding in there
2093 for (PhiMapType::iterator
2094 I = phiMap.begin(), E = phiMap.end(); I != E; ++I) {
2095 assert(I->first != Inst && "Inst is still a key in PHI map!");
2097 for (SmallPtrSet<Instruction*, 4>::iterator
2098 II = I->second.begin(), IE = I->second.end(); II != IE; ++II) {
2099 assert(*II != Inst && "Inst is still a value in PHI map!");
2103 // Walk through the value number scope to make sure the instruction isn't
2104 // ferreted away in it.
2105 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2106 I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
2107 const ValueNumberScope *VNS = I->second;
2110 for (DenseMap<uint32_t, Value*>::iterator
2111 II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
2112 assert(II->second != Inst && "Inst still in value numbering scope!");