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/Value.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/PostOrderIterator.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/Dominators.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/Local.h"
45 STATISTIC(NumGVNInstr, "Number of instructions deleted");
46 STATISTIC(NumGVNLoad, "Number of loads deleted");
47 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
48 STATISTIC(NumGVNBlocks, "Number of blocks merged");
49 STATISTIC(NumPRELoad, "Number of loads PRE'd");
51 static cl::opt<bool> EnablePRE("enable-pre",
52 cl::init(true), cl::Hidden);
53 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 /// This class holds the mapping between values and value numbers. It is used
60 /// as an efficient mechanism to determine the expression-wise equivalence of
63 struct VISIBILITY_HIDDEN Expression {
64 enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
65 UDIV, SDIV, FDIV, UREM, SREM,
66 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
67 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
68 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
69 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
70 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
71 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
72 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
73 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
74 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
77 ExpressionOpcode opcode;
82 SmallVector<uint32_t, 4> varargs;
86 Expression(ExpressionOpcode o) : opcode(o) { }
88 bool operator==(const Expression &other) const {
89 if (opcode != other.opcode)
91 else if (opcode == EMPTY || opcode == TOMBSTONE)
93 else if (type != other.type)
95 else if (function != other.function)
97 else if (firstVN != other.firstVN)
99 else if (secondVN != other.secondVN)
101 else if (thirdVN != other.thirdVN)
104 if (varargs.size() != other.varargs.size())
107 for (size_t i = 0; i < varargs.size(); ++i)
108 if (varargs[i] != other.varargs[i])
115 bool operator!=(const Expression &other) const {
116 return !(*this == other);
120 class VISIBILITY_HIDDEN ValueTable {
122 DenseMap<Value*, uint32_t> valueNumbering;
123 DenseMap<Expression, uint32_t> expressionNumbering;
125 MemoryDependenceAnalysis* MD;
128 uint32_t nextValueNumber;
130 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
131 Expression::ExpressionOpcode getOpcode(CmpInst* C);
132 Expression::ExpressionOpcode getOpcode(CastInst* C);
133 Expression create_expression(BinaryOperator* BO);
134 Expression create_expression(CmpInst* C);
135 Expression create_expression(ShuffleVectorInst* V);
136 Expression create_expression(ExtractElementInst* C);
137 Expression create_expression(InsertElementInst* V);
138 Expression create_expression(SelectInst* V);
139 Expression create_expression(CastInst* C);
140 Expression create_expression(GetElementPtrInst* G);
141 Expression create_expression(CallInst* C);
142 Expression create_expression(Constant* C);
144 ValueTable() : nextValueNumber(1) { }
145 uint32_t lookup_or_add(Value* V);
146 uint32_t lookup(Value* V) const;
147 void add(Value* V, uint32_t num);
149 void erase(Value* v);
151 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
152 AliasAnalysis *getAliasAnalysis() const { return AA; }
153 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
154 void setDomTree(DominatorTree* D) { DT = D; }
155 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
156 void verifyRemoved(const Value *) const;
161 template <> struct DenseMapInfo<Expression> {
162 static inline Expression getEmptyKey() {
163 return Expression(Expression::EMPTY);
166 static inline Expression getTombstoneKey() {
167 return Expression(Expression::TOMBSTONE);
170 static unsigned getHashValue(const Expression e) {
171 unsigned hash = e.opcode;
173 hash = e.firstVN + hash * 37;
174 hash = e.secondVN + hash * 37;
175 hash = e.thirdVN + hash * 37;
177 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
178 (unsigned)((uintptr_t)e.type >> 9)) +
181 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
182 E = e.varargs.end(); I != E; ++I)
183 hash = *I + hash * 37;
185 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
186 (unsigned)((uintptr_t)e.function >> 9)) +
191 static bool isEqual(const Expression &LHS, const Expression &RHS) {
194 static bool isPod() { return true; }
198 //===----------------------------------------------------------------------===//
199 // ValueTable Internal Functions
200 //===----------------------------------------------------------------------===//
201 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
202 switch(BO->getOpcode()) {
203 default: // THIS SHOULD NEVER HAPPEN
204 assert(0 && "Binary operator with unknown opcode?");
205 case Instruction::Add: return Expression::ADD;
206 case Instruction::FAdd: return Expression::FADD;
207 case Instruction::Sub: return Expression::SUB;
208 case Instruction::FSub: return Expression::FSUB;
209 case Instruction::Mul: return Expression::MUL;
210 case Instruction::FMul: return Expression::FMUL;
211 case Instruction::UDiv: return Expression::UDIV;
212 case Instruction::SDiv: return Expression::SDIV;
213 case Instruction::FDiv: return Expression::FDIV;
214 case Instruction::URem: return Expression::UREM;
215 case Instruction::SRem: return Expression::SREM;
216 case Instruction::FRem: return Expression::FREM;
217 case Instruction::Shl: return Expression::SHL;
218 case Instruction::LShr: return Expression::LSHR;
219 case Instruction::AShr: return Expression::ASHR;
220 case Instruction::And: return Expression::AND;
221 case Instruction::Or: return Expression::OR;
222 case Instruction::Xor: return Expression::XOR;
226 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
227 if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
228 switch (C->getPredicate()) {
229 default: // THIS SHOULD NEVER HAPPEN
230 assert(0 && "Comparison with unknown predicate?");
231 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
232 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
233 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
234 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
235 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
236 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
237 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
238 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
239 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
240 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
243 assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
244 switch (C->getPredicate()) {
245 default: // THIS SHOULD NEVER HAPPEN
246 assert(0 && "Comparison with unknown predicate?");
247 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
248 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
249 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
250 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
251 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
252 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
253 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
254 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
255 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
256 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
257 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
258 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
259 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
260 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
264 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
265 switch(C->getOpcode()) {
266 default: // THIS SHOULD NEVER HAPPEN
267 assert(0 && "Cast operator with unknown opcode?");
268 case Instruction::Trunc: return Expression::TRUNC;
269 case Instruction::ZExt: return Expression::ZEXT;
270 case Instruction::SExt: return Expression::SEXT;
271 case Instruction::FPToUI: return Expression::FPTOUI;
272 case Instruction::FPToSI: return Expression::FPTOSI;
273 case Instruction::UIToFP: return Expression::UITOFP;
274 case Instruction::SIToFP: return Expression::SITOFP;
275 case Instruction::FPTrunc: return Expression::FPTRUNC;
276 case Instruction::FPExt: return Expression::FPEXT;
277 case Instruction::PtrToInt: return Expression::PTRTOINT;
278 case Instruction::IntToPtr: return Expression::INTTOPTR;
279 case Instruction::BitCast: return Expression::BITCAST;
283 Expression ValueTable::create_expression(CallInst* C) {
286 e.type = C->getType();
290 e.function = C->getCalledFunction();
291 e.opcode = Expression::CALL;
293 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
295 e.varargs.push_back(lookup_or_add(*I));
300 Expression ValueTable::create_expression(BinaryOperator* BO) {
303 e.firstVN = lookup_or_add(BO->getOperand(0));
304 e.secondVN = lookup_or_add(BO->getOperand(1));
307 e.type = BO->getType();
308 e.opcode = getOpcode(BO);
313 Expression ValueTable::create_expression(CmpInst* C) {
316 e.firstVN = lookup_or_add(C->getOperand(0));
317 e.secondVN = lookup_or_add(C->getOperand(1));
320 e.type = C->getType();
321 e.opcode = getOpcode(C);
326 Expression ValueTable::create_expression(CastInst* C) {
329 e.firstVN = lookup_or_add(C->getOperand(0));
333 e.type = C->getType();
334 e.opcode = getOpcode(C);
339 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
342 e.firstVN = lookup_or_add(S->getOperand(0));
343 e.secondVN = lookup_or_add(S->getOperand(1));
344 e.thirdVN = lookup_or_add(S->getOperand(2));
346 e.type = S->getType();
347 e.opcode = Expression::SHUFFLE;
352 Expression ValueTable::create_expression(ExtractElementInst* E) {
355 e.firstVN = lookup_or_add(E->getOperand(0));
356 e.secondVN = lookup_or_add(E->getOperand(1));
359 e.type = E->getType();
360 e.opcode = Expression::EXTRACT;
365 Expression ValueTable::create_expression(InsertElementInst* I) {
368 e.firstVN = lookup_or_add(I->getOperand(0));
369 e.secondVN = lookup_or_add(I->getOperand(1));
370 e.thirdVN = lookup_or_add(I->getOperand(2));
372 e.type = I->getType();
373 e.opcode = Expression::INSERT;
378 Expression ValueTable::create_expression(SelectInst* I) {
381 e.firstVN = lookup_or_add(I->getCondition());
382 e.secondVN = lookup_or_add(I->getTrueValue());
383 e.thirdVN = lookup_or_add(I->getFalseValue());
385 e.type = I->getType();
386 e.opcode = Expression::SELECT;
391 Expression ValueTable::create_expression(GetElementPtrInst* G) {
394 e.firstVN = lookup_or_add(G->getPointerOperand());
398 e.type = G->getType();
399 e.opcode = Expression::GEP;
401 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
403 e.varargs.push_back(lookup_or_add(*I));
408 //===----------------------------------------------------------------------===//
409 // ValueTable External Functions
410 //===----------------------------------------------------------------------===//
412 /// add - Insert a value into the table with a specified value number.
413 void ValueTable::add(Value* V, uint32_t num) {
414 valueNumbering.insert(std::make_pair(V, num));
417 /// lookup_or_add - Returns the value number for the specified value, assigning
418 /// it a new number if it did not have one before.
419 uint32_t ValueTable::lookup_or_add(Value* V) {
420 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
421 if (VI != valueNumbering.end())
424 if (CallInst* C = dyn_cast<CallInst>(V)) {
425 if (AA->doesNotAccessMemory(C)) {
426 Expression e = create_expression(C);
428 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
429 if (EI != expressionNumbering.end()) {
430 valueNumbering.insert(std::make_pair(V, EI->second));
433 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
434 valueNumbering.insert(std::make_pair(V, nextValueNumber));
436 return nextValueNumber++;
438 } else if (AA->onlyReadsMemory(C)) {
439 Expression e = create_expression(C);
441 if (expressionNumbering.find(e) == expressionNumbering.end()) {
442 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
443 valueNumbering.insert(std::make_pair(V, nextValueNumber));
444 return nextValueNumber++;
447 MemDepResult local_dep = MD->getDependency(C);
449 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
450 valueNumbering.insert(std::make_pair(V, nextValueNumber));
451 return nextValueNumber++;
454 if (local_dep.isDef()) {
455 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
457 if (local_cdep->getNumOperands() != C->getNumOperands()) {
458 valueNumbering.insert(std::make_pair(V, nextValueNumber));
459 return nextValueNumber++;
462 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
463 uint32_t c_vn = lookup_or_add(C->getOperand(i));
464 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
466 valueNumbering.insert(std::make_pair(V, nextValueNumber));
467 return nextValueNumber++;
471 uint32_t v = lookup_or_add(local_cdep);
472 valueNumbering.insert(std::make_pair(V, v));
477 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
478 MD->getNonLocalCallDependency(CallSite(C));
479 // FIXME: call/call dependencies for readonly calls should return def, not
480 // clobber! Move the checking logic to MemDep!
483 // Check to see if we have a single dominating call instruction that is
485 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
486 const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
487 // Ignore non-local dependencies.
488 if (I->second.isNonLocal())
491 // We don't handle non-depedencies. If we already have a call, reject
492 // instruction dependencies.
493 if (I->second.isClobber() || cdep != 0) {
498 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
499 // FIXME: All duplicated with non-local case.
500 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
501 cdep = NonLocalDepCall;
510 valueNumbering.insert(std::make_pair(V, nextValueNumber));
511 return nextValueNumber++;
514 if (cdep->getNumOperands() != C->getNumOperands()) {
515 valueNumbering.insert(std::make_pair(V, nextValueNumber));
516 return nextValueNumber++;
518 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
519 uint32_t c_vn = lookup_or_add(C->getOperand(i));
520 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
522 valueNumbering.insert(std::make_pair(V, nextValueNumber));
523 return nextValueNumber++;
527 uint32_t v = lookup_or_add(cdep);
528 valueNumbering.insert(std::make_pair(V, v));
532 valueNumbering.insert(std::make_pair(V, nextValueNumber));
533 return nextValueNumber++;
535 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
536 Expression e = create_expression(BO);
538 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
539 if (EI != expressionNumbering.end()) {
540 valueNumbering.insert(std::make_pair(V, EI->second));
543 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
544 valueNumbering.insert(std::make_pair(V, nextValueNumber));
546 return nextValueNumber++;
548 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
549 Expression e = create_expression(C);
551 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
552 if (EI != expressionNumbering.end()) {
553 valueNumbering.insert(std::make_pair(V, EI->second));
556 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
557 valueNumbering.insert(std::make_pair(V, nextValueNumber));
559 return nextValueNumber++;
561 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
562 Expression e = create_expression(U);
564 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
565 if (EI != expressionNumbering.end()) {
566 valueNumbering.insert(std::make_pair(V, EI->second));
569 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
570 valueNumbering.insert(std::make_pair(V, nextValueNumber));
572 return nextValueNumber++;
574 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
575 Expression e = create_expression(U);
577 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
578 if (EI != expressionNumbering.end()) {
579 valueNumbering.insert(std::make_pair(V, EI->second));
582 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
583 valueNumbering.insert(std::make_pair(V, nextValueNumber));
585 return nextValueNumber++;
587 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
588 Expression e = create_expression(U);
590 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
591 if (EI != expressionNumbering.end()) {
592 valueNumbering.insert(std::make_pair(V, EI->second));
595 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
596 valueNumbering.insert(std::make_pair(V, nextValueNumber));
598 return nextValueNumber++;
600 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
601 Expression e = create_expression(U);
603 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
604 if (EI != expressionNumbering.end()) {
605 valueNumbering.insert(std::make_pair(V, EI->second));
608 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
609 valueNumbering.insert(std::make_pair(V, nextValueNumber));
611 return nextValueNumber++;
613 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
614 Expression e = create_expression(U);
616 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
617 if (EI != expressionNumbering.end()) {
618 valueNumbering.insert(std::make_pair(V, EI->second));
621 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
622 valueNumbering.insert(std::make_pair(V, nextValueNumber));
624 return nextValueNumber++;
626 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
627 Expression e = create_expression(U);
629 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
630 if (EI != expressionNumbering.end()) {
631 valueNumbering.insert(std::make_pair(V, EI->second));
634 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
635 valueNumbering.insert(std::make_pair(V, nextValueNumber));
637 return nextValueNumber++;
640 valueNumbering.insert(std::make_pair(V, nextValueNumber));
641 return nextValueNumber++;
645 /// lookup - Returns the value number of the specified value. Fails if
646 /// the value has not yet been numbered.
647 uint32_t ValueTable::lookup(Value* V) const {
648 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
649 assert(VI != valueNumbering.end() && "Value not numbered?");
653 /// clear - Remove all entries from the ValueTable
654 void ValueTable::clear() {
655 valueNumbering.clear();
656 expressionNumbering.clear();
660 /// erase - Remove a value from the value numbering
661 void ValueTable::erase(Value* V) {
662 valueNumbering.erase(V);
665 /// verifyRemoved - Verify that the value is removed from all internal data
667 void ValueTable::verifyRemoved(const Value *V) const {
668 for (DenseMap<Value*, uint32_t>::iterator
669 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
670 assert(I->first != V && "Inst still occurs in value numbering map!");
674 //===----------------------------------------------------------------------===//
676 //===----------------------------------------------------------------------===//
679 struct VISIBILITY_HIDDEN ValueNumberScope {
680 ValueNumberScope* parent;
681 DenseMap<uint32_t, Value*> table;
683 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
689 class VISIBILITY_HIDDEN GVN : public FunctionPass {
690 bool runOnFunction(Function &F);
692 static char ID; // Pass identification, replacement for typeid
693 GVN() : FunctionPass(&ID) { }
696 MemoryDependenceAnalysis *MD;
700 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
702 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
706 // This transformation requires dominator postdominator info
707 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
708 AU.addRequired<DominatorTree>();
709 AU.addRequired<MemoryDependenceAnalysis>();
710 AU.addRequired<AliasAnalysis>();
712 AU.addPreserved<DominatorTree>();
713 AU.addPreserved<AliasAnalysis>();
717 // FIXME: eliminate or document these better
718 bool processLoad(LoadInst* L,
719 SmallVectorImpl<Instruction*> &toErase);
720 bool processInstruction(Instruction* I,
721 SmallVectorImpl<Instruction*> &toErase);
722 bool processNonLocalLoad(LoadInst* L,
723 SmallVectorImpl<Instruction*> &toErase);
724 bool processBlock(BasicBlock* BB);
725 Value *GetValueForBlock(BasicBlock *BB, Instruction* orig,
726 DenseMap<BasicBlock*, Value*> &Phis,
727 bool top_level = false);
728 void dump(DenseMap<uint32_t, Value*>& d);
729 bool iterateOnFunction(Function &F);
730 Value* CollapsePhi(PHINode* p);
731 bool isSafeReplacement(PHINode* p, Instruction* inst);
732 bool performPRE(Function& F);
733 Value* lookupNumber(BasicBlock* BB, uint32_t num);
734 bool mergeBlockIntoPredecessor(BasicBlock* BB);
735 Value* AttemptRedundancyElimination(Instruction* orig, unsigned valno);
736 void cleanupGlobalSets();
737 void verifyRemoved(const Instruction *I) const;
743 // createGVNPass - The public interface to this file...
744 FunctionPass *llvm::createGVNPass() { return new GVN(); }
746 static RegisterPass<GVN> X("gvn",
747 "Global Value Numbering");
749 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
751 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
752 E = d.end(); I != E; ++I) {
753 printf("%d\n", I->first);
759 Value* GVN::CollapsePhi(PHINode* p) {
760 Value* constVal = p->hasConstantValue();
761 if (!constVal) return 0;
763 Instruction* inst = dyn_cast<Instruction>(constVal);
767 if (DT->dominates(inst, p))
768 if (isSafeReplacement(p, inst))
773 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
774 if (!isa<PHINode>(inst))
777 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
779 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
780 if (use_phi->getParent() == inst->getParent())
786 /// GetValueForBlock - Get the value to use within the specified basic block.
787 /// available values are in Phis.
788 Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction* orig,
789 DenseMap<BasicBlock*, Value*> &Phis,
792 // If we have already computed this value, return the previously computed val.
793 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
794 if (V != Phis.end() && !top_level) return V->second;
796 // If the block is unreachable, just return undef, since this path
797 // can't actually occur at runtime.
798 if (!DT->isReachableFromEntry(BB))
799 return Phis[BB] = Context->getUndef(orig->getType());
801 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
802 Value *ret = GetValueForBlock(Pred, orig, Phis);
807 // Get the number of predecessors of this block so we can reserve space later.
808 // If there is already a PHI in it, use the #preds from it, otherwise count.
809 // Getting it from the PHI is constant time.
811 if (PHINode *ExistingPN = dyn_cast<PHINode>(BB->begin()))
812 NumPreds = ExistingPN->getNumIncomingValues();
814 NumPreds = std::distance(pred_begin(BB), pred_end(BB));
816 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
817 // now, then get values to fill in the incoming values for the PHI.
818 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
820 PN->reserveOperandSpace(NumPreds);
822 Phis.insert(std::make_pair(BB, PN));
824 // Fill in the incoming values for the block.
825 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
826 Value* val = GetValueForBlock(*PI, orig, Phis);
827 PN->addIncoming(val, *PI);
830 VN.getAliasAnalysis()->copyValue(orig, PN);
832 // Attempt to collapse PHI nodes that are trivially redundant
833 Value* v = CollapsePhi(PN);
835 // Cache our phi construction results
836 if (LoadInst* L = dyn_cast<LoadInst>(orig))
837 phiMap[L->getPointerOperand()].insert(PN);
839 phiMap[orig].insert(PN);
844 PN->replaceAllUsesWith(v);
845 if (isa<PointerType>(v->getType()))
846 MD->invalidateCachedPointerInfo(v);
848 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
849 E = Phis.end(); I != E; ++I)
853 DEBUG(cerr << "GVN removed: " << *PN);
854 MD->removeInstruction(PN);
855 PN->eraseFromParent();
856 DEBUG(verifyRemoved(PN));
862 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
863 /// we're analyzing is fully available in the specified block. As we go, keep
864 /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
865 /// map is actually a tri-state map with the following values:
866 /// 0) we know the block *is not* fully available.
867 /// 1) we know the block *is* fully available.
868 /// 2) we do not know whether the block is fully available or not, but we are
869 /// currently speculating that it will be.
870 /// 3) we are speculating for this block and have used that to speculate for
872 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
873 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
874 // Optimistically assume that the block is fully available and check to see
875 // if we already know about this block in one lookup.
876 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
877 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
879 // If the entry already existed for this block, return the precomputed value.
881 // If this is a speculative "available" value, mark it as being used for
882 // speculation of other blocks.
883 if (IV.first->second == 2)
884 IV.first->second = 3;
885 return IV.first->second != 0;
888 // Otherwise, see if it is fully available in all predecessors.
889 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
891 // If this block has no predecessors, it isn't live-in here.
893 goto SpeculationFailure;
895 for (; PI != PE; ++PI)
896 // If the value isn't fully available in one of our predecessors, then it
897 // isn't fully available in this block either. Undo our previous
898 // optimistic assumption and bail out.
899 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
900 goto SpeculationFailure;
904 // SpeculationFailure - If we get here, we found out that this is not, after
905 // all, a fully-available block. We have a problem if we speculated on this and
906 // used the speculation to mark other blocks as available.
908 char &BBVal = FullyAvailableBlocks[BB];
910 // If we didn't speculate on this, just return with it set to false.
916 // If we did speculate on this value, we could have blocks set to 1 that are
917 // incorrect. Walk the (transitive) successors of this block and mark them as
919 SmallVector<BasicBlock*, 32> BBWorklist;
920 BBWorklist.push_back(BB);
922 while (!BBWorklist.empty()) {
923 BasicBlock *Entry = BBWorklist.pop_back_val();
924 // Note that this sets blocks to 0 (unavailable) if they happen to not
925 // already be in FullyAvailableBlocks. This is safe.
926 char &EntryVal = FullyAvailableBlocks[Entry];
927 if (EntryVal == 0) continue; // Already unavailable.
929 // Mark as unavailable.
932 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
933 BBWorklist.push_back(*I);
939 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
940 /// non-local by performing PHI construction.
941 bool GVN::processNonLocalLoad(LoadInst *LI,
942 SmallVectorImpl<Instruction*> &toErase) {
943 // Find the non-local dependencies of the load.
944 SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
945 MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
947 //DEBUG(cerr << "INVESTIGATING NONLOCAL LOAD: " << Deps.size() << *LI);
949 // If we had to process more than one hundred blocks to find the
950 // dependencies, this load isn't worth worrying about. Optimizing
951 // it will be too expensive.
952 if (Deps.size() > 100)
955 // If we had a phi translation failure, we'll have a single entry which is a
956 // clobber in the current block. Reject this early.
957 if (Deps.size() == 1 && Deps[0].second.isClobber()) {
959 DOUT << "GVN: non-local load ";
960 WriteAsOperand(*DOUT.stream(), LI);
961 DOUT << " is clobbered by " << *Deps[0].second.getInst();
966 // Filter out useless results (non-locals, etc). Keep track of the blocks
967 // where we have a value available in repl, also keep track of whether we see
968 // dependencies that produce an unknown value for the load (such as a call
969 // that could potentially clobber the load).
970 SmallVector<std::pair<BasicBlock*, Value*>, 16> ValuesPerBlock;
971 SmallVector<BasicBlock*, 16> UnavailableBlocks;
973 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
974 BasicBlock *DepBB = Deps[i].first;
975 MemDepResult DepInfo = Deps[i].second;
977 if (DepInfo.isClobber()) {
978 UnavailableBlocks.push_back(DepBB);
982 Instruction *DepInst = DepInfo.getInst();
984 // Loading the allocation -> undef.
985 if (isa<AllocationInst>(DepInst)) {
986 ValuesPerBlock.push_back(std::make_pair(DepBB,
987 Context->getUndef(LI->getType())));
991 if (StoreInst* S = dyn_cast<StoreInst>(DepInst)) {
992 // Reject loads and stores that are to the same address but are of
994 // NOTE: 403.gcc does have this case (e.g. in readonly_fields_p) because
995 // of bitfield access, it would be interesting to optimize for it at some
997 if (S->getOperand(0)->getType() != LI->getType()) {
998 UnavailableBlocks.push_back(DepBB);
1002 ValuesPerBlock.push_back(std::make_pair(DepBB, S->getOperand(0)));
1004 } else if (LoadInst* LD = dyn_cast<LoadInst>(DepInst)) {
1005 if (LD->getType() != LI->getType()) {
1006 UnavailableBlocks.push_back(DepBB);
1009 ValuesPerBlock.push_back(std::make_pair(DepBB, LD));
1011 UnavailableBlocks.push_back(DepBB);
1016 // If we have no predecessors that produce a known value for this load, exit
1018 if (ValuesPerBlock.empty()) return false;
1020 // If all of the instructions we depend on produce a known value for this
1021 // load, then it is fully redundant and we can use PHI insertion to compute
1022 // its value. Insert PHIs and remove the fully redundant value now.
1023 if (UnavailableBlocks.empty()) {
1024 // Use cached PHI construction information from previous runs
1025 SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1026 // FIXME: What does phiMap do? Are we positive it isn't getting invalidated?
1027 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1029 if ((*I)->getParent() == LI->getParent()) {
1030 DEBUG(cerr << "GVN REMOVING NONLOCAL LOAD #1: " << *LI);
1031 LI->replaceAllUsesWith(*I);
1032 if (isa<PointerType>((*I)->getType()))
1033 MD->invalidateCachedPointerInfo(*I);
1034 toErase.push_back(LI);
1039 ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I));
1042 DEBUG(cerr << "GVN REMOVING NONLOCAL LOAD: " << *LI);
1044 DenseMap<BasicBlock*, Value*> BlockReplValues;
1045 BlockReplValues.insert(ValuesPerBlock.begin(), ValuesPerBlock.end());
1046 // Perform PHI construction.
1047 Value* v = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1048 LI->replaceAllUsesWith(v);
1050 if (isa<PHINode>(v))
1052 if (isa<PointerType>(v->getType()))
1053 MD->invalidateCachedPointerInfo(v);
1054 toErase.push_back(LI);
1059 if (!EnablePRE || !EnableLoadPRE)
1062 // Okay, we have *some* definitions of the value. This means that the value
1063 // is available in some of our (transitive) predecessors. Lets think about
1064 // doing PRE of this load. This will involve inserting a new load into the
1065 // predecessor when it's not available. We could do this in general, but
1066 // prefer to not increase code size. As such, we only do this when we know
1067 // that we only have to insert *one* load (which means we're basically moving
1068 // the load, not inserting a new one).
1070 SmallPtrSet<BasicBlock *, 4> Blockers;
1071 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1072 Blockers.insert(UnavailableBlocks[i]);
1074 // Lets find first basic block with more than one predecessor. Walk backwards
1075 // through predecessors if needed.
1076 BasicBlock *LoadBB = LI->getParent();
1077 BasicBlock *TmpBB = LoadBB;
1079 bool isSinglePred = false;
1080 bool allSingleSucc = true;
1081 while (TmpBB->getSinglePredecessor()) {
1082 isSinglePred = true;
1083 TmpBB = TmpBB->getSinglePredecessor();
1084 if (!TmpBB) // If haven't found any, bail now.
1086 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1088 if (Blockers.count(TmpBB))
1090 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1091 allSingleSucc = false;
1097 // If we have a repl set with LI itself in it, this means we have a loop where
1098 // at least one of the values is LI. Since this means that we won't be able
1099 // to eliminate LI even if we insert uses in the other predecessors, we will
1100 // end up increasing code size. Reject this by scanning for LI.
1101 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1102 if (ValuesPerBlock[i].second == LI)
1107 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1108 if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].second))
1109 // "Hot" Instruction is in some loop (because it dominates its dep.
1111 if (DT->dominates(LI, I)) {
1116 // We are interested only in "hot" instructions. We don't want to do any
1117 // mis-optimizations here.
1122 // Okay, we have some hope :). Check to see if the loaded value is fully
1123 // available in all but one predecessor.
1124 // FIXME: If we could restructure the CFG, we could make a common pred with
1125 // all the preds that don't have an available LI and insert a new load into
1127 BasicBlock *UnavailablePred = 0;
1129 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1130 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1131 FullyAvailableBlocks[ValuesPerBlock[i].first] = true;
1132 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1133 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1135 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1137 if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1140 // If this load is not available in multiple predecessors, reject it.
1141 if (UnavailablePred && UnavailablePred != *PI)
1143 UnavailablePred = *PI;
1146 assert(UnavailablePred != 0 &&
1147 "Fully available value should be eliminated above!");
1149 // If the loaded pointer is PHI node defined in this block, do PHI translation
1150 // to get its value in the predecessor.
1151 Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
1153 // Make sure the value is live in the predecessor. If it was defined by a
1154 // non-PHI instruction in this block, we don't know how to recompute it above.
1155 if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1156 if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
1157 DEBUG(cerr << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
1158 << *LPInst << *LI << "\n");
1162 // We don't currently handle critical edges :(
1163 if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
1164 DEBUG(cerr << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
1165 << UnavailablePred->getName() << "': " << *LI);
1169 // Make sure it is valid to move this load here. We have to watch out for:
1170 // @1 = getelementptr (i8* p, ...
1171 // test p and branch if == 0
1173 // It is valid to have the getelementptr before the test, even if p can be 0,
1174 // as getelementptr only does address arithmetic.
1175 // If we are not pushing the value through any multiple-successor blocks
1176 // we do not have this case. Otherwise, check that the load is safe to
1177 // put anywhere; this can be improved, but should be conservatively safe.
1178 if (!allSingleSucc &&
1179 !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1182 // Okay, we can eliminate this load by inserting a reload in the predecessor
1183 // and using PHI construction to get the value in the other predecessors, do
1185 DEBUG(cerr << "GVN REMOVING PRE LOAD: " << *LI);
1187 Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1189 UnavailablePred->getTerminator());
1191 SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1192 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1194 ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I));
1196 DenseMap<BasicBlock*, Value*> BlockReplValues;
1197 BlockReplValues.insert(ValuesPerBlock.begin(), ValuesPerBlock.end());
1198 BlockReplValues[UnavailablePred] = NewLoad;
1200 // Perform PHI construction.
1201 Value* v = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1202 LI->replaceAllUsesWith(v);
1203 if (isa<PHINode>(v))
1205 if (isa<PointerType>(v->getType()))
1206 MD->invalidateCachedPointerInfo(v);
1207 toErase.push_back(LI);
1212 /// processLoad - Attempt to eliminate a load, first by eliminating it
1213 /// locally, and then attempting non-local elimination if that fails.
1214 bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1215 if (L->isVolatile())
1218 Value* pointer = L->getPointerOperand();
1220 // ... to a pointer that has been loaded from before...
1221 MemDepResult dep = MD->getDependency(L);
1223 // If the value isn't available, don't do anything!
1224 if (dep.isClobber()) {
1226 // fast print dep, using operator<< on instruction would be too slow
1227 DOUT << "GVN: load ";
1228 WriteAsOperand(*DOUT.stream(), L);
1229 Instruction *I = dep.getInst();
1230 DOUT << " is clobbered by " << *I;
1235 // If it is defined in another block, try harder.
1236 if (dep.isNonLocal())
1237 return processNonLocalLoad(L, toErase);
1239 Instruction *DepInst = dep.getInst();
1240 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1241 // Only forward substitute stores to loads of the same type.
1242 // FIXME: Could do better!
1243 if (DepSI->getPointerOperand()->getType() != pointer->getType())
1247 L->replaceAllUsesWith(DepSI->getOperand(0));
1248 if (isa<PointerType>(DepSI->getOperand(0)->getType()))
1249 MD->invalidateCachedPointerInfo(DepSI->getOperand(0));
1250 toErase.push_back(L);
1255 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1256 // Only forward substitute stores to loads of the same type.
1257 // FIXME: Could do better! load i32 -> load i8 -> truncate on little endian.
1258 if (DepLI->getType() != L->getType())
1262 L->replaceAllUsesWith(DepLI);
1263 if (isa<PointerType>(DepLI->getType()))
1264 MD->invalidateCachedPointerInfo(DepLI);
1265 toErase.push_back(L);
1270 // If this load really doesn't depend on anything, then we must be loading an
1271 // undef value. This can happen when loading for a fresh allocation with no
1272 // intervening stores, for example.
1273 if (isa<AllocationInst>(DepInst)) {
1274 L->replaceAllUsesWith(Context->getUndef(L->getType()));
1275 toErase.push_back(L);
1283 Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) {
1284 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1285 if (I == localAvail.end())
1288 ValueNumberScope* locals = I->second;
1291 DenseMap<uint32_t, Value*>::iterator I = locals->table.find(num);
1292 if (I != locals->table.end())
1295 locals = locals->parent;
1301 /// AttemptRedundancyElimination - If the "fast path" of redundancy elimination
1302 /// by inheritance from the dominator fails, see if we can perform phi
1303 /// construction to eliminate the redundancy.
1304 Value* GVN::AttemptRedundancyElimination(Instruction* orig, unsigned valno) {
1305 BasicBlock* BaseBlock = orig->getParent();
1307 SmallPtrSet<BasicBlock*, 4> Visited;
1308 SmallVector<BasicBlock*, 8> Stack;
1309 Stack.push_back(BaseBlock);
1311 DenseMap<BasicBlock*, Value*> Results;
1313 // Walk backwards through our predecessors, looking for instances of the
1314 // value number we're looking for. Instances are recorded in the Results
1315 // map, which is then used to perform phi construction.
1316 while (!Stack.empty()) {
1317 BasicBlock* Current = Stack.back();
1320 // If we've walked all the way to a proper dominator, then give up. Cases
1321 // where the instance is in the dominator will have been caught by the fast
1322 // path, and any cases that require phi construction further than this are
1323 // probably not worth it anyways. Note that this is a SIGNIFICANT compile
1324 // time improvement.
1325 if (DT->properlyDominates(Current, orig->getParent())) return 0;
1327 DenseMap<BasicBlock*, ValueNumberScope*>::iterator LA =
1328 localAvail.find(Current);
1329 if (LA == localAvail.end()) return 0;
1330 DenseMap<uint32_t, Value*>::iterator V = LA->second->table.find(valno);
1332 if (V != LA->second->table.end()) {
1333 // Found an instance, record it.
1334 Results.insert(std::make_pair(Current, V->second));
1338 // If we reach the beginning of the function, then give up.
1339 if (pred_begin(Current) == pred_end(Current))
1342 for (pred_iterator PI = pred_begin(Current), PE = pred_end(Current);
1344 if (Visited.insert(*PI))
1345 Stack.push_back(*PI);
1348 // If we didn't find instances, give up. Otherwise, perform phi construction.
1349 if (Results.size() == 0)
1352 return GetValueForBlock(BaseBlock, orig, Results, true);
1355 /// processInstruction - When calculating availability, handle an instruction
1356 /// by inserting it into the appropriate sets
1357 bool GVN::processInstruction(Instruction *I,
1358 SmallVectorImpl<Instruction*> &toErase) {
1359 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1360 bool changed = processLoad(L, toErase);
1363 unsigned num = VN.lookup_or_add(L);
1364 localAvail[I->getParent()]->table.insert(std::make_pair(num, L));
1370 uint32_t nextNum = VN.getNextUnusedValueNumber();
1371 unsigned num = VN.lookup_or_add(I);
1373 if (BranchInst* BI = dyn_cast<BranchInst>(I)) {
1374 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1376 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1379 Value* branchCond = BI->getCondition();
1380 uint32_t condVN = VN.lookup_or_add(branchCond);
1382 BasicBlock* trueSucc = BI->getSuccessor(0);
1383 BasicBlock* falseSucc = BI->getSuccessor(1);
1385 if (trueSucc->getSinglePredecessor())
1386 localAvail[trueSucc]->table[condVN] = Context->getConstantIntTrue();
1387 if (falseSucc->getSinglePredecessor())
1388 localAvail[falseSucc]->table[condVN] = Context->getConstantIntFalse();
1392 // Allocations are always uniquely numbered, so we can save time and memory
1393 // by fast failing them.
1394 } else if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
1395 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1399 // Collapse PHI nodes
1400 if (PHINode* p = dyn_cast<PHINode>(I)) {
1401 Value* constVal = CollapsePhi(p);
1404 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1406 PI->second.erase(p);
1408 p->replaceAllUsesWith(constVal);
1409 if (isa<PointerType>(constVal->getType()))
1410 MD->invalidateCachedPointerInfo(constVal);
1413 toErase.push_back(p);
1415 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1418 // If the number we were assigned was a brand new VN, then we don't
1419 // need to do a lookup to see if the number already exists
1420 // somewhere in the domtree: it can't!
1421 } else if (num == nextNum) {
1422 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1424 // Perform fast-path value-number based elimination of values inherited from
1426 } else if (Value* repl = lookupNumber(I->getParent(), num)) {
1429 I->replaceAllUsesWith(repl);
1430 if (isa<PointerType>(repl->getType()))
1431 MD->invalidateCachedPointerInfo(repl);
1432 toErase.push_back(I);
1436 // Perform slow-pathvalue-number based elimination with phi construction.
1437 } else if (Value* repl = AttemptRedundancyElimination(I, num)) {
1440 I->replaceAllUsesWith(repl);
1441 if (isa<PointerType>(repl->getType()))
1442 MD->invalidateCachedPointerInfo(repl);
1443 toErase.push_back(I);
1447 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1453 /// runOnFunction - This is the main transformation entry point for a function.
1454 bool GVN::runOnFunction(Function& F) {
1455 MD = &getAnalysis<MemoryDependenceAnalysis>();
1456 DT = &getAnalysis<DominatorTree>();
1457 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1461 bool changed = false;
1462 bool shouldContinue = true;
1464 // Merge unconditional branches, allowing PRE to catch more
1465 // optimization opportunities.
1466 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1467 BasicBlock* BB = FI;
1469 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1470 if (removedBlock) NumGVNBlocks++;
1472 changed |= removedBlock;
1475 unsigned Iteration = 0;
1477 while (shouldContinue) {
1478 DEBUG(cerr << "GVN iteration: " << Iteration << "\n");
1479 shouldContinue = iterateOnFunction(F);
1480 changed |= shouldContinue;
1485 bool PREChanged = true;
1486 while (PREChanged) {
1487 PREChanged = performPRE(F);
1488 changed |= PREChanged;
1491 // FIXME: Should perform GVN again after PRE does something. PRE can move
1492 // computations into blocks where they become fully redundant. Note that
1493 // we can't do this until PRE's critical edge splitting updates memdep.
1494 // Actually, when this happens, we should just fully integrate PRE into GVN.
1496 cleanupGlobalSets();
1502 bool GVN::processBlock(BasicBlock* BB) {
1503 // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1504 // incrementing BI before processing an instruction).
1505 SmallVector<Instruction*, 8> toErase;
1506 bool changed_function = false;
1508 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1510 changed_function |= processInstruction(BI, toErase);
1511 if (toErase.empty()) {
1516 // If we need some instructions deleted, do it now.
1517 NumGVNInstr += toErase.size();
1519 // Avoid iterator invalidation.
1520 bool AtStart = BI == BB->begin();
1524 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1525 E = toErase.end(); I != E; ++I) {
1526 DEBUG(cerr << "GVN removed: " << **I);
1527 MD->removeInstruction(*I);
1528 (*I)->eraseFromParent();
1529 DEBUG(verifyRemoved(*I));
1539 return changed_function;
1542 /// performPRE - Perform a purely local form of PRE that looks for diamond
1543 /// control flow patterns and attempts to perform simple PRE at the join point.
1544 bool GVN::performPRE(Function& F) {
1545 bool Changed = false;
1546 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1547 DenseMap<BasicBlock*, Value*> predMap;
1548 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1549 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1550 BasicBlock* CurrentBlock = *DI;
1552 // Nothing to PRE in the entry block.
1553 if (CurrentBlock == &F.getEntryBlock()) continue;
1555 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1556 BE = CurrentBlock->end(); BI != BE; ) {
1557 Instruction *CurInst = BI++;
1559 if (isa<AllocationInst>(CurInst) || isa<TerminatorInst>(CurInst) ||
1560 isa<PHINode>(CurInst) || (CurInst->getType() == Type::VoidTy) ||
1561 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
1562 isa<DbgInfoIntrinsic>(CurInst))
1565 uint32_t valno = VN.lookup(CurInst);
1567 // Look for the predecessors for PRE opportunities. We're
1568 // only trying to solve the basic diamond case, where
1569 // a value is computed in the successor and one predecessor,
1570 // but not the other. We also explicitly disallow cases
1571 // where the successor is its own predecessor, because they're
1572 // more complicated to get right.
1573 unsigned numWith = 0;
1574 unsigned numWithout = 0;
1575 BasicBlock* PREPred = 0;
1578 for (pred_iterator PI = pred_begin(CurrentBlock),
1579 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1580 // We're not interested in PRE where the block is its
1581 // own predecessor, on in blocks with predecessors
1582 // that are not reachable.
1583 if (*PI == CurrentBlock) {
1586 } else if (!localAvail.count(*PI)) {
1591 DenseMap<uint32_t, Value*>::iterator predV =
1592 localAvail[*PI]->table.find(valno);
1593 if (predV == localAvail[*PI]->table.end()) {
1596 } else if (predV->second == CurInst) {
1599 predMap[*PI] = predV->second;
1604 // Don't do PRE when it might increase code size, i.e. when
1605 // we would need to insert instructions in more than one pred.
1606 if (numWithout != 1 || numWith == 0)
1609 // We can't do PRE safely on a critical edge, so instead we schedule
1610 // the edge to be split and perform the PRE the next time we iterate
1612 unsigned succNum = 0;
1613 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1615 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
1620 if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1621 toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1625 // Instantiate the expression the in predecessor that lacked it.
1626 // Because we are going top-down through the block, all value numbers
1627 // will be available in the predecessor by the time we need them. Any
1628 // that weren't original present will have been instantiated earlier
1630 Instruction* PREInstr = CurInst->clone();
1631 bool success = true;
1632 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
1633 Value *Op = PREInstr->getOperand(i);
1634 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
1637 if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
1638 PREInstr->setOperand(i, V);
1645 // Fail out if we encounter an operand that is not available in
1646 // the PRE predecessor. This is typically because of loads which
1647 // are not value numbered precisely.
1650 DEBUG(verifyRemoved(PREInstr));
1654 PREInstr->insertBefore(PREPred->getTerminator());
1655 PREInstr->setName(CurInst->getName() + ".pre");
1656 predMap[PREPred] = PREInstr;
1657 VN.add(PREInstr, valno);
1660 // Update the availability map to include the new instruction.
1661 localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr));
1663 // Create a PHI to make the value available in this block.
1664 PHINode* Phi = PHINode::Create(CurInst->getType(),
1665 CurInst->getName() + ".pre-phi",
1666 CurrentBlock->begin());
1667 for (pred_iterator PI = pred_begin(CurrentBlock),
1668 PE = pred_end(CurrentBlock); PI != PE; ++PI)
1669 Phi->addIncoming(predMap[*PI], *PI);
1672 localAvail[CurrentBlock]->table[valno] = Phi;
1674 CurInst->replaceAllUsesWith(Phi);
1675 if (isa<PointerType>(Phi->getType()))
1676 MD->invalidateCachedPointerInfo(Phi);
1679 DEBUG(cerr << "GVN PRE removed: " << *CurInst);
1680 MD->removeInstruction(CurInst);
1681 CurInst->eraseFromParent();
1682 DEBUG(verifyRemoved(CurInst));
1687 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1688 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1689 SplitCriticalEdge(I->first, I->second, this);
1691 return Changed || toSplit.size();
1694 /// iterateOnFunction - Executes one iteration of GVN
1695 bool GVN::iterateOnFunction(Function &F) {
1696 cleanupGlobalSets();
1698 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1699 DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
1701 localAvail[DI->getBlock()] =
1702 new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
1704 localAvail[DI->getBlock()] = new ValueNumberScope(0);
1707 // Top-down walk of the dominator tree
1708 bool changed = false;
1710 // Needed for value numbering with phi construction to work.
1711 ReversePostOrderTraversal<Function*> RPOT(&F);
1712 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
1713 RE = RPOT.end(); RI != RE; ++RI)
1714 changed |= processBlock(*RI);
1716 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1717 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
1718 changed |= processBlock(DI->getBlock());
1724 void GVN::cleanupGlobalSets() {
1728 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1729 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1734 /// verifyRemoved - Verify that the specified instruction does not occur in our
1735 /// internal data structures.
1736 void GVN::verifyRemoved(const Instruction *Inst) const {
1737 VN.verifyRemoved(Inst);
1739 // Walk through the PHI map to make sure the instruction isn't hiding in there
1741 for (PhiMapType::iterator
1742 I = phiMap.begin(), E = phiMap.end(); I != E; ++I) {
1743 assert(I->first != Inst && "Inst is still a key in PHI map!");
1745 for (SmallPtrSet<Instruction*, 4>::iterator
1746 II = I->second.begin(), IE = I->second.end(); II != IE; ++II) {
1747 assert(*II != Inst && "Inst is still a value in PHI map!");
1751 // Walk through the value number scope to make sure the instruction isn't
1752 // ferreted away in it.
1753 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1754 I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
1755 const ValueNumberScope *VNS = I->second;
1758 for (DenseMap<uint32_t, Value*>::iterator
1759 II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
1760 assert(II->second != Inst && "Inst still in value numbering scope!");