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/AssumptionCache.h" 20 #include "llvm/Analysis/GlobalsModRef.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(NumCSECVP, "Number of compare instructions CVP'd"); 44 STATISTIC(NumCSELoad, "Number of load instructions CSE'd"); 45 STATISTIC(NumCSECall, "Number of call instructions CSE'd"); 46 STATISTIC(NumDSE, "Number of trivial dead stores removed"); 47 48 //===----------------------------------------------------------------------===// 49 // SimpleValue 50 //===----------------------------------------------------------------------===// 51 52 namespace { 53 /// \brief Struct representing the available values in the scoped hash table. 54 struct SimpleValue { 55 Instruction *Inst; 56 57 SimpleValue(Instruction *I) : Inst(I) { 58 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!"); 59 } 60 61 bool isSentinel() const { 62 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() || 63 Inst == DenseMapInfo<Instruction *>::getTombstoneKey(); 64 } 65 66 static bool canHandle(Instruction *Inst) { 67 // This can only handle non-void readnone functions. 68 if (CallInst *CI = dyn_cast<CallInst>(Inst)) 69 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy(); 70 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) || 71 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) || 72 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) || 73 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) || 74 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst); 75 } 76 }; 77 } 78 79 namespace llvm { 80 template <> struct DenseMapInfo<SimpleValue> { 81 static inline SimpleValue getEmptyKey() { 82 return DenseMapInfo<Instruction *>::getEmptyKey(); 83 } 84 static inline SimpleValue getTombstoneKey() { 85 return DenseMapInfo<Instruction *>::getTombstoneKey(); 86 } 87 static unsigned getHashValue(SimpleValue Val); 88 static bool isEqual(SimpleValue LHS, SimpleValue RHS); 89 }; 90 } 91 92 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) { 93 Instruction *Inst = Val.Inst; 94 // Hash in all of the operands as pointers. 95 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) { 96 Value *LHS = BinOp->getOperand(0); 97 Value *RHS = BinOp->getOperand(1); 98 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1)) 99 std::swap(LHS, RHS); 100 101 return hash_combine(BinOp->getOpcode(), LHS, RHS); 102 } 103 104 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) { 105 Value *LHS = CI->getOperand(0); 106 Value *RHS = CI->getOperand(1); 107 CmpInst::Predicate Pred = CI->getPredicate(); 108 if (Inst->getOperand(0) > Inst->getOperand(1)) { 109 std::swap(LHS, RHS); 110 Pred = CI->getSwappedPredicate(); 111 } 112 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS); 113 } 114 115 if (CastInst *CI = dyn_cast<CastInst>(Inst)) 116 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0)); 117 118 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst)) 119 return hash_combine(EVI->getOpcode(), EVI->getOperand(0), 120 hash_combine_range(EVI->idx_begin(), EVI->idx_end())); 121 122 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst)) 123 return hash_combine(IVI->getOpcode(), IVI->getOperand(0), 124 IVI->getOperand(1), 125 hash_combine_range(IVI->idx_begin(), IVI->idx_end())); 126 127 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) || 128 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) || 129 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) || 130 isa<ShuffleVectorInst>(Inst)) && 131 "Invalid/unknown instruction"); 132 133 // Mix in the opcode. 134 return hash_combine( 135 Inst->getOpcode(), 136 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end())); 137 } 138 139 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) { 140 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst; 141 142 if (LHS.isSentinel() || RHS.isSentinel()) 143 return LHSI == RHSI; 144 145 if (LHSI->getOpcode() != RHSI->getOpcode()) 146 return false; 147 if (LHSI->isIdenticalToWhenDefined(RHSI)) 148 return true; 149 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()) 153 return false; 154 155 assert(isa<BinaryOperator>(RHSI) && 156 "same opcode, but different instruction type?"); 157 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI); 158 159 // Commuted equality 160 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) && 161 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0); 162 } 163 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) { 164 assert(isa<CmpInst>(RHSI) && 165 "same opcode, but different instruction type?"); 166 CmpInst *RHSCmp = cast<CmpInst>(RHSI); 167 // Commuted equality 168 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) && 169 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) && 170 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate(); 171 } 172 173 return false; 174 } 175 176 //===----------------------------------------------------------------------===// 177 // CallValue 178 //===----------------------------------------------------------------------===// 179 180 namespace { 181 /// \brief Struct representing the available call values in the scoped hash 182 /// table. 183 struct CallValue { 184 Instruction *Inst; 185 186 CallValue(Instruction *I) : Inst(I) { 187 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!"); 188 } 189 190 bool isSentinel() const { 191 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() || 192 Inst == DenseMapInfo<Instruction *>::getTombstoneKey(); 193 } 194 195 static bool canHandle(Instruction *Inst) { 196 // Don't value number anything that returns void. 197 if (Inst->getType()->isVoidTy()) 198 return false; 199 200 CallInst *CI = dyn_cast<CallInst>(Inst); 201 if (!CI || !CI->onlyReadsMemory()) 202 return false; 203 return true; 204 } 205 }; 206 } 207 208 namespace llvm { 209 template <> struct DenseMapInfo<CallValue> { 210 static inline CallValue getEmptyKey() { 211 return DenseMapInfo<Instruction *>::getEmptyKey(); 212 } 213 static inline CallValue getTombstoneKey() { 214 return DenseMapInfo<Instruction *>::getTombstoneKey(); 215 } 216 static unsigned getHashValue(CallValue Val); 217 static bool isEqual(CallValue LHS, CallValue RHS); 218 }; 219 } 220 221 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) { 222 Instruction *Inst = Val.Inst; 223 // Hash all of the operands as pointers and mix in the opcode. 224 return hash_combine( 225 Inst->getOpcode(), 226 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end())); 227 } 228 229 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) { 230 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst; 231 if (LHS.isSentinel() || RHS.isSentinel()) 232 return LHSI == RHSI; 233 return LHSI->isIdenticalTo(RHSI); 234 } 235 236 //===----------------------------------------------------------------------===// 237 // EarlyCSE implementation 238 //===----------------------------------------------------------------------===// 239 240 namespace { 241 /// \brief A simple and fast domtree-based CSE pass. 242 /// 243 /// This pass does a simple depth-first walk over the dominator tree, 244 /// eliminating trivially redundant instructions and using instsimplify to 245 /// canonicalize things as it goes. It is intended to be fast and catch obvious 246 /// cases so that instcombine and other passes are more effective. It is 247 /// expected that a later pass of GVN will catch the interesting/hard cases. 248 class EarlyCSE { 249 public: 250 const TargetLibraryInfo &TLI; 251 const TargetTransformInfo &TTI; 252 DominatorTree &DT; 253 AssumptionCache &AC; 254 typedef RecyclingAllocator< 255 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy; 256 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>, 257 AllocatorTy> ScopedHTType; 258 259 /// \brief A scoped hash table of the current values of all of our simple 260 /// scalar expressions. 261 /// 262 /// As we walk down the domtree, we look to see if instructions are in this: 263 /// if so, we replace them with what we find, otherwise we insert them so 264 /// that dominated values can succeed in their lookup. 265 ScopedHTType AvailableValues; 266 267 /// A scoped hash table of the current values of previously encounted memory 268 /// locations. 269 /// 270 /// This allows us to get efficient access to dominating loads or stores when 271 /// we have a fully redundant load. In addition to the most recent load, we 272 /// keep track of a generation count of the read, which is compared against 273 /// the current generation count. The current generation count is incremented 274 /// after every possibly writing memory operation, which ensures that we only 275 /// CSE loads with other loads that have no intervening store. Ordering 276 /// events (such as fences or atomic instructions) increment the generation 277 /// count as well; essentially, we model these as writes to all possible 278 /// locations. Note that atomic and/or volatile loads and stores can be 279 /// present the table; it is the responsibility of the consumer to inspect 280 /// the atomicity/volatility if needed. 281 struct LoadValue { 282 Instruction *Inst; 283 unsigned Generation; 284 int MatchingId; 285 bool IsAtomic; 286 LoadValue() 287 : Inst(nullptr), Generation(0), MatchingId(-1), IsAtomic(false) {} 288 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId, 289 bool IsAtomic) 290 : Inst(Inst), Generation(Generation), MatchingId(MatchingId), 291 IsAtomic(IsAtomic) {} 292 }; 293 typedef RecyclingAllocator<BumpPtrAllocator, 294 ScopedHashTableVal<Value *, LoadValue>> 295 LoadMapAllocator; 296 typedef ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>, 297 LoadMapAllocator> LoadHTType; 298 LoadHTType AvailableLoads; 299 300 /// \brief A scoped hash table of the current values of read-only call 301 /// values. 302 /// 303 /// It uses the same generation count as loads. 304 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType; 305 CallHTType AvailableCalls; 306 307 /// \brief This is the current generation of the memory value. 308 unsigned CurrentGeneration; 309 310 /// \brief Set up the EarlyCSE runner for a particular function. 311 EarlyCSE(const TargetLibraryInfo &TLI, const TargetTransformInfo &TTI, 312 DominatorTree &DT, AssumptionCache &AC) 313 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {} 314 315 bool run(); 316 317 private: 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. 321 class NodeScope { 322 public: 323 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 324 CallHTType &AvailableCalls) 325 : Scope(AvailableValues), LoadScope(AvailableLoads), 326 CallScope(AvailableCalls) {} 327 328 private: 329 NodeScope(const NodeScope &) = delete; 330 void operator=(const NodeScope &) = delete; 331 332 ScopedHTType::ScopeTy Scope; 333 LoadHTType::ScopeTy LoadScope; 334 CallHTType::ScopeTy CallScope; 335 }; 336 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 separately. 341 class StackNode { 342 public: 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), 348 Processed(false) {} 349 350 // Accessors. 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; 358 ++ChildIter; 359 return child; 360 } 361 DomTreeNode::iterator end() { return EndIter; } 362 bool isProcessed() { return Processed; } 363 void process() { Processed = true; } 364 365 private: 366 StackNode(const StackNode &) = delete; 367 void operator=(const StackNode &) = delete; 368 369 // Members. 370 unsigned CurrentGeneration; 371 unsigned ChildGeneration; 372 DomTreeNode *Node; 373 DomTreeNode::iterator ChildIter; 374 DomTreeNode::iterator EndIter; 375 NodeScope Scopes; 376 bool Processed; 377 }; 378 379 /// \brief Wrapper class to handle memory instructions, including loads, 380 /// stores and intrinsic loads and stores defined by the target. 381 class ParseMemoryInst { 382 public: 383 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI) 384 : IsTargetMemInst(false), Inst(Inst) { 385 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) 386 if (TTI.getTgtMemIntrinsic(II, Info) && Info.NumMemRefs == 1) 387 IsTargetMemInst = true; 388 } 389 bool isLoad() const { 390 if (IsTargetMemInst) return Info.ReadMem; 391 return isa<LoadInst>(Inst); 392 } 393 bool isStore() const { 394 if (IsTargetMemInst) return Info.WriteMem; 395 return isa<StoreInst>(Inst); 396 } 397 bool isAtomic() const { 398 if (IsTargetMemInst) { 399 assert(Info.IsSimple && "need to refine IsSimple in TTI"); 400 return false; 401 } 402 return Inst->isAtomic(); 403 } 404 bool isUnordered() const { 405 if (IsTargetMemInst) { 406 assert(Info.IsSimple && "need to refine IsSimple in TTI"); 407 return true; 408 } 409 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 410 return LI->isUnordered(); 411 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 412 return SI->isUnordered(); 413 } 414 // Conservative answer 415 return !Inst->isAtomic(); 416 } 417 418 bool isVolatile() const { 419 if (IsTargetMemInst) { 420 assert(Info.IsSimple && "need to refine IsSimple in TTI"); 421 return false; 422 } 423 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 424 return LI->isVolatile(); 425 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 426 return SI->isVolatile(); 427 } 428 // Conservative answer 429 return true; 430 } 431 432 433 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const { 434 return (getPointerOperand() == Inst.getPointerOperand() && 435 getMatchingId() == Inst.getMatchingId()); 436 } 437 bool isValid() const { return getPointerOperand() != nullptr; } 438 439 // For regular (non-intrinsic) loads/stores, this is set to -1. For 440 // intrinsic loads/stores, the id is retrieved from the corresponding 441 // field in the MemIntrinsicInfo structure. That field contains 442 // non-negative values only. 443 int getMatchingId() const { 444 if (IsTargetMemInst) return Info.MatchingId; 445 return -1; 446 } 447 Value *getPointerOperand() const { 448 if (IsTargetMemInst) return Info.PtrVal; 449 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 450 return LI->getPointerOperand(); 451 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 452 return SI->getPointerOperand(); 453 } 454 return nullptr; 455 } 456 bool mayReadFromMemory() const { 457 if (IsTargetMemInst) return Info.ReadMem; 458 return Inst->mayReadFromMemory(); 459 } 460 bool mayWriteToMemory() const { 461 if (IsTargetMemInst) return Info.WriteMem; 462 return Inst->mayWriteToMemory(); 463 } 464 465 private: 466 bool IsTargetMemInst; 467 MemIntrinsicInfo Info; 468 Instruction *Inst; 469 }; 470 471 bool processNode(DomTreeNode *Node); 472 473 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const { 474 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 475 return LI; 476 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 477 return SI->getValueOperand(); 478 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported"); 479 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst), 480 ExpectedType); 481 } 482 }; 483 } 484 485 bool EarlyCSE::processNode(DomTreeNode *Node) { 486 bool Changed = false; 487 BasicBlock *BB = Node->getBlock(); 488 489 // If this block has a single predecessor, then the predecessor is the parent 490 // of the domtree node and all of the live out memory values are still current 491 // in this block. If this block has multiple predecessors, then they could 492 // have invalidated the live-out memory values of our parent value. For now, 493 // just be conservative and invalidate memory if this block has multiple 494 // predecessors. 495 if (!BB->getSinglePredecessor()) 496 ++CurrentGeneration; 497 498 // If this node has a single predecessor which ends in a conditional branch, 499 // we can infer the value of the branch condition given that we took this 500 // path. We need the single predecessor to ensure there's not another path 501 // which reaches this block where the condition might hold a different 502 // value. Since we're adding this to the scoped hash table (like any other 503 // def), it will have been popped if we encounter a future merge block. 504 if (BasicBlock *Pred = BB->getSinglePredecessor()) 505 if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator())) 506 if (BI->isConditional()) 507 if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition())) 508 if (SimpleValue::canHandle(CondInst)) { 509 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB); 510 auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ? 511 ConstantInt::getTrue(BB->getContext()) : 512 ConstantInt::getFalse(BB->getContext()); 513 AvailableValues.insert(CondInst, ConditionalConstant); 514 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '" 515 << CondInst->getName() << "' as " << *ConditionalConstant 516 << " in " << BB->getName() << "\n"); 517 // Replace all dominated uses with the known value. 518 if (unsigned Count = 519 replaceDominatedUsesWith(CondInst, ConditionalConstant, DT, 520 BasicBlockEdge(Pred, BB))) { 521 Changed = true; 522 NumCSECVP = NumCSECVP + Count; 523 } 524 } 525 526 /// LastStore - Keep track of the last non-volatile store that we saw... for 527 /// as long as there in no instruction that reads memory. If we see a store 528 /// to the same location, we delete the dead store. This zaps trivial dead 529 /// stores which can occur in bitfield code among other things. 530 Instruction *LastStore = nullptr; 531 532 const DataLayout &DL = BB->getModule()->getDataLayout(); 533 534 // See if any instructions in the block can be eliminated. If so, do it. If 535 // not, add them to AvailableValues. 536 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 537 Instruction *Inst = &*I++; 538 539 // Dead instructions should just be removed. 540 if (isInstructionTriviallyDead(Inst, &TLI)) { 541 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n'); 542 Inst->eraseFromParent(); 543 Changed = true; 544 ++NumSimplify; 545 continue; 546 } 547 548 // Skip assume intrinsics, they don't really have side effects (although 549 // they're marked as such to ensure preservation of control dependencies), 550 // and this pass will not disturb any of the assumption's control 551 // dependencies. 552 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) { 553 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n'); 554 continue; 555 } 556 557 if (match(Inst, m_Intrinsic<Intrinsic::experimental_guard>())) { 558 Value *Cond = cast<CallInst>(Inst)->getArgOperand(0); 559 560 if (match(Cond, m_One())) { 561 // Elide guards on true, since operationally they're no-ops. In the 562 // future we can consider more sophisticated tradeoffs here with 563 // consideration to potential for check widening, but for now we keep 564 // things simple. 565 Inst->eraseFromParent(); 566 } else if (auto *CondI = dyn_cast<Instruction>(Cond)) { 567 // The condition we're on guarding here is true for all dominated 568 // locations. 569 if (SimpleValue::canHandle(CondI)) 570 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext())); 571 } 572 573 // Guard intrinsics read all memory, but don't write any memory. 574 // Accordingly, don't update the generation but consume the last store (to 575 // avoid an incorrect DSE). 576 LastStore = nullptr; 577 continue; 578 } 579 580 // If the instruction can be simplified (e.g. X+0 = X) then replace it with 581 // its simpler value. 582 if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) { 583 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n'); 584 Inst->replaceAllUsesWith(V); 585 Inst->eraseFromParent(); 586 Changed = true; 587 ++NumSimplify; 588 continue; 589 } 590 591 // If this is a simple instruction that we can value number, process it. 592 if (SimpleValue::canHandle(Inst)) { 593 // See if the instruction has an available value. If so, use it. 594 if (Value *V = AvailableValues.lookup(Inst)) { 595 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n'); 596 if (auto *I = dyn_cast<Instruction>(V)) 597 I->andIRFlags(Inst); 598 Inst->replaceAllUsesWith(V); 599 Inst->eraseFromParent(); 600 Changed = true; 601 ++NumCSE; 602 continue; 603 } 604 605 // Otherwise, just remember that this value is available. 606 AvailableValues.insert(Inst, Inst); 607 continue; 608 } 609 610 ParseMemoryInst MemInst(Inst, TTI); 611 // If this is a non-volatile load, process it. 612 if (MemInst.isValid() && MemInst.isLoad()) { 613 // (conservatively) we can't peak past the ordering implied by this 614 // operation, but we can add this load to our set of available values 615 if (MemInst.isVolatile() || !MemInst.isUnordered()) { 616 LastStore = nullptr; 617 ++CurrentGeneration; 618 } 619 620 // If we have an available version of this load, and if it is the right 621 // generation, replace this instruction. 622 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand()); 623 if (InVal.Inst != nullptr && InVal.Generation == CurrentGeneration && 624 InVal.MatchingId == MemInst.getMatchingId() && 625 // We don't yet handle removing loads with ordering of any kind. 626 !MemInst.isVolatile() && MemInst.isUnordered() && 627 // We can't replace an atomic load with one which isn't also atomic. 628 InVal.IsAtomic >= MemInst.isAtomic()) { 629 Value *Op = getOrCreateResult(InVal.Inst, Inst->getType()); 630 if (Op != nullptr) { 631 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst 632 << " to: " << *InVal.Inst << '\n'); 633 if (!Inst->use_empty()) 634 Inst->replaceAllUsesWith(Op); 635 Inst->eraseFromParent(); 636 Changed = true; 637 ++NumCSELoad; 638 continue; 639 } 640 } 641 642 // Otherwise, remember that we have this instruction. 643 AvailableLoads.insert( 644 MemInst.getPointerOperand(), 645 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(), 646 MemInst.isAtomic())); 647 LastStore = nullptr; 648 continue; 649 } 650 651 // If this instruction may read from memory, forget LastStore. 652 // Load/store intrinsics will indicate both a read and a write to 653 // memory. The target may override this (e.g. so that a store intrinsic 654 // does not read from memory, and thus will be treated the same as a 655 // regular store for commoning purposes). 656 if (Inst->mayReadFromMemory() && 657 !(MemInst.isValid() && !MemInst.mayReadFromMemory())) 658 LastStore = nullptr; 659 660 // If this is a read-only call, process it. 661 if (CallValue::canHandle(Inst)) { 662 // If we have an available version of this call, and if it is the right 663 // generation, replace this instruction. 664 std::pair<Value *, unsigned> InVal = AvailableCalls.lookup(Inst); 665 if (InVal.first != nullptr && InVal.second == CurrentGeneration) { 666 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst 667 << " to: " << *InVal.first << '\n'); 668 if (!Inst->use_empty()) 669 Inst->replaceAllUsesWith(InVal.first); 670 Inst->eraseFromParent(); 671 Changed = true; 672 ++NumCSECall; 673 continue; 674 } 675 676 // Otherwise, remember that we have this instruction. 677 AvailableCalls.insert( 678 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration)); 679 continue; 680 } 681 682 // A release fence requires that all stores complete before it, but does 683 // not prevent the reordering of following loads 'before' the fence. As a 684 // result, we don't need to consider it as writing to memory and don't need 685 // to advance the generation. We do need to prevent DSE across the fence, 686 // but that's handled above. 687 if (FenceInst *FI = dyn_cast<FenceInst>(Inst)) 688 if (FI->getOrdering() == AtomicOrdering::Release) { 689 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above"); 690 continue; 691 } 692 693 // write back DSE - If we write back the same value we just loaded from 694 // the same location and haven't passed any intervening writes or ordering 695 // operations, we can remove the write. The primary benefit is in allowing 696 // the available load table to remain valid and value forward past where 697 // the store originally was. 698 if (MemInst.isValid() && MemInst.isStore()) { 699 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand()); 700 if (InVal.Inst && 701 InVal.Inst == getOrCreateResult(Inst, InVal.Inst->getType()) && 702 InVal.Generation == CurrentGeneration && 703 InVal.MatchingId == MemInst.getMatchingId() && 704 // We don't yet handle removing stores with ordering of any kind. 705 !MemInst.isVolatile() && MemInst.isUnordered()) { 706 assert((!LastStore || 707 ParseMemoryInst(LastStore, TTI).getPointerOperand() == 708 MemInst.getPointerOperand()) && 709 "can't have an intervening store!"); 710 DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n'); 711 Inst->eraseFromParent(); 712 Changed = true; 713 ++NumDSE; 714 // We can avoid incrementing the generation count since we were able 715 // to eliminate this store. 716 continue; 717 } 718 } 719 720 // Okay, this isn't something we can CSE at all. Check to see if it is 721 // something that could modify memory. If so, our available memory values 722 // cannot be used so bump the generation count. 723 if (Inst->mayWriteToMemory()) { 724 ++CurrentGeneration; 725 726 if (MemInst.isValid() && MemInst.isStore()) { 727 // We do a trivial form of DSE if there are two stores to the same 728 // location with no intervening loads. Delete the earlier store. 729 // At the moment, we don't remove ordered stores, but do remove 730 // unordered atomic stores. There's no special requirement (for 731 // unordered atomics) about removing atomic stores only in favor of 732 // other atomic stores since we we're going to execute the non-atomic 733 // one anyway and the atomic one might never have become visible. 734 if (LastStore) { 735 ParseMemoryInst LastStoreMemInst(LastStore, TTI); 736 assert(LastStoreMemInst.isUnordered() && 737 !LastStoreMemInst.isVolatile() && 738 "Violated invariant"); 739 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) { 740 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore 741 << " due to: " << *Inst << '\n'); 742 LastStore->eraseFromParent(); 743 Changed = true; 744 ++NumDSE; 745 LastStore = nullptr; 746 } 747 // fallthrough - we can exploit information about this store 748 } 749 750 // Okay, we just invalidated anything we knew about loaded values. Try 751 // to salvage *something* by remembering that the stored value is a live 752 // version of the pointer. It is safe to forward from volatile stores 753 // to non-volatile loads, so we don't have to check for volatility of 754 // the store. 755 AvailableLoads.insert( 756 MemInst.getPointerOperand(), 757 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(), 758 MemInst.isAtomic())); 759 760 // Remember that this was the last unordered store we saw for DSE. We 761 // don't yet handle DSE on ordered or volatile stores since we don't 762 // have a good way to model the ordering requirement for following 763 // passes once the store is removed. We could insert a fence, but 764 // since fences are slightly stronger than stores in their ordering, 765 // it's not clear this is a profitable transform. Another option would 766 // be to merge the ordering with that of the post dominating store. 767 if (MemInst.isUnordered() && !MemInst.isVolatile()) 768 LastStore = Inst; 769 else 770 LastStore = nullptr; 771 } 772 } 773 } 774 775 return Changed; 776 } 777 778 bool EarlyCSE::run() { 779 // Note, deque is being used here because there is significant performance 780 // gains over vector when the container becomes very large due to the 781 // specific access patterns. For more information see the mailing list 782 // discussion on this: 783 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html 784 std::deque<StackNode *> nodesToProcess; 785 786 bool Changed = false; 787 788 // Process the root node. 789 nodesToProcess.push_back(new StackNode( 790 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration, 791 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end())); 792 793 // Save the current generation. 794 unsigned LiveOutGeneration = CurrentGeneration; 795 796 // Process the stack. 797 while (!nodesToProcess.empty()) { 798 // Grab the first item off the stack. Set the current generation, remove 799 // the node from the stack, and process it. 800 StackNode *NodeToProcess = nodesToProcess.back(); 801 802 // Initialize class members. 803 CurrentGeneration = NodeToProcess->currentGeneration(); 804 805 // Check if the node needs to be processed. 806 if (!NodeToProcess->isProcessed()) { 807 // Process the node. 808 Changed |= processNode(NodeToProcess->node()); 809 NodeToProcess->childGeneration(CurrentGeneration); 810 NodeToProcess->process(); 811 } else if (NodeToProcess->childIter() != NodeToProcess->end()) { 812 // Push the next child onto the stack. 813 DomTreeNode *child = NodeToProcess->nextChild(); 814 nodesToProcess.push_back( 815 new StackNode(AvailableValues, AvailableLoads, AvailableCalls, 816 NodeToProcess->childGeneration(), child, child->begin(), 817 child->end())); 818 } else { 819 // It has been processed, and there are no more children to process, 820 // so delete it and pop it off the stack. 821 delete NodeToProcess; 822 nodesToProcess.pop_back(); 823 } 824 } // while (!nodes...) 825 826 // Reset the current generation. 827 CurrentGeneration = LiveOutGeneration; 828 829 return Changed; 830 } 831 832 PreservedAnalyses EarlyCSEPass::run(Function &F, 833 AnalysisManager<Function> &AM) { 834 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 835 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 836 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 837 auto &AC = AM.getResult<AssumptionAnalysis>(F); 838 839 EarlyCSE CSE(TLI, TTI, DT, AC); 840 841 if (!CSE.run()) 842 return PreservedAnalyses::all(); 843 844 // CSE preserves the dominator tree because it doesn't mutate the CFG. 845 // FIXME: Bundle this with other CFG-preservation. 846 PreservedAnalyses PA; 847 PA.preserve<DominatorTreeAnalysis>(); 848 return PA; 849 } 850 851 namespace { 852 /// \brief A simple and fast domtree-based CSE pass. 853 /// 854 /// This pass does a simple depth-first walk over the dominator tree, 855 /// eliminating trivially redundant instructions and using instsimplify to 856 /// canonicalize things as it goes. It is intended to be fast and catch obvious 857 /// cases so that instcombine and other passes are more effective. It is 858 /// expected that a later pass of GVN will catch the interesting/hard cases. 859 class EarlyCSELegacyPass : public FunctionPass { 860 public: 861 static char ID; 862 863 EarlyCSELegacyPass() : FunctionPass(ID) { 864 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry()); 865 } 866 867 bool runOnFunction(Function &F) override { 868 if (skipFunction(F)) 869 return false; 870 871 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 872 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 873 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 874 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 875 876 EarlyCSE CSE(TLI, TTI, DT, AC); 877 878 return CSE.run(); 879 } 880 881 void getAnalysisUsage(AnalysisUsage &AU) const override { 882 AU.addRequired<AssumptionCacheTracker>(); 883 AU.addRequired<DominatorTreeWrapperPass>(); 884 AU.addRequired<TargetLibraryInfoWrapperPass>(); 885 AU.addRequired<TargetTransformInfoWrapperPass>(); 886 AU.addPreserved<GlobalsAAWrapperPass>(); 887 AU.setPreservesCFG(); 888 } 889 }; 890 } 891 892 char EarlyCSELegacyPass::ID = 0; 893 894 FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); } 895 896 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false, 897 false) 898 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 899 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 900 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 901 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 902 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false) 903