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/EarlyCSE.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/Scalar.h"
32 #include "llvm/Transforms/Utils/Local.h"
35 using namespace llvm::PatternMatch;
37 #define DEBUG_TYPE "early-cse"
39 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
40 STATISTIC(NumCSE, "Number of instructions CSE'd");
41 STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
42 STATISTIC(NumCSECall, "Number of call instructions CSE'd");
43 STATISTIC(NumDSE, "Number of trivial dead stores removed");
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
50 /// \brief Struct representing the available values in the scoped hash table.
54 SimpleValue(Instruction *I) : Inst(I) {
55 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
58 bool isSentinel() const {
59 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
60 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
63 static bool canHandle(Instruction *Inst) {
64 // This can only handle non-void readnone functions.
65 if (CallInst *CI = dyn_cast<CallInst>(Inst))
66 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
67 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
68 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
69 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
70 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
71 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
77 template <> struct DenseMapInfo<SimpleValue> {
78 static inline SimpleValue getEmptyKey() {
79 return DenseMapInfo<Instruction *>::getEmptyKey();
81 static inline SimpleValue getTombstoneKey() {
82 return DenseMapInfo<Instruction *>::getTombstoneKey();
84 static unsigned getHashValue(SimpleValue Val);
85 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
89 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
90 Instruction *Inst = Val.Inst;
91 // Hash in all of the operands as pointers.
92 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
93 Value *LHS = BinOp->getOperand(0);
94 Value *RHS = BinOp->getOperand(1);
95 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
98 if (isa<OverflowingBinaryOperator>(BinOp)) {
99 // Hash the overflow behavior
101 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
102 BinOp->hasNoUnsignedWrap() *
103 OverflowingBinaryOperator::NoUnsignedWrap;
104 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
107 return hash_combine(BinOp->getOpcode(), LHS, RHS);
110 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
111 Value *LHS = CI->getOperand(0);
112 Value *RHS = CI->getOperand(1);
113 CmpInst::Predicate Pred = CI->getPredicate();
114 if (Inst->getOperand(0) > Inst->getOperand(1)) {
116 Pred = CI->getSwappedPredicate();
118 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
121 if (CastInst *CI = dyn_cast<CastInst>(Inst))
122 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
124 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
125 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
126 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
128 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
129 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
131 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
133 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
134 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
135 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
136 isa<ShuffleVectorInst>(Inst)) &&
137 "Invalid/unknown instruction");
139 // Mix in the opcode.
142 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
145 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
146 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
148 if (LHS.isSentinel() || RHS.isSentinel())
151 if (LHSI->getOpcode() != RHSI->getOpcode())
153 if (LHSI->isIdenticalTo(RHSI))
156 // If we're not strictly identical, we still might be a commutable instruction
157 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
158 if (!LHSBinOp->isCommutative())
161 assert(isa<BinaryOperator>(RHSI) &&
162 "same opcode, but different instruction type?");
163 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
165 // Check overflow attributes
166 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
167 assert(isa<OverflowingBinaryOperator>(RHSBinOp) &&
168 "same opcode, but different operator type?");
169 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
170 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
175 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
176 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
178 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
179 assert(isa<CmpInst>(RHSI) &&
180 "same opcode, but different instruction type?");
181 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
183 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
184 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
185 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
191 //===----------------------------------------------------------------------===//
193 //===----------------------------------------------------------------------===//
196 /// \brief Struct representing the available call values in the scoped hash
201 CallValue(Instruction *I) : Inst(I) {
202 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
205 bool isSentinel() const {
206 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
207 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
210 static bool canHandle(Instruction *Inst) {
211 // Don't value number anything that returns void.
212 if (Inst->getType()->isVoidTy())
215 CallInst *CI = dyn_cast<CallInst>(Inst);
216 if (!CI || !CI->onlyReadsMemory())
224 template <> struct DenseMapInfo<CallValue> {
225 static inline CallValue getEmptyKey() {
226 return DenseMapInfo<Instruction *>::getEmptyKey();
228 static inline CallValue getTombstoneKey() {
229 return DenseMapInfo<Instruction *>::getTombstoneKey();
231 static unsigned getHashValue(CallValue Val);
232 static bool isEqual(CallValue LHS, CallValue RHS);
236 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
237 Instruction *Inst = Val.Inst;
238 // Hash all of the operands as pointers and mix in the opcode.
241 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
244 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
245 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
246 if (LHS.isSentinel() || RHS.isSentinel())
248 return LHSI->isIdenticalTo(RHSI);
251 //===----------------------------------------------------------------------===//
252 // EarlyCSE implementation
253 //===----------------------------------------------------------------------===//
256 /// \brief A simple and fast domtree-based CSE pass.
258 /// This pass does a simple depth-first walk over the dominator tree,
259 /// eliminating trivially redundant instructions and using instsimplify to
260 /// canonicalize things as it goes. It is intended to be fast and catch obvious
261 /// cases so that instcombine and other passes are more effective. It is
262 /// expected that a later pass of GVN will catch the interesting/hard cases.
266 const TargetLibraryInfo &TLI;
267 const TargetTransformInfo &TTI;
270 typedef RecyclingAllocator<
271 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
272 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
273 AllocatorTy> ScopedHTType;
275 /// \brief A scoped hash table of the current values of all of our simple
276 /// scalar expressions.
278 /// As we walk down the domtree, we look to see if instructions are in this:
279 /// if so, we replace them with what we find, otherwise we insert them so
280 /// that dominated values can succeed in their lookup.
281 ScopedHTType AvailableValues;
283 /// \brief A scoped hash table of the current values of loads.
285 /// This allows us to get efficient access to dominating loads when we have
286 /// a fully redundant load. In addition to the most recent load, we keep
287 /// track of a generation count of the read, which is compared against the
288 /// current generation count. The current generation count is incremented
289 /// after every possibly writing memory operation, which ensures that we only
290 /// CSE loads with other loads that have no intervening store.
291 typedef RecyclingAllocator<
293 ScopedHashTableVal<Value *, std::pair<Value *, unsigned>>>
295 typedef ScopedHashTable<Value *, std::pair<Value *, unsigned>,
296 DenseMapInfo<Value *>, LoadMapAllocator> LoadHTType;
297 LoadHTType AvailableLoads;
299 /// \brief A scoped hash table of the current values of read-only call
302 /// It uses the same generation count as loads.
303 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
304 CallHTType AvailableCalls;
306 /// \brief This is the current generation of the memory value.
307 unsigned CurrentGeneration;
309 /// \brief Set up the EarlyCSE runner for a particular function.
310 EarlyCSE(Function &F, const TargetLibraryInfo &TLI,
311 const TargetTransformInfo &TTI, DominatorTree &DT,
313 : F(F), TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {}
318 // Almost a POD, but needs to call the constructors for the scoped hash
319 // tables so that a new scope gets pushed on. These are RAII so that the
320 // scope gets popped when the NodeScope is destroyed.
323 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
324 CallHTType &AvailableCalls)
325 : Scope(AvailableValues), LoadScope(AvailableLoads),
326 CallScope(AvailableCalls) {}
329 NodeScope(const NodeScope &) = delete;
330 void operator=(const NodeScope &) = delete;
332 ScopedHTType::ScopeTy Scope;
333 LoadHTType::ScopeTy LoadScope;
334 CallHTType::ScopeTy CallScope;
337 // Contains all the needed information to create a stack for doing a depth
338 // first tranversal of the tree. This includes scopes for values, loads, and
339 // calls as well as the generation. There is a child iterator so that the
340 // children do not need to be store spearately.
343 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
344 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
345 DomTreeNode::iterator child, DomTreeNode::iterator end)
346 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
347 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
351 unsigned currentGeneration() { return CurrentGeneration; }
352 unsigned childGeneration() { return ChildGeneration; }
353 void childGeneration(unsigned generation) { ChildGeneration = generation; }
354 DomTreeNode *node() { return Node; }
355 DomTreeNode::iterator childIter() { return ChildIter; }
356 DomTreeNode *nextChild() {
357 DomTreeNode *child = *ChildIter;
361 DomTreeNode::iterator end() { return EndIter; }
362 bool isProcessed() { return Processed; }
363 void process() { Processed = true; }
366 StackNode(const StackNode &) = delete;
367 void operator=(const StackNode &) = delete;
370 unsigned CurrentGeneration;
371 unsigned ChildGeneration;
373 DomTreeNode::iterator ChildIter;
374 DomTreeNode::iterator EndIter;
379 /// \brief Wrapper class to handle memory instructions, including loads,
380 /// stores and intrinsic loads and stores defined by the target.
381 class ParseMemoryInst {
383 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
384 : Load(false), Store(false), Vol(false), MayReadFromMemory(false),
385 MayWriteToMemory(false), MatchingId(-1), Ptr(nullptr) {
386 MayReadFromMemory = Inst->mayReadFromMemory();
387 MayWriteToMemory = Inst->mayWriteToMemory();
388 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
389 MemIntrinsicInfo Info;
390 if (!TTI.getTgtMemIntrinsic(II, Info))
392 if (Info.NumMemRefs == 1) {
393 Store = Info.WriteMem;
395 MatchingId = Info.MatchingId;
396 MayReadFromMemory = Info.ReadMem;
397 MayWriteToMemory = Info.WriteMem;
401 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
403 Vol = !LI->isSimple();
404 Ptr = LI->getPointerOperand();
405 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
407 Vol = !SI->isSimple();
408 Ptr = SI->getPointerOperand();
411 bool isLoad() { return Load; }
412 bool isStore() { return Store; }
413 bool isVolatile() { return Vol; }
414 bool isMatchingMemLoc(const ParseMemoryInst &Inst) {
415 return Ptr == Inst.Ptr && MatchingId == Inst.MatchingId;
417 bool isValid() { return Ptr != nullptr; }
418 int getMatchingId() { return MatchingId; }
419 Value *getPtr() { return Ptr; }
420 bool mayReadFromMemory() { return MayReadFromMemory; }
421 bool mayWriteToMemory() { return MayWriteToMemory; }
427 bool MayReadFromMemory;
428 bool MayWriteToMemory;
429 // For regular (non-intrinsic) loads/stores, this is set to -1. For
430 // intrinsic loads/stores, the id is retrieved from the corresponding
431 // field in the MemIntrinsicInfo structure. That field contains
432 // non-negative values only.
437 bool processNode(DomTreeNode *Node);
439 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
440 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
442 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
443 return SI->getValueOperand();
444 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
445 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
451 bool EarlyCSE::processNode(DomTreeNode *Node) {
452 BasicBlock *BB = Node->getBlock();
454 // If this block has a single predecessor, then the predecessor is the parent
455 // of the domtree node and all of the live out memory values are still current
456 // in this block. If this block has multiple predecessors, then they could
457 // have invalidated the live-out memory values of our parent value. For now,
458 // just be conservative and invalidate memory if this block has multiple
460 if (!BB->getSinglePredecessor())
463 /// LastStore - Keep track of the last non-volatile store that we saw... for
464 /// as long as there in no instruction that reads memory. If we see a store
465 /// to the same location, we delete the dead store. This zaps trivial dead
466 /// stores which can occur in bitfield code among other things.
467 Instruction *LastStore = nullptr;
469 bool Changed = false;
470 const DataLayout &DL = BB->getModule()->getDataLayout();
472 // See if any instructions in the block can be eliminated. If so, do it. If
473 // not, add them to AvailableValues.
474 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
475 Instruction *Inst = I++;
477 // Dead instructions should just be removed.
478 if (isInstructionTriviallyDead(Inst, &TLI)) {
479 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
480 Inst->eraseFromParent();
486 // Skip assume intrinsics, they don't really have side effects (although
487 // they're marked as such to ensure preservation of control dependencies),
488 // and this pass will not disturb any of the assumption's control
490 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
491 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
495 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
496 // its simpler value.
497 if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
498 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
499 Inst->replaceAllUsesWith(V);
500 Inst->eraseFromParent();
506 // If this is a simple instruction that we can value number, process it.
507 if (SimpleValue::canHandle(Inst)) {
508 // See if the instruction has an available value. If so, use it.
509 if (Value *V = AvailableValues.lookup(Inst)) {
510 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
511 Inst->replaceAllUsesWith(V);
512 Inst->eraseFromParent();
518 // Otherwise, just remember that this value is available.
519 AvailableValues.insert(Inst, Inst);
523 ParseMemoryInst MemInst(Inst, TTI);
524 // If this is a non-volatile load, process it.
525 if (MemInst.isValid() && MemInst.isLoad()) {
526 // Ignore volatile loads.
527 if (MemInst.isVolatile()) {
529 // Don't CSE across synchronization boundaries.
530 if (Inst->mayWriteToMemory())
535 // If we have an available version of this load, and if it is the right
536 // generation, replace this instruction.
537 std::pair<Value *, unsigned> InVal =
538 AvailableLoads.lookup(MemInst.getPtr());
539 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
540 Value *Op = getOrCreateResult(InVal.first, Inst->getType());
542 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
543 << " to: " << *InVal.first << '\n');
544 if (!Inst->use_empty())
545 Inst->replaceAllUsesWith(Op);
546 Inst->eraseFromParent();
553 // Otherwise, remember that we have this instruction.
554 AvailableLoads.insert(MemInst.getPtr(), std::pair<Value *, unsigned>(
555 Inst, CurrentGeneration));
560 // If this instruction may read from memory, forget LastStore.
561 // Load/store intrinsics will indicate both a read and a write to
562 // memory. The target may override this (e.g. so that a store intrinsic
563 // does not read from memory, and thus will be treated the same as a
564 // regular store for commoning purposes).
565 if (Inst->mayReadFromMemory() &&
566 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
569 // If this is a read-only call, process it.
570 if (CallValue::canHandle(Inst)) {
571 // If we have an available version of this call, and if it is the right
572 // generation, replace this instruction.
573 std::pair<Value *, unsigned> InVal = AvailableCalls.lookup(Inst);
574 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
575 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
576 << " to: " << *InVal.first << '\n');
577 if (!Inst->use_empty())
578 Inst->replaceAllUsesWith(InVal.first);
579 Inst->eraseFromParent();
585 // Otherwise, remember that we have this instruction.
586 AvailableCalls.insert(
587 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
591 // Okay, this isn't something we can CSE at all. Check to see if it is
592 // something that could modify memory. If so, our available memory values
593 // cannot be used so bump the generation count.
594 if (Inst->mayWriteToMemory()) {
597 if (MemInst.isValid() && MemInst.isStore()) {
598 // We do a trivial form of DSE if there are two stores to the same
599 // location with no intervening loads. Delete the earlier store.
601 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
602 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
603 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
604 << " due to: " << *Inst << '\n');
605 LastStore->eraseFromParent();
610 // fallthrough - we can exploit information about this store
613 // Okay, we just invalidated anything we knew about loaded values. Try
614 // to salvage *something* by remembering that the stored value is a live
615 // version of the pointer. It is safe to forward from volatile stores
616 // to non-volatile loads, so we don't have to check for volatility of
618 AvailableLoads.insert(MemInst.getPtr(), std::pair<Value *, unsigned>(
619 Inst, CurrentGeneration));
621 // Remember that this was the last store we saw for DSE.
622 if (!MemInst.isVolatile())
631 bool EarlyCSE::run() {
632 // Note, deque is being used here because there is significant performance
633 // gains over vector when the container becomes very large due to the
634 // specific access patterns. For more information see the mailing list
635 // discussion on this:
636 // http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
637 std::deque<StackNode *> nodesToProcess;
639 bool Changed = false;
641 // Process the root node.
642 nodesToProcess.push_back(new StackNode(
643 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
644 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
646 // Save the current generation.
647 unsigned LiveOutGeneration = CurrentGeneration;
649 // Process the stack.
650 while (!nodesToProcess.empty()) {
651 // Grab the first item off the stack. Set the current generation, remove
652 // the node from the stack, and process it.
653 StackNode *NodeToProcess = nodesToProcess.back();
655 // Initialize class members.
656 CurrentGeneration = NodeToProcess->currentGeneration();
658 // Check if the node needs to be processed.
659 if (!NodeToProcess->isProcessed()) {
661 Changed |= processNode(NodeToProcess->node());
662 NodeToProcess->childGeneration(CurrentGeneration);
663 NodeToProcess->process();
664 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
665 // Push the next child onto the stack.
666 DomTreeNode *child = NodeToProcess->nextChild();
667 nodesToProcess.push_back(
668 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
669 NodeToProcess->childGeneration(), child, child->begin(),
672 // It has been processed, and there are no more children to process,
673 // so delete it and pop it off the stack.
674 delete NodeToProcess;
675 nodesToProcess.pop_back();
677 } // while (!nodes...)
679 // Reset the current generation.
680 CurrentGeneration = LiveOutGeneration;
685 PreservedAnalyses EarlyCSEPass::run(Function &F,
686 AnalysisManager<Function> *AM) {
687 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
688 auto &TTI = AM->getResult<TargetIRAnalysis>(F);
689 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
690 auto &AC = AM->getResult<AssumptionAnalysis>(F);
692 EarlyCSE CSE(F, TLI, TTI, DT, AC);
695 return PreservedAnalyses::all();
697 // CSE preserves the dominator tree because it doesn't mutate the CFG.
698 // FIXME: Bundle this with other CFG-preservation.
699 PreservedAnalyses PA;
700 PA.preserve<DominatorTreeAnalysis>();
705 /// \brief A simple and fast domtree-based CSE pass.
707 /// This pass does a simple depth-first walk over the dominator tree,
708 /// eliminating trivially redundant instructions and using instsimplify to
709 /// canonicalize things as it goes. It is intended to be fast and catch obvious
710 /// cases so that instcombine and other passes are more effective. It is
711 /// expected that a later pass of GVN will catch the interesting/hard cases.
712 class EarlyCSELegacyPass : public FunctionPass {
716 EarlyCSELegacyPass() : FunctionPass(ID) {
717 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
720 bool runOnFunction(Function &F) override {
721 if (skipOptnoneFunction(F))
724 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
725 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
726 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
727 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
729 EarlyCSE CSE(F, TLI, TTI, DT, AC);
734 void getAnalysisUsage(AnalysisUsage &AU) const override {
735 AU.addRequired<AssumptionCacheTracker>();
736 AU.addRequired<DominatorTreeWrapperPass>();
737 AU.addRequired<TargetLibraryInfoWrapperPass>();
738 AU.addRequired<TargetTransformInfoWrapperPass>();
739 AU.setPreservesCFG();
744 char EarlyCSELegacyPass::ID = 0;
746 FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); }
748 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
750 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
751 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
752 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
753 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
754 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)