1 //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
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 a simple dominator tree walk that eliminates trivially
11 // redundant instructions.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/ADT/ScopedHashTable.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/RecyclingAllocator.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/Transforms/Utils/Local.h"
34 using namespace llvm::PatternMatch;
36 #define DEBUG_TYPE "early-cse"
38 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
39 STATISTIC(NumCSE, "Number of instructions CSE'd");
40 STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
41 STATISTIC(NumCSECall, "Number of call instructions CSE'd");
42 STATISTIC(NumDSE, "Number of trivial dead stores removed");
44 static unsigned getHash(const void *V) {
45 return DenseMapInfo<const void*>::getHashValue(V);
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
53 /// \brief Struct representing the available values in the scoped hash table.
57 SimpleValue(Instruction *I) : Inst(I) {
58 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
61 bool isSentinel() const {
62 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
63 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
66 static bool canHandle(Instruction *Inst) {
67 // This can only handle non-void readnone functions.
68 if (CallInst *CI = dyn_cast<CallInst>(Inst))
69 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
70 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
71 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
72 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
73 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
74 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
80 template <> struct DenseMapInfo<SimpleValue> {
81 static inline SimpleValue getEmptyKey() {
82 return DenseMapInfo<Instruction *>::getEmptyKey();
84 static inline SimpleValue getTombstoneKey() {
85 return DenseMapInfo<Instruction *>::getTombstoneKey();
87 static unsigned getHashValue(SimpleValue Val);
88 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
92 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
93 Instruction *Inst = Val.Inst;
94 // Hash in all of the operands as pointers.
95 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
96 Value *LHS = BinOp->getOperand(0);
97 Value *RHS = BinOp->getOperand(1);
98 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
101 if (isa<OverflowingBinaryOperator>(BinOp)) {
102 // Hash the overflow behavior
104 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
105 BinOp->hasNoUnsignedWrap() *
106 OverflowingBinaryOperator::NoUnsignedWrap;
107 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
110 return hash_combine(BinOp->getOpcode(), LHS, RHS);
113 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
114 Value *LHS = CI->getOperand(0);
115 Value *RHS = CI->getOperand(1);
116 CmpInst::Predicate Pred = CI->getPredicate();
117 if (Inst->getOperand(0) > Inst->getOperand(1)) {
119 Pred = CI->getSwappedPredicate();
121 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
124 if (CastInst *CI = dyn_cast<CastInst>(Inst))
125 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
127 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
128 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
129 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
131 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
132 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
134 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
136 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
137 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
138 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
139 isa<ShuffleVectorInst>(Inst)) &&
140 "Invalid/unknown instruction");
142 // Mix in the opcode.
145 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
148 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
149 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
151 if (LHS.isSentinel() || RHS.isSentinel())
154 if (LHSI->getOpcode() != RHSI->getOpcode())
156 if (LHSI->isIdenticalTo(RHSI))
159 // If we're not strictly identical, we still might be a commutable instruction
160 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
161 if (!LHSBinOp->isCommutative())
164 assert(isa<BinaryOperator>(RHSI) &&
165 "same opcode, but different instruction type?");
166 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
168 // Check overflow attributes
169 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
170 assert(isa<OverflowingBinaryOperator>(RHSBinOp) &&
171 "same opcode, but different operator type?");
172 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
173 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
178 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
179 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
181 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
182 assert(isa<CmpInst>(RHSI) &&
183 "same opcode, but different instruction type?");
184 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
186 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
187 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
188 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
194 //===----------------------------------------------------------------------===//
196 //===----------------------------------------------------------------------===//
199 /// \brief Struct representing the available call values in the scoped hash
204 CallValue(Instruction *I) : Inst(I) {
205 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
208 bool isSentinel() const {
209 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
210 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
213 static bool canHandle(Instruction *Inst) {
214 // Don't value number anything that returns void.
215 if (Inst->getType()->isVoidTy())
218 CallInst *CI = dyn_cast<CallInst>(Inst);
219 if (!CI || !CI->onlyReadsMemory())
227 template <> struct DenseMapInfo<CallValue> {
228 static inline CallValue getEmptyKey() {
229 return DenseMapInfo<Instruction *>::getEmptyKey();
231 static inline CallValue getTombstoneKey() {
232 return DenseMapInfo<Instruction *>::getTombstoneKey();
234 static unsigned getHashValue(CallValue Val);
235 static bool isEqual(CallValue LHS, CallValue RHS);
239 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
240 Instruction *Inst = Val.Inst;
241 // Hash in all of the operands as pointers.
243 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
244 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
245 "Cannot value number calls with metadata operands");
246 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
249 // Mix in the opcode.
250 return (Res << 1) ^ Inst->getOpcode();
253 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
254 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
255 if (LHS.isSentinel() || RHS.isSentinel())
257 return LHSI->isIdenticalTo(RHSI);
260 //===----------------------------------------------------------------------===//
262 //===----------------------------------------------------------------------===//
266 /// \brief A simple and fast domtree-based CSE pass.
268 /// This pass does a simple depth-first walk over the dominator tree,
269 /// eliminating trivially redundant instructions and using instsimplify to
270 /// canonicalize things as it goes. It is intended to be fast and catch obvious
271 /// cases so that instcombine and other passes are more effective. It is
272 /// expected that a later pass of GVN will catch the interesting/hard cases.
273 class EarlyCSE : public FunctionPass {
275 const DataLayout *DL;
276 const TargetLibraryInfo *TLI;
277 const TargetTransformInfo *TTI;
280 typedef RecyclingAllocator<
281 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
282 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
283 AllocatorTy> ScopedHTType;
285 /// \brief A scoped hash table of the current values of all of our simple
286 /// scalar expressions.
288 /// As we walk down the domtree, we look to see if instructions are in this:
289 /// if so, we replace them with what we find, otherwise we insert them so
290 /// that dominated values can succeed in their lookup.
291 ScopedHTType *AvailableValues;
293 /// \brief A scoped hash table of the current values of loads.
295 /// This allows us to get efficient access to dominating loads when we have
296 /// a fully redundant load. In addition to the most recent load, we keep
297 /// track of a generation count of the read, which is compared against the
298 /// current generation count. The current generation count is incremented
299 /// after every possibly writing memory operation, which ensures that we only
300 /// CSE loads with other loads that have no intervening store.
301 typedef RecyclingAllocator<
303 ScopedHashTableVal<Value *, std::pair<Value *, unsigned>>>
305 typedef ScopedHashTable<Value *, std::pair<Value *, unsigned>,
306 DenseMapInfo<Value *>, LoadMapAllocator> LoadHTType;
307 LoadHTType *AvailableLoads;
309 /// \brief A scoped hash table of the current values of read-only call
312 /// It uses the same generation count as loads.
313 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
314 CallHTType *AvailableCalls;
316 /// \brief This is the current generation of the memory value.
317 unsigned CurrentGeneration;
320 explicit EarlyCSE() : FunctionPass(ID) {
321 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
324 bool runOnFunction(Function &F) override;
327 // Almost a POD, but needs to call the constructors for the scoped hash
328 // tables so that a new scope gets pushed on. These are RAII so that the
329 // scope gets popped when the NodeScope is destroyed.
332 NodeScope(ScopedHTType *availableValues, LoadHTType *availableLoads,
333 CallHTType *availableCalls)
334 : Scope(*availableValues), LoadScope(*availableLoads),
335 CallScope(*availableCalls) {}
338 NodeScope(const NodeScope &) LLVM_DELETED_FUNCTION;
339 void operator=(const NodeScope &) LLVM_DELETED_FUNCTION;
341 ScopedHTType::ScopeTy Scope;
342 LoadHTType::ScopeTy LoadScope;
343 CallHTType::ScopeTy CallScope;
346 // Contains all the needed information to create a stack for doing a depth
347 // first tranversal of the tree. This includes scopes for values, loads, and
348 // calls as well as the generation. There is a child iterator so that the
349 // children do not need to be store spearately.
352 StackNode(ScopedHTType *availableValues, LoadHTType *availableLoads,
353 CallHTType *availableCalls, unsigned cg, DomTreeNode *n,
354 DomTreeNode::iterator child, DomTreeNode::iterator end)
355 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
356 EndIter(end), Scopes(availableValues, availableLoads, availableCalls),
360 unsigned currentGeneration() { return CurrentGeneration; }
361 unsigned childGeneration() { return ChildGeneration; }
362 void childGeneration(unsigned generation) { ChildGeneration = generation; }
363 DomTreeNode *node() { return Node; }
364 DomTreeNode::iterator childIter() { return ChildIter; }
365 DomTreeNode *nextChild() {
366 DomTreeNode *child = *ChildIter;
370 DomTreeNode::iterator end() { return EndIter; }
371 bool isProcessed() { return Processed; }
372 void process() { Processed = true; }
375 StackNode(const StackNode &) LLVM_DELETED_FUNCTION;
376 void operator=(const StackNode &) LLVM_DELETED_FUNCTION;
379 unsigned CurrentGeneration;
380 unsigned ChildGeneration;
382 DomTreeNode::iterator ChildIter;
383 DomTreeNode::iterator EndIter;
388 /// \brief Wrapper class to handle memory instructions, including loads,
389 /// stores and intrinsic loads and stores defined by the target.
390 class ParseMemoryInst {
392 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo *TTI)
393 : Load(false), Store(false), Vol(false), MayReadFromMemory(false),
394 MayWriteToMemory(false), MatchingId(-1), Ptr(nullptr) {
395 MayReadFromMemory = Inst->mayReadFromMemory();
396 MayWriteToMemory = Inst->mayWriteToMemory();
397 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
398 MemIntrinsicInfo Info;
399 if (!TTI->getTgtMemIntrinsic(II, Info))
401 if (Info.NumMemRefs == 1) {
402 Store = Info.WriteMem;
404 MatchingId = Info.MatchingId;
405 MayReadFromMemory = Info.ReadMem;
406 MayWriteToMemory = Info.WriteMem;
410 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
412 Vol = !LI->isSimple();
413 Ptr = LI->getPointerOperand();
414 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
416 Vol = !SI->isSimple();
417 Ptr = SI->getPointerOperand();
420 bool isLoad() { return Load; }
421 bool isStore() { return Store; }
422 bool isVolatile() { return Vol; }
423 bool isMatchingMemLoc(const ParseMemoryInst &Inst) {
424 return Ptr == Inst.Ptr && MatchingId == Inst.MatchingId;
426 bool isValid() { return Ptr != nullptr; }
427 int getMatchingId() { return MatchingId; }
428 Value *getPtr() { return Ptr; }
429 bool mayReadFromMemory() { return MayReadFromMemory; }
430 bool mayWriteToMemory() { return MayWriteToMemory; }
436 bool MayReadFromMemory;
437 bool MayWriteToMemory;
438 // For regular (non-intrinsic) loads/stores, this is set to -1. For
439 // intrinsic loads/stores, the id is retrieved from the corresponding
440 // field in the MemIntrinsicInfo structure. That field contains
441 // non-negative values only.
446 bool processNode(DomTreeNode *Node);
448 void getAnalysisUsage(AnalysisUsage &AU) const override {
449 AU.addRequired<AssumptionCacheTracker>();
450 AU.addRequired<DominatorTreeWrapperPass>();
451 AU.addRequired<TargetLibraryInfoWrapperPass>();
452 AU.addRequired<TargetTransformInfo>();
453 AU.setPreservesCFG();
456 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
457 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
459 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
460 return SI->getValueOperand();
461 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
462 return TTI->getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
468 char EarlyCSE::ID = 0;
470 FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSE(); }
472 INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
473 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
474 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
475 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
476 INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
478 bool EarlyCSE::processNode(DomTreeNode *Node) {
479 BasicBlock *BB = Node->getBlock();
481 // If this block has a single predecessor, then the predecessor is the parent
482 // of the domtree node and all of the live out memory values are still current
483 // in this block. If this block has multiple predecessors, then they could
484 // have invalidated the live-out memory values of our parent value. For now,
485 // just be conservative and invalidate memory if this block has multiple
487 if (!BB->getSinglePredecessor())
490 /// LastStore - Keep track of the last non-volatile store that we saw... for
491 /// as long as there in no instruction that reads memory. If we see a store
492 /// to the same location, we delete the dead store. This zaps trivial dead
493 /// stores which can occur in bitfield code among other things.
494 Instruction *LastStore = nullptr;
496 bool Changed = false;
498 // See if any instructions in the block can be eliminated. If so, do it. If
499 // not, add them to AvailableValues.
500 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
501 Instruction *Inst = I++;
503 // Dead instructions should just be removed.
504 if (isInstructionTriviallyDead(Inst, TLI)) {
505 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
506 Inst->eraseFromParent();
512 // Skip assume intrinsics, they don't really have side effects (although
513 // they're marked as such to ensure preservation of control dependencies),
514 // and this pass will not disturb any of the assumption's control
516 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
517 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
521 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
522 // its simpler value.
523 if (Value *V = SimplifyInstruction(Inst, DL, TLI, DT, AC)) {
524 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
525 Inst->replaceAllUsesWith(V);
526 Inst->eraseFromParent();
532 // If this is a simple instruction that we can value number, process it.
533 if (SimpleValue::canHandle(Inst)) {
534 // See if the instruction has an available value. If so, use it.
535 if (Value *V = AvailableValues->lookup(Inst)) {
536 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
537 Inst->replaceAllUsesWith(V);
538 Inst->eraseFromParent();
544 // Otherwise, just remember that this value is available.
545 AvailableValues->insert(Inst, Inst);
549 ParseMemoryInst MemInst(Inst, TTI);
550 // If this is a non-volatile load, process it.
551 if (MemInst.isValid() && MemInst.isLoad()) {
552 // Ignore volatile loads.
553 if (MemInst.isVolatile()) {
558 // If we have an available version of this load, and if it is the right
559 // generation, replace this instruction.
560 std::pair<Value *, unsigned> InVal =
561 AvailableLoads->lookup(MemInst.getPtr());
562 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
563 Value *Op = getOrCreateResult(InVal.first, Inst->getType());
565 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
566 << " to: " << *InVal.first << '\n');
567 if (!Inst->use_empty())
568 Inst->replaceAllUsesWith(Op);
569 Inst->eraseFromParent();
576 // Otherwise, remember that we have this instruction.
577 AvailableLoads->insert(MemInst.getPtr(), std::pair<Value *, unsigned>(
578 Inst, CurrentGeneration));
583 // If this instruction may read from memory, forget LastStore.
584 // Load/store intrinsics will indicate both a read and a write to
585 // memory. The target may override this (e.g. so that a store intrinsic
586 // does not read from memory, and thus will be treated the same as a
587 // regular store for commoning purposes).
588 if (Inst->mayReadFromMemory() &&
589 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
592 // If this is a read-only call, process it.
593 if (CallValue::canHandle(Inst)) {
594 // If we have an available version of this call, and if it is the right
595 // generation, replace this instruction.
596 std::pair<Value *, unsigned> InVal = AvailableCalls->lookup(Inst);
597 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
598 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
599 << " to: " << *InVal.first << '\n');
600 if (!Inst->use_empty())
601 Inst->replaceAllUsesWith(InVal.first);
602 Inst->eraseFromParent();
608 // Otherwise, remember that we have this instruction.
609 AvailableCalls->insert(
610 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
614 // Okay, this isn't something we can CSE at all. Check to see if it is
615 // something that could modify memory. If so, our available memory values
616 // cannot be used so bump the generation count.
617 if (Inst->mayWriteToMemory()) {
620 if (MemInst.isValid() && MemInst.isStore()) {
621 // We do a trivial form of DSE if there are two stores to the same
622 // location with no intervening loads. Delete the earlier store.
624 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
625 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
626 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
627 << " due to: " << *Inst << '\n');
628 LastStore->eraseFromParent();
633 // fallthrough - we can exploit information about this store
636 // Okay, we just invalidated anything we knew about loaded values. Try
637 // to salvage *something* by remembering that the stored value is a live
638 // version of the pointer. It is safe to forward from volatile stores
639 // to non-volatile loads, so we don't have to check for volatility of
641 AvailableLoads->insert(MemInst.getPtr(), std::pair<Value *, unsigned>(
642 Inst, CurrentGeneration));
644 // Remember that this was the last store we saw for DSE.
645 if (!MemInst.isVolatile())
654 bool EarlyCSE::runOnFunction(Function &F) {
655 if (skipOptnoneFunction(F))
658 // Note, deque is being used here because there is significant performance
659 // gains over vector when the container becomes very large due to the
660 // specific access patterns. For more information see the mailing list
661 // discussion on this:
662 // http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
663 std::deque<StackNode *> nodesToProcess;
665 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
666 DL = DLP ? &DLP->getDataLayout() : nullptr;
667 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
668 TTI = &getAnalysis<TargetTransformInfo>();
669 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
670 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
672 // Tables that the pass uses when walking the domtree.
673 ScopedHTType AVTable;
674 AvailableValues = &AVTable;
675 LoadHTType LoadTable;
676 AvailableLoads = &LoadTable;
677 CallHTType CallTable;
678 AvailableCalls = &CallTable;
680 CurrentGeneration = 0;
681 bool Changed = false;
683 // Process the root node.
684 nodesToProcess.push_back(new StackNode(
685 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
686 DT->getRootNode(), DT->getRootNode()->begin(), DT->getRootNode()->end()));
688 // Save the current generation.
689 unsigned LiveOutGeneration = CurrentGeneration;
691 // Process the stack.
692 while (!nodesToProcess.empty()) {
693 // Grab the first item off the stack. Set the current generation, remove
694 // the node from the stack, and process it.
695 StackNode *NodeToProcess = nodesToProcess.back();
697 // Initialize class members.
698 CurrentGeneration = NodeToProcess->currentGeneration();
700 // Check if the node needs to be processed.
701 if (!NodeToProcess->isProcessed()) {
703 Changed |= processNode(NodeToProcess->node());
704 NodeToProcess->childGeneration(CurrentGeneration);
705 NodeToProcess->process();
706 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
707 // Push the next child onto the stack.
708 DomTreeNode *child = NodeToProcess->nextChild();
709 nodesToProcess.push_back(
710 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
711 NodeToProcess->childGeneration(), child, child->begin(),
714 // It has been processed, and there are no more children to process,
715 // so delete it and pop it off the stack.
716 delete NodeToProcess;
717 nodesToProcess.pop_back();
719 } // while (!nodes...)
721 // Reset the current generation.
722 CurrentGeneration = LiveOutGeneration;