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 #define DEBUG_TYPE "early-cse"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/ADT/Hashing.h"
18 #include "llvm/ADT/ScopedHashTable.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/RecyclingAllocator.h"
27 #include "llvm/Target/TargetLibraryInfo.h"
28 #include "llvm/Transforms/Utils/Local.h"
32 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
33 STATISTIC(NumCSE, "Number of instructions CSE'd");
34 STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
35 STATISTIC(NumCSECall, "Number of call instructions CSE'd");
36 STATISTIC(NumDSE, "Number of trivial dead stores removed");
38 static unsigned getHash(const void *V) {
39 return DenseMapInfo<const void*>::getHashValue(V);
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
47 /// SimpleValue - Instances of this struct represent available values in the
48 /// scoped hash table.
52 SimpleValue(Instruction *I) : Inst(I) {
53 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
56 bool isSentinel() const {
57 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
58 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
61 static bool canHandle(Instruction *Inst) {
62 // This can only handle non-void readnone functions.
63 if (CallInst *CI = dyn_cast<CallInst>(Inst))
64 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
65 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
66 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
67 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
68 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
69 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
75 template<> struct DenseMapInfo<SimpleValue> {
76 static inline SimpleValue getEmptyKey() {
77 return DenseMapInfo<Instruction*>::getEmptyKey();
79 static inline SimpleValue getTombstoneKey() {
80 return DenseMapInfo<Instruction*>::getTombstoneKey();
82 static unsigned getHashValue(SimpleValue Val);
83 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
87 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
88 Instruction *Inst = Val.Inst;
89 // Hash in all of the operands as pointers.
90 if (BinaryOperator* BinOp = dyn_cast<BinaryOperator>(Inst)) {
91 Value *LHS = BinOp->getOperand(0);
92 Value *RHS = BinOp->getOperand(1);
93 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
96 if (isa<OverflowingBinaryOperator>(BinOp)) {
97 // Hash the overflow behavior
99 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
100 BinOp->hasNoUnsignedWrap() * OverflowingBinaryOperator::NoUnsignedWrap;
101 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
104 return hash_combine(BinOp->getOpcode(), LHS, RHS);
107 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
108 Value *LHS = CI->getOperand(0);
109 Value *RHS = CI->getOperand(1);
110 CmpInst::Predicate Pred = CI->getPredicate();
111 if (Inst->getOperand(0) > Inst->getOperand(1)) {
113 Pred = CI->getSwappedPredicate();
115 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
118 if (CastInst *CI = dyn_cast<CastInst>(Inst))
119 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
121 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
122 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
123 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
125 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
126 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
128 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
130 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
131 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
132 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
133 isa<ShuffleVectorInst>(Inst)) && "Invalid/unknown instruction");
135 // Mix in the opcode.
136 return hash_combine(Inst->getOpcode(),
137 hash_combine_range(Inst->value_op_begin(),
138 Inst->value_op_end()));
141 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
142 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
144 if (LHS.isSentinel() || RHS.isSentinel())
147 if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
148 if (LHSI->isIdenticalTo(RHSI)) return true;
150 // If we're not strictly identical, we still might be a commutable instruction
151 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
152 if (!LHSBinOp->isCommutative())
155 assert(isa<BinaryOperator>(RHSI)
156 && "same opcode, but different instruction type?");
157 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
159 // Check overflow attributes
160 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
161 assert(isa<OverflowingBinaryOperator>(RHSBinOp)
162 && "same opcode, but different operator type?");
163 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
164 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
169 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
170 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
172 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
173 assert(isa<CmpInst>(RHSI)
174 && "same opcode, but different instruction type?");
175 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
177 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
178 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
179 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
185 //===----------------------------------------------------------------------===//
187 //===----------------------------------------------------------------------===//
190 /// CallValue - Instances of this struct represent available call values in
191 /// the scoped hash table.
195 CallValue(Instruction *I) : Inst(I) {
196 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
199 bool isSentinel() const {
200 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
201 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
204 static bool canHandle(Instruction *Inst) {
205 // Don't value number anything that returns void.
206 if (Inst->getType()->isVoidTy())
209 CallInst *CI = dyn_cast<CallInst>(Inst);
210 if (CI == 0 || !CI->onlyReadsMemory())
218 template<> struct DenseMapInfo<CallValue> {
219 static inline CallValue getEmptyKey() {
220 return DenseMapInfo<Instruction*>::getEmptyKey();
222 static inline CallValue getTombstoneKey() {
223 return DenseMapInfo<Instruction*>::getTombstoneKey();
225 static unsigned getHashValue(CallValue Val);
226 static bool isEqual(CallValue LHS, CallValue RHS);
229 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
230 Instruction *Inst = Val.Inst;
231 // Hash in all of the operands as pointers.
233 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
234 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
235 "Cannot value number calls with metadata operands");
236 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
239 // Mix in the opcode.
240 return (Res << 1) ^ Inst->getOpcode();
243 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
244 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
245 if (LHS.isSentinel() || RHS.isSentinel())
247 return LHSI->isIdenticalTo(RHSI);
251 //===----------------------------------------------------------------------===//
253 //===----------------------------------------------------------------------===//
257 /// EarlyCSE - This pass does a simple depth-first walk over the dominator
258 /// tree, eliminating trivially redundant instructions and using instsimplify
259 /// to canonicalize things as it goes. It is intended to be fast and catch
260 /// obvious cases so that instcombine and other passes are more effective. It
261 /// is expected that a later pass of GVN will catch the interesting/hard
263 class EarlyCSE : public FunctionPass {
265 const DataLayout *DL;
266 const TargetLibraryInfo *TLI;
268 typedef RecyclingAllocator<BumpPtrAllocator,
269 ScopedHashTableVal<SimpleValue, Value*> > AllocatorTy;
270 typedef ScopedHashTable<SimpleValue, Value*, DenseMapInfo<SimpleValue>,
271 AllocatorTy> ScopedHTType;
273 /// AvailableValues - This scoped hash table contains the current values of
274 /// all of our simple scalar expressions. As we walk down the domtree, we
275 /// look to see if instructions are in this: if so, we replace them with what
276 /// we find, otherwise we insert them so that dominated values can succeed in
278 ScopedHTType *AvailableValues;
280 /// AvailableLoads - This scoped hash table contains the current values
281 /// of loads. This allows us to get efficient access to dominating loads when
282 /// we have a fully redundant load. In addition to the most recent load, we
283 /// keep track of a generation count of the read, which is compared against
284 /// the current generation count. The current generation count is
285 /// incremented after every possibly writing memory operation, which ensures
286 /// that we only CSE loads with other loads that have no intervening store.
287 typedef RecyclingAllocator<BumpPtrAllocator,
288 ScopedHashTableVal<Value*, std::pair<Value*, unsigned> > > LoadMapAllocator;
289 typedef ScopedHashTable<Value*, std::pair<Value*, unsigned>,
290 DenseMapInfo<Value*>, LoadMapAllocator> LoadHTType;
291 LoadHTType *AvailableLoads;
293 /// AvailableCalls - This scoped hash table contains the current values
294 /// of read-only call values. It uses the same generation count as loads.
295 typedef ScopedHashTable<CallValue, std::pair<Value*, unsigned> > CallHTType;
296 CallHTType *AvailableCalls;
298 /// CurrentGeneration - This is the current generation of the memory value.
299 unsigned CurrentGeneration;
302 explicit EarlyCSE() : FunctionPass(ID) {
303 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
306 bool runOnFunction(Function &F) override;
310 // NodeScope - almost a POD, but needs to call the constructors for the
311 // scoped hash tables so that a new scope gets pushed on. These are RAII so
312 // that the scope gets popped when the NodeScope is destroyed.
315 NodeScope(ScopedHTType *availableValues,
316 LoadHTType *availableLoads,
317 CallHTType *availableCalls) :
318 Scope(*availableValues),
319 LoadScope(*availableLoads),
320 CallScope(*availableCalls) {}
323 NodeScope(const NodeScope&) LLVM_DELETED_FUNCTION;
324 void operator=(const NodeScope&) LLVM_DELETED_FUNCTION;
326 ScopedHTType::ScopeTy Scope;
327 LoadHTType::ScopeTy LoadScope;
328 CallHTType::ScopeTy CallScope;
331 // StackNode - contains all the needed information to create a stack for
332 // doing a depth first tranversal of the tree. This includes scopes for
333 // values, loads, and calls as well as the generation. There is a child
334 // iterator so that the children do not need to be store spearately.
337 StackNode(ScopedHTType *availableValues,
338 LoadHTType *availableLoads,
339 CallHTType *availableCalls,
340 unsigned cg, DomTreeNode *n,
341 DomTreeNode::iterator child, DomTreeNode::iterator end) :
342 CurrentGeneration(cg), ChildGeneration(cg), Node(n),
343 ChildIter(child), EndIter(end),
344 Scopes(availableValues, availableLoads, availableCalls),
348 unsigned currentGeneration() { return CurrentGeneration; }
349 unsigned childGeneration() { return ChildGeneration; }
350 void childGeneration(unsigned generation) { ChildGeneration = generation; }
351 DomTreeNode *node() { return Node; }
352 DomTreeNode::iterator childIter() { return ChildIter; }
353 DomTreeNode *nextChild() {
354 DomTreeNode *child = *ChildIter;
358 DomTreeNode::iterator end() { return EndIter; }
359 bool isProcessed() { return Processed; }
360 void process() { Processed = true; }
363 StackNode(const StackNode&) LLVM_DELETED_FUNCTION;
364 void operator=(const StackNode&) LLVM_DELETED_FUNCTION;
367 unsigned CurrentGeneration;
368 unsigned ChildGeneration;
370 DomTreeNode::iterator ChildIter;
371 DomTreeNode::iterator EndIter;
376 bool processNode(DomTreeNode *Node);
378 // This transformation requires dominator postdominator info
379 void getAnalysisUsage(AnalysisUsage &AU) const override {
380 AU.addRequired<DominatorTreeWrapperPass>();
381 AU.addRequired<TargetLibraryInfo>();
382 AU.setPreservesCFG();
387 char EarlyCSE::ID = 0;
389 // createEarlyCSEPass - The public interface to this file.
390 FunctionPass *llvm::createEarlyCSEPass() {
391 return new EarlyCSE();
394 INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
395 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
396 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
397 INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
399 bool EarlyCSE::processNode(DomTreeNode *Node) {
400 BasicBlock *BB = Node->getBlock();
402 // If this block has a single predecessor, then the predecessor is the parent
403 // of the domtree node and all of the live out memory values are still current
404 // in this block. If this block has multiple predecessors, then they could
405 // have invalidated the live-out memory values of our parent value. For now,
406 // just be conservative and invalidate memory if this block has multiple
408 if (BB->getSinglePredecessor() == 0)
411 /// LastStore - Keep track of the last non-volatile store that we saw... for
412 /// as long as there in no instruction that reads memory. If we see a store
413 /// to the same location, we delete the dead store. This zaps trivial dead
414 /// stores which can occur in bitfield code among other things.
415 StoreInst *LastStore = 0;
417 bool Changed = false;
419 // See if any instructions in the block can be eliminated. If so, do it. If
420 // not, add them to AvailableValues.
421 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
422 Instruction *Inst = I++;
424 // Dead instructions should just be removed.
425 if (isInstructionTriviallyDead(Inst, TLI)) {
426 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
427 Inst->eraseFromParent();
433 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
434 // its simpler value.
435 if (Value *V = SimplifyInstruction(Inst, DL, TLI, DT)) {
436 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
437 Inst->replaceAllUsesWith(V);
438 Inst->eraseFromParent();
444 // If this is a simple instruction that we can value number, process it.
445 if (SimpleValue::canHandle(Inst)) {
446 // See if the instruction has an available value. If so, use it.
447 if (Value *V = AvailableValues->lookup(Inst)) {
448 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
449 Inst->replaceAllUsesWith(V);
450 Inst->eraseFromParent();
456 // Otherwise, just remember that this value is available.
457 AvailableValues->insert(Inst, Inst);
461 // If this is a non-volatile load, process it.
462 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
463 // Ignore volatile loads.
464 if (!LI->isSimple()) {
469 // If we have an available version of this load, and if it is the right
470 // generation, replace this instruction.
471 std::pair<Value*, unsigned> InVal =
472 AvailableLoads->lookup(Inst->getOperand(0));
473 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
474 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst << " to: "
475 << *InVal.first << '\n');
476 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
477 Inst->eraseFromParent();
483 // Otherwise, remember that we have this instruction.
484 AvailableLoads->insert(Inst->getOperand(0),
485 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
490 // If this instruction may read from memory, forget LastStore.
491 if (Inst->mayReadFromMemory())
494 // If this is a read-only call, process it.
495 if (CallValue::canHandle(Inst)) {
496 // If we have an available version of this call, and if it is the right
497 // generation, replace this instruction.
498 std::pair<Value*, unsigned> InVal = AvailableCalls->lookup(Inst);
499 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
500 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst << " to: "
501 << *InVal.first << '\n');
502 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
503 Inst->eraseFromParent();
509 // Otherwise, remember that we have this instruction.
510 AvailableCalls->insert(Inst,
511 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
515 // Okay, this isn't something we can CSE at all. Check to see if it is
516 // something that could modify memory. If so, our available memory values
517 // cannot be used so bump the generation count.
518 if (Inst->mayWriteToMemory()) {
521 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
522 // We do a trivial form of DSE if there are two stores to the same
523 // location with no intervening loads. Delete the earlier store.
525 LastStore->getPointerOperand() == SI->getPointerOperand()) {
526 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore << " due to: "
528 LastStore->eraseFromParent();
535 // Okay, we just invalidated anything we knew about loaded values. Try
536 // to salvage *something* by remembering that the stored value is a live
537 // version of the pointer. It is safe to forward from volatile stores
538 // to non-volatile loads, so we don't have to check for volatility of
540 AvailableLoads->insert(SI->getPointerOperand(),
541 std::pair<Value*, unsigned>(SI->getValueOperand(), CurrentGeneration));
543 // Remember that this was the last store we saw for DSE.
554 bool EarlyCSE::runOnFunction(Function &F) {
555 if (skipOptnoneFunction(F))
558 std::vector<StackNode *> nodesToProcess;
560 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
561 DL = DLP ? &DLP->getDataLayout() : 0;
562 TLI = &getAnalysis<TargetLibraryInfo>();
563 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
565 // Tables that the pass uses when walking the domtree.
566 ScopedHTType AVTable;
567 AvailableValues = &AVTable;
568 LoadHTType LoadTable;
569 AvailableLoads = &LoadTable;
570 CallHTType CallTable;
571 AvailableCalls = &CallTable;
573 CurrentGeneration = 0;
574 bool Changed = false;
576 // Process the root node.
577 nodesToProcess.push_back(
578 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
579 CurrentGeneration, DT->getRootNode(),
580 DT->getRootNode()->begin(),
581 DT->getRootNode()->end()));
583 // Save the current generation.
584 unsigned LiveOutGeneration = CurrentGeneration;
586 // Process the stack.
587 while (!nodesToProcess.empty()) {
588 // Grab the first item off the stack. Set the current generation, remove
589 // the node from the stack, and process it.
590 StackNode *NodeToProcess = nodesToProcess.back();
592 // Initialize class members.
593 CurrentGeneration = NodeToProcess->currentGeneration();
595 // Check if the node needs to be processed.
596 if (!NodeToProcess->isProcessed()) {
598 Changed |= processNode(NodeToProcess->node());
599 NodeToProcess->childGeneration(CurrentGeneration);
600 NodeToProcess->process();
601 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
602 // Push the next child onto the stack.
603 DomTreeNode *child = NodeToProcess->nextChild();
604 nodesToProcess.push_back(
605 new StackNode(AvailableValues,
608 NodeToProcess->childGeneration(), child,
609 child->begin(), child->end()));
611 // It has been processed, and there are no more children to process,
612 // so delete it and pop it off the stack.
613 delete NodeToProcess;
614 nodesToProcess.pop_back();
616 } // while (!nodes...)
618 // Reset the current generation.
619 CurrentGeneration = LiveOutGeneration;