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/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/SSAUpdater.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/DepthFirstIterator.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Support/Allocator.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/IRBuilder.h"
46 STATISTIC(NumGVNInstr, "Number of instructions deleted");
47 STATISTIC(NumGVNLoad, "Number of loads deleted");
48 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
49 STATISTIC(NumGVNBlocks, "Number of blocks merged");
50 STATISTIC(NumPRELoad, "Number of loads PRE'd");
52 static cl::opt<bool> EnablePRE("enable-pre",
53 cl::init(true), cl::Hidden);
54 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
56 //===----------------------------------------------------------------------===//
58 //===----------------------------------------------------------------------===//
60 /// This class holds the mapping between values and value numbers. It is used
61 /// as an efficient mechanism to determine the expression-wise equivalence of
67 SmallVector<uint32_t, 4> varargs;
69 Expression(uint32_t o = ~2U) : opcode(o) { }
71 bool operator==(const Expression &other) const {
72 if (opcode != other.opcode)
74 if (opcode == ~0U || opcode == ~1U)
76 if (type != other.type)
78 if (varargs != other.varargs)
85 DenseMap<Value*, uint32_t> valueNumbering;
86 DenseMap<Expression, uint32_t> expressionNumbering;
88 MemoryDependenceAnalysis *MD;
91 uint32_t nextValueNumber;
93 Expression create_expression(Instruction* I);
94 uint32_t lookup_or_add_call(CallInst* C);
96 ValueTable() : nextValueNumber(1) { }
97 uint32_t lookup_or_add(Value *V);
98 uint32_t lookup(Value *V) const;
99 void add(Value *V, uint32_t num);
101 void erase(Value *v);
102 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
103 AliasAnalysis *getAliasAnalysis() const { return AA; }
104 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
105 void setDomTree(DominatorTree* D) { DT = D; }
106 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
107 void verifyRemoved(const Value *) const;
112 template <> struct DenseMapInfo<Expression> {
113 static inline Expression getEmptyKey() {
117 static inline Expression getTombstoneKey() {
121 static unsigned getHashValue(const Expression e) {
122 unsigned hash = e.opcode;
124 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
125 (unsigned)((uintptr_t)e.type >> 9));
127 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
128 E = e.varargs.end(); I != E; ++I)
129 hash = *I + hash * 37;
133 static bool isEqual(const Expression &LHS, const Expression &RHS) {
140 //===----------------------------------------------------------------------===//
141 // ValueTable Internal Functions
142 //===----------------------------------------------------------------------===//
145 Expression ValueTable::create_expression(Instruction *I) {
147 e.type = I->getType();
148 e.opcode = I->getOpcode();
149 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
151 e.varargs.push_back(lookup_or_add(*OI));
153 if (CmpInst *C = dyn_cast<CmpInst>(I))
154 e.opcode = (C->getOpcode() << 8) | C->getPredicate();
155 else if (ExtractValueInst *E = dyn_cast<ExtractValueInst>(I)) {
156 for (ExtractValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
158 e.varargs.push_back(*II);
159 } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
160 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
162 e.varargs.push_back(*II);
168 //===----------------------------------------------------------------------===//
169 // ValueTable External Functions
170 //===----------------------------------------------------------------------===//
172 /// add - Insert a value into the table with a specified value number.
173 void ValueTable::add(Value *V, uint32_t num) {
174 valueNumbering.insert(std::make_pair(V, num));
177 uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
178 if (AA->doesNotAccessMemory(C)) {
179 Expression exp = create_expression(C);
180 uint32_t& e = expressionNumbering[exp];
181 if (!e) e = nextValueNumber++;
182 valueNumbering[C] = e;
184 } else if (AA->onlyReadsMemory(C)) {
185 Expression exp = create_expression(C);
186 uint32_t& e = expressionNumbering[exp];
188 e = nextValueNumber++;
189 valueNumbering[C] = e;
193 e = nextValueNumber++;
194 valueNumbering[C] = e;
198 MemDepResult local_dep = MD->getDependency(C);
200 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
201 valueNumbering[C] = nextValueNumber;
202 return nextValueNumber++;
205 if (local_dep.isDef()) {
206 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
208 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
209 valueNumbering[C] = nextValueNumber;
210 return nextValueNumber++;
213 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
214 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
215 uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
217 valueNumbering[C] = nextValueNumber;
218 return nextValueNumber++;
222 uint32_t v = lookup_or_add(local_cdep);
223 valueNumbering[C] = v;
228 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
229 MD->getNonLocalCallDependency(CallSite(C));
230 // FIXME: Move the checking logic to MemDep!
233 // Check to see if we have a single dominating call instruction that is
235 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
236 const NonLocalDepEntry *I = &deps[i];
237 if (I->getResult().isNonLocal())
240 // We don't handle non-definitions. If we already have a call, reject
241 // instruction dependencies.
242 if (!I->getResult().isDef() || cdep != 0) {
247 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
248 // FIXME: All duplicated with non-local case.
249 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
250 cdep = NonLocalDepCall;
259 valueNumbering[C] = nextValueNumber;
260 return nextValueNumber++;
263 if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
264 valueNumbering[C] = nextValueNumber;
265 return nextValueNumber++;
267 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
268 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
269 uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
271 valueNumbering[C] = nextValueNumber;
272 return nextValueNumber++;
276 uint32_t v = lookup_or_add(cdep);
277 valueNumbering[C] = v;
281 valueNumbering[C] = nextValueNumber;
282 return nextValueNumber++;
286 /// lookup_or_add - Returns the value number for the specified value, assigning
287 /// it a new number if it did not have one before.
288 uint32_t ValueTable::lookup_or_add(Value *V) {
289 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
290 if (VI != valueNumbering.end())
293 if (!isa<Instruction>(V)) {
294 valueNumbering[V] = nextValueNumber;
295 return nextValueNumber++;
298 Instruction* I = cast<Instruction>(V);
300 switch (I->getOpcode()) {
301 case Instruction::Call:
302 return lookup_or_add_call(cast<CallInst>(I));
303 case Instruction::Add:
304 case Instruction::FAdd:
305 case Instruction::Sub:
306 case Instruction::FSub:
307 case Instruction::Mul:
308 case Instruction::FMul:
309 case Instruction::UDiv:
310 case Instruction::SDiv:
311 case Instruction::FDiv:
312 case Instruction::URem:
313 case Instruction::SRem:
314 case Instruction::FRem:
315 case Instruction::Shl:
316 case Instruction::LShr:
317 case Instruction::AShr:
318 case Instruction::And:
319 case Instruction::Or :
320 case Instruction::Xor:
321 case Instruction::ICmp:
322 case Instruction::FCmp:
323 case Instruction::Trunc:
324 case Instruction::ZExt:
325 case Instruction::SExt:
326 case Instruction::FPToUI:
327 case Instruction::FPToSI:
328 case Instruction::UIToFP:
329 case Instruction::SIToFP:
330 case Instruction::FPTrunc:
331 case Instruction::FPExt:
332 case Instruction::PtrToInt:
333 case Instruction::IntToPtr:
334 case Instruction::BitCast:
335 case Instruction::Select:
336 case Instruction::ExtractElement:
337 case Instruction::InsertElement:
338 case Instruction::ShuffleVector:
339 case Instruction::ExtractValue:
340 case Instruction::InsertValue:
341 case Instruction::GetElementPtr:
342 exp = create_expression(I);
345 valueNumbering[V] = nextValueNumber;
346 return nextValueNumber++;
349 uint32_t& e = expressionNumbering[exp];
350 if (!e) e = nextValueNumber++;
351 valueNumbering[V] = e;
355 /// lookup - Returns the value number of the specified value. Fails if
356 /// the value has not yet been numbered.
357 uint32_t ValueTable::lookup(Value *V) const {
358 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
359 assert(VI != valueNumbering.end() && "Value not numbered?");
363 /// clear - Remove all entries from the ValueTable.
364 void ValueTable::clear() {
365 valueNumbering.clear();
366 expressionNumbering.clear();
370 /// erase - Remove a value from the value numbering.
371 void ValueTable::erase(Value *V) {
372 valueNumbering.erase(V);
375 /// verifyRemoved - Verify that the value is removed from all internal data
377 void ValueTable::verifyRemoved(const Value *V) const {
378 for (DenseMap<Value*, uint32_t>::const_iterator
379 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
380 assert(I->first != V && "Inst still occurs in value numbering map!");
384 //===----------------------------------------------------------------------===//
386 //===----------------------------------------------------------------------===//
390 class GVN : public FunctionPass {
392 MemoryDependenceAnalysis *MD;
394 const TargetData *TD;
398 /// LeaderTable - A mapping from value numbers to lists of Value*'s that
399 /// have that value number. Use findLeader to query it.
400 struct LeaderTableEntry {
403 LeaderTableEntry *Next;
405 DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
406 BumpPtrAllocator TableAllocator;
408 SmallVector<Instruction*, 8> InstrsToErase;
410 static char ID; // Pass identification, replacement for typeid
411 explicit GVN(bool noloads = false)
412 : FunctionPass(ID), NoLoads(noloads), MD(0) {
413 initializeGVNPass(*PassRegistry::getPassRegistry());
416 bool runOnFunction(Function &F);
418 /// markInstructionForDeletion - This removes the specified instruction from
419 /// our various maps and marks it for deletion.
420 void markInstructionForDeletion(Instruction *I) {
422 InstrsToErase.push_back(I);
425 const TargetData *getTargetData() const { return TD; }
426 DominatorTree &getDominatorTree() const { return *DT; }
427 AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
428 MemoryDependenceAnalysis &getMemDep() const { return *MD; }
430 /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
431 /// its value number.
432 void addToLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
433 LeaderTableEntry &Curr = LeaderTable[N];
440 LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
443 Node->Next = Curr.Next;
447 /// removeFromLeaderTable - Scan the list of values corresponding to a given
448 /// value number, and remove the given value if encountered.
449 void removeFromLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
450 LeaderTableEntry* Prev = 0;
451 LeaderTableEntry* Curr = &LeaderTable[N];
453 while (Curr->Val != V || Curr->BB != BB) {
459 Prev->Next = Curr->Next;
465 LeaderTableEntry* Next = Curr->Next;
466 Curr->Val = Next->Val;
468 Curr->Next = Next->Next;
473 // List of critical edges to be split between iterations.
474 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
476 // This transformation requires dominator postdominator info
477 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
478 AU.addRequired<DominatorTree>();
480 AU.addRequired<MemoryDependenceAnalysis>();
481 AU.addRequired<AliasAnalysis>();
483 AU.addPreserved<DominatorTree>();
484 AU.addPreserved<AliasAnalysis>();
489 // FIXME: eliminate or document these better
490 bool processLoad(LoadInst *L);
491 bool processInstruction(Instruction *I);
492 bool processNonLocalLoad(LoadInst *L);
493 bool processBlock(BasicBlock *BB);
494 void dump(DenseMap<uint32_t, Value*> &d);
495 bool iterateOnFunction(Function &F);
496 bool performPRE(Function &F);
497 Value *findLeader(BasicBlock *BB, uint32_t num);
498 void cleanupGlobalSets();
499 void verifyRemoved(const Instruction *I) const;
500 bool splitCriticalEdges();
506 // createGVNPass - The public interface to this file...
507 FunctionPass *llvm::createGVNPass(bool NoLoads) {
508 return new GVN(NoLoads);
511 INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
512 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
513 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
514 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
515 INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
517 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
519 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
520 E = d.end(); I != E; ++I) {
521 errs() << I->first << "\n";
527 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
528 /// we're analyzing is fully available in the specified block. As we go, keep
529 /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
530 /// map is actually a tri-state map with the following values:
531 /// 0) we know the block *is not* fully available.
532 /// 1) we know the block *is* fully available.
533 /// 2) we do not know whether the block is fully available or not, but we are
534 /// currently speculating that it will be.
535 /// 3) we are speculating for this block and have used that to speculate for
537 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
538 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
539 // Optimistically assume that the block is fully available and check to see
540 // if we already know about this block in one lookup.
541 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
542 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
544 // If the entry already existed for this block, return the precomputed value.
546 // If this is a speculative "available" value, mark it as being used for
547 // speculation of other blocks.
548 if (IV.first->second == 2)
549 IV.first->second = 3;
550 return IV.first->second != 0;
553 // Otherwise, see if it is fully available in all predecessors.
554 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
556 // If this block has no predecessors, it isn't live-in here.
558 goto SpeculationFailure;
560 for (; PI != PE; ++PI)
561 // If the value isn't fully available in one of our predecessors, then it
562 // isn't fully available in this block either. Undo our previous
563 // optimistic assumption and bail out.
564 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
565 goto SpeculationFailure;
569 // SpeculationFailure - If we get here, we found out that this is not, after
570 // all, a fully-available block. We have a problem if we speculated on this and
571 // used the speculation to mark other blocks as available.
573 char &BBVal = FullyAvailableBlocks[BB];
575 // If we didn't speculate on this, just return with it set to false.
581 // If we did speculate on this value, we could have blocks set to 1 that are
582 // incorrect. Walk the (transitive) successors of this block and mark them as
584 SmallVector<BasicBlock*, 32> BBWorklist;
585 BBWorklist.push_back(BB);
588 BasicBlock *Entry = BBWorklist.pop_back_val();
589 // Note that this sets blocks to 0 (unavailable) if they happen to not
590 // already be in FullyAvailableBlocks. This is safe.
591 char &EntryVal = FullyAvailableBlocks[Entry];
592 if (EntryVal == 0) continue; // Already unavailable.
594 // Mark as unavailable.
597 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
598 BBWorklist.push_back(*I);
599 } while (!BBWorklist.empty());
605 /// CanCoerceMustAliasedValueToLoad - Return true if
606 /// CoerceAvailableValueToLoadType will succeed.
607 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
609 const TargetData &TD) {
610 // If the loaded or stored value is an first class array or struct, don't try
611 // to transform them. We need to be able to bitcast to integer.
612 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
613 StoredVal->getType()->isStructTy() ||
614 StoredVal->getType()->isArrayTy())
617 // The store has to be at least as big as the load.
618 if (TD.getTypeSizeInBits(StoredVal->getType()) <
619 TD.getTypeSizeInBits(LoadTy))
626 /// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
627 /// then a load from a must-aliased pointer of a different type, try to coerce
628 /// the stored value. LoadedTy is the type of the load we want to replace and
629 /// InsertPt is the place to insert new instructions.
631 /// If we can't do it, return null.
632 static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
633 const Type *LoadedTy,
634 Instruction *InsertPt,
635 const TargetData &TD) {
636 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
639 // If this is already the right type, just return it.
640 const Type *StoredValTy = StoredVal->getType();
642 uint64_t StoreSize = TD.getTypeStoreSizeInBits(StoredValTy);
643 uint64_t LoadSize = TD.getTypeStoreSizeInBits(LoadedTy);
645 // If the store and reload are the same size, we can always reuse it.
646 if (StoreSize == LoadSize) {
647 // Pointer to Pointer -> use bitcast.
648 if (StoredValTy->isPointerTy() && LoadedTy->isPointerTy())
649 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
651 // Convert source pointers to integers, which can be bitcast.
652 if (StoredValTy->isPointerTy()) {
653 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
654 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
657 const Type *TypeToCastTo = LoadedTy;
658 if (TypeToCastTo->isPointerTy())
659 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
661 if (StoredValTy != TypeToCastTo)
662 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
664 // Cast to pointer if the load needs a pointer type.
665 if (LoadedTy->isPointerTy())
666 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
671 // If the loaded value is smaller than the available value, then we can
672 // extract out a piece from it. If the available value is too small, then we
673 // can't do anything.
674 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
676 // Convert source pointers to integers, which can be manipulated.
677 if (StoredValTy->isPointerTy()) {
678 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
679 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
682 // Convert vectors and fp to integer, which can be manipulated.
683 if (!StoredValTy->isIntegerTy()) {
684 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
685 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
688 // If this is a big-endian system, we need to shift the value down to the low
689 // bits so that a truncate will work.
690 if (TD.isBigEndian()) {
691 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
692 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
695 // Truncate the integer to the right size now.
696 const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
697 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
699 if (LoadedTy == NewIntTy)
702 // If the result is a pointer, inttoptr.
703 if (LoadedTy->isPointerTy())
704 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
706 // Otherwise, bitcast.
707 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
710 /// AnalyzeLoadFromClobberingWrite - This function is called when we have a
711 /// memdep query of a load that ends up being a clobbering memory write (store,
712 /// memset, memcpy, memmove). This means that the write *may* provide bits used
713 /// by the load but we can't be sure because the pointers don't mustalias.
715 /// Check this case to see if there is anything more we can do before we give
716 /// up. This returns -1 if we have to give up, or a byte number in the stored
717 /// value of the piece that feeds the load.
718 static int AnalyzeLoadFromClobberingWrite(const Type *LoadTy, Value *LoadPtr,
720 uint64_t WriteSizeInBits,
721 const TargetData &TD) {
722 // If the loaded or stored value is an first class array or struct, don't try
723 // to transform them. We need to be able to bitcast to integer.
724 if (LoadTy->isStructTy() || LoadTy->isArrayTy())
727 int64_t StoreOffset = 0, LoadOffset = 0;
728 Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr, StoreOffset,TD);
729 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, TD);
730 if (StoreBase != LoadBase)
733 // If the load and store are to the exact same address, they should have been
734 // a must alias. AA must have gotten confused.
735 // FIXME: Study to see if/when this happens. One case is forwarding a memset
736 // to a load from the base of the memset.
738 if (LoadOffset == StoreOffset) {
739 dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
740 << "Base = " << *StoreBase << "\n"
741 << "Store Ptr = " << *WritePtr << "\n"
742 << "Store Offs = " << StoreOffset << "\n"
743 << "Load Ptr = " << *LoadPtr << "\n";
748 // If the load and store don't overlap at all, the store doesn't provide
749 // anything to the load. In this case, they really don't alias at all, AA
750 // must have gotten confused.
751 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy);
753 if ((WriteSizeInBits & 7) | (LoadSize & 7))
755 uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
759 bool isAAFailure = false;
760 if (StoreOffset < LoadOffset)
761 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
763 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
767 dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
768 << "Base = " << *StoreBase << "\n"
769 << "Store Ptr = " << *WritePtr << "\n"
770 << "Store Offs = " << StoreOffset << "\n"
771 << "Load Ptr = " << *LoadPtr << "\n";
777 // If the Load isn't completely contained within the stored bits, we don't
778 // have all the bits to feed it. We could do something crazy in the future
779 // (issue a smaller load then merge the bits in) but this seems unlikely to be
781 if (StoreOffset > LoadOffset ||
782 StoreOffset+StoreSize < LoadOffset+LoadSize)
785 // Okay, we can do this transformation. Return the number of bytes into the
786 // store that the load is.
787 return LoadOffset-StoreOffset;
790 /// AnalyzeLoadFromClobberingStore - This function is called when we have a
791 /// memdep query of a load that ends up being a clobbering store.
792 static int AnalyzeLoadFromClobberingStore(const Type *LoadTy, Value *LoadPtr,
794 const TargetData &TD) {
795 // Cannot handle reading from store of first-class aggregate yet.
796 if (DepSI->getValueOperand()->getType()->isStructTy() ||
797 DepSI->getValueOperand()->getType()->isArrayTy())
800 Value *StorePtr = DepSI->getPointerOperand();
801 uint64_t StoreSize =TD.getTypeSizeInBits(DepSI->getValueOperand()->getType());
802 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
803 StorePtr, StoreSize, TD);
806 /// AnalyzeLoadFromClobberingLoad - This function is called when we have a
807 /// memdep query of a load that ends up being clobbered by another load. See if
808 /// the other load can feed into the second load.
809 static int AnalyzeLoadFromClobberingLoad(const Type *LoadTy, Value *LoadPtr,
810 LoadInst *DepLI, const TargetData &TD){
811 // Cannot handle reading from store of first-class aggregate yet.
812 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
815 Value *DepPtr = DepLI->getPointerOperand();
816 uint64_t DepSize = TD.getTypeSizeInBits(DepLI->getType());
817 int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, TD);
818 if (R != -1) return R;
820 // If we have a load/load clobber an DepLI can be widened to cover this load,
821 // then we should widen it!
822 int64_t LoadOffs = 0;
823 const Value *LoadBase =
824 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, TD);
825 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
827 unsigned Size = MemoryDependenceAnalysis::
828 getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, TD);
829 if (Size == 0) return -1;
831 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, TD);
836 static int AnalyzeLoadFromClobberingMemInst(const Type *LoadTy, Value *LoadPtr,
838 const TargetData &TD) {
839 // If the mem operation is a non-constant size, we can't handle it.
840 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
841 if (SizeCst == 0) return -1;
842 uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
844 // If this is memset, we just need to see if the offset is valid in the size
846 if (MI->getIntrinsicID() == Intrinsic::memset)
847 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
850 // If we have a memcpy/memmove, the only case we can handle is if this is a
851 // copy from constant memory. In that case, we can read directly from the
853 MemTransferInst *MTI = cast<MemTransferInst>(MI);
855 Constant *Src = dyn_cast<Constant>(MTI->getSource());
856 if (Src == 0) return -1;
858 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &TD));
859 if (GV == 0 || !GV->isConstant()) return -1;
861 // See if the access is within the bounds of the transfer.
862 int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
863 MI->getDest(), MemSizeInBits, TD);
867 // Otherwise, see if we can constant fold a load from the constant with the
868 // offset applied as appropriate.
869 Src = ConstantExpr::getBitCast(Src,
870 llvm::Type::getInt8PtrTy(Src->getContext()));
871 Constant *OffsetCst =
872 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
873 Src = ConstantExpr::getGetElementPtr(Src, &OffsetCst, 1);
874 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
875 if (ConstantFoldLoadFromConstPtr(Src, &TD))
881 /// GetStoreValueForLoad - This function is called when we have a
882 /// memdep query of a load that ends up being a clobbering store. This means
883 /// that the store provides bits used by the load but we the pointers don't
884 /// mustalias. Check this case to see if there is anything more we can do
885 /// before we give up.
886 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
888 Instruction *InsertPt, const TargetData &TD){
889 LLVMContext &Ctx = SrcVal->getType()->getContext();
891 uint64_t StoreSize = (TD.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
892 uint64_t LoadSize = (TD.getTypeSizeInBits(LoadTy) + 7) / 8;
894 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
896 // Compute which bits of the stored value are being used by the load. Convert
897 // to an integer type to start with.
898 if (SrcVal->getType()->isPointerTy())
899 SrcVal = Builder.CreatePtrToInt(SrcVal, TD.getIntPtrType(Ctx), "tmp");
900 if (!SrcVal->getType()->isIntegerTy())
901 SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8),
904 // Shift the bits to the least significant depending on endianness.
906 if (TD.isLittleEndian())
909 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
912 SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt, "tmp");
914 if (LoadSize != StoreSize)
915 SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8),
918 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
921 /// GetStoreValueForLoad - This function is called when we have a
922 /// memdep query of a load that ends up being a clobbering load. This means
923 /// that the load *may* provide bits used by the load but we can't be sure
924 /// because the pointers don't mustalias. Check this case to see if there is
925 /// anything more we can do before we give up.
926 static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
927 const Type *LoadTy, Instruction *InsertPt,
929 const TargetData &TD = *gvn.getTargetData();
930 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
931 // widen SrcVal out to a larger load.
932 unsigned SrcValSize = TD.getTypeStoreSize(SrcVal->getType());
933 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
934 if (Offset+LoadSize > SrcValSize) {
935 assert(!SrcVal->isVolatile() && "Cannot widen volatile load!");
936 assert(isa<IntegerType>(SrcVal->getType())&&"Can't widen non-integer load");
937 // If we have a load/load clobber an DepLI can be widened to cover this
938 // load, then we should widen it to the next power of 2 size big enough!
939 unsigned NewLoadSize = Offset+LoadSize;
940 if (!isPowerOf2_32(NewLoadSize))
941 NewLoadSize = NextPowerOf2(NewLoadSize);
943 Value *PtrVal = SrcVal->getPointerOperand();
945 // Insert the new load after the old load. This ensures that subsequent
946 // memdep queries will find the new load. We can't easily remove the old
947 // load completely because it is already in the value numbering table.
948 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
949 const Type *DestPTy =
950 IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
951 DestPTy = PointerType::get(DestPTy,
952 cast<PointerType>(PtrVal->getType())->getAddressSpace());
953 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
954 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
955 LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
956 NewLoad->takeName(SrcVal);
957 NewLoad->setAlignment(SrcVal->getAlignment());
959 DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
960 DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
962 // Replace uses of the original load with the wider load. On a big endian
963 // system, we need to shift down to get the relevant bits.
965 if (TD.isBigEndian())
966 RV = Builder.CreateLShr(RV,
967 NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
968 RV = Builder.CreateTrunc(RV, SrcVal->getType());
969 SrcVal->replaceAllUsesWith(RV);
971 // We would like to use gvn.markInstructionForDeletion here, but we can't
972 // because the load is already memoized into the leader map table that GVN
973 // tracks. It is potentially possible to remove the load from the table,
974 // but then there all of the operations based on it would need to be
975 // rehashed. Just leave the dead load around.
976 gvn.getMemDep().removeInstruction(SrcVal);
980 return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, TD);
984 /// GetMemInstValueForLoad - This function is called when we have a
985 /// memdep query of a load that ends up being a clobbering mem intrinsic.
986 static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
987 const Type *LoadTy, Instruction *InsertPt,
988 const TargetData &TD){
989 LLVMContext &Ctx = LoadTy->getContext();
990 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
992 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
994 // We know that this method is only called when the mem transfer fully
995 // provides the bits for the load.
996 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
997 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
998 // independently of what the offset is.
999 Value *Val = MSI->getValue();
1001 Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1003 Value *OneElt = Val;
1005 // Splat the value out to the right number of bits.
1006 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1007 // If we can double the number of bytes set, do it.
1008 if (NumBytesSet*2 <= LoadSize) {
1009 Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1010 Val = Builder.CreateOr(Val, ShVal);
1015 // Otherwise insert one byte at a time.
1016 Value *ShVal = Builder.CreateShl(Val, 1*8);
1017 Val = Builder.CreateOr(OneElt, ShVal);
1021 return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, TD);
1024 // Otherwise, this is a memcpy/memmove from a constant global.
1025 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1026 Constant *Src = cast<Constant>(MTI->getSource());
1028 // Otherwise, see if we can constant fold a load from the constant with the
1029 // offset applied as appropriate.
1030 Src = ConstantExpr::getBitCast(Src,
1031 llvm::Type::getInt8PtrTy(Src->getContext()));
1032 Constant *OffsetCst =
1033 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1034 Src = ConstantExpr::getGetElementPtr(Src, &OffsetCst, 1);
1035 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1036 return ConstantFoldLoadFromConstPtr(Src, &TD);
1041 struct AvailableValueInBlock {
1042 /// BB - The basic block in question.
1045 SimpleVal, // A simple offsetted value that is accessed.
1046 LoadVal, // A value produced by a load.
1047 MemIntrin // A memory intrinsic which is loaded from.
1050 /// V - The value that is live out of the block.
1051 PointerIntPair<Value *, 2, ValType> Val;
1053 /// Offset - The byte offset in Val that is interesting for the load query.
1056 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1057 unsigned Offset = 0) {
1058 AvailableValueInBlock Res;
1060 Res.Val.setPointer(V);
1061 Res.Val.setInt(SimpleVal);
1062 Res.Offset = Offset;
1066 static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
1067 unsigned Offset = 0) {
1068 AvailableValueInBlock Res;
1070 Res.Val.setPointer(MI);
1071 Res.Val.setInt(MemIntrin);
1072 Res.Offset = Offset;
1076 static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
1077 unsigned Offset = 0) {
1078 AvailableValueInBlock Res;
1080 Res.Val.setPointer(LI);
1081 Res.Val.setInt(LoadVal);
1082 Res.Offset = Offset;
1086 bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
1087 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
1088 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
1090 Value *getSimpleValue() const {
1091 assert(isSimpleValue() && "Wrong accessor");
1092 return Val.getPointer();
1095 LoadInst *getCoercedLoadValue() const {
1096 assert(isCoercedLoadValue() && "Wrong accessor");
1097 return cast<LoadInst>(Val.getPointer());
1100 MemIntrinsic *getMemIntrinValue() const {
1101 assert(isMemIntrinValue() && "Wrong accessor");
1102 return cast<MemIntrinsic>(Val.getPointer());
1105 /// MaterializeAdjustedValue - Emit code into this block to adjust the value
1106 /// defined here to the specified type. This handles various coercion cases.
1107 Value *MaterializeAdjustedValue(const Type *LoadTy, GVN &gvn) const {
1109 if (isSimpleValue()) {
1110 Res = getSimpleValue();
1111 if (Res->getType() != LoadTy) {
1112 const TargetData *TD = gvn.getTargetData();
1113 assert(TD && "Need target data to handle type mismatch case");
1114 Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1117 DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
1118 << *getSimpleValue() << '\n'
1119 << *Res << '\n' << "\n\n\n");
1121 } else if (isCoercedLoadValue()) {
1122 LoadInst *Load = getCoercedLoadValue();
1123 if (Load->getType() == LoadTy && Offset == 0) {
1126 Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
1129 DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
1130 << *getCoercedLoadValue() << '\n'
1131 << *Res << '\n' << "\n\n\n");
1134 const TargetData *TD = gvn.getTargetData();
1135 assert(TD && "Need target data to handle type mismatch case");
1136 Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1137 LoadTy, BB->getTerminator(), *TD);
1138 DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1139 << " " << *getMemIntrinValue() << '\n'
1140 << *Res << '\n' << "\n\n\n");
1146 } // end anonymous namespace
1148 /// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1149 /// construct SSA form, allowing us to eliminate LI. This returns the value
1150 /// that should be used at LI's definition site.
1151 static Value *ConstructSSAForLoadSet(LoadInst *LI,
1152 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1154 // Check for the fully redundant, dominating load case. In this case, we can
1155 // just use the dominating value directly.
1156 if (ValuesPerBlock.size() == 1 &&
1157 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1159 return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
1161 // Otherwise, we have to construct SSA form.
1162 SmallVector<PHINode*, 8> NewPHIs;
1163 SSAUpdater SSAUpdate(&NewPHIs);
1164 SSAUpdate.Initialize(LI->getType(), LI->getName());
1166 const Type *LoadTy = LI->getType();
1168 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1169 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1170 BasicBlock *BB = AV.BB;
1172 if (SSAUpdate.HasValueForBlock(BB))
1175 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
1178 // Perform PHI construction.
1179 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1181 // If new PHI nodes were created, notify alias analysis.
1182 if (V->getType()->isPointerTy()) {
1183 AliasAnalysis *AA = gvn.getAliasAnalysis();
1185 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1186 AA->copyValue(LI, NewPHIs[i]);
1188 // Now that we've copied information to the new PHIs, scan through
1189 // them again and inform alias analysis that we've added potentially
1190 // escaping uses to any values that are operands to these PHIs.
1191 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1192 PHINode *P = NewPHIs[i];
1193 for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii)
1194 AA->addEscapingUse(P->getOperandUse(2*ii));
1201 static bool isLifetimeStart(const Instruction *Inst) {
1202 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1203 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1207 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1208 /// non-local by performing PHI construction.
1209 bool GVN::processNonLocalLoad(LoadInst *LI) {
1210 // Find the non-local dependencies of the load.
1211 SmallVector<NonLocalDepResult, 64> Deps;
1212 AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1213 MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
1214 //DEBUG(dbgs() << "INVESTIGATING NONLOCAL LOAD: "
1215 // << Deps.size() << *LI << '\n');
1217 // If we had to process more than one hundred blocks to find the
1218 // dependencies, this load isn't worth worrying about. Optimizing
1219 // it will be too expensive.
1220 if (Deps.size() > 100)
1223 // If we had a phi translation failure, we'll have a single entry which is a
1224 // clobber in the current block. Reject this early.
1225 if (Deps.size() == 1 && Deps[0].getResult().isUnknown()) {
1227 dbgs() << "GVN: non-local load ";
1228 WriteAsOperand(dbgs(), LI);
1229 dbgs() << " has unknown dependencies\n";
1234 // Filter out useless results (non-locals, etc). Keep track of the blocks
1235 // where we have a value available in repl, also keep track of whether we see
1236 // dependencies that produce an unknown value for the load (such as a call
1237 // that could potentially clobber the load).
1238 SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
1239 SmallVector<BasicBlock*, 16> UnavailableBlocks;
1241 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1242 BasicBlock *DepBB = Deps[i].getBB();
1243 MemDepResult DepInfo = Deps[i].getResult();
1245 if (DepInfo.isUnknown()) {
1246 UnavailableBlocks.push_back(DepBB);
1250 if (DepInfo.isClobber()) {
1251 // The address being loaded in this non-local block may not be the same as
1252 // the pointer operand of the load if PHI translation occurs. Make sure
1253 // to consider the right address.
1254 Value *Address = Deps[i].getAddress();
1256 // If the dependence is to a store that writes to a superset of the bits
1257 // read by the load, we can extract the bits we need for the load from the
1259 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1260 if (TD && Address) {
1261 int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
1264 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1265 DepSI->getValueOperand(),
1272 // Check to see if we have something like this:
1275 // if we have this, replace the later with an extraction from the former.
1276 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1277 // If this is a clobber and L is the first instruction in its block, then
1278 // we have the first instruction in the entry block.
1279 if (DepLI != LI && Address && TD) {
1280 int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1281 LI->getPointerOperand(),
1285 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1292 // If the clobbering value is a memset/memcpy/memmove, see if we can
1293 // forward a value on from it.
1294 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
1295 if (TD && Address) {
1296 int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
1299 ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1306 UnavailableBlocks.push_back(DepBB);
1310 assert(DepInfo.isDef() && "Expecting def here");
1312 Instruction *DepInst = DepInfo.getInst();
1314 // Loading the allocation -> undef.
1315 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst) ||
1316 // Loading immediately after lifetime begin -> undef.
1317 isLifetimeStart(DepInst)) {
1318 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1319 UndefValue::get(LI->getType())));
1323 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1324 // Reject loads and stores that are to the same address but are of
1325 // different types if we have to.
1326 if (S->getValueOperand()->getType() != LI->getType()) {
1327 // If the stored value is larger or equal to the loaded value, we can
1329 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
1330 LI->getType(), *TD)) {
1331 UnavailableBlocks.push_back(DepBB);
1336 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1337 S->getValueOperand()));
1341 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1342 // If the types mismatch and we can't handle it, reject reuse of the load.
1343 if (LD->getType() != LI->getType()) {
1344 // If the stored value is larger or equal to the loaded value, we can
1346 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
1347 UnavailableBlocks.push_back(DepBB);
1351 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
1355 UnavailableBlocks.push_back(DepBB);
1359 // If we have no predecessors that produce a known value for this load, exit
1361 if (ValuesPerBlock.empty()) return false;
1363 // If all of the instructions we depend on produce a known value for this
1364 // load, then it is fully redundant and we can use PHI insertion to compute
1365 // its value. Insert PHIs and remove the fully redundant value now.
1366 if (UnavailableBlocks.empty()) {
1367 DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1369 // Perform PHI construction.
1370 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1371 LI->replaceAllUsesWith(V);
1373 if (isa<PHINode>(V))
1375 if (V->getType()->isPointerTy())
1376 MD->invalidateCachedPointerInfo(V);
1377 markInstructionForDeletion(LI);
1382 if (!EnablePRE || !EnableLoadPRE)
1385 // Okay, we have *some* definitions of the value. This means that the value
1386 // is available in some of our (transitive) predecessors. Lets think about
1387 // doing PRE of this load. This will involve inserting a new load into the
1388 // predecessor when it's not available. We could do this in general, but
1389 // prefer to not increase code size. As such, we only do this when we know
1390 // that we only have to insert *one* load (which means we're basically moving
1391 // the load, not inserting a new one).
1393 SmallPtrSet<BasicBlock *, 4> Blockers;
1394 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1395 Blockers.insert(UnavailableBlocks[i]);
1397 // Lets find first basic block with more than one predecessor. Walk backwards
1398 // through predecessors if needed.
1399 BasicBlock *LoadBB = LI->getParent();
1400 BasicBlock *TmpBB = LoadBB;
1402 bool isSinglePred = false;
1403 bool allSingleSucc = true;
1404 while (TmpBB->getSinglePredecessor()) {
1405 isSinglePred = true;
1406 TmpBB = TmpBB->getSinglePredecessor();
1407 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1409 if (Blockers.count(TmpBB))
1412 // If any of these blocks has more than one successor (i.e. if the edge we
1413 // just traversed was critical), then there are other paths through this
1414 // block along which the load may not be anticipated. Hoisting the load
1415 // above this block would be adding the load to execution paths along
1416 // which it was not previously executed.
1417 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1424 // FIXME: It is extremely unclear what this loop is doing, other than
1425 // artificially restricting loadpre.
1428 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1429 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1430 if (AV.isSimpleValue())
1431 // "Hot" Instruction is in some loop (because it dominates its dep.
1433 if (Instruction *I = dyn_cast<Instruction>(AV.getSimpleValue()))
1434 if (DT->dominates(LI, I)) {
1440 // We are interested only in "hot" instructions. We don't want to do any
1441 // mis-optimizations here.
1446 // Check to see how many predecessors have the loaded value fully
1448 DenseMap<BasicBlock*, Value*> PredLoads;
1449 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1450 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1451 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
1452 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1453 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1455 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> NeedToSplit;
1456 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1458 BasicBlock *Pred = *PI;
1459 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
1462 PredLoads[Pred] = 0;
1464 if (Pred->getTerminator()->getNumSuccessors() != 1) {
1465 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1466 DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1467 << Pred->getName() << "': " << *LI << '\n');
1470 unsigned SuccNum = GetSuccessorNumber(Pred, LoadBB);
1471 NeedToSplit.push_back(std::make_pair(Pred->getTerminator(), SuccNum));
1474 if (!NeedToSplit.empty()) {
1475 toSplit.append(NeedToSplit.begin(), NeedToSplit.end());
1479 // Decide whether PRE is profitable for this load.
1480 unsigned NumUnavailablePreds = PredLoads.size();
1481 assert(NumUnavailablePreds != 0 &&
1482 "Fully available value should be eliminated above!");
1484 // If this load is unavailable in multiple predecessors, reject it.
1485 // FIXME: If we could restructure the CFG, we could make a common pred with
1486 // all the preds that don't have an available LI and insert a new load into
1488 if (NumUnavailablePreds != 1)
1491 // Check if the load can safely be moved to all the unavailable predecessors.
1492 bool CanDoPRE = true;
1493 SmallVector<Instruction*, 8> NewInsts;
1494 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1495 E = PredLoads.end(); I != E; ++I) {
1496 BasicBlock *UnavailablePred = I->first;
1498 // Do PHI translation to get its value in the predecessor if necessary. The
1499 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1501 // If all preds have a single successor, then we know it is safe to insert
1502 // the load on the pred (?!?), so we can insert code to materialize the
1503 // pointer if it is not available.
1504 PHITransAddr Address(LI->getPointerOperand(), TD);
1506 if (allSingleSucc) {
1507 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1510 Address.PHITranslateValue(LoadBB, UnavailablePred, DT);
1511 LoadPtr = Address.getAddr();
1514 // If we couldn't find or insert a computation of this phi translated value,
1517 DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1518 << *LI->getPointerOperand() << "\n");
1523 // Make sure it is valid to move this load here. We have to watch out for:
1524 // @1 = getelementptr (i8* p, ...
1525 // test p and branch if == 0
1527 // It is valid to have the getelementptr before the test, even if p can
1528 // be 0, as getelementptr only does address arithmetic.
1529 // If we are not pushing the value through any multiple-successor blocks
1530 // we do not have this case. Otherwise, check that the load is safe to
1531 // put anywhere; this can be improved, but should be conservatively safe.
1532 if (!allSingleSucc &&
1533 // FIXME: REEVALUTE THIS.
1534 !isSafeToLoadUnconditionally(LoadPtr,
1535 UnavailablePred->getTerminator(),
1536 LI->getAlignment(), TD)) {
1541 I->second = LoadPtr;
1545 while (!NewInsts.empty()) {
1546 Instruction *I = NewInsts.pop_back_val();
1547 if (MD) MD->removeInstruction(I);
1548 I->eraseFromParent();
1553 // Okay, we can eliminate this load by inserting a reload in the predecessor
1554 // and using PHI construction to get the value in the other predecessors, do
1556 DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1557 DEBUG(if (!NewInsts.empty())
1558 dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
1559 << *NewInsts.back() << '\n');
1561 // Assign value numbers to the new instructions.
1562 for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1563 // FIXME: We really _ought_ to insert these value numbers into their
1564 // parent's availability map. However, in doing so, we risk getting into
1565 // ordering issues. If a block hasn't been processed yet, we would be
1566 // marking a value as AVAIL-IN, which isn't what we intend.
1567 VN.lookup_or_add(NewInsts[i]);
1570 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1571 E = PredLoads.end(); I != E; ++I) {
1572 BasicBlock *UnavailablePred = I->first;
1573 Value *LoadPtr = I->second;
1575 Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1577 UnavailablePred->getTerminator());
1579 // Transfer the old load's TBAA tag to the new load.
1580 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1581 NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1583 // Transfer DebugLoc.
1584 NewLoad->setDebugLoc(LI->getDebugLoc());
1586 // Add the newly created load.
1587 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1589 MD->invalidateCachedPointerInfo(LoadPtr);
1590 DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1593 // Perform PHI construction.
1594 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1595 LI->replaceAllUsesWith(V);
1596 if (isa<PHINode>(V))
1598 if (V->getType()->isPointerTy())
1599 MD->invalidateCachedPointerInfo(V);
1600 markInstructionForDeletion(LI);
1605 /// processLoad - Attempt to eliminate a load, first by eliminating it
1606 /// locally, and then attempting non-local elimination if that fails.
1607 bool GVN::processLoad(LoadInst *L) {
1611 if (L->isVolatile())
1614 if (L->use_empty()) {
1615 markInstructionForDeletion(L);
1619 // ... to a pointer that has been loaded from before...
1620 MemDepResult Dep = MD->getDependency(L);
1622 // If we have a clobber and target data is around, see if this is a clobber
1623 // that we can fix up through code synthesis.
1624 if (Dep.isClobber() && TD) {
1625 // Check to see if we have something like this:
1626 // store i32 123, i32* %P
1627 // %A = bitcast i32* %P to i8*
1628 // %B = gep i8* %A, i32 1
1631 // We could do that by recognizing if the clobber instructions are obviously
1632 // a common base + constant offset, and if the previous store (or memset)
1633 // completely covers this load. This sort of thing can happen in bitfield
1635 Value *AvailVal = 0;
1636 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1637 int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1638 L->getPointerOperand(),
1641 AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1642 L->getType(), L, *TD);
1645 // Check to see if we have something like this:
1648 // if we have this, replace the later with an extraction from the former.
1649 if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1650 // If this is a clobber and L is the first instruction in its block, then
1651 // we have the first instruction in the entry block.
1655 int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1656 L->getPointerOperand(),
1659 AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
1662 // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1663 // a value on from it.
1664 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
1665 int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1666 L->getPointerOperand(),
1669 AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *TD);
1673 DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
1674 << *AvailVal << '\n' << *L << "\n\n\n");
1676 // Replace the load!
1677 L->replaceAllUsesWith(AvailVal);
1678 if (AvailVal->getType()->isPointerTy())
1679 MD->invalidateCachedPointerInfo(AvailVal);
1680 markInstructionForDeletion(L);
1686 // If the value isn't available, don't do anything!
1687 if (Dep.isClobber()) {
1689 // fast print dep, using operator<< on instruction is too slow.
1690 dbgs() << "GVN: load ";
1691 WriteAsOperand(dbgs(), L);
1692 Instruction *I = Dep.getInst();
1693 dbgs() << " is clobbered by " << *I << '\n';
1698 if (Dep.isUnknown()) {
1700 // fast print dep, using operator<< on instruction is too slow.
1701 dbgs() << "GVN: load ";
1702 WriteAsOperand(dbgs(), L);
1703 dbgs() << " has unknown dependence\n";
1708 // If it is defined in another block, try harder.
1709 if (Dep.isNonLocal())
1710 return processNonLocalLoad(L);
1712 assert(Dep.isDef() && "Expecting def here");
1714 Instruction *DepInst = Dep.getInst();
1715 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1716 Value *StoredVal = DepSI->getValueOperand();
1718 // The store and load are to a must-aliased pointer, but they may not
1719 // actually have the same type. See if we know how to reuse the stored
1720 // value (depending on its type).
1721 if (StoredVal->getType() != L->getType()) {
1723 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1728 DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1729 << '\n' << *L << "\n\n\n");
1736 L->replaceAllUsesWith(StoredVal);
1737 if (StoredVal->getType()->isPointerTy())
1738 MD->invalidateCachedPointerInfo(StoredVal);
1739 markInstructionForDeletion(L);
1744 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1745 Value *AvailableVal = DepLI;
1747 // The loads are of a must-aliased pointer, but they may not actually have
1748 // the same type. See if we know how to reuse the previously loaded value
1749 // (depending on its type).
1750 if (DepLI->getType() != L->getType()) {
1752 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1754 if (AvailableVal == 0)
1757 DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1758 << "\n" << *L << "\n\n\n");
1765 L->replaceAllUsesWith(AvailableVal);
1766 if (DepLI->getType()->isPointerTy())
1767 MD->invalidateCachedPointerInfo(DepLI);
1768 markInstructionForDeletion(L);
1773 // If this load really doesn't depend on anything, then we must be loading an
1774 // undef value. This can happen when loading for a fresh allocation with no
1775 // intervening stores, for example.
1776 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
1777 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1778 markInstructionForDeletion(L);
1783 // If this load occurs either right after a lifetime begin,
1784 // then the loaded value is undefined.
1785 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
1786 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1787 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1788 markInstructionForDeletion(L);
1797 // findLeader - In order to find a leader for a given value number at a
1798 // specific basic block, we first obtain the list of all Values for that number,
1799 // and then scan the list to find one whose block dominates the block in
1800 // question. This is fast because dominator tree queries consist of only
1801 // a few comparisons of DFS numbers.
1802 Value *GVN::findLeader(BasicBlock *BB, uint32_t num) {
1803 LeaderTableEntry Vals = LeaderTable[num];
1804 if (!Vals.Val) return 0;
1807 if (DT->dominates(Vals.BB, BB)) {
1809 if (isa<Constant>(Val)) return Val;
1812 LeaderTableEntry* Next = Vals.Next;
1814 if (DT->dominates(Next->BB, BB)) {
1815 if (isa<Constant>(Next->Val)) return Next->Val;
1816 if (!Val) Val = Next->Val;
1826 /// processInstruction - When calculating availability, handle an instruction
1827 /// by inserting it into the appropriate sets
1828 bool GVN::processInstruction(Instruction *I) {
1829 // Ignore dbg info intrinsics.
1830 if (isa<DbgInfoIntrinsic>(I))
1833 // If the instruction can be easily simplified then do so now in preference
1834 // to value numbering it. Value numbering often exposes redundancies, for
1835 // example if it determines that %y is equal to %x then the instruction
1836 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
1837 if (Value *V = SimplifyInstruction(I, TD, DT)) {
1838 I->replaceAllUsesWith(V);
1839 if (MD && V->getType()->isPointerTy())
1840 MD->invalidateCachedPointerInfo(V);
1841 markInstructionForDeletion(I);
1845 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1846 if (processLoad(LI))
1849 unsigned Num = VN.lookup_or_add(LI);
1850 addToLeaderTable(Num, LI, LI->getParent());
1854 // For conditions branches, we can perform simple conditional propagation on
1855 // the condition value itself.
1856 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1857 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1860 Value *BranchCond = BI->getCondition();
1861 uint32_t CondVN = VN.lookup_or_add(BranchCond);
1863 BasicBlock *TrueSucc = BI->getSuccessor(0);
1864 BasicBlock *FalseSucc = BI->getSuccessor(1);
1866 if (TrueSucc->getSinglePredecessor())
1867 addToLeaderTable(CondVN,
1868 ConstantInt::getTrue(TrueSucc->getContext()),
1870 if (FalseSucc->getSinglePredecessor())
1871 addToLeaderTable(CondVN,
1872 ConstantInt::getFalse(TrueSucc->getContext()),
1878 // Instructions with void type don't return a value, so there's
1879 // no point in trying to find redudancies in them.
1880 if (I->getType()->isVoidTy()) return false;
1882 uint32_t NextNum = VN.getNextUnusedValueNumber();
1883 unsigned Num = VN.lookup_or_add(I);
1885 // Allocations are always uniquely numbered, so we can save time and memory
1886 // by fast failing them.
1887 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
1888 addToLeaderTable(Num, I, I->getParent());
1892 // If the number we were assigned was a brand new VN, then we don't
1893 // need to do a lookup to see if the number already exists
1894 // somewhere in the domtree: it can't!
1895 if (Num == NextNum) {
1896 addToLeaderTable(Num, I, I->getParent());
1900 // Perform fast-path value-number based elimination of values inherited from
1902 Value *repl = findLeader(I->getParent(), Num);
1904 // Failure, just remember this instance for future use.
1905 addToLeaderTable(Num, I, I->getParent());
1910 I->replaceAllUsesWith(repl);
1911 if (MD && repl->getType()->isPointerTy())
1912 MD->invalidateCachedPointerInfo(repl);
1913 markInstructionForDeletion(I);
1917 /// runOnFunction - This is the main transformation entry point for a function.
1918 bool GVN::runOnFunction(Function& F) {
1920 MD = &getAnalysis<MemoryDependenceAnalysis>();
1921 DT = &getAnalysis<DominatorTree>();
1922 TD = getAnalysisIfAvailable<TargetData>();
1923 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1927 bool Changed = false;
1928 bool ShouldContinue = true;
1930 // Merge unconditional branches, allowing PRE to catch more
1931 // optimization opportunities.
1932 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1933 BasicBlock *BB = FI++;
1935 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1936 if (removedBlock) ++NumGVNBlocks;
1938 Changed |= removedBlock;
1941 unsigned Iteration = 0;
1942 while (ShouldContinue) {
1943 DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
1944 ShouldContinue = iterateOnFunction(F);
1945 if (splitCriticalEdges())
1946 ShouldContinue = true;
1947 Changed |= ShouldContinue;
1952 bool PREChanged = true;
1953 while (PREChanged) {
1954 PREChanged = performPRE(F);
1955 Changed |= PREChanged;
1958 // FIXME: Should perform GVN again after PRE does something. PRE can move
1959 // computations into blocks where they become fully redundant. Note that
1960 // we can't do this until PRE's critical edge splitting updates memdep.
1961 // Actually, when this happens, we should just fully integrate PRE into GVN.
1963 cleanupGlobalSets();
1969 bool GVN::processBlock(BasicBlock *BB) {
1970 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
1971 // (and incrementing BI before processing an instruction).
1972 assert(InstrsToErase.empty() &&
1973 "We expect InstrsToErase to be empty across iterations");
1974 bool ChangedFunction = false;
1976 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1978 ChangedFunction |= processInstruction(BI);
1979 if (InstrsToErase.empty()) {
1984 // If we need some instructions deleted, do it now.
1985 NumGVNInstr += InstrsToErase.size();
1987 // Avoid iterator invalidation.
1988 bool AtStart = BI == BB->begin();
1992 for (SmallVector<Instruction*, 4>::iterator I = InstrsToErase.begin(),
1993 E = InstrsToErase.end(); I != E; ++I) {
1994 DEBUG(dbgs() << "GVN removed: " << **I << '\n');
1995 if (MD) MD->removeInstruction(*I);
1996 (*I)->eraseFromParent();
1997 DEBUG(verifyRemoved(*I));
1999 InstrsToErase.clear();
2007 return ChangedFunction;
2010 /// performPRE - Perform a purely local form of PRE that looks for diamond
2011 /// control flow patterns and attempts to perform simple PRE at the join point.
2012 bool GVN::performPRE(Function &F) {
2013 bool Changed = false;
2014 DenseMap<BasicBlock*, Value*> predMap;
2015 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2016 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
2017 BasicBlock *CurrentBlock = *DI;
2019 // Nothing to PRE in the entry block.
2020 if (CurrentBlock == &F.getEntryBlock()) continue;
2022 for (BasicBlock::iterator BI = CurrentBlock->begin(),
2023 BE = CurrentBlock->end(); BI != BE; ) {
2024 Instruction *CurInst = BI++;
2026 if (isa<AllocaInst>(CurInst) ||
2027 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
2028 CurInst->getType()->isVoidTy() ||
2029 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2030 isa<DbgInfoIntrinsic>(CurInst))
2033 // We don't currently value number ANY inline asm calls.
2034 if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2035 if (CallI->isInlineAsm())
2038 uint32_t ValNo = VN.lookup(CurInst);
2040 // Look for the predecessors for PRE opportunities. We're
2041 // only trying to solve the basic diamond case, where
2042 // a value is computed in the successor and one predecessor,
2043 // but not the other. We also explicitly disallow cases
2044 // where the successor is its own predecessor, because they're
2045 // more complicated to get right.
2046 unsigned NumWith = 0;
2047 unsigned NumWithout = 0;
2048 BasicBlock *PREPred = 0;
2051 for (pred_iterator PI = pred_begin(CurrentBlock),
2052 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
2053 BasicBlock *P = *PI;
2054 // We're not interested in PRE where the block is its
2055 // own predecessor, or in blocks with predecessors
2056 // that are not reachable.
2057 if (P == CurrentBlock) {
2060 } else if (!DT->dominates(&F.getEntryBlock(), P)) {
2065 Value* predV = findLeader(P, ValNo);
2069 } else if (predV == CurInst) {
2077 // Don't do PRE when it might increase code size, i.e. when
2078 // we would need to insert instructions in more than one pred.
2079 if (NumWithout != 1 || NumWith == 0)
2082 // Don't do PRE across indirect branch.
2083 if (isa<IndirectBrInst>(PREPred->getTerminator()))
2086 // We can't do PRE safely on a critical edge, so instead we schedule
2087 // the edge to be split and perform the PRE the next time we iterate
2089 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2090 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2091 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2095 // Instantiate the expression in the predecessor that lacked it.
2096 // Because we are going top-down through the block, all value numbers
2097 // will be available in the predecessor by the time we need them. Any
2098 // that weren't originally present will have been instantiated earlier
2100 Instruction *PREInstr = CurInst->clone();
2101 bool success = true;
2102 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2103 Value *Op = PREInstr->getOperand(i);
2104 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2107 if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
2108 PREInstr->setOperand(i, V);
2115 // Fail out if we encounter an operand that is not available in
2116 // the PRE predecessor. This is typically because of loads which
2117 // are not value numbered precisely.
2120 DEBUG(verifyRemoved(PREInstr));
2124 PREInstr->insertBefore(PREPred->getTerminator());
2125 PREInstr->setName(CurInst->getName() + ".pre");
2126 PREInstr->setDebugLoc(CurInst->getDebugLoc());
2127 predMap[PREPred] = PREInstr;
2128 VN.add(PREInstr, ValNo);
2131 // Update the availability map to include the new instruction.
2132 addToLeaderTable(ValNo, PREInstr, PREPred);
2134 // Create a PHI to make the value available in this block.
2135 pred_iterator PB = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
2136 PHINode* Phi = PHINode::Create(CurInst->getType(), std::distance(PB, PE),
2137 CurInst->getName() + ".pre-phi",
2138 CurrentBlock->begin());
2139 for (pred_iterator PI = PB; PI != PE; ++PI) {
2140 BasicBlock *P = *PI;
2141 Phi->addIncoming(predMap[P], P);
2145 addToLeaderTable(ValNo, Phi, CurrentBlock);
2146 Phi->setDebugLoc(CurInst->getDebugLoc());
2147 CurInst->replaceAllUsesWith(Phi);
2148 if (Phi->getType()->isPointerTy()) {
2149 // Because we have added a PHI-use of the pointer value, it has now
2150 // "escaped" from alias analysis' perspective. We need to inform
2152 for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee; ++ii)
2153 VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(2*ii));
2156 MD->invalidateCachedPointerInfo(Phi);
2159 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2161 DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2162 if (MD) MD->removeInstruction(CurInst);
2163 CurInst->eraseFromParent();
2164 DEBUG(verifyRemoved(CurInst));
2169 if (splitCriticalEdges())
2175 /// splitCriticalEdges - Split critical edges found during the previous
2176 /// iteration that may enable further optimization.
2177 bool GVN::splitCriticalEdges() {
2178 if (toSplit.empty())
2181 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2182 SplitCriticalEdge(Edge.first, Edge.second, this);
2183 } while (!toSplit.empty());
2184 if (MD) MD->invalidateCachedPredecessors();
2188 /// iterateOnFunction - Executes one iteration of GVN
2189 bool GVN::iterateOnFunction(Function &F) {
2190 cleanupGlobalSets();
2192 // Top-down walk of the dominator tree
2193 bool Changed = false;
2195 // Needed for value numbering with phi construction to work.
2196 ReversePostOrderTraversal<Function*> RPOT(&F);
2197 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2198 RE = RPOT.end(); RI != RE; ++RI)
2199 Changed |= processBlock(*RI);
2201 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2202 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
2203 Changed |= processBlock(DI->getBlock());
2209 void GVN::cleanupGlobalSets() {
2211 LeaderTable.clear();
2212 TableAllocator.Reset();
2215 /// verifyRemoved - Verify that the specified instruction does not occur in our
2216 /// internal data structures.
2217 void GVN::verifyRemoved(const Instruction *Inst) const {
2218 VN.verifyRemoved(Inst);
2220 // Walk through the value number scope to make sure the instruction isn't
2221 // ferreted away in it.
2222 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2223 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2224 const LeaderTableEntry *Node = &I->second;
2225 assert(Node->Val != Inst && "Inst still in value numbering scope!");
2227 while (Node->Next) {
2229 assert(Node->Val != Inst && "Inst still in value numbering scope!");