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 *DefInst; 283 unsigned Generation; 284 int MatchingId; 285 bool IsAtomic; 286 LoadValue() 287 : DefInst(nullptr), Generation(0), MatchingId(-1), IsAtomic(false) {} 288 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId, 289 bool IsAtomic) 290 : DefInst(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<Instruction *, unsigned>> 305 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(const TargetLibraryInfo &TLI, const TargetTransformInfo &TTI, 313 DominatorTree &DT, AssumptionCache &AC) 314 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {} 315 316 bool run(); 317 318 private: 319 // Almost a POD, but needs to call the constructors for the scoped hash 320 // tables so that a new scope gets pushed on. These are RAII so that the 321 // scope gets popped when the NodeScope is destroyed. 322 class NodeScope { 323 public: 324 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 325 CallHTType &AvailableCalls) 326 : Scope(AvailableValues), LoadScope(AvailableLoads), 327 CallScope(AvailableCalls) {} 328 329 private: 330 NodeScope(const NodeScope &) = delete; 331 void operator=(const NodeScope &) = delete; 332 333 ScopedHTType::ScopeTy Scope; 334 LoadHTType::ScopeTy LoadScope; 335 CallHTType::ScopeTy CallScope; 336 }; 337 338 // Contains all the needed information to create a stack for doing a depth 339 // first tranversal of the tree. This includes scopes for values, loads, and 340 // calls as well as the generation. There is a child iterator so that the 341 // children do not need to be store separately. 342 class StackNode { 343 public: 344 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 345 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n, 346 DomTreeNode::iterator child, DomTreeNode::iterator end) 347 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child), 348 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls), 349 Processed(false) {} 350 351 // Accessors. 352 unsigned currentGeneration() { return CurrentGeneration; } 353 unsigned childGeneration() { return ChildGeneration; } 354 void childGeneration(unsigned generation) { ChildGeneration = generation; } 355 DomTreeNode *node() { return Node; } 356 DomTreeNode::iterator childIter() { return ChildIter; } 357 DomTreeNode *nextChild() { 358 DomTreeNode *child = *ChildIter; 359 ++ChildIter; 360 return child; 361 } 362 DomTreeNode::iterator end() { return EndIter; } 363 bool isProcessed() { return Processed; } 364 void process() { Processed = true; } 365 366 private: 367 StackNode(const StackNode &) = delete; 368 void operator=(const StackNode &) = delete; 369 370 // Members. 371 unsigned CurrentGeneration; 372 unsigned ChildGeneration; 373 DomTreeNode *Node; 374 DomTreeNode::iterator ChildIter; 375 DomTreeNode::iterator EndIter; 376 NodeScope Scopes; 377 bool Processed; 378 }; 379 380 /// \brief Wrapper class to handle memory instructions, including loads, 381 /// stores and intrinsic loads and stores defined by the target. 382 class ParseMemoryInst { 383 public: 384 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI) 385 : IsTargetMemInst(false), Inst(Inst) { 386 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) 387 if (TTI.getTgtMemIntrinsic(II, Info) && Info.NumMemRefs == 1) 388 IsTargetMemInst = true; 389 } 390 bool isLoad() const { 391 if (IsTargetMemInst) return Info.ReadMem; 392 return isa<LoadInst>(Inst); 393 } 394 bool isStore() const { 395 if (IsTargetMemInst) return Info.WriteMem; 396 return isa<StoreInst>(Inst); 397 } 398 bool isAtomic() const { 399 if (IsTargetMemInst) { 400 assert(Info.IsSimple && "need to refine IsSimple in TTI"); 401 return false; 402 } 403 return Inst->isAtomic(); 404 } 405 bool isUnordered() const { 406 if (IsTargetMemInst) { 407 assert(Info.IsSimple && "need to refine IsSimple in TTI"); 408 return true; 409 } 410 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 411 return LI->isUnordered(); 412 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 413 return SI->isUnordered(); 414 } 415 // Conservative answer 416 return !Inst->isAtomic(); 417 } 418 419 bool isVolatile() const { 420 if (IsTargetMemInst) { 421 assert(Info.IsSimple && "need to refine IsSimple in TTI"); 422 return false; 423 } 424 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 425 return LI->isVolatile(); 426 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 427 return SI->isVolatile(); 428 } 429 // Conservative answer 430 return true; 431 } 432 433 434 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const { 435 return (getPointerOperand() == Inst.getPointerOperand() && 436 getMatchingId() == Inst.getMatchingId()); 437 } 438 bool isValid() const { return getPointerOperand() != nullptr; } 439 440 // For regular (non-intrinsic) loads/stores, this is set to -1. For 441 // intrinsic loads/stores, the id is retrieved from the corresponding 442 // field in the MemIntrinsicInfo structure. That field contains 443 // non-negative values only. 444 int getMatchingId() const { 445 if (IsTargetMemInst) return Info.MatchingId; 446 return -1; 447 } 448 Value *getPointerOperand() const { 449 if (IsTargetMemInst) return Info.PtrVal; 450 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 451 return LI->getPointerOperand(); 452 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 453 return SI->getPointerOperand(); 454 } 455 return nullptr; 456 } 457 bool mayReadFromMemory() const { 458 if (IsTargetMemInst) return Info.ReadMem; 459 return Inst->mayReadFromMemory(); 460 } 461 bool mayWriteToMemory() const { 462 if (IsTargetMemInst) return Info.WriteMem; 463 return Inst->mayWriteToMemory(); 464 } 465 466 private: 467 bool IsTargetMemInst; 468 MemIntrinsicInfo Info; 469 Instruction *Inst; 470 }; 471 472 bool processNode(DomTreeNode *Node); 473 474 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const { 475 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 476 return LI; 477 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 478 return SI->getValueOperand(); 479 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported"); 480 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst), 481 ExpectedType); 482 } 483 }; 484 } 485 486 bool EarlyCSE::processNode(DomTreeNode *Node) { 487 bool Changed = false; 488 BasicBlock *BB = Node->getBlock(); 489 490 // If this block has a single predecessor, then the predecessor is the parent 491 // of the domtree node and all of the live out memory values are still current 492 // in this block. If this block has multiple predecessors, then they could 493 // have invalidated the live-out memory values of our parent value. For now, 494 // just be conservative and invalidate memory if this block has multiple 495 // predecessors. 496 if (!BB->getSinglePredecessor()) 497 ++CurrentGeneration; 498 499 // If this node has a single predecessor which ends in a conditional branch, 500 // we can infer the value of the branch condition given that we took this 501 // path. We need the single predecessor to ensure there's not another path 502 // which reaches this block where the condition might hold a different 503 // value. Since we're adding this to the scoped hash table (like any other 504 // def), it will have been popped if we encounter a future merge block. 505 if (BasicBlock *Pred = BB->getSinglePredecessor()) 506 if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator())) 507 if (BI->isConditional()) 508 if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition())) 509 if (SimpleValue::canHandle(CondInst)) { 510 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB); 511 auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ? 512 ConstantInt::getTrue(BB->getContext()) : 513 ConstantInt::getFalse(BB->getContext()); 514 AvailableValues.insert(CondInst, ConditionalConstant); 515 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '" 516 << CondInst->getName() << "' as " << *ConditionalConstant 517 << " in " << BB->getName() << "\n"); 518 // Replace all dominated uses with the known value. 519 if (unsigned Count = 520 replaceDominatedUsesWith(CondInst, ConditionalConstant, DT, 521 BasicBlockEdge(Pred, BB))) { 522 Changed = true; 523 NumCSECVP = NumCSECVP + Count; 524 } 525 } 526 527 /// LastStore - Keep track of the last non-volatile store that we saw... for 528 /// as long as there in no instruction that reads memory. If we see a store 529 /// to the same location, we delete the dead store. This zaps trivial dead 530 /// stores which can occur in bitfield code among other things. 531 Instruction *LastStore = nullptr; 532 533 const DataLayout &DL = BB->getModule()->getDataLayout(); 534 535 // See if any instructions in the block can be eliminated. If so, do it. If 536 // not, add them to AvailableValues. 537 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 538 Instruction *Inst = &*I++; 539 540 // Dead instructions should just be removed. 541 if (isInstructionTriviallyDead(Inst, &TLI)) { 542 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n'); 543 Inst->eraseFromParent(); 544 Changed = true; 545 ++NumSimplify; 546 continue; 547 } 548 549 // Skip assume intrinsics, they don't really have side effects (although 550 // they're marked as such to ensure preservation of control dependencies), 551 // and this pass will not disturb any of the assumption's control 552 // dependencies. 553 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) { 554 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n'); 555 continue; 556 } 557 558 if (match(Inst, m_Intrinsic<Intrinsic::experimental_guard>())) { 559 if (auto *CondI = 560 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) { 561 // The condition we're on guarding here is true for all dominated 562 // locations. 563 if (SimpleValue::canHandle(CondI)) 564 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext())); 565 } 566 567 // Guard intrinsics read all memory, but don't write any memory. 568 // Accordingly, don't update the generation but consume the last store (to 569 // avoid an incorrect DSE). 570 LastStore = nullptr; 571 continue; 572 } 573 574 // If the instruction can be simplified (e.g. X+0 = X) then replace it with 575 // its simpler value. 576 if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) { 577 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n'); 578 Inst->replaceAllUsesWith(V); 579 Inst->eraseFromParent(); 580 Changed = true; 581 ++NumSimplify; 582 continue; 583 } 584 585 // If this is a simple instruction that we can value number, process it. 586 if (SimpleValue::canHandle(Inst)) { 587 // See if the instruction has an available value. If so, use it. 588 if (Value *V = AvailableValues.lookup(Inst)) { 589 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n'); 590 if (auto *I = dyn_cast<Instruction>(V)) 591 I->andIRFlags(Inst); 592 Inst->replaceAllUsesWith(V); 593 Inst->eraseFromParent(); 594 Changed = true; 595 ++NumCSE; 596 continue; 597 } 598 599 // Otherwise, just remember that this value is available. 600 AvailableValues.insert(Inst, Inst); 601 continue; 602 } 603 604 ParseMemoryInst MemInst(Inst, TTI); 605 // If this is a non-volatile load, process it. 606 if (MemInst.isValid() && MemInst.isLoad()) { 607 // (conservatively) we can't peak past the ordering implied by this 608 // operation, but we can add this load to our set of available values 609 if (MemInst.isVolatile() || !MemInst.isUnordered()) { 610 LastStore = nullptr; 611 ++CurrentGeneration; 612 } 613 614 // If we have an available version of this load, and if it is the right 615 // generation, replace this instruction. 616 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand()); 617 if (InVal.DefInst != nullptr && InVal.Generation == CurrentGeneration && 618 InVal.MatchingId == MemInst.getMatchingId() && 619 // We don't yet handle removing loads with ordering of any kind. 620 !MemInst.isVolatile() && MemInst.isUnordered() && 621 // We can't replace an atomic load with one which isn't also atomic. 622 InVal.IsAtomic >= MemInst.isAtomic()) { 623 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType()); 624 if (Op != nullptr) { 625 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst 626 << " to: " << *InVal.DefInst << '\n'); 627 if (!Inst->use_empty()) 628 Inst->replaceAllUsesWith(Op); 629 Inst->eraseFromParent(); 630 Changed = true; 631 ++NumCSELoad; 632 continue; 633 } 634 } 635 636 // Otherwise, remember that we have this instruction. 637 AvailableLoads.insert( 638 MemInst.getPointerOperand(), 639 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(), 640 MemInst.isAtomic())); 641 LastStore = nullptr; 642 continue; 643 } 644 645 // If this instruction may read from memory, forget LastStore. 646 // Load/store intrinsics will indicate both a read and a write to 647 // memory. The target may override this (e.g. so that a store intrinsic 648 // does not read from memory, and thus will be treated the same as a 649 // regular store for commoning purposes). 650 if (Inst->mayReadFromMemory() && 651 !(MemInst.isValid() && !MemInst.mayReadFromMemory())) 652 LastStore = nullptr; 653 654 // If this is a read-only call, process it. 655 if (CallValue::canHandle(Inst)) { 656 // If we have an available version of this call, and if it is the right 657 // generation, replace this instruction. 658 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst); 659 if (InVal.first != nullptr && InVal.second == CurrentGeneration) { 660 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst 661 << " to: " << *InVal.first << '\n'); 662 if (!Inst->use_empty()) 663 Inst->replaceAllUsesWith(InVal.first); 664 Inst->eraseFromParent(); 665 Changed = true; 666 ++NumCSECall; 667 continue; 668 } 669 670 // Otherwise, remember that we have this instruction. 671 AvailableCalls.insert( 672 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration)); 673 continue; 674 } 675 676 // A release fence requires that all stores complete before it, but does 677 // not prevent the reordering of following loads 'before' the fence. As a 678 // result, we don't need to consider it as writing to memory and don't need 679 // to advance the generation. We do need to prevent DSE across the fence, 680 // but that's handled above. 681 if (FenceInst *FI = dyn_cast<FenceInst>(Inst)) 682 if (FI->getOrdering() == AtomicOrdering::Release) { 683 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above"); 684 continue; 685 } 686 687 // write back DSE - If we write back the same value we just loaded from 688 // the same location and haven't passed any intervening writes or ordering 689 // operations, we can remove the write. The primary benefit is in allowing 690 // the available load table to remain valid and value forward past where 691 // the store originally was. 692 if (MemInst.isValid() && MemInst.isStore()) { 693 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand()); 694 if (InVal.DefInst && 695 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) && 696 InVal.Generation == CurrentGeneration && 697 InVal.MatchingId == MemInst.getMatchingId() && 698 // We don't yet handle removing stores with ordering of any kind. 699 !MemInst.isVolatile() && MemInst.isUnordered()) { 700 assert((!LastStore || 701 ParseMemoryInst(LastStore, TTI).getPointerOperand() == 702 MemInst.getPointerOperand()) && 703 "can't have an intervening store!"); 704 DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n'); 705 Inst->eraseFromParent(); 706 Changed = true; 707 ++NumDSE; 708 // We can avoid incrementing the generation count since we were able 709 // to eliminate this store. 710 continue; 711 } 712 } 713 714 // Okay, this isn't something we can CSE at all. Check to see if it is 715 // something that could modify memory. If so, our available memory values 716 // cannot be used so bump the generation count. 717 if (Inst->mayWriteToMemory()) { 718 ++CurrentGeneration; 719 720 if (MemInst.isValid() && MemInst.isStore()) { 721 // We do a trivial form of DSE if there are two stores to the same 722 // location with no intervening loads. Delete the earlier store. 723 // At the moment, we don't remove ordered stores, but do remove 724 // unordered atomic stores. There's no special requirement (for 725 // unordered atomics) about removing atomic stores only in favor of 726 // other atomic stores since we we're going to execute the non-atomic 727 // one anyway and the atomic one might never have become visible. 728 if (LastStore) { 729 ParseMemoryInst LastStoreMemInst(LastStore, TTI); 730 assert(LastStoreMemInst.isUnordered() && 731 !LastStoreMemInst.isVolatile() && 732 "Violated invariant"); 733 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) { 734 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore 735 << " due to: " << *Inst << '\n'); 736 LastStore->eraseFromParent(); 737 Changed = true; 738 ++NumDSE; 739 LastStore = nullptr; 740 } 741 // fallthrough - we can exploit information about this store 742 } 743 744 // Okay, we just invalidated anything we knew about loaded values. Try 745 // to salvage *something* by remembering that the stored value is a live 746 // version of the pointer. It is safe to forward from volatile stores 747 // to non-volatile loads, so we don't have to check for volatility of 748 // the store. 749 AvailableLoads.insert( 750 MemInst.getPointerOperand(), 751 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(), 752 MemInst.isAtomic())); 753 754 // Remember that this was the last unordered store we saw for DSE. We 755 // don't yet handle DSE on ordered or volatile stores since we don't 756 // have a good way to model the ordering requirement for following 757 // passes once the store is removed. We could insert a fence, but 758 // since fences are slightly stronger than stores in their ordering, 759 // it's not clear this is a profitable transform. Another option would 760 // be to merge the ordering with that of the post dominating store. 761 if (MemInst.isUnordered() && !MemInst.isVolatile()) 762 LastStore = Inst; 763 else 764 LastStore = nullptr; 765 } 766 } 767 } 768 769 return Changed; 770 } 771 772 bool EarlyCSE::run() { 773 // Note, deque is being used here because there is significant performance 774 // gains over vector when the container becomes very large due to the 775 // specific access patterns. For more information see the mailing list 776 // discussion on this: 777 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html 778 std::deque<StackNode *> nodesToProcess; 779 780 bool Changed = false; 781 782 // Process the root node. 783 nodesToProcess.push_back(new StackNode( 784 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration, 785 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end())); 786 787 // Save the current generation. 788 unsigned LiveOutGeneration = CurrentGeneration; 789 790 // Process the stack. 791 while (!nodesToProcess.empty()) { 792 // Grab the first item off the stack. Set the current generation, remove 793 // the node from the stack, and process it. 794 StackNode *NodeToProcess = nodesToProcess.back(); 795 796 // Initialize class members. 797 CurrentGeneration = NodeToProcess->currentGeneration(); 798 799 // Check if the node needs to be processed. 800 if (!NodeToProcess->isProcessed()) { 801 // Process the node. 802 Changed |= processNode(NodeToProcess->node()); 803 NodeToProcess->childGeneration(CurrentGeneration); 804 NodeToProcess->process(); 805 } else if (NodeToProcess->childIter() != NodeToProcess->end()) { 806 // Push the next child onto the stack. 807 DomTreeNode *child = NodeToProcess->nextChild(); 808 nodesToProcess.push_back( 809 new StackNode(AvailableValues, AvailableLoads, AvailableCalls, 810 NodeToProcess->childGeneration(), child, child->begin(), 811 child->end())); 812 } else { 813 // It has been processed, and there are no more children to process, 814 // so delete it and pop it off the stack. 815 delete NodeToProcess; 816 nodesToProcess.pop_back(); 817 } 818 } // while (!nodes...) 819 820 // Reset the current generation. 821 CurrentGeneration = LiveOutGeneration; 822 823 return Changed; 824 } 825 826 PreservedAnalyses EarlyCSEPass::run(Function &F, 827 AnalysisManager<Function> &AM) { 828 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 829 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 830 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 831 auto &AC = AM.getResult<AssumptionAnalysis>(F); 832 833 EarlyCSE CSE(TLI, TTI, DT, AC); 834 835 if (!CSE.run()) 836 return PreservedAnalyses::all(); 837 838 // CSE preserves the dominator tree because it doesn't mutate the CFG. 839 // FIXME: Bundle this with other CFG-preservation. 840 PreservedAnalyses PA; 841 PA.preserve<DominatorTreeAnalysis>(); 842 return PA; 843 } 844 845 namespace { 846 /// \brief A simple and fast domtree-based CSE pass. 847 /// 848 /// This pass does a simple depth-first walk over the dominator tree, 849 /// eliminating trivially redundant instructions and using instsimplify to 850 /// canonicalize things as it goes. It is intended to be fast and catch obvious 851 /// cases so that instcombine and other passes are more effective. It is 852 /// expected that a later pass of GVN will catch the interesting/hard cases. 853 class EarlyCSELegacyPass : public FunctionPass { 854 public: 855 static char ID; 856 857 EarlyCSELegacyPass() : FunctionPass(ID) { 858 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry()); 859 } 860 861 bool runOnFunction(Function &F) override { 862 if (skipFunction(F)) 863 return false; 864 865 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 866 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 867 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 868 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 869 870 EarlyCSE CSE(TLI, TTI, DT, AC); 871 872 return CSE.run(); 873 } 874 875 void getAnalysisUsage(AnalysisUsage &AU) const override { 876 AU.addRequired<AssumptionCacheTracker>(); 877 AU.addRequired<DominatorTreeWrapperPass>(); 878 AU.addRequired<TargetLibraryInfoWrapperPass>(); 879 AU.addRequired<TargetTransformInfoWrapperPass>(); 880 AU.addPreserved<GlobalsAAWrapperPass>(); 881 AU.setPreservesCFG(); 882 } 883 }; 884 } 885 886 char EarlyCSELegacyPass::ID = 0; 887 888 FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); } 889 890 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false, 891 false) 892 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 893 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 894 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 895 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 896 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false) 897