1 //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass performs a simple dominator tree walk that eliminates trivially 11 // redundant instructions. 12 // 13 //===----------------------------------------------------------------------===// 14 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" 35 #include <deque> 36 using namespace llvm; 37 using namespace llvm::PatternMatch; 38 39 #define DEBUG_TYPE "early-cse" 40 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"); 46 47 //===----------------------------------------------------------------------===// 48 // SimpleValue 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// \brief Struct representing the available values in the scoped hash table. 53 struct SimpleValue { 54 Instruction *Inst; 55 56 SimpleValue(Instruction *I) : Inst(I) { 57 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!"); 58 } 59 60 bool isSentinel() const { 61 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() || 62 Inst == DenseMapInfo<Instruction *>::getTombstoneKey(); 63 } 64 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); 74 } 75 }; 76 } 77 78 namespace llvm { 79 template <> struct DenseMapInfo<SimpleValue> { 80 static inline SimpleValue getEmptyKey() { 81 return DenseMapInfo<Instruction *>::getEmptyKey(); 82 } 83 static inline SimpleValue getTombstoneKey() { 84 return DenseMapInfo<Instruction *>::getTombstoneKey(); 85 } 86 static unsigned getHashValue(SimpleValue Val); 87 static bool isEqual(SimpleValue LHS, SimpleValue RHS); 88 }; 89 } 90 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)) 98 std::swap(LHS, RHS); 99 100 if (isa<OverflowingBinaryOperator>(BinOp)) { 101 // Hash the overflow behavior 102 unsigned Overflow = 103 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap | 104 BinOp->hasNoUnsignedWrap() * 105 OverflowingBinaryOperator::NoUnsignedWrap; 106 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS); 107 } 108 109 return hash_combine(BinOp->getOpcode(), LHS, RHS); 110 } 111 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)) { 117 std::swap(LHS, RHS); 118 Pred = CI->getSwappedPredicate(); 119 } 120 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS); 121 } 122 123 if (CastInst *CI = dyn_cast<CastInst>(Inst)) 124 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0)); 125 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())); 129 130 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst)) 131 return hash_combine(IVI->getOpcode(), IVI->getOperand(0), 132 IVI->getOperand(1), 133 hash_combine_range(IVI->idx_begin(), IVI->idx_end())); 134 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"); 140 141 // Mix in the opcode. 142 return hash_combine( 143 Inst->getOpcode(), 144 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end())); 145 } 146 147 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) { 148 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst; 149 150 if (LHS.isSentinel() || RHS.isSentinel()) 151 return LHSI == RHSI; 152 153 if (LHSI->getOpcode() != RHSI->getOpcode()) 154 return false; 155 if (LHSI->isIdenticalTo(RHSI)) 156 return true; 157 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()) 161 return false; 162 163 assert(isa<BinaryOperator>(RHSI) && 164 "same opcode, but different instruction type?"); 165 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI); 166 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()) 173 return false; 174 } 175 176 // Commuted equality 177 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) && 178 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0); 179 } 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); 184 // Commuted equality 185 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) && 186 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) && 187 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate(); 188 } 189 190 return false; 191 } 192 193 //===----------------------------------------------------------------------===// 194 // CallValue 195 //===----------------------------------------------------------------------===// 196 197 namespace { 198 /// \brief Struct representing the available call values in the scoped hash 199 /// table. 200 struct CallValue { 201 Instruction *Inst; 202 203 CallValue(Instruction *I) : Inst(I) { 204 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!"); 205 } 206 207 bool isSentinel() const { 208 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() || 209 Inst == DenseMapInfo<Instruction *>::getTombstoneKey(); 210 } 211 212 static bool canHandle(Instruction *Inst) { 213 // Don't value number anything that returns void. 214 if (Inst->getType()->isVoidTy()) 215 return false; 216 217 CallInst *CI = dyn_cast<CallInst>(Inst); 218 if (!CI || !CI->onlyReadsMemory()) 219 return false; 220 return true; 221 } 222 }; 223 } 224 225 namespace llvm { 226 template <> struct DenseMapInfo<CallValue> { 227 static inline CallValue getEmptyKey() { 228 return DenseMapInfo<Instruction *>::getEmptyKey(); 229 } 230 static inline CallValue getTombstoneKey() { 231 return DenseMapInfo<Instruction *>::getTombstoneKey(); 232 } 233 static unsigned getHashValue(CallValue Val); 234 static bool isEqual(CallValue LHS, CallValue RHS); 235 }; 236 } 237 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. 241 return hash_combine( 242 Inst->getOpcode(), 243 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end())); 244 } 245 246 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) { 247 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst; 248 if (LHS.isSentinel() || RHS.isSentinel()) 249 return LHSI == RHSI; 250 return LHSI->isIdenticalTo(RHSI); 251 } 252 253 //===----------------------------------------------------------------------===// 254 // EarlyCSE implementation 255 //===----------------------------------------------------------------------===// 256 257 namespace { 258 /// \brief A simple and fast domtree-based CSE pass. 259 /// 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. 265 class EarlyCSE { 266 public: 267 Function &F; 268 const TargetLibraryInfo &TLI; 269 const TargetTransformInfo &TTI; 270 DominatorTree &DT; 271 AssumptionCache &AC; 272 typedef RecyclingAllocator< 273 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy; 274 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>, 275 AllocatorTy> ScopedHTType; 276 277 /// \brief A scoped hash table of the current values of all of our simple 278 /// scalar expressions. 279 /// 280 /// As we walk down the domtree, we look to see if instructions are in this: 281 /// if so, we replace them with what we find, otherwise we insert them so 282 /// that dominated values can succeed in their lookup. 283 ScopedHTType AvailableValues; 284 285 /// \brief A scoped hash table of the current values of loads. 286 /// 287 /// This allows us to get efficient access to dominating loads when we have 288 /// a fully redundant load. In addition to the most recent load, we keep 289 /// track of a generation count of the read, which is compared against the 290 /// 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. 293 typedef RecyclingAllocator< 294 BumpPtrAllocator, 295 ScopedHashTableVal<Value *, std::pair<Value *, unsigned>>> 296 LoadMapAllocator; 297 typedef ScopedHashTable<Value *, std::pair<Value *, unsigned>, 298 DenseMapInfo<Value *>, LoadMapAllocator> LoadHTType; 299 LoadHTType AvailableLoads; 300 301 /// \brief A scoped hash table of the current values of read-only call 302 /// values. 303 /// 304 /// It uses the same generation count as loads. 305 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType; 306 CallHTType AvailableCalls; 307 308 /// \brief This is the current generation of the memory value. 309 unsigned CurrentGeneration; 310 311 /// \brief Set up the EarlyCSE runner for a particular function. 312 EarlyCSE(Function &F, const TargetLibraryInfo &TLI, 313 const TargetTransformInfo &TTI, DominatorTree &DT, 314 AssumptionCache &AC) 315 : F(F), TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {} 316 317 bool run(); 318 319 private: 320 // Almost a POD, but needs to call the constructors for the scoped hash 321 // tables so that a new scope gets pushed on. These are RAII so that the 322 // scope gets popped when the NodeScope is destroyed. 323 class NodeScope { 324 public: 325 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 326 CallHTType &AvailableCalls) 327 : Scope(AvailableValues), LoadScope(AvailableLoads), 328 CallScope(AvailableCalls) {} 329 330 private: 331 NodeScope(const NodeScope &) = delete; 332 void operator=(const NodeScope &) = delete; 333 334 ScopedHTType::ScopeTy Scope; 335 LoadHTType::ScopeTy LoadScope; 336 CallHTType::ScopeTy CallScope; 337 }; 338 339 // Contains all the needed information to create a stack for doing a depth 340 // first tranversal of the tree. This includes scopes for values, loads, and 341 // calls as well as the generation. There is a child iterator so that the 342 // children do not need to be store spearately. 343 class StackNode { 344 public: 345 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 346 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n, 347 DomTreeNode::iterator child, DomTreeNode::iterator end) 348 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child), 349 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls), 350 Processed(false) {} 351 352 // Accessors. 353 unsigned currentGeneration() { return CurrentGeneration; } 354 unsigned childGeneration() { return ChildGeneration; } 355 void childGeneration(unsigned generation) { ChildGeneration = generation; } 356 DomTreeNode *node() { return Node; } 357 DomTreeNode::iterator childIter() { return ChildIter; } 358 DomTreeNode *nextChild() { 359 DomTreeNode *child = *ChildIter; 360 ++ChildIter; 361 return child; 362 } 363 DomTreeNode::iterator end() { return EndIter; } 364 bool isProcessed() { return Processed; } 365 void process() { Processed = true; } 366 367 private: 368 StackNode(const StackNode &) = delete; 369 void operator=(const StackNode &) = delete; 370 371 // Members. 372 unsigned CurrentGeneration; 373 unsigned ChildGeneration; 374 DomTreeNode *Node; 375 DomTreeNode::iterator ChildIter; 376 DomTreeNode::iterator EndIter; 377 NodeScope Scopes; 378 bool Processed; 379 }; 380 381 /// \brief Wrapper class to handle memory instructions, including loads, 382 /// stores and intrinsic loads and stores defined by the target. 383 class ParseMemoryInst { 384 public: 385 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI) 386 : Load(false), Store(false), Vol(false), MayReadFromMemory(false), 387 MayWriteToMemory(false), MatchingId(-1), Ptr(nullptr) { 388 MayReadFromMemory = Inst->mayReadFromMemory(); 389 MayWriteToMemory = Inst->mayWriteToMemory(); 390 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 391 MemIntrinsicInfo Info; 392 if (!TTI.getTgtMemIntrinsic(II, Info)) 393 return; 394 if (Info.NumMemRefs == 1) { 395 Store = Info.WriteMem; 396 Load = Info.ReadMem; 397 MatchingId = Info.MatchingId; 398 MayReadFromMemory = Info.ReadMem; 399 MayWriteToMemory = Info.WriteMem; 400 Vol = Info.Vol; 401 Ptr = Info.PtrVal; 402 } 403 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 404 Load = true; 405 Vol = !LI->isSimple(); 406 Ptr = LI->getPointerOperand(); 407 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 408 Store = true; 409 Vol = !SI->isSimple(); 410 Ptr = SI->getPointerOperand(); 411 } 412 } 413 bool isLoad() { return Load; } 414 bool isStore() { return Store; } 415 bool isVolatile() { return Vol; } 416 bool isMatchingMemLoc(const ParseMemoryInst &Inst) { 417 return Ptr == Inst.Ptr && MatchingId == Inst.MatchingId; 418 } 419 bool isValid() { return Ptr != nullptr; } 420 int getMatchingId() { return MatchingId; } 421 Value *getPtr() { return Ptr; } 422 bool mayReadFromMemory() { return MayReadFromMemory; } 423 bool mayWriteToMemory() { return MayWriteToMemory; } 424 425 private: 426 bool Load; 427 bool Store; 428 bool Vol; 429 bool MayReadFromMemory; 430 bool MayWriteToMemory; 431 // For regular (non-intrinsic) loads/stores, this is set to -1. For 432 // intrinsic loads/stores, the id is retrieved from the corresponding 433 // field in the MemIntrinsicInfo structure. That field contains 434 // non-negative values only. 435 int MatchingId; 436 Value *Ptr; 437 }; 438 439 bool processNode(DomTreeNode *Node); 440 441 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const { 442 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 443 return LI; 444 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 445 return SI->getValueOperand(); 446 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported"); 447 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst), 448 ExpectedType); 449 } 450 }; 451 } 452 453 bool EarlyCSE::processNode(DomTreeNode *Node) { 454 BasicBlock *BB = Node->getBlock(); 455 456 // If this block has a single predecessor, then the predecessor is the parent 457 // of the domtree node and all of the live out memory values are still current 458 // in this block. If this block has multiple predecessors, then they could 459 // have invalidated the live-out memory values of our parent value. For now, 460 // just be conservative and invalidate memory if this block has multiple 461 // predecessors. 462 if (!BB->getSinglePredecessor()) 463 ++CurrentGeneration; 464 465 // If this node has a single predecessor which ends in a conditional branch, 466 // we can infer the value of the branch condition given that we took this 467 // path. We need the single predeccesor to ensure there's not another path 468 // which reaches this block where the condition might hold a different 469 // value. Since we're adding this to the scoped hash table (like any other 470 // def), it will have been popped if we encounter a future merge block. 471 if (BasicBlock *Pred = BB->getSinglePredecessor()) 472 if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator())) 473 if (BI->isConditional()) 474 if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition())) 475 if (SimpleValue::canHandle(CondInst)) { 476 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB); 477 auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ? 478 ConstantInt::getTrue(BB->getContext()) : 479 ConstantInt::getFalse(BB->getContext()); 480 AvailableValues.insert(CondInst, ConditionalConstant); 481 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '" 482 << CondInst->getName() << "' as " << *ConditionalConstant 483 << " in " << BB->getName() << "\n"); 484 // Replace all dominated uses with the known value 485 replaceDominatedUsesWith(CondInst, ConditionalConstant, DT, 486 BasicBlockEdge(Pred, BB)); 487 } 488 489 /// LastStore - Keep track of the last non-volatile store that we saw... for 490 /// as long as there in no instruction that reads memory. If we see a store 491 /// to the same location, we delete the dead store. This zaps trivial dead 492 /// stores which can occur in bitfield code among other things. 493 Instruction *LastStore = nullptr; 494 495 bool Changed = false; 496 const DataLayout &DL = BB->getModule()->getDataLayout(); 497 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++; 502 503 // Dead instructions should just be removed. 504 if (isInstructionTriviallyDead(Inst, &TLI)) { 505 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n'); 506 Inst->eraseFromParent(); 507 Changed = true; 508 ++NumSimplify; 509 continue; 510 } 511 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 515 // dependencies. 516 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) { 517 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n'); 518 continue; 519 } 520 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(); 527 Changed = true; 528 ++NumSimplify; 529 continue; 530 } 531 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(); 539 Changed = true; 540 ++NumCSE; 541 continue; 542 } 543 544 // Otherwise, just remember that this value is available. 545 AvailableValues.insert(Inst, Inst); 546 continue; 547 } 548 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()) { 554 LastStore = nullptr; 555 // Don't CSE across synchronization boundaries. 556 if (Inst->mayWriteToMemory()) 557 ++CurrentGeneration; 558 continue; 559 } 560 561 // If we have an available version of this load, and if it is the right 562 // generation, replace this instruction. 563 std::pair<Value *, unsigned> InVal = 564 AvailableLoads.lookup(MemInst.getPtr()); 565 if (InVal.first != nullptr && InVal.second == CurrentGeneration) { 566 Value *Op = getOrCreateResult(InVal.first, Inst->getType()); 567 if (Op != nullptr) { 568 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst 569 << " to: " << *InVal.first << '\n'); 570 if (!Inst->use_empty()) 571 Inst->replaceAllUsesWith(Op); 572 Inst->eraseFromParent(); 573 Changed = true; 574 ++NumCSELoad; 575 continue; 576 } 577 } 578 579 // Otherwise, remember that we have this instruction. 580 AvailableLoads.insert(MemInst.getPtr(), std::pair<Value *, unsigned>( 581 Inst, CurrentGeneration)); 582 LastStore = nullptr; 583 continue; 584 } 585 586 // If this instruction may read from memory, forget LastStore. 587 // Load/store intrinsics will indicate both a read and a write to 588 // memory. The target may override this (e.g. so that a store intrinsic 589 // does not read from memory, and thus will be treated the same as a 590 // regular store for commoning purposes). 591 if (Inst->mayReadFromMemory() && 592 !(MemInst.isValid() && !MemInst.mayReadFromMemory())) 593 LastStore = nullptr; 594 595 // If this is a read-only call, process it. 596 if (CallValue::canHandle(Inst)) { 597 // If we have an available version of this call, and if it is the right 598 // generation, replace this instruction. 599 std::pair<Value *, unsigned> InVal = AvailableCalls.lookup(Inst); 600 if (InVal.first != nullptr && InVal.second == CurrentGeneration) { 601 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst 602 << " to: " << *InVal.first << '\n'); 603 if (!Inst->use_empty()) 604 Inst->replaceAllUsesWith(InVal.first); 605 Inst->eraseFromParent(); 606 Changed = true; 607 ++NumCSECall; 608 continue; 609 } 610 611 // Otherwise, remember that we have this instruction. 612 AvailableCalls.insert( 613 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration)); 614 continue; 615 } 616 617 // A release fence requires that all stores complete before it, but does 618 // not prevent the reordering of following loads 'before' the fence. As a 619 // result, we don't need to consider it as writing to memory and don't need 620 // to advance the generation. We do need to prevent DSE across the fence, 621 // but that's handled above. 622 if (FenceInst *FI = dyn_cast<FenceInst>(Inst)) 623 if (FI->getOrdering() == Release) { 624 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above"); 625 continue; 626 } 627 628 // Okay, this isn't something we can CSE at all. Check to see if it is 629 // something that could modify memory. If so, our available memory values 630 // cannot be used so bump the generation count. 631 if (Inst->mayWriteToMemory()) { 632 ++CurrentGeneration; 633 634 if (MemInst.isValid() && MemInst.isStore()) { 635 // We do a trivial form of DSE if there are two stores to the same 636 // location with no intervening loads. Delete the earlier store. 637 if (LastStore) { 638 ParseMemoryInst LastStoreMemInst(LastStore, TTI); 639 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) { 640 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore 641 << " due to: " << *Inst << '\n'); 642 LastStore->eraseFromParent(); 643 Changed = true; 644 ++NumDSE; 645 LastStore = nullptr; 646 } 647 // fallthrough - we can exploit information about this store 648 } 649 650 // Okay, we just invalidated anything we knew about loaded values. Try 651 // to salvage *something* by remembering that the stored value is a live 652 // version of the pointer. It is safe to forward from volatile stores 653 // to non-volatile loads, so we don't have to check for volatility of 654 // the store. 655 AvailableLoads.insert(MemInst.getPtr(), std::pair<Value *, unsigned>( 656 Inst, CurrentGeneration)); 657 658 // Remember that this was the last store we saw for DSE. 659 if (!MemInst.isVolatile()) 660 LastStore = Inst; 661 } 662 } 663 } 664 665 return Changed; 666 } 667 668 bool EarlyCSE::run() { 669 // Note, deque is being used here because there is significant performance 670 // gains over vector when the container becomes very large due to the 671 // specific access patterns. For more information see the mailing list 672 // discussion on this: 673 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html 674 std::deque<StackNode *> nodesToProcess; 675 676 bool Changed = false; 677 678 // Process the root node. 679 nodesToProcess.push_back(new StackNode( 680 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration, 681 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end())); 682 683 // Save the current generation. 684 unsigned LiveOutGeneration = CurrentGeneration; 685 686 // Process the stack. 687 while (!nodesToProcess.empty()) { 688 // Grab the first item off the stack. Set the current generation, remove 689 // the node from the stack, and process it. 690 StackNode *NodeToProcess = nodesToProcess.back(); 691 692 // Initialize class members. 693 CurrentGeneration = NodeToProcess->currentGeneration(); 694 695 // Check if the node needs to be processed. 696 if (!NodeToProcess->isProcessed()) { 697 // Process the node. 698 Changed |= processNode(NodeToProcess->node()); 699 NodeToProcess->childGeneration(CurrentGeneration); 700 NodeToProcess->process(); 701 } else if (NodeToProcess->childIter() != NodeToProcess->end()) { 702 // Push the next child onto the stack. 703 DomTreeNode *child = NodeToProcess->nextChild(); 704 nodesToProcess.push_back( 705 new StackNode(AvailableValues, AvailableLoads, AvailableCalls, 706 NodeToProcess->childGeneration(), child, child->begin(), 707 child->end())); 708 } else { 709 // It has been processed, and there are no more children to process, 710 // so delete it and pop it off the stack. 711 delete NodeToProcess; 712 nodesToProcess.pop_back(); 713 } 714 } // while (!nodes...) 715 716 // Reset the current generation. 717 CurrentGeneration = LiveOutGeneration; 718 719 return Changed; 720 } 721 722 PreservedAnalyses EarlyCSEPass::run(Function &F, 723 AnalysisManager<Function> *AM) { 724 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F); 725 auto &TTI = AM->getResult<TargetIRAnalysis>(F); 726 auto &DT = AM->getResult<DominatorTreeAnalysis>(F); 727 auto &AC = AM->getResult<AssumptionAnalysis>(F); 728 729 EarlyCSE CSE(F, TLI, TTI, DT, AC); 730 731 if (!CSE.run()) 732 return PreservedAnalyses::all(); 733 734 // CSE preserves the dominator tree because it doesn't mutate the CFG. 735 // FIXME: Bundle this with other CFG-preservation. 736 PreservedAnalyses PA; 737 PA.preserve<DominatorTreeAnalysis>(); 738 return PA; 739 } 740 741 namespace { 742 /// \brief A simple and fast domtree-based CSE pass. 743 /// 744 /// This pass does a simple depth-first walk over the dominator tree, 745 /// eliminating trivially redundant instructions and using instsimplify to 746 /// canonicalize things as it goes. It is intended to be fast and catch obvious 747 /// cases so that instcombine and other passes are more effective. It is 748 /// expected that a later pass of GVN will catch the interesting/hard cases. 749 class EarlyCSELegacyPass : public FunctionPass { 750 public: 751 static char ID; 752 753 EarlyCSELegacyPass() : FunctionPass(ID) { 754 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry()); 755 } 756 757 bool runOnFunction(Function &F) override { 758 if (skipOptnoneFunction(F)) 759 return false; 760 761 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 762 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 763 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 764 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 765 766 EarlyCSE CSE(F, TLI, TTI, DT, AC); 767 768 return CSE.run(); 769 } 770 771 void getAnalysisUsage(AnalysisUsage &AU) const override { 772 AU.addRequired<AssumptionCacheTracker>(); 773 AU.addRequired<DominatorTreeWrapperPass>(); 774 AU.addRequired<TargetLibraryInfoWrapperPass>(); 775 AU.addRequired<TargetTransformInfoWrapperPass>(); 776 AU.addPreserved<GlobalsAAWrapperPass>(); 777 AU.setPreservesCFG(); 778 } 779 }; 780 } 781 782 char EarlyCSELegacyPass::ID = 0; 783 784 FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); } 785 786 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false, 787 false) 788 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 789 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 790 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 791 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 792 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false) 793