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/GlobalsModRef.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/RecyclingAllocator.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Scalar.h"
34 #include "llvm/Transforms/Utils/Local.h"
37 using namespace llvm::PatternMatch;
39 #define DEBUG_TYPE "early-cse"
41 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
42 STATISTIC(NumCSE, "Number of instructions CSE'd");
43 STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
44 STATISTIC(NumCSECall, "Number of call instructions CSE'd");
45 STATISTIC(NumDSE, "Number of trivial dead stores removed");
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
52 /// \brief Struct representing the available values in the scoped hash table.
56 SimpleValue(Instruction *I) : Inst(I) {
57 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
60 bool isSentinel() const {
61 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
62 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
65 static bool canHandle(Instruction *Inst) {
66 // This can only handle non-void readnone functions.
67 if (CallInst *CI = dyn_cast<CallInst>(Inst))
68 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
69 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
70 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
71 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
72 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
73 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
79 template <> struct DenseMapInfo<SimpleValue> {
80 static inline SimpleValue getEmptyKey() {
81 return DenseMapInfo<Instruction *>::getEmptyKey();
83 static inline SimpleValue getTombstoneKey() {
84 return DenseMapInfo<Instruction *>::getTombstoneKey();
86 static unsigned getHashValue(SimpleValue Val);
87 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
91 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
92 Instruction *Inst = Val.Inst;
93 // Hash in all of the operands as pointers.
94 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
95 Value *LHS = BinOp->getOperand(0);
96 Value *RHS = BinOp->getOperand(1);
97 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
100 if (isa<OverflowingBinaryOperator>(BinOp)) {
101 // Hash the overflow behavior
103 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
104 BinOp->hasNoUnsignedWrap() *
105 OverflowingBinaryOperator::NoUnsignedWrap;
106 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
109 return hash_combine(BinOp->getOpcode(), LHS, RHS);
112 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
113 Value *LHS = CI->getOperand(0);
114 Value *RHS = CI->getOperand(1);
115 CmpInst::Predicate Pred = CI->getPredicate();
116 if (Inst->getOperand(0) > Inst->getOperand(1)) {
118 Pred = CI->getSwappedPredicate();
120 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
123 if (CastInst *CI = dyn_cast<CastInst>(Inst))
124 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
126 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
127 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
128 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
130 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
131 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
133 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
135 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
136 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
137 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
138 isa<ShuffleVectorInst>(Inst)) &&
139 "Invalid/unknown instruction");
141 // Mix in the opcode.
144 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
147 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
148 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
150 if (LHS.isSentinel() || RHS.isSentinel())
153 if (LHSI->getOpcode() != RHSI->getOpcode())
155 if (LHSI->isIdenticalTo(RHSI))
158 // If we're not strictly identical, we still might be a commutable instruction
159 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
160 if (!LHSBinOp->isCommutative())
163 assert(isa<BinaryOperator>(RHSI) &&
164 "same opcode, but different instruction type?");
165 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
167 // Check overflow attributes
168 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
169 assert(isa<OverflowingBinaryOperator>(RHSBinOp) &&
170 "same opcode, but different operator type?");
171 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
172 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
177 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
178 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
180 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
181 assert(isa<CmpInst>(RHSI) &&
182 "same opcode, but different instruction type?");
183 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
185 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
186 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
187 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
193 //===----------------------------------------------------------------------===//
195 //===----------------------------------------------------------------------===//
198 /// \brief Struct representing the available call values in the scoped hash
203 CallValue(Instruction *I) : Inst(I) {
204 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
207 bool isSentinel() const {
208 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
209 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
212 static bool canHandle(Instruction *Inst) {
213 // Don't value number anything that returns void.
214 if (Inst->getType()->isVoidTy())
217 CallInst *CI = dyn_cast<CallInst>(Inst);
218 if (!CI || !CI->onlyReadsMemory())
226 template <> struct DenseMapInfo<CallValue> {
227 static inline CallValue getEmptyKey() {
228 return DenseMapInfo<Instruction *>::getEmptyKey();
230 static inline CallValue getTombstoneKey() {
231 return DenseMapInfo<Instruction *>::getTombstoneKey();
233 static unsigned getHashValue(CallValue Val);
234 static bool isEqual(CallValue LHS, CallValue RHS);
238 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
239 Instruction *Inst = Val.Inst;
240 // Hash all of the operands as pointers and mix in the opcode.
243 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
246 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
247 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
248 if (LHS.isSentinel() || RHS.isSentinel())
250 return LHSI->isIdenticalTo(RHSI);
253 //===----------------------------------------------------------------------===//
254 // EarlyCSE implementation
255 //===----------------------------------------------------------------------===//
258 /// \brief A simple and fast domtree-based CSE pass.
260 /// This pass does a simple depth-first walk over the dominator tree,
261 /// eliminating trivially redundant instructions and using instsimplify to
262 /// canonicalize things as it goes. It is intended to be fast and catch obvious
263 /// cases so that instcombine and other passes are more effective. It is
264 /// expected that a later pass of GVN will catch the interesting/hard cases.
267 const TargetLibraryInfo &TLI;
268 const TargetTransformInfo &TTI;
271 typedef RecyclingAllocator<
272 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
273 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
274 AllocatorTy> ScopedHTType;
276 /// \brief A scoped hash table of the current values of all of our simple
277 /// scalar expressions.
279 /// As we walk down the domtree, we look to see if instructions are in this:
280 /// if so, we replace them with what we find, otherwise we insert them so
281 /// that dominated values can succeed in their lookup.
282 ScopedHTType AvailableValues;
284 /// A scoped hash table of the current values of previously encounted memory
287 /// This allows us to get efficient access to dominating loads or stores when
288 /// we have a fully redundant load. In addition to the most recent load, we
289 /// keep track of a generation count of the read, which is compared against
290 /// the current generation count. The current generation count is incremented
291 /// after every possibly writing memory operation, which ensures that we only
292 /// CSE loads with other loads that have no intervening store. Ordering
293 /// events (such as fences or atomic instructions) increment the generation
294 /// count as well; essentially, we model these as writes to all possible
295 /// locations. Note that atomic and/or volatile loads and stores can be
296 /// present the table; it is the responsibility of the consumer to inspect
297 /// the atomicity/volatility if needed.
304 : Data(nullptr), Generation(0), MatchingId(-1), IsAtomic(false) {}
305 LoadValue(Value *Data, unsigned Generation, unsigned MatchingId,
307 : Data(Data), Generation(Generation), MatchingId(MatchingId),
308 IsAtomic(IsAtomic) {}
310 typedef RecyclingAllocator<BumpPtrAllocator,
311 ScopedHashTableVal<Value *, LoadValue>>
313 typedef ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
314 LoadMapAllocator> LoadHTType;
315 LoadHTType AvailableLoads;
317 /// \brief A scoped hash table of the current values of read-only call
320 /// It uses the same generation count as loads.
321 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
322 CallHTType AvailableCalls;
324 /// \brief This is the current generation of the memory value.
325 unsigned CurrentGeneration;
327 /// \brief Set up the EarlyCSE runner for a particular function.
328 EarlyCSE(const TargetLibraryInfo &TLI, const TargetTransformInfo &TTI,
329 DominatorTree &DT, AssumptionCache &AC)
330 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {}
335 // Almost a POD, but needs to call the constructors for the scoped hash
336 // tables so that a new scope gets pushed on. These are RAII so that the
337 // scope gets popped when the NodeScope is destroyed.
340 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
341 CallHTType &AvailableCalls)
342 : Scope(AvailableValues), LoadScope(AvailableLoads),
343 CallScope(AvailableCalls) {}
346 NodeScope(const NodeScope &) = delete;
347 void operator=(const NodeScope &) = delete;
349 ScopedHTType::ScopeTy Scope;
350 LoadHTType::ScopeTy LoadScope;
351 CallHTType::ScopeTy CallScope;
354 // Contains all the needed information to create a stack for doing a depth
355 // first tranversal of the tree. This includes scopes for values, loads, and
356 // calls as well as the generation. There is a child iterator so that the
357 // children do not need to be store spearately.
360 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
361 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
362 DomTreeNode::iterator child, DomTreeNode::iterator end)
363 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
364 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
368 unsigned currentGeneration() { return CurrentGeneration; }
369 unsigned childGeneration() { return ChildGeneration; }
370 void childGeneration(unsigned generation) { ChildGeneration = generation; }
371 DomTreeNode *node() { return Node; }
372 DomTreeNode::iterator childIter() { return ChildIter; }
373 DomTreeNode *nextChild() {
374 DomTreeNode *child = *ChildIter;
378 DomTreeNode::iterator end() { return EndIter; }
379 bool isProcessed() { return Processed; }
380 void process() { Processed = true; }
383 StackNode(const StackNode &) = delete;
384 void operator=(const StackNode &) = delete;
387 unsigned CurrentGeneration;
388 unsigned ChildGeneration;
390 DomTreeNode::iterator ChildIter;
391 DomTreeNode::iterator EndIter;
396 /// \brief Wrapper class to handle memory instructions, including loads,
397 /// stores and intrinsic loads and stores defined by the target.
398 class ParseMemoryInst {
400 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
401 : IsTargetMemInst(false), Inst(Inst) {
402 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
403 if (TTI.getTgtMemIntrinsic(II, Info) && Info.NumMemRefs == 1)
404 IsTargetMemInst = true;
406 bool isLoad() const {
407 if (IsTargetMemInst) return Info.ReadMem;
408 return isa<LoadInst>(Inst);
410 bool isStore() const {
411 if (IsTargetMemInst) return Info.WriteMem;
412 return isa<StoreInst>(Inst);
414 bool isSimple() const {
415 if (IsTargetMemInst) return Info.IsSimple;
416 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
417 return LI->isSimple();
418 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
419 return SI->isSimple();
421 return Inst->isAtomic();
423 bool isAtomic() const {
424 if (IsTargetMemInst) {
425 assert(Info.IsSimple && "need to refine IsSimple in TTI");
428 return Inst->isAtomic();
430 bool isUnordered() const {
431 if (IsTargetMemInst) {
432 assert(Info.IsSimple && "need to refine IsSimple in TTI");
435 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
436 return LI->isUnordered();
437 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
438 return SI->isUnordered();
440 // Conservative answer
441 return !Inst->isAtomic();
444 bool isVolatile() const {
445 if (IsTargetMemInst) {
446 assert(Info.IsSimple && "need to refine IsSimple in TTI");
449 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
450 return LI->isVolatile();
451 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
452 return SI->isVolatile();
454 // Conservative answer
459 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
460 return (getPointerOperand() == Inst.getPointerOperand() &&
461 getMatchingId() == Inst.getMatchingId());
463 bool isValid() const { return getPointerOperand() != nullptr; }
465 // For regular (non-intrinsic) loads/stores, this is set to -1. For
466 // intrinsic loads/stores, the id is retrieved from the corresponding
467 // field in the MemIntrinsicInfo structure. That field contains
468 // non-negative values only.
469 int getMatchingId() const {
470 if (IsTargetMemInst) return Info.MatchingId;
473 Value *getPointerOperand() const {
474 if (IsTargetMemInst) return Info.PtrVal;
475 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
476 return LI->getPointerOperand();
477 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
478 return SI->getPointerOperand();
482 bool mayReadFromMemory() const {
483 if (IsTargetMemInst) return Info.ReadMem;
484 return Inst->mayReadFromMemory();
486 bool mayWriteToMemory() const {
487 if (IsTargetMemInst) return Info.WriteMem;
488 return Inst->mayWriteToMemory();
492 bool IsTargetMemInst;
493 MemIntrinsicInfo Info;
497 bool processNode(DomTreeNode *Node);
499 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
500 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
502 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
503 return SI->getValueOperand();
504 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
505 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
511 bool EarlyCSE::processNode(DomTreeNode *Node) {
512 BasicBlock *BB = Node->getBlock();
514 // If this block has a single predecessor, then the predecessor is the parent
515 // of the domtree node and all of the live out memory values are still current
516 // in this block. If this block has multiple predecessors, then they could
517 // have invalidated the live-out memory values of our parent value. For now,
518 // just be conservative and invalidate memory if this block has multiple
520 if (!BB->getSinglePredecessor())
523 // If this node has a single predecessor which ends in a conditional branch,
524 // we can infer the value of the branch condition given that we took this
525 // path. We need the single predeccesor to ensure there's not another path
526 // which reaches this block where the condition might hold a different
527 // value. Since we're adding this to the scoped hash table (like any other
528 // def), it will have been popped if we encounter a future merge block.
529 if (BasicBlock *Pred = BB->getSinglePredecessor())
530 if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
531 if (BI->isConditional())
532 if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition()))
533 if (SimpleValue::canHandle(CondInst)) {
534 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
535 auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ?
536 ConstantInt::getTrue(BB->getContext()) :
537 ConstantInt::getFalse(BB->getContext());
538 AvailableValues.insert(CondInst, ConditionalConstant);
539 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
540 << CondInst->getName() << "' as " << *ConditionalConstant
541 << " in " << BB->getName() << "\n");
542 // Replace all dominated uses with the known value
543 replaceDominatedUsesWith(CondInst, ConditionalConstant, DT,
544 BasicBlockEdge(Pred, BB));
547 /// LastStore - Keep track of the last non-volatile store that we saw... for
548 /// as long as there in no instruction that reads memory. If we see a store
549 /// to the same location, we delete the dead store. This zaps trivial dead
550 /// stores which can occur in bitfield code among other things.
551 Instruction *LastStore = nullptr;
553 bool Changed = false;
554 const DataLayout &DL = BB->getModule()->getDataLayout();
556 // See if any instructions in the block can be eliminated. If so, do it. If
557 // not, add them to AvailableValues.
558 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
559 Instruction *Inst = &*I++;
561 // Dead instructions should just be removed.
562 if (isInstructionTriviallyDead(Inst, &TLI)) {
563 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
564 Inst->eraseFromParent();
570 // Skip assume intrinsics, they don't really have side effects (although
571 // they're marked as such to ensure preservation of control dependencies),
572 // and this pass will not disturb any of the assumption's control
574 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
575 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
579 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
580 // its simpler value.
581 if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
582 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
583 Inst->replaceAllUsesWith(V);
584 Inst->eraseFromParent();
590 // If this is a simple instruction that we can value number, process it.
591 if (SimpleValue::canHandle(Inst)) {
592 // See if the instruction has an available value. If so, use it.
593 if (Value *V = AvailableValues.lookup(Inst)) {
594 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
595 Inst->replaceAllUsesWith(V);
596 Inst->eraseFromParent();
602 // Otherwise, just remember that this value is available.
603 AvailableValues.insert(Inst, Inst);
607 ParseMemoryInst MemInst(Inst, TTI);
608 // If this is a non-volatile load, process it.
609 if (MemInst.isValid() && MemInst.isLoad()) {
610 // (conservatively) we can't peak past the ordering implied by this
611 // operation, but we can add this load to our set of available values
612 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
617 // If we have an available version of this load, and if it is the right
618 // generation, replace this instruction.
619 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
620 if (InVal.Data != nullptr && InVal.Generation == CurrentGeneration &&
621 InVal.MatchingId == MemInst.getMatchingId() &&
622 // We don't yet handle removing loads with ordering of any kind.
623 !MemInst.isVolatile() && MemInst.isUnordered() &&
624 // We can't replace an atomic load with one which isn't also atomic.
625 InVal.IsAtomic >= MemInst.isAtomic()) {
626 Value *Op = getOrCreateResult(InVal.Data, Inst->getType());
628 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
629 << " to: " << *InVal.Data << '\n');
630 if (!Inst->use_empty())
631 Inst->replaceAllUsesWith(Op);
632 Inst->eraseFromParent();
639 // Otherwise, remember that we have this instruction.
640 AvailableLoads.insert(
641 MemInst.getPointerOperand(),
642 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
643 MemInst.isAtomic()));
648 // If this instruction may read from memory, forget LastStore.
649 // Load/store intrinsics will indicate both a read and a write to
650 // memory. The target may override this (e.g. so that a store intrinsic
651 // does not read from memory, and thus will be treated the same as a
652 // regular store for commoning purposes).
653 if (Inst->mayReadFromMemory() &&
654 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
657 // If this is a read-only call, process it.
658 if (CallValue::canHandle(Inst)) {
659 // If we have an available version of this call, and if it is the right
660 // generation, replace this instruction.
661 std::pair<Value *, unsigned> InVal = AvailableCalls.lookup(Inst);
662 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
663 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
664 << " to: " << *InVal.first << '\n');
665 if (!Inst->use_empty())
666 Inst->replaceAllUsesWith(InVal.first);
667 Inst->eraseFromParent();
673 // Otherwise, remember that we have this instruction.
674 AvailableCalls.insert(
675 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
679 // A release fence requires that all stores complete before it, but does
680 // not prevent the reordering of following loads 'before' the fence. As a
681 // result, we don't need to consider it as writing to memory and don't need
682 // to advance the generation. We do need to prevent DSE across the fence,
683 // but that's handled above.
684 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
685 if (FI->getOrdering() == Release) {
686 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
690 // Okay, this isn't something we can CSE at all. Check to see if it is
691 // something that could modify memory. If so, our available memory values
692 // cannot be used so bump the generation count.
693 if (Inst->mayWriteToMemory()) {
696 if (MemInst.isValid() && MemInst.isStore()) {
697 // We do a trivial form of DSE if there are two stores to the same
698 // location with no intervening loads. Delete the earlier store. Note
699 // that we can delete an earlier simple store even if the following one
700 // is ordered/volatile/atomic store.
702 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
703 assert(LastStoreMemInst.isSimple() && "Violated invariant");
704 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
705 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
706 << " due to: " << *Inst << '\n');
707 LastStore->eraseFromParent();
712 // fallthrough - we can exploit information about this store
715 // Okay, we just invalidated anything we knew about loaded values. Try
716 // to salvage *something* by remembering that the stored value is a live
717 // version of the pointer. It is safe to forward from volatile stores
718 // to non-volatile loads, so we don't have to check for volatility of
720 AvailableLoads.insert(
721 MemInst.getPointerOperand(),
722 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
723 MemInst.isAtomic()));
725 // Remember that this was the last normal store we saw for DSE.
726 // Note that we can't delete an earlier atomic or volatile store in
727 // favor of a later one which isn't. We could in principle remove an
728 // earlier unordered store if the later one is also unordered.
729 if (MemInst.isSimple())
740 bool EarlyCSE::run() {
741 // Note, deque is being used here because there is significant performance
742 // gains over vector when the container becomes very large due to the
743 // specific access patterns. For more information see the mailing list
744 // discussion on this:
745 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
746 std::deque<StackNode *> nodesToProcess;
748 bool Changed = false;
750 // Process the root node.
751 nodesToProcess.push_back(new StackNode(
752 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
753 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
755 // Save the current generation.
756 unsigned LiveOutGeneration = CurrentGeneration;
758 // Process the stack.
759 while (!nodesToProcess.empty()) {
760 // Grab the first item off the stack. Set the current generation, remove
761 // the node from the stack, and process it.
762 StackNode *NodeToProcess = nodesToProcess.back();
764 // Initialize class members.
765 CurrentGeneration = NodeToProcess->currentGeneration();
767 // Check if the node needs to be processed.
768 if (!NodeToProcess->isProcessed()) {
770 Changed |= processNode(NodeToProcess->node());
771 NodeToProcess->childGeneration(CurrentGeneration);
772 NodeToProcess->process();
773 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
774 // Push the next child onto the stack.
775 DomTreeNode *child = NodeToProcess->nextChild();
776 nodesToProcess.push_back(
777 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
778 NodeToProcess->childGeneration(), child, child->begin(),
781 // It has been processed, and there are no more children to process,
782 // so delete it and pop it off the stack.
783 delete NodeToProcess;
784 nodesToProcess.pop_back();
786 } // while (!nodes...)
788 // Reset the current generation.
789 CurrentGeneration = LiveOutGeneration;
794 PreservedAnalyses EarlyCSEPass::run(Function &F,
795 AnalysisManager<Function> *AM) {
796 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
797 auto &TTI = AM->getResult<TargetIRAnalysis>(F);
798 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
799 auto &AC = AM->getResult<AssumptionAnalysis>(F);
801 EarlyCSE CSE(TLI, TTI, DT, AC);
804 return PreservedAnalyses::all();
806 // CSE preserves the dominator tree because it doesn't mutate the CFG.
807 // FIXME: Bundle this with other CFG-preservation.
808 PreservedAnalyses PA;
809 PA.preserve<DominatorTreeAnalysis>();
814 /// \brief A simple and fast domtree-based CSE pass.
816 /// This pass does a simple depth-first walk over the dominator tree,
817 /// eliminating trivially redundant instructions and using instsimplify to
818 /// canonicalize things as it goes. It is intended to be fast and catch obvious
819 /// cases so that instcombine and other passes are more effective. It is
820 /// expected that a later pass of GVN will catch the interesting/hard cases.
821 class EarlyCSELegacyPass : public FunctionPass {
825 EarlyCSELegacyPass() : FunctionPass(ID) {
826 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
829 bool runOnFunction(Function &F) override {
830 if (skipOptnoneFunction(F))
833 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
834 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
835 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
836 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
838 EarlyCSE CSE(TLI, TTI, DT, AC);
843 void getAnalysisUsage(AnalysisUsage &AU) const override {
844 AU.addRequired<AssumptionCacheTracker>();
845 AU.addRequired<DominatorTreeWrapperPass>();
846 AU.addRequired<TargetLibraryInfoWrapperPass>();
847 AU.addRequired<TargetTransformInfoWrapperPass>();
848 AU.addPreserved<GlobalsAAWrapperPass>();
849 AU.setPreservesCFG();
854 char EarlyCSELegacyPass::ID = 0;
856 FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); }
858 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
860 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
861 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
862 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
863 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
864 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)