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/GlobalVariable.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/Loads.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
30 #include "llvm/Analysis/PHITransAddr.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetLibraryInfo.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/SSAUpdater.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/DepthFirstIterator.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/IRBuilder.h"
45 #include "llvm/Support/PatternMatch.h"
47 using namespace PatternMatch;
49 STATISTIC(NumGVNInstr, "Number of instructions deleted");
50 STATISTIC(NumGVNLoad, "Number of loads deleted");
51 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
52 STATISTIC(NumGVNBlocks, "Number of blocks merged");
53 STATISTIC(NumGVNSimpl, "Number of instructions simplified");
54 STATISTIC(NumGVNEqProp, "Number of equalities propagated");
55 STATISTIC(NumPRELoad, "Number of loads PRE'd");
57 static cl::opt<bool> EnablePRE("enable-pre",
58 cl::init(true), cl::Hidden);
59 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
61 //===----------------------------------------------------------------------===//
63 //===----------------------------------------------------------------------===//
65 /// This class holds the mapping between values and value numbers. It is used
66 /// as an efficient mechanism to determine the expression-wise equivalence of
72 SmallVector<uint32_t, 4> varargs;
74 Expression(uint32_t o = ~2U) : opcode(o) { }
76 bool operator==(const Expression &other) const {
77 if (opcode != other.opcode)
79 if (opcode == ~0U || opcode == ~1U)
81 if (type != other.type)
83 if (varargs != other.varargs)
90 DenseMap<Value*, uint32_t> valueNumbering;
91 DenseMap<Expression, uint32_t> expressionNumbering;
93 MemoryDependenceAnalysis *MD;
96 uint32_t nextValueNumber;
98 Expression create_expression(Instruction* I);
99 Expression create_extractvalue_expression(ExtractValueInst* EI);
100 uint32_t lookup_or_add_call(CallInst* C);
102 ValueTable() : nextValueNumber(1) { }
103 uint32_t lookup_or_add(Value *V);
104 uint32_t lookup(Value *V) const;
105 void add(Value *V, uint32_t num);
107 void erase(Value *v);
108 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
109 AliasAnalysis *getAliasAnalysis() const { return AA; }
110 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
111 void setDomTree(DominatorTree* D) { DT = D; }
112 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
113 void verifyRemoved(const Value *) const;
118 template <> struct DenseMapInfo<Expression> {
119 static inline Expression getEmptyKey() {
123 static inline Expression getTombstoneKey() {
127 static unsigned getHashValue(const Expression e) {
128 unsigned hash = e.opcode;
130 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
131 (unsigned)((uintptr_t)e.type >> 9));
133 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
134 E = e.varargs.end(); I != E; ++I)
135 hash = *I + hash * 37;
139 static bool isEqual(const Expression &LHS, const Expression &RHS) {
146 //===----------------------------------------------------------------------===//
147 // ValueTable Internal Functions
148 //===----------------------------------------------------------------------===//
150 Expression ValueTable::create_expression(Instruction *I) {
152 e.type = I->getType();
153 e.opcode = I->getOpcode();
154 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
156 e.varargs.push_back(lookup_or_add(*OI));
157 if (I->isCommutative()) {
158 // Ensure that commutative instructions that only differ by a permutation
159 // of their operands get the same value number by sorting the operand value
160 // numbers. Since all commutative instructions have two operands it is more
161 // efficient to sort by hand rather than using, say, std::sort.
162 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
163 if (e.varargs[0] > e.varargs[1])
164 std::swap(e.varargs[0], e.varargs[1]);
167 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
168 // Sort the operand value numbers so x<y and y>x get the same value number.
169 CmpInst::Predicate Predicate = C->getPredicate();
170 if (e.varargs[0] > e.varargs[1]) {
171 std::swap(e.varargs[0], e.varargs[1]);
172 Predicate = CmpInst::getSwappedPredicate(Predicate);
174 e.opcode = (C->getOpcode() << 8) | Predicate;
175 } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
176 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
178 e.varargs.push_back(*II);
184 Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
185 assert(EI != 0 && "Not an ExtractValueInst?");
187 e.type = EI->getType();
190 IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
191 if (I != 0 && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
192 // EI might be an extract from one of our recognised intrinsics. If it
193 // is we'll synthesize a semantically equivalent expression instead on
194 // an extract value expression.
195 switch (I->getIntrinsicID()) {
196 case Intrinsic::sadd_with_overflow:
197 case Intrinsic::uadd_with_overflow:
198 e.opcode = Instruction::Add;
200 case Intrinsic::ssub_with_overflow:
201 case Intrinsic::usub_with_overflow:
202 e.opcode = Instruction::Sub;
204 case Intrinsic::smul_with_overflow:
205 case Intrinsic::umul_with_overflow:
206 e.opcode = Instruction::Mul;
213 // Intrinsic recognized. Grab its args to finish building the expression.
214 assert(I->getNumArgOperands() == 2 &&
215 "Expect two args for recognised intrinsics.");
216 e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
217 e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
222 // Not a recognised intrinsic. Fall back to producing an extract value
224 e.opcode = EI->getOpcode();
225 for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
227 e.varargs.push_back(lookup_or_add(*OI));
229 for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
231 e.varargs.push_back(*II);
236 //===----------------------------------------------------------------------===//
237 // ValueTable External Functions
238 //===----------------------------------------------------------------------===//
240 /// add - Insert a value into the table with a specified value number.
241 void ValueTable::add(Value *V, uint32_t num) {
242 valueNumbering.insert(std::make_pair(V, num));
245 uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
246 if (AA->doesNotAccessMemory(C)) {
247 Expression exp = create_expression(C);
248 uint32_t& e = expressionNumbering[exp];
249 if (!e) e = nextValueNumber++;
250 valueNumbering[C] = e;
252 } else if (AA->onlyReadsMemory(C)) {
253 Expression exp = create_expression(C);
254 uint32_t& e = expressionNumbering[exp];
256 e = nextValueNumber++;
257 valueNumbering[C] = e;
261 e = nextValueNumber++;
262 valueNumbering[C] = e;
266 MemDepResult local_dep = MD->getDependency(C);
268 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
269 valueNumbering[C] = nextValueNumber;
270 return nextValueNumber++;
273 if (local_dep.isDef()) {
274 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
276 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
277 valueNumbering[C] = nextValueNumber;
278 return nextValueNumber++;
281 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
282 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
283 uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
285 valueNumbering[C] = nextValueNumber;
286 return nextValueNumber++;
290 uint32_t v = lookup_or_add(local_cdep);
291 valueNumbering[C] = v;
296 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
297 MD->getNonLocalCallDependency(CallSite(C));
298 // FIXME: Move the checking logic to MemDep!
301 // Check to see if we have a single dominating call instruction that is
303 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
304 const NonLocalDepEntry *I = &deps[i];
305 if (I->getResult().isNonLocal())
308 // We don't handle non-definitions. If we already have a call, reject
309 // instruction dependencies.
310 if (!I->getResult().isDef() || cdep != 0) {
315 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
316 // FIXME: All duplicated with non-local case.
317 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
318 cdep = NonLocalDepCall;
327 valueNumbering[C] = nextValueNumber;
328 return nextValueNumber++;
331 if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
332 valueNumbering[C] = nextValueNumber;
333 return nextValueNumber++;
335 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
336 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
337 uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
339 valueNumbering[C] = nextValueNumber;
340 return nextValueNumber++;
344 uint32_t v = lookup_or_add(cdep);
345 valueNumbering[C] = v;
349 valueNumbering[C] = nextValueNumber;
350 return nextValueNumber++;
354 /// lookup_or_add - Returns the value number for the specified value, assigning
355 /// it a new number if it did not have one before.
356 uint32_t ValueTable::lookup_or_add(Value *V) {
357 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
358 if (VI != valueNumbering.end())
361 if (!isa<Instruction>(V)) {
362 valueNumbering[V] = nextValueNumber;
363 return nextValueNumber++;
366 Instruction* I = cast<Instruction>(V);
368 switch (I->getOpcode()) {
369 case Instruction::Call:
370 return lookup_or_add_call(cast<CallInst>(I));
371 case Instruction::Add:
372 case Instruction::FAdd:
373 case Instruction::Sub:
374 case Instruction::FSub:
375 case Instruction::Mul:
376 case Instruction::FMul:
377 case Instruction::UDiv:
378 case Instruction::SDiv:
379 case Instruction::FDiv:
380 case Instruction::URem:
381 case Instruction::SRem:
382 case Instruction::FRem:
383 case Instruction::Shl:
384 case Instruction::LShr:
385 case Instruction::AShr:
386 case Instruction::And:
387 case Instruction::Or :
388 case Instruction::Xor:
389 case Instruction::ICmp:
390 case Instruction::FCmp:
391 case Instruction::Trunc:
392 case Instruction::ZExt:
393 case Instruction::SExt:
394 case Instruction::FPToUI:
395 case Instruction::FPToSI:
396 case Instruction::UIToFP:
397 case Instruction::SIToFP:
398 case Instruction::FPTrunc:
399 case Instruction::FPExt:
400 case Instruction::PtrToInt:
401 case Instruction::IntToPtr:
402 case Instruction::BitCast:
403 case Instruction::Select:
404 case Instruction::ExtractElement:
405 case Instruction::InsertElement:
406 case Instruction::ShuffleVector:
407 case Instruction::InsertValue:
408 case Instruction::GetElementPtr:
409 exp = create_expression(I);
411 case Instruction::ExtractValue:
412 exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
415 valueNumbering[V] = nextValueNumber;
416 return nextValueNumber++;
419 uint32_t& e = expressionNumbering[exp];
420 if (!e) e = nextValueNumber++;
421 valueNumbering[V] = e;
425 /// lookup - Returns the value number of the specified value. Fails if
426 /// the value has not yet been numbered.
427 uint32_t ValueTable::lookup(Value *V) const {
428 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
429 assert(VI != valueNumbering.end() && "Value not numbered?");
433 /// clear - Remove all entries from the ValueTable.
434 void ValueTable::clear() {
435 valueNumbering.clear();
436 expressionNumbering.clear();
440 /// erase - Remove a value from the value numbering.
441 void ValueTable::erase(Value *V) {
442 valueNumbering.erase(V);
445 /// verifyRemoved - Verify that the value is removed from all internal data
447 void ValueTable::verifyRemoved(const Value *V) const {
448 for (DenseMap<Value*, uint32_t>::const_iterator
449 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
450 assert(I->first != V && "Inst still occurs in value numbering map!");
454 //===----------------------------------------------------------------------===//
456 //===----------------------------------------------------------------------===//
460 class GVN : public FunctionPass {
462 MemoryDependenceAnalysis *MD;
464 const TargetData *TD;
465 const TargetLibraryInfo *TLI;
469 /// LeaderTable - A mapping from value numbers to lists of Value*'s that
470 /// have that value number. Use findLeader to query it.
471 struct LeaderTableEntry {
474 LeaderTableEntry *Next;
476 DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
477 BumpPtrAllocator TableAllocator;
479 SmallVector<Instruction*, 8> InstrsToErase;
481 static char ID; // Pass identification, replacement for typeid
482 explicit GVN(bool noloads = false)
483 : FunctionPass(ID), NoLoads(noloads), MD(0) {
484 initializeGVNPass(*PassRegistry::getPassRegistry());
487 bool runOnFunction(Function &F);
489 /// markInstructionForDeletion - This removes the specified instruction from
490 /// our various maps and marks it for deletion.
491 void markInstructionForDeletion(Instruction *I) {
493 InstrsToErase.push_back(I);
496 const TargetData *getTargetData() const { return TD; }
497 DominatorTree &getDominatorTree() const { return *DT; }
498 AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
499 MemoryDependenceAnalysis &getMemDep() const { return *MD; }
501 /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
502 /// its value number.
503 void addToLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
504 LeaderTableEntry &Curr = LeaderTable[N];
511 LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
514 Node->Next = Curr.Next;
518 /// removeFromLeaderTable - Scan the list of values corresponding to a given
519 /// value number, and remove the given value if encountered.
520 void removeFromLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
521 LeaderTableEntry* Prev = 0;
522 LeaderTableEntry* Curr = &LeaderTable[N];
524 while (Curr->Val != V || Curr->BB != BB) {
530 Prev->Next = Curr->Next;
536 LeaderTableEntry* Next = Curr->Next;
537 Curr->Val = Next->Val;
539 Curr->Next = Next->Next;
544 // List of critical edges to be split between iterations.
545 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
547 // This transformation requires dominator postdominator info
548 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
549 AU.addRequired<DominatorTree>();
550 AU.addRequired<TargetLibraryInfo>();
552 AU.addRequired<MemoryDependenceAnalysis>();
553 AU.addRequired<AliasAnalysis>();
555 AU.addPreserved<DominatorTree>();
556 AU.addPreserved<AliasAnalysis>();
561 // FIXME: eliminate or document these better
562 bool processLoad(LoadInst *L);
563 bool processInstruction(Instruction *I);
564 bool processNonLocalLoad(LoadInst *L);
565 bool processBlock(BasicBlock *BB);
566 void dump(DenseMap<uint32_t, Value*> &d);
567 bool iterateOnFunction(Function &F);
568 bool performPRE(Function &F);
569 Value *findLeader(BasicBlock *BB, uint32_t num);
570 void cleanupGlobalSets();
571 void verifyRemoved(const Instruction *I) const;
572 bool splitCriticalEdges();
573 unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
575 bool propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root);
581 // createGVNPass - The public interface to this file...
582 FunctionPass *llvm::createGVNPass(bool NoLoads) {
583 return new GVN(NoLoads);
586 INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
587 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
588 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
589 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
590 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
591 INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
593 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
595 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
596 E = d.end(); I != E; ++I) {
597 errs() << I->first << "\n";
603 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
604 /// we're analyzing is fully available in the specified block. As we go, keep
605 /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
606 /// map is actually a tri-state map with the following values:
607 /// 0) we know the block *is not* fully available.
608 /// 1) we know the block *is* fully available.
609 /// 2) we do not know whether the block is fully available or not, but we are
610 /// currently speculating that it will be.
611 /// 3) we are speculating for this block and have used that to speculate for
613 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
614 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
615 // Optimistically assume that the block is fully available and check to see
616 // if we already know about this block in one lookup.
617 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
618 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
620 // If the entry already existed for this block, return the precomputed value.
622 // If this is a speculative "available" value, mark it as being used for
623 // speculation of other blocks.
624 if (IV.first->second == 2)
625 IV.first->second = 3;
626 return IV.first->second != 0;
629 // Otherwise, see if it is fully available in all predecessors.
630 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
632 // If this block has no predecessors, it isn't live-in here.
634 goto SpeculationFailure;
636 for (; PI != PE; ++PI)
637 // If the value isn't fully available in one of our predecessors, then it
638 // isn't fully available in this block either. Undo our previous
639 // optimistic assumption and bail out.
640 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
641 goto SpeculationFailure;
645 // SpeculationFailure - If we get here, we found out that this is not, after
646 // all, a fully-available block. We have a problem if we speculated on this and
647 // used the speculation to mark other blocks as available.
649 char &BBVal = FullyAvailableBlocks[BB];
651 // If we didn't speculate on this, just return with it set to false.
657 // If we did speculate on this value, we could have blocks set to 1 that are
658 // incorrect. Walk the (transitive) successors of this block and mark them as
660 SmallVector<BasicBlock*, 32> BBWorklist;
661 BBWorklist.push_back(BB);
664 BasicBlock *Entry = BBWorklist.pop_back_val();
665 // Note that this sets blocks to 0 (unavailable) if they happen to not
666 // already be in FullyAvailableBlocks. This is safe.
667 char &EntryVal = FullyAvailableBlocks[Entry];
668 if (EntryVal == 0) continue; // Already unavailable.
670 // Mark as unavailable.
673 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
674 BBWorklist.push_back(*I);
675 } while (!BBWorklist.empty());
681 /// CanCoerceMustAliasedValueToLoad - Return true if
682 /// CoerceAvailableValueToLoadType will succeed.
683 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
685 const TargetData &TD) {
686 // If the loaded or stored value is an first class array or struct, don't try
687 // to transform them. We need to be able to bitcast to integer.
688 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
689 StoredVal->getType()->isStructTy() ||
690 StoredVal->getType()->isArrayTy())
693 // The store has to be at least as big as the load.
694 if (TD.getTypeSizeInBits(StoredVal->getType()) <
695 TD.getTypeSizeInBits(LoadTy))
702 /// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
703 /// then a load from a must-aliased pointer of a different type, try to coerce
704 /// the stored value. LoadedTy is the type of the load we want to replace and
705 /// InsertPt is the place to insert new instructions.
707 /// If we can't do it, return null.
708 static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
710 Instruction *InsertPt,
711 const TargetData &TD) {
712 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
715 // If this is already the right type, just return it.
716 Type *StoredValTy = StoredVal->getType();
718 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
719 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
721 // If the store and reload are the same size, we can always reuse it.
722 if (StoreSize == LoadSize) {
723 // Pointer to Pointer -> use bitcast.
724 if (StoredValTy->isPointerTy() && LoadedTy->isPointerTy())
725 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
727 // Convert source pointers to integers, which can be bitcast.
728 if (StoredValTy->isPointerTy()) {
729 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
730 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
733 Type *TypeToCastTo = LoadedTy;
734 if (TypeToCastTo->isPointerTy())
735 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
737 if (StoredValTy != TypeToCastTo)
738 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
740 // Cast to pointer if the load needs a pointer type.
741 if (LoadedTy->isPointerTy())
742 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
747 // If the loaded value is smaller than the available value, then we can
748 // extract out a piece from it. If the available value is too small, then we
749 // can't do anything.
750 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
752 // Convert source pointers to integers, which can be manipulated.
753 if (StoredValTy->isPointerTy()) {
754 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
755 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
758 // Convert vectors and fp to integer, which can be manipulated.
759 if (!StoredValTy->isIntegerTy()) {
760 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
761 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
764 // If this is a big-endian system, we need to shift the value down to the low
765 // bits so that a truncate will work.
766 if (TD.isBigEndian()) {
767 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
768 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
771 // Truncate the integer to the right size now.
772 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
773 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
775 if (LoadedTy == NewIntTy)
778 // If the result is a pointer, inttoptr.
779 if (LoadedTy->isPointerTy())
780 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
782 // Otherwise, bitcast.
783 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
786 /// AnalyzeLoadFromClobberingWrite - This function is called when we have a
787 /// memdep query of a load that ends up being a clobbering memory write (store,
788 /// memset, memcpy, memmove). This means that the write *may* provide bits used
789 /// by the load but we can't be sure because the pointers don't mustalias.
791 /// Check this case to see if there is anything more we can do before we give
792 /// up. This returns -1 if we have to give up, or a byte number in the stored
793 /// value of the piece that feeds the load.
794 static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
796 uint64_t WriteSizeInBits,
797 const TargetData &TD) {
798 // If the loaded or stored value is a first class array or struct, don't try
799 // to transform them. We need to be able to bitcast to integer.
800 if (LoadTy->isStructTy() || LoadTy->isArrayTy())
803 int64_t StoreOffset = 0, LoadOffset = 0;
804 Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr, StoreOffset,TD);
805 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, TD);
806 if (StoreBase != LoadBase)
809 // If the load and store are to the exact same address, they should have been
810 // a must alias. AA must have gotten confused.
811 // FIXME: Study to see if/when this happens. One case is forwarding a memset
812 // to a load from the base of the memset.
814 if (LoadOffset == StoreOffset) {
815 dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
816 << "Base = " << *StoreBase << "\n"
817 << "Store Ptr = " << *WritePtr << "\n"
818 << "Store Offs = " << StoreOffset << "\n"
819 << "Load Ptr = " << *LoadPtr << "\n";
824 // If the load and store don't overlap at all, the store doesn't provide
825 // anything to the load. In this case, they really don't alias at all, AA
826 // must have gotten confused.
827 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy);
829 if ((WriteSizeInBits & 7) | (LoadSize & 7))
831 uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
835 bool isAAFailure = false;
836 if (StoreOffset < LoadOffset)
837 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
839 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
843 dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
844 << "Base = " << *StoreBase << "\n"
845 << "Store Ptr = " << *WritePtr << "\n"
846 << "Store Offs = " << StoreOffset << "\n"
847 << "Load Ptr = " << *LoadPtr << "\n";
853 // If the Load isn't completely contained within the stored bits, we don't
854 // have all the bits to feed it. We could do something crazy in the future
855 // (issue a smaller load then merge the bits in) but this seems unlikely to be
857 if (StoreOffset > LoadOffset ||
858 StoreOffset+StoreSize < LoadOffset+LoadSize)
861 // Okay, we can do this transformation. Return the number of bytes into the
862 // store that the load is.
863 return LoadOffset-StoreOffset;
866 /// AnalyzeLoadFromClobberingStore - This function is called when we have a
867 /// memdep query of a load that ends up being a clobbering store.
868 static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
870 const TargetData &TD) {
871 // Cannot handle reading from store of first-class aggregate yet.
872 if (DepSI->getValueOperand()->getType()->isStructTy() ||
873 DepSI->getValueOperand()->getType()->isArrayTy())
876 Value *StorePtr = DepSI->getPointerOperand();
877 uint64_t StoreSize =TD.getTypeSizeInBits(DepSI->getValueOperand()->getType());
878 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
879 StorePtr, StoreSize, TD);
882 /// AnalyzeLoadFromClobberingLoad - This function is called when we have a
883 /// memdep query of a load that ends up being clobbered by another load. See if
884 /// the other load can feed into the second load.
885 static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
886 LoadInst *DepLI, const TargetData &TD){
887 // Cannot handle reading from store of first-class aggregate yet.
888 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
891 Value *DepPtr = DepLI->getPointerOperand();
892 uint64_t DepSize = TD.getTypeSizeInBits(DepLI->getType());
893 int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, TD);
894 if (R != -1) return R;
896 // If we have a load/load clobber an DepLI can be widened to cover this load,
897 // then we should widen it!
898 int64_t LoadOffs = 0;
899 const Value *LoadBase =
900 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, TD);
901 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
903 unsigned Size = MemoryDependenceAnalysis::
904 getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, TD);
905 if (Size == 0) return -1;
907 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, TD);
912 static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
914 const TargetData &TD) {
915 // If the mem operation is a non-constant size, we can't handle it.
916 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
917 if (SizeCst == 0) return -1;
918 uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
920 // If this is memset, we just need to see if the offset is valid in the size
922 if (MI->getIntrinsicID() == Intrinsic::memset)
923 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
926 // If we have a memcpy/memmove, the only case we can handle is if this is a
927 // copy from constant memory. In that case, we can read directly from the
929 MemTransferInst *MTI = cast<MemTransferInst>(MI);
931 Constant *Src = dyn_cast<Constant>(MTI->getSource());
932 if (Src == 0) return -1;
934 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &TD));
935 if (GV == 0 || !GV->isConstant()) return -1;
937 // See if the access is within the bounds of the transfer.
938 int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
939 MI->getDest(), MemSizeInBits, TD);
943 // Otherwise, see if we can constant fold a load from the constant with the
944 // offset applied as appropriate.
945 Src = ConstantExpr::getBitCast(Src,
946 llvm::Type::getInt8PtrTy(Src->getContext()));
947 Constant *OffsetCst =
948 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
949 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
950 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
951 if (ConstantFoldLoadFromConstPtr(Src, &TD))
957 /// GetStoreValueForLoad - This function is called when we have a
958 /// memdep query of a load that ends up being a clobbering store. This means
959 /// that the store provides bits used by the load but we the pointers don't
960 /// mustalias. Check this case to see if there is anything more we can do
961 /// before we give up.
962 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
964 Instruction *InsertPt, const TargetData &TD){
965 LLVMContext &Ctx = SrcVal->getType()->getContext();
967 uint64_t StoreSize = (TD.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
968 uint64_t LoadSize = (TD.getTypeSizeInBits(LoadTy) + 7) / 8;
970 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
972 // Compute which bits of the stored value are being used by the load. Convert
973 // to an integer type to start with.
974 if (SrcVal->getType()->isPointerTy())
975 SrcVal = Builder.CreatePtrToInt(SrcVal, TD.getIntPtrType(Ctx));
976 if (!SrcVal->getType()->isIntegerTy())
977 SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
979 // Shift the bits to the least significant depending on endianness.
981 if (TD.isLittleEndian())
984 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
987 SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
989 if (LoadSize != StoreSize)
990 SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
992 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
995 /// GetLoadValueForLoad - This function is called when we have a
996 /// memdep query of a load that ends up being a clobbering load. This means
997 /// that the load *may* provide bits used by the load but we can't be sure
998 /// because the pointers don't mustalias. Check this case to see if there is
999 /// anything more we can do before we give up.
1000 static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
1001 Type *LoadTy, Instruction *InsertPt,
1003 const TargetData &TD = *gvn.getTargetData();
1004 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
1005 // widen SrcVal out to a larger load.
1006 unsigned SrcValSize = TD.getTypeStoreSize(SrcVal->getType());
1007 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
1008 if (Offset+LoadSize > SrcValSize) {
1009 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
1010 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
1011 // If we have a load/load clobber an DepLI can be widened to cover this
1012 // load, then we should widen it to the next power of 2 size big enough!
1013 unsigned NewLoadSize = Offset+LoadSize;
1014 if (!isPowerOf2_32(NewLoadSize))
1015 NewLoadSize = NextPowerOf2(NewLoadSize);
1017 Value *PtrVal = SrcVal->getPointerOperand();
1019 // Insert the new load after the old load. This ensures that subsequent
1020 // memdep queries will find the new load. We can't easily remove the old
1021 // load completely because it is already in the value numbering table.
1022 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
1024 IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1025 DestPTy = PointerType::get(DestPTy,
1026 cast<PointerType>(PtrVal->getType())->getAddressSpace());
1027 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
1028 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1029 LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1030 NewLoad->takeName(SrcVal);
1031 NewLoad->setAlignment(SrcVal->getAlignment());
1033 DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1034 DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1036 // Replace uses of the original load with the wider load. On a big endian
1037 // system, we need to shift down to get the relevant bits.
1038 Value *RV = NewLoad;
1039 if (TD.isBigEndian())
1040 RV = Builder.CreateLShr(RV,
1041 NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1042 RV = Builder.CreateTrunc(RV, SrcVal->getType());
1043 SrcVal->replaceAllUsesWith(RV);
1045 // We would like to use gvn.markInstructionForDeletion here, but we can't
1046 // because the load is already memoized into the leader map table that GVN
1047 // tracks. It is potentially possible to remove the load from the table,
1048 // but then there all of the operations based on it would need to be
1049 // rehashed. Just leave the dead load around.
1050 gvn.getMemDep().removeInstruction(SrcVal);
1054 return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, TD);
1058 /// GetMemInstValueForLoad - This function is called when we have a
1059 /// memdep query of a load that ends up being a clobbering mem intrinsic.
1060 static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
1061 Type *LoadTy, Instruction *InsertPt,
1062 const TargetData &TD){
1063 LLVMContext &Ctx = LoadTy->getContext();
1064 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1066 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1068 // We know that this method is only called when the mem transfer fully
1069 // provides the bits for the load.
1070 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1071 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1072 // independently of what the offset is.
1073 Value *Val = MSI->getValue();
1075 Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1077 Value *OneElt = Val;
1079 // Splat the value out to the right number of bits.
1080 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1081 // If we can double the number of bytes set, do it.
1082 if (NumBytesSet*2 <= LoadSize) {
1083 Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1084 Val = Builder.CreateOr(Val, ShVal);
1089 // Otherwise insert one byte at a time.
1090 Value *ShVal = Builder.CreateShl(Val, 1*8);
1091 Val = Builder.CreateOr(OneElt, ShVal);
1095 return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, TD);
1098 // Otherwise, this is a memcpy/memmove from a constant global.
1099 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1100 Constant *Src = cast<Constant>(MTI->getSource());
1102 // Otherwise, see if we can constant fold a load from the constant with the
1103 // offset applied as appropriate.
1104 Src = ConstantExpr::getBitCast(Src,
1105 llvm::Type::getInt8PtrTy(Src->getContext()));
1106 Constant *OffsetCst =
1107 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1108 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
1109 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1110 return ConstantFoldLoadFromConstPtr(Src, &TD);
1115 struct AvailableValueInBlock {
1116 /// BB - The basic block in question.
1119 SimpleVal, // A simple offsetted value that is accessed.
1120 LoadVal, // A value produced by a load.
1121 MemIntrin // A memory intrinsic which is loaded from.
1124 /// V - The value that is live out of the block.
1125 PointerIntPair<Value *, 2, ValType> Val;
1127 /// Offset - The byte offset in Val that is interesting for the load query.
1130 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1131 unsigned Offset = 0) {
1132 AvailableValueInBlock Res;
1134 Res.Val.setPointer(V);
1135 Res.Val.setInt(SimpleVal);
1136 Res.Offset = Offset;
1140 static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
1141 unsigned Offset = 0) {
1142 AvailableValueInBlock Res;
1144 Res.Val.setPointer(MI);
1145 Res.Val.setInt(MemIntrin);
1146 Res.Offset = Offset;
1150 static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
1151 unsigned Offset = 0) {
1152 AvailableValueInBlock Res;
1154 Res.Val.setPointer(LI);
1155 Res.Val.setInt(LoadVal);
1156 Res.Offset = Offset;
1160 bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
1161 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
1162 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
1164 Value *getSimpleValue() const {
1165 assert(isSimpleValue() && "Wrong accessor");
1166 return Val.getPointer();
1169 LoadInst *getCoercedLoadValue() const {
1170 assert(isCoercedLoadValue() && "Wrong accessor");
1171 return cast<LoadInst>(Val.getPointer());
1174 MemIntrinsic *getMemIntrinValue() const {
1175 assert(isMemIntrinValue() && "Wrong accessor");
1176 return cast<MemIntrinsic>(Val.getPointer());
1179 /// MaterializeAdjustedValue - Emit code into this block to adjust the value
1180 /// defined here to the specified type. This handles various coercion cases.
1181 Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
1183 if (isSimpleValue()) {
1184 Res = getSimpleValue();
1185 if (Res->getType() != LoadTy) {
1186 const TargetData *TD = gvn.getTargetData();
1187 assert(TD && "Need target data to handle type mismatch case");
1188 Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1191 DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
1192 << *getSimpleValue() << '\n'
1193 << *Res << '\n' << "\n\n\n");
1195 } else if (isCoercedLoadValue()) {
1196 LoadInst *Load = getCoercedLoadValue();
1197 if (Load->getType() == LoadTy && Offset == 0) {
1200 Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
1203 DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
1204 << *getCoercedLoadValue() << '\n'
1205 << *Res << '\n' << "\n\n\n");
1208 const TargetData *TD = gvn.getTargetData();
1209 assert(TD && "Need target data to handle type mismatch case");
1210 Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1211 LoadTy, BB->getTerminator(), *TD);
1212 DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1213 << " " << *getMemIntrinValue() << '\n'
1214 << *Res << '\n' << "\n\n\n");
1220 } // end anonymous namespace
1222 /// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1223 /// construct SSA form, allowing us to eliminate LI. This returns the value
1224 /// that should be used at LI's definition site.
1225 static Value *ConstructSSAForLoadSet(LoadInst *LI,
1226 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1228 // Check for the fully redundant, dominating load case. In this case, we can
1229 // just use the dominating value directly.
1230 if (ValuesPerBlock.size() == 1 &&
1231 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1233 return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
1235 // Otherwise, we have to construct SSA form.
1236 SmallVector<PHINode*, 8> NewPHIs;
1237 SSAUpdater SSAUpdate(&NewPHIs);
1238 SSAUpdate.Initialize(LI->getType(), LI->getName());
1240 Type *LoadTy = LI->getType();
1242 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1243 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1244 BasicBlock *BB = AV.BB;
1246 if (SSAUpdate.HasValueForBlock(BB))
1249 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
1252 // Perform PHI construction.
1253 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1255 // If new PHI nodes were created, notify alias analysis.
1256 if (V->getType()->isPointerTy()) {
1257 AliasAnalysis *AA = gvn.getAliasAnalysis();
1259 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1260 AA->copyValue(LI, NewPHIs[i]);
1262 // Now that we've copied information to the new PHIs, scan through
1263 // them again and inform alias analysis that we've added potentially
1264 // escaping uses to any values that are operands to these PHIs.
1265 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1266 PHINode *P = NewPHIs[i];
1267 for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1268 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1269 AA->addEscapingUse(P->getOperandUse(jj));
1277 static bool isLifetimeStart(const Instruction *Inst) {
1278 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1279 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1283 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1284 /// non-local by performing PHI construction.
1285 bool GVN::processNonLocalLoad(LoadInst *LI) {
1286 // Find the non-local dependencies of the load.
1287 SmallVector<NonLocalDepResult, 64> Deps;
1288 AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1289 MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
1290 //DEBUG(dbgs() << "INVESTIGATING NONLOCAL LOAD: "
1291 // << Deps.size() << *LI << '\n');
1293 // If we had to process more than one hundred blocks to find the
1294 // dependencies, this load isn't worth worrying about. Optimizing
1295 // it will be too expensive.
1296 unsigned NumDeps = Deps.size();
1300 // If we had a phi translation failure, we'll have a single entry which is a
1301 // clobber in the current block. Reject this early.
1303 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1305 dbgs() << "GVN: non-local load ";
1306 WriteAsOperand(dbgs(), LI);
1307 dbgs() << " has unknown dependencies\n";
1312 // Filter out useless results (non-locals, etc). Keep track of the blocks
1313 // where we have a value available in repl, also keep track of whether we see
1314 // dependencies that produce an unknown value for the load (such as a call
1315 // that could potentially clobber the load).
1316 SmallVector<AvailableValueInBlock, 64> ValuesPerBlock;
1317 SmallVector<BasicBlock*, 64> UnavailableBlocks;
1319 for (unsigned i = 0, e = NumDeps; i != e; ++i) {
1320 BasicBlock *DepBB = Deps[i].getBB();
1321 MemDepResult DepInfo = Deps[i].getResult();
1323 if (!DepInfo.isDef() && !DepInfo.isClobber()) {
1324 UnavailableBlocks.push_back(DepBB);
1328 if (DepInfo.isClobber()) {
1329 // The address being loaded in this non-local block may not be the same as
1330 // the pointer operand of the load if PHI translation occurs. Make sure
1331 // to consider the right address.
1332 Value *Address = Deps[i].getAddress();
1334 // If the dependence is to a store that writes to a superset of the bits
1335 // read by the load, we can extract the bits we need for the load from the
1337 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1338 if (TD && Address) {
1339 int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
1342 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1343 DepSI->getValueOperand(),
1350 // Check to see if we have something like this:
1353 // if we have this, replace the later with an extraction from the former.
1354 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1355 // If this is a clobber and L is the first instruction in its block, then
1356 // we have the first instruction in the entry block.
1357 if (DepLI != LI && Address && TD) {
1358 int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1359 LI->getPointerOperand(),
1363 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1370 // If the clobbering value is a memset/memcpy/memmove, see if we can
1371 // forward a value on from it.
1372 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
1373 if (TD && Address) {
1374 int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
1377 ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1384 UnavailableBlocks.push_back(DepBB);
1388 // DepInfo.isDef() here
1390 Instruction *DepInst = DepInfo.getInst();
1392 // Loading the allocation -> undef.
1393 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst) ||
1394 // Loading immediately after lifetime begin -> undef.
1395 isLifetimeStart(DepInst)) {
1396 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1397 UndefValue::get(LI->getType())));
1401 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1402 // Reject loads and stores that are to the same address but are of
1403 // different types if we have to.
1404 if (S->getValueOperand()->getType() != LI->getType()) {
1405 // If the stored value is larger or equal to the loaded value, we can
1407 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
1408 LI->getType(), *TD)) {
1409 UnavailableBlocks.push_back(DepBB);
1414 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1415 S->getValueOperand()));
1419 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1420 // If the types mismatch and we can't handle it, reject reuse of the load.
1421 if (LD->getType() != LI->getType()) {
1422 // If the stored value is larger or equal to the loaded value, we can
1424 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
1425 UnavailableBlocks.push_back(DepBB);
1429 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
1433 UnavailableBlocks.push_back(DepBB);
1437 // If we have no predecessors that produce a known value for this load, exit
1439 if (ValuesPerBlock.empty()) return false;
1441 // If all of the instructions we depend on produce a known value for this
1442 // load, then it is fully redundant and we can use PHI insertion to compute
1443 // its value. Insert PHIs and remove the fully redundant value now.
1444 if (UnavailableBlocks.empty()) {
1445 DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1447 // Perform PHI construction.
1448 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1449 LI->replaceAllUsesWith(V);
1451 if (isa<PHINode>(V))
1453 if (V->getType()->isPointerTy())
1454 MD->invalidateCachedPointerInfo(V);
1455 markInstructionForDeletion(LI);
1460 if (!EnablePRE || !EnableLoadPRE)
1463 // Okay, we have *some* definitions of the value. This means that the value
1464 // is available in some of our (transitive) predecessors. Lets think about
1465 // doing PRE of this load. This will involve inserting a new load into the
1466 // predecessor when it's not available. We could do this in general, but
1467 // prefer to not increase code size. As such, we only do this when we know
1468 // that we only have to insert *one* load (which means we're basically moving
1469 // the load, not inserting a new one).
1471 SmallPtrSet<BasicBlock *, 4> Blockers;
1472 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1473 Blockers.insert(UnavailableBlocks[i]);
1475 // Let's find the first basic block with more than one predecessor. Walk
1476 // backwards through predecessors if needed.
1477 BasicBlock *LoadBB = LI->getParent();
1478 BasicBlock *TmpBB = LoadBB;
1480 bool isSinglePred = false;
1481 bool allSingleSucc = true;
1482 while (TmpBB->getSinglePredecessor()) {
1483 isSinglePred = true;
1484 TmpBB = TmpBB->getSinglePredecessor();
1485 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1487 if (Blockers.count(TmpBB))
1490 // If any of these blocks has more than one successor (i.e. if the edge we
1491 // just traversed was critical), then there are other paths through this
1492 // block along which the load may not be anticipated. Hoisting the load
1493 // above this block would be adding the load to execution paths along
1494 // which it was not previously executed.
1495 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1502 // FIXME: It is extremely unclear what this loop is doing, other than
1503 // artificially restricting loadpre.
1506 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1507 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1508 if (AV.isSimpleValue())
1509 // "Hot" Instruction is in some loop (because it dominates its dep.
1511 if (Instruction *I = dyn_cast<Instruction>(AV.getSimpleValue()))
1512 if (DT->dominates(LI, I)) {
1518 // We are interested only in "hot" instructions. We don't want to do any
1519 // mis-optimizations here.
1524 // Check to see how many predecessors have the loaded value fully
1526 DenseMap<BasicBlock*, Value*> PredLoads;
1527 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1528 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1529 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
1530 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1531 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1533 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> NeedToSplit;
1534 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1536 BasicBlock *Pred = *PI;
1537 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
1540 PredLoads[Pred] = 0;
1542 if (Pred->getTerminator()->getNumSuccessors() != 1) {
1543 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1544 DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1545 << Pred->getName() << "': " << *LI << '\n');
1549 if (LoadBB->isLandingPad()) {
1551 << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1552 << Pred->getName() << "': " << *LI << '\n');
1556 unsigned SuccNum = GetSuccessorNumber(Pred, LoadBB);
1557 NeedToSplit.push_back(std::make_pair(Pred->getTerminator(), SuccNum));
1561 if (!NeedToSplit.empty()) {
1562 toSplit.append(NeedToSplit.begin(), NeedToSplit.end());
1566 // Decide whether PRE is profitable for this load.
1567 unsigned NumUnavailablePreds = PredLoads.size();
1568 assert(NumUnavailablePreds != 0 &&
1569 "Fully available value should be eliminated above!");
1571 // If this load is unavailable in multiple predecessors, reject it.
1572 // FIXME: If we could restructure the CFG, we could make a common pred with
1573 // all the preds that don't have an available LI and insert a new load into
1575 if (NumUnavailablePreds != 1)
1578 // Check if the load can safely be moved to all the unavailable predecessors.
1579 bool CanDoPRE = true;
1580 SmallVector<Instruction*, 8> NewInsts;
1581 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1582 E = PredLoads.end(); I != E; ++I) {
1583 BasicBlock *UnavailablePred = I->first;
1585 // Do PHI translation to get its value in the predecessor if necessary. The
1586 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1588 // If all preds have a single successor, then we know it is safe to insert
1589 // the load on the pred (?!?), so we can insert code to materialize the
1590 // pointer if it is not available.
1591 PHITransAddr Address(LI->getPointerOperand(), TD);
1593 if (allSingleSucc) {
1594 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1597 Address.PHITranslateValue(LoadBB, UnavailablePred, DT);
1598 LoadPtr = Address.getAddr();
1601 // If we couldn't find or insert a computation of this phi translated value,
1604 DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1605 << *LI->getPointerOperand() << "\n");
1610 // Make sure it is valid to move this load here. We have to watch out for:
1611 // @1 = getelementptr (i8* p, ...
1612 // test p and branch if == 0
1614 // It is valid to have the getelementptr before the test, even if p can
1615 // be 0, as getelementptr only does address arithmetic.
1616 // If we are not pushing the value through any multiple-successor blocks
1617 // we do not have this case. Otherwise, check that the load is safe to
1618 // put anywhere; this can be improved, but should be conservatively safe.
1619 if (!allSingleSucc &&
1620 // FIXME: REEVALUTE THIS.
1621 !isSafeToLoadUnconditionally(LoadPtr,
1622 UnavailablePred->getTerminator(),
1623 LI->getAlignment(), TD)) {
1628 I->second = LoadPtr;
1632 while (!NewInsts.empty()) {
1633 Instruction *I = NewInsts.pop_back_val();
1634 if (MD) MD->removeInstruction(I);
1635 I->eraseFromParent();
1640 // Okay, we can eliminate this load by inserting a reload in the predecessor
1641 // and using PHI construction to get the value in the other predecessors, do
1643 DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1644 DEBUG(if (!NewInsts.empty())
1645 dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
1646 << *NewInsts.back() << '\n');
1648 // Assign value numbers to the new instructions.
1649 for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1650 // FIXME: We really _ought_ to insert these value numbers into their
1651 // parent's availability map. However, in doing so, we risk getting into
1652 // ordering issues. If a block hasn't been processed yet, we would be
1653 // marking a value as AVAIL-IN, which isn't what we intend.
1654 VN.lookup_or_add(NewInsts[i]);
1657 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1658 E = PredLoads.end(); I != E; ++I) {
1659 BasicBlock *UnavailablePred = I->first;
1660 Value *LoadPtr = I->second;
1662 Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1664 UnavailablePred->getTerminator());
1666 // Transfer the old load's TBAA tag to the new load.
1667 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1668 NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1670 // Transfer DebugLoc.
1671 NewLoad->setDebugLoc(LI->getDebugLoc());
1673 // Add the newly created load.
1674 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1676 MD->invalidateCachedPointerInfo(LoadPtr);
1677 DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1680 // Perform PHI construction.
1681 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1682 LI->replaceAllUsesWith(V);
1683 if (isa<PHINode>(V))
1685 if (V->getType()->isPointerTy())
1686 MD->invalidateCachedPointerInfo(V);
1687 markInstructionForDeletion(LI);
1692 /// processLoad - Attempt to eliminate a load, first by eliminating it
1693 /// locally, and then attempting non-local elimination if that fails.
1694 bool GVN::processLoad(LoadInst *L) {
1701 if (L->use_empty()) {
1702 markInstructionForDeletion(L);
1706 // ... to a pointer that has been loaded from before...
1707 MemDepResult Dep = MD->getDependency(L);
1709 // If we have a clobber and target data is around, see if this is a clobber
1710 // that we can fix up through code synthesis.
1711 if (Dep.isClobber() && TD) {
1712 // Check to see if we have something like this:
1713 // store i32 123, i32* %P
1714 // %A = bitcast i32* %P to i8*
1715 // %B = gep i8* %A, i32 1
1718 // We could do that by recognizing if the clobber instructions are obviously
1719 // a common base + constant offset, and if the previous store (or memset)
1720 // completely covers this load. This sort of thing can happen in bitfield
1722 Value *AvailVal = 0;
1723 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1724 int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1725 L->getPointerOperand(),
1728 AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1729 L->getType(), L, *TD);
1732 // Check to see if we have something like this:
1735 // if we have this, replace the later with an extraction from the former.
1736 if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1737 // If this is a clobber and L is the first instruction in its block, then
1738 // we have the first instruction in the entry block.
1742 int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1743 L->getPointerOperand(),
1746 AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
1749 // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1750 // a value on from it.
1751 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
1752 int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1753 L->getPointerOperand(),
1756 AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *TD);
1760 DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
1761 << *AvailVal << '\n' << *L << "\n\n\n");
1763 // Replace the load!
1764 L->replaceAllUsesWith(AvailVal);
1765 if (AvailVal->getType()->isPointerTy())
1766 MD->invalidateCachedPointerInfo(AvailVal);
1767 markInstructionForDeletion(L);
1773 // If the value isn't available, don't do anything!
1774 if (Dep.isClobber()) {
1776 // fast print dep, using operator<< on instruction is too slow.
1777 dbgs() << "GVN: load ";
1778 WriteAsOperand(dbgs(), L);
1779 Instruction *I = Dep.getInst();
1780 dbgs() << " is clobbered by " << *I << '\n';
1785 // If it is defined in another block, try harder.
1786 if (Dep.isNonLocal())
1787 return processNonLocalLoad(L);
1791 // fast print dep, using operator<< on instruction is too slow.
1792 dbgs() << "GVN: load ";
1793 WriteAsOperand(dbgs(), L);
1794 dbgs() << " has unknown dependence\n";
1799 Instruction *DepInst = Dep.getInst();
1800 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1801 Value *StoredVal = DepSI->getValueOperand();
1803 // The store and load are to a must-aliased pointer, but they may not
1804 // actually have the same type. See if we know how to reuse the stored
1805 // value (depending on its type).
1806 if (StoredVal->getType() != L->getType()) {
1808 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1813 DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1814 << '\n' << *L << "\n\n\n");
1821 L->replaceAllUsesWith(StoredVal);
1822 if (StoredVal->getType()->isPointerTy())
1823 MD->invalidateCachedPointerInfo(StoredVal);
1824 markInstructionForDeletion(L);
1829 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1830 Value *AvailableVal = DepLI;
1832 // The loads are of a must-aliased pointer, but they may not actually have
1833 // the same type. See if we know how to reuse the previously loaded value
1834 // (depending on its type).
1835 if (DepLI->getType() != L->getType()) {
1837 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1839 if (AvailableVal == 0)
1842 DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1843 << "\n" << *L << "\n\n\n");
1850 L->replaceAllUsesWith(AvailableVal);
1851 if (DepLI->getType()->isPointerTy())
1852 MD->invalidateCachedPointerInfo(DepLI);
1853 markInstructionForDeletion(L);
1858 // If this load really doesn't depend on anything, then we must be loading an
1859 // undef value. This can happen when loading for a fresh allocation with no
1860 // intervening stores, for example.
1861 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
1862 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1863 markInstructionForDeletion(L);
1868 // If this load occurs either right after a lifetime begin,
1869 // then the loaded value is undefined.
1870 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
1871 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1872 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1873 markInstructionForDeletion(L);
1882 // findLeader - In order to find a leader for a given value number at a
1883 // specific basic block, we first obtain the list of all Values for that number,
1884 // and then scan the list to find one whose block dominates the block in
1885 // question. This is fast because dominator tree queries consist of only
1886 // a few comparisons of DFS numbers.
1887 Value *GVN::findLeader(BasicBlock *BB, uint32_t num) {
1888 LeaderTableEntry Vals = LeaderTable[num];
1889 if (!Vals.Val) return 0;
1892 if (DT->dominates(Vals.BB, BB)) {
1894 if (isa<Constant>(Val)) return Val;
1897 LeaderTableEntry* Next = Vals.Next;
1899 if (DT->dominates(Next->BB, BB)) {
1900 if (isa<Constant>(Next->Val)) return Next->Val;
1901 if (!Val) Val = Next->Val;
1910 /// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
1911 /// use is dominated by the given basic block. Returns the number of uses that
1913 unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
1916 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1918 Use &U = (UI++).getUse();
1919 if (DT->dominates(Root, cast<Instruction>(U.getUser())->getParent())) {
1927 /// propagateEquality - The given values are known to be equal in every block
1928 /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
1929 /// 'RHS' everywhere in the scope. Returns whether a change was made.
1930 bool GVN::propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root) {
1931 if (LHS == RHS) return false;
1932 assert(LHS->getType() == RHS->getType() && "Equal but types differ!");
1934 // Don't try to propagate equalities between constants.
1935 if (isa<Constant>(LHS) && isa<Constant>(RHS))
1938 // Make sure that any constants are on the right-hand side. In general the
1939 // best results are obtained by placing the longest lived value on the RHS.
1940 if (isa<Constant>(LHS))
1941 std::swap(LHS, RHS);
1943 // If neither term is constant then bail out. This is not for correctness,
1944 // it's just that the non-constant case is much less useful: it occurs just
1945 // as often as the constant case but handling it hardly ever results in an
1947 if (!isa<Constant>(RHS))
1950 // If value numbering later deduces that an instruction in the scope is equal
1951 // to 'LHS' then ensure it will be turned into 'RHS'.
1952 addToLeaderTable(VN.lookup_or_add(LHS), RHS, Root);
1954 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
1955 // LHS always has at least one use that is not dominated by Root, this will
1956 // never do anything if LHS has only one use.
1957 bool Changed = false;
1958 if (!LHS->hasOneUse()) {
1959 unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
1960 Changed |= NumReplacements > 0;
1961 NumGVNEqProp += NumReplacements;
1964 // Now try to deduce additional equalities from this one. For example, if the
1965 // known equality was "(A != B)" == "false" then it follows that A and B are
1966 // equal in the scope. Only boolean equalities with an explicit true or false
1967 // RHS are currently supported.
1968 if (!RHS->getType()->isIntegerTy(1))
1969 // Not a boolean equality - bail out.
1971 ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
1973 // RHS neither 'true' nor 'false' - bail out.
1975 // Whether RHS equals 'true'. Otherwise it equals 'false'.
1976 bool isKnownTrue = CI->isAllOnesValue();
1977 bool isKnownFalse = !isKnownTrue;
1979 // If "A && B" is known true then both A and B are known true. If "A || B"
1980 // is known false then both A and B are known false.
1982 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
1983 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
1984 Changed |= propagateEquality(A, RHS, Root);
1985 Changed |= propagateEquality(B, RHS, Root);
1989 // If we are propagating an equality like "(A == B)" == "true" then also
1990 // propagate the equality A == B.
1991 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
1992 // Only equality comparisons are supported.
1993 if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
1994 (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE)) {
1995 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1996 Changed |= propagateEquality(Op0, Op1, Root);
2004 /// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'. Return
2005 /// true if every path from the entry block to 'Dst' passes via this edge. In
2006 /// particular 'Dst' must not be reachable via another edge from 'Src'.
2007 static bool isOnlyReachableViaThisEdge(BasicBlock *Src, BasicBlock *Dst,
2008 DominatorTree *DT) {
2009 // While in theory it is interesting to consider the case in which Dst has
2010 // more than one predecessor, because Dst might be part of a loop which is
2011 // only reachable from Src, in practice it is pointless since at the time
2012 // GVN runs all such loops have preheaders, which means that Dst will have
2013 // been changed to have only one predecessor, namely Src.
2014 BasicBlock *Pred = Dst->getSinglePredecessor();
2015 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
2020 /// processInstruction - When calculating availability, handle an instruction
2021 /// by inserting it into the appropriate sets
2022 bool GVN::processInstruction(Instruction *I) {
2023 // Ignore dbg info intrinsics.
2024 if (isa<DbgInfoIntrinsic>(I))
2027 // If the instruction can be easily simplified then do so now in preference
2028 // to value numbering it. Value numbering often exposes redundancies, for
2029 // example if it determines that %y is equal to %x then the instruction
2030 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
2031 if (Value *V = SimplifyInstruction(I, TD, TLI, DT)) {
2032 I->replaceAllUsesWith(V);
2033 if (MD && V->getType()->isPointerTy())
2034 MD->invalidateCachedPointerInfo(V);
2035 markInstructionForDeletion(I);
2040 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2041 if (processLoad(LI))
2044 unsigned Num = VN.lookup_or_add(LI);
2045 addToLeaderTable(Num, LI, LI->getParent());
2049 // For conditional branches, we can perform simple conditional propagation on
2050 // the condition value itself.
2051 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
2052 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
2055 Value *BranchCond = BI->getCondition();
2057 BasicBlock *TrueSucc = BI->getSuccessor(0);
2058 BasicBlock *FalseSucc = BI->getSuccessor(1);
2059 BasicBlock *Parent = BI->getParent();
2060 bool Changed = false;
2062 if (isOnlyReachableViaThisEdge(Parent, TrueSucc, DT))
2063 Changed |= propagateEquality(BranchCond,
2064 ConstantInt::getTrue(TrueSucc->getContext()),
2067 if (isOnlyReachableViaThisEdge(Parent, FalseSucc, DT))
2068 Changed |= propagateEquality(BranchCond,
2069 ConstantInt::getFalse(FalseSucc->getContext()),
2075 // For switches, propagate the case values into the case destinations.
2076 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2077 Value *SwitchCond = SI->getCondition();
2078 BasicBlock *Parent = SI->getParent();
2079 bool Changed = false;
2080 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
2081 BasicBlock *Dst = SI->getCaseSuccessor(i);
2082 if (isOnlyReachableViaThisEdge(Parent, Dst, DT))
2083 Changed |= propagateEquality(SwitchCond, SI->getCaseValue(i), Dst);
2088 // Instructions with void type don't return a value, so there's
2089 // no point in trying to find redudancies in them.
2090 if (I->getType()->isVoidTy()) return false;
2092 uint32_t NextNum = VN.getNextUnusedValueNumber();
2093 unsigned Num = VN.lookup_or_add(I);
2095 // Allocations are always uniquely numbered, so we can save time and memory
2096 // by fast failing them.
2097 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
2098 addToLeaderTable(Num, I, I->getParent());
2102 // If the number we were assigned was a brand new VN, then we don't
2103 // need to do a lookup to see if the number already exists
2104 // somewhere in the domtree: it can't!
2105 if (Num == NextNum) {
2106 addToLeaderTable(Num, I, I->getParent());
2110 // Perform fast-path value-number based elimination of values inherited from
2112 Value *repl = findLeader(I->getParent(), Num);
2114 // Failure, just remember this instance for future use.
2115 addToLeaderTable(Num, I, I->getParent());
2120 I->replaceAllUsesWith(repl);
2121 if (MD && repl->getType()->isPointerTy())
2122 MD->invalidateCachedPointerInfo(repl);
2123 markInstructionForDeletion(I);
2127 /// runOnFunction - This is the main transformation entry point for a function.
2128 bool GVN::runOnFunction(Function& F) {
2130 MD = &getAnalysis<MemoryDependenceAnalysis>();
2131 DT = &getAnalysis<DominatorTree>();
2132 TD = getAnalysisIfAvailable<TargetData>();
2133 TLI = &getAnalysis<TargetLibraryInfo>();
2134 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
2138 bool Changed = false;
2139 bool ShouldContinue = true;
2141 // Merge unconditional branches, allowing PRE to catch more
2142 // optimization opportunities.
2143 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
2144 BasicBlock *BB = FI++;
2146 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
2147 if (removedBlock) ++NumGVNBlocks;
2149 Changed |= removedBlock;
2152 unsigned Iteration = 0;
2153 while (ShouldContinue) {
2154 DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
2155 ShouldContinue = iterateOnFunction(F);
2156 if (splitCriticalEdges())
2157 ShouldContinue = true;
2158 Changed |= ShouldContinue;
2163 bool PREChanged = true;
2164 while (PREChanged) {
2165 PREChanged = performPRE(F);
2166 Changed |= PREChanged;
2169 // FIXME: Should perform GVN again after PRE does something. PRE can move
2170 // computations into blocks where they become fully redundant. Note that
2171 // we can't do this until PRE's critical edge splitting updates memdep.
2172 // Actually, when this happens, we should just fully integrate PRE into GVN.
2174 cleanupGlobalSets();
2180 bool GVN::processBlock(BasicBlock *BB) {
2181 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2182 // (and incrementing BI before processing an instruction).
2183 assert(InstrsToErase.empty() &&
2184 "We expect InstrsToErase to be empty across iterations");
2185 bool ChangedFunction = false;
2187 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2189 ChangedFunction |= processInstruction(BI);
2190 if (InstrsToErase.empty()) {
2195 // If we need some instructions deleted, do it now.
2196 NumGVNInstr += InstrsToErase.size();
2198 // Avoid iterator invalidation.
2199 bool AtStart = BI == BB->begin();
2203 for (SmallVector<Instruction*, 4>::iterator I = InstrsToErase.begin(),
2204 E = InstrsToErase.end(); I != E; ++I) {
2205 DEBUG(dbgs() << "GVN removed: " << **I << '\n');
2206 if (MD) MD->removeInstruction(*I);
2207 (*I)->eraseFromParent();
2208 DEBUG(verifyRemoved(*I));
2210 InstrsToErase.clear();
2218 return ChangedFunction;
2221 /// performPRE - Perform a purely local form of PRE that looks for diamond
2222 /// control flow patterns and attempts to perform simple PRE at the join point.
2223 bool GVN::performPRE(Function &F) {
2224 bool Changed = false;
2225 DenseMap<BasicBlock*, Value*> predMap;
2226 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2227 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
2228 BasicBlock *CurrentBlock = *DI;
2230 // Nothing to PRE in the entry block.
2231 if (CurrentBlock == &F.getEntryBlock()) continue;
2233 // Don't perform PRE on a landing pad.
2234 if (CurrentBlock->isLandingPad()) continue;
2236 for (BasicBlock::iterator BI = CurrentBlock->begin(),
2237 BE = CurrentBlock->end(); BI != BE; ) {
2238 Instruction *CurInst = BI++;
2240 if (isa<AllocaInst>(CurInst) ||
2241 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
2242 CurInst->getType()->isVoidTy() ||
2243 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2244 isa<DbgInfoIntrinsic>(CurInst))
2247 // We don't currently value number ANY inline asm calls.
2248 if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2249 if (CallI->isInlineAsm())
2252 uint32_t ValNo = VN.lookup(CurInst);
2254 // Look for the predecessors for PRE opportunities. We're
2255 // only trying to solve the basic diamond case, where
2256 // a value is computed in the successor and one predecessor,
2257 // but not the other. We also explicitly disallow cases
2258 // where the successor is its own predecessor, because they're
2259 // more complicated to get right.
2260 unsigned NumWith = 0;
2261 unsigned NumWithout = 0;
2262 BasicBlock *PREPred = 0;
2265 for (pred_iterator PI = pred_begin(CurrentBlock),
2266 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
2267 BasicBlock *P = *PI;
2268 // We're not interested in PRE where the block is its
2269 // own predecessor, or in blocks with predecessors
2270 // that are not reachable.
2271 if (P == CurrentBlock) {
2274 } else if (!DT->dominates(&F.getEntryBlock(), P)) {
2279 Value* predV = findLeader(P, ValNo);
2283 } else if (predV == CurInst) {
2291 // Don't do PRE when it might increase code size, i.e. when
2292 // we would need to insert instructions in more than one pred.
2293 if (NumWithout != 1 || NumWith == 0)
2296 // Don't do PRE across indirect branch.
2297 if (isa<IndirectBrInst>(PREPred->getTerminator()))
2300 // We can't do PRE safely on a critical edge, so instead we schedule
2301 // the edge to be split and perform the PRE the next time we iterate
2303 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2304 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2305 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2309 // Instantiate the expression in the predecessor that lacked it.
2310 // Because we are going top-down through the block, all value numbers
2311 // will be available in the predecessor by the time we need them. Any
2312 // that weren't originally present will have been instantiated earlier
2314 Instruction *PREInstr = CurInst->clone();
2315 bool success = true;
2316 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2317 Value *Op = PREInstr->getOperand(i);
2318 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2321 if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
2322 PREInstr->setOperand(i, V);
2329 // Fail out if we encounter an operand that is not available in
2330 // the PRE predecessor. This is typically because of loads which
2331 // are not value numbered precisely.
2334 DEBUG(verifyRemoved(PREInstr));
2338 PREInstr->insertBefore(PREPred->getTerminator());
2339 PREInstr->setName(CurInst->getName() + ".pre");
2340 PREInstr->setDebugLoc(CurInst->getDebugLoc());
2341 predMap[PREPred] = PREInstr;
2342 VN.add(PREInstr, ValNo);
2345 // Update the availability map to include the new instruction.
2346 addToLeaderTable(ValNo, PREInstr, PREPred);
2348 // Create a PHI to make the value available in this block.
2349 pred_iterator PB = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
2350 PHINode* Phi = PHINode::Create(CurInst->getType(), std::distance(PB, PE),
2351 CurInst->getName() + ".pre-phi",
2352 CurrentBlock->begin());
2353 for (pred_iterator PI = PB; PI != PE; ++PI) {
2354 BasicBlock *P = *PI;
2355 Phi->addIncoming(predMap[P], P);
2359 addToLeaderTable(ValNo, Phi, CurrentBlock);
2360 Phi->setDebugLoc(CurInst->getDebugLoc());
2361 CurInst->replaceAllUsesWith(Phi);
2362 if (Phi->getType()->isPointerTy()) {
2363 // Because we have added a PHI-use of the pointer value, it has now
2364 // "escaped" from alias analysis' perspective. We need to inform
2366 for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2368 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2369 VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2373 MD->invalidateCachedPointerInfo(Phi);
2376 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2378 DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2379 if (MD) MD->removeInstruction(CurInst);
2380 CurInst->eraseFromParent();
2381 DEBUG(verifyRemoved(CurInst));
2386 if (splitCriticalEdges())
2392 /// splitCriticalEdges - Split critical edges found during the previous
2393 /// iteration that may enable further optimization.
2394 bool GVN::splitCriticalEdges() {
2395 if (toSplit.empty())
2398 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2399 SplitCriticalEdge(Edge.first, Edge.second, this);
2400 } while (!toSplit.empty());
2401 if (MD) MD->invalidateCachedPredecessors();
2405 /// iterateOnFunction - Executes one iteration of GVN
2406 bool GVN::iterateOnFunction(Function &F) {
2407 cleanupGlobalSets();
2409 // Top-down walk of the dominator tree
2410 bool Changed = false;
2412 // Needed for value numbering with phi construction to work.
2413 ReversePostOrderTraversal<Function*> RPOT(&F);
2414 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2415 RE = RPOT.end(); RI != RE; ++RI)
2416 Changed |= processBlock(*RI);
2418 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2419 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
2420 Changed |= processBlock(DI->getBlock());
2426 void GVN::cleanupGlobalSets() {
2428 LeaderTable.clear();
2429 TableAllocator.Reset();
2432 /// verifyRemoved - Verify that the specified instruction does not occur in our
2433 /// internal data structures.
2434 void GVN::verifyRemoved(const Instruction *Inst) const {
2435 VN.verifyRemoved(Inst);
2437 // Walk through the value number scope to make sure the instruction isn't
2438 // ferreted away in it.
2439 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2440 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2441 const LeaderTableEntry *Node = &I->second;
2442 assert(Node->Val != Inst && "Inst still in value numbering scope!");
2444 while (Node->Next) {
2446 assert(Node->Val != Inst && "Inst still in value numbering scope!");