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/DenseMapInfo.h" 17 #include "llvm/ADT/Hashing.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/ScopedHashTable.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AssumptionCache.h" 24 #include "llvm/Analysis/GlobalsModRef.h" 25 #include "llvm/Analysis/InstructionSimplify.h" 26 #include "llvm/Analysis/MemorySSA.h" 27 #include "llvm/Analysis/MemorySSAUpdater.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/TargetTransformInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/Constants.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/Dominators.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/InstrTypes.h" 37 #include "llvm/IR/Instruction.h" 38 #include "llvm/IR/Instructions.h" 39 #include "llvm/IR/IntrinsicInst.h" 40 #include "llvm/IR/Intrinsics.h" 41 #include "llvm/IR/LLVMContext.h" 42 #include "llvm/IR/PassManager.h" 43 #include "llvm/IR/PatternMatch.h" 44 #include "llvm/IR/Type.h" 45 #include "llvm/IR/Use.h" 46 #include "llvm/IR/Value.h" 47 #include "llvm/Pass.h" 48 #include "llvm/Support/Allocator.h" 49 #include "llvm/Support/AtomicOrdering.h" 50 #include "llvm/Support/Casting.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Support/RecyclingAllocator.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include "llvm/Transforms/Scalar.h" 55 #include "llvm/Transforms/Utils/Local.h" 56 #include <cassert> 57 #include <deque> 58 #include <memory> 59 #include <utility> 60 61 using namespace llvm; 62 using namespace llvm::PatternMatch; 63 64 #define DEBUG_TYPE "early-cse" 65 66 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd"); 67 STATISTIC(NumCSE, "Number of instructions CSE'd"); 68 STATISTIC(NumCSECVP, "Number of compare instructions CVP'd"); 69 STATISTIC(NumCSELoad, "Number of load instructions CSE'd"); 70 STATISTIC(NumCSECall, "Number of call instructions CSE'd"); 71 STATISTIC(NumDSE, "Number of trivial dead stores removed"); 72 73 //===----------------------------------------------------------------------===// 74 // SimpleValue 75 //===----------------------------------------------------------------------===// 76 77 namespace { 78 79 /// \brief Struct representing the available values in the scoped hash table. 80 struct SimpleValue { 81 Instruction *Inst; 82 83 SimpleValue(Instruction *I) : Inst(I) { 84 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!"); 85 } 86 87 bool isSentinel() const { 88 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() || 89 Inst == DenseMapInfo<Instruction *>::getTombstoneKey(); 90 } 91 92 static bool canHandle(Instruction *Inst) { 93 // This can only handle non-void readnone functions. 94 if (CallInst *CI = dyn_cast<CallInst>(Inst)) 95 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy(); 96 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) || 97 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) || 98 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) || 99 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) || 100 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst); 101 } 102 }; 103 104 } // end anonymous namespace 105 106 namespace llvm { 107 108 template <> struct DenseMapInfo<SimpleValue> { 109 static inline SimpleValue getEmptyKey() { 110 return DenseMapInfo<Instruction *>::getEmptyKey(); 111 } 112 113 static inline SimpleValue getTombstoneKey() { 114 return DenseMapInfo<Instruction *>::getTombstoneKey(); 115 } 116 117 static unsigned getHashValue(SimpleValue Val); 118 static bool isEqual(SimpleValue LHS, SimpleValue RHS); 119 }; 120 121 } // end namespace llvm 122 123 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) { 124 Instruction *Inst = Val.Inst; 125 // Hash in all of the operands as pointers. 126 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) { 127 Value *LHS = BinOp->getOperand(0); 128 Value *RHS = BinOp->getOperand(1); 129 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1)) 130 std::swap(LHS, RHS); 131 132 return hash_combine(BinOp->getOpcode(), LHS, RHS); 133 } 134 135 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) { 136 Value *LHS = CI->getOperand(0); 137 Value *RHS = CI->getOperand(1); 138 CmpInst::Predicate Pred = CI->getPredicate(); 139 if (Inst->getOperand(0) > Inst->getOperand(1)) { 140 std::swap(LHS, RHS); 141 Pred = CI->getSwappedPredicate(); 142 } 143 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS); 144 } 145 146 // Hash min/max/abs (cmp + select) to allow for commuted operands. 147 // Min/max may also have non-canonical compare predicate (eg, the compare for 148 // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the 149 // compare. 150 Value *A, *B; 151 SelectPatternFlavor SPF = matchSelectPattern(Inst, A, B).Flavor; 152 // TODO: We should also detect FP min/max. 153 if (SPF == SPF_SMIN || SPF == SPF_SMAX || 154 SPF == SPF_UMIN || SPF == SPF_UMAX || 155 SPF == SPF_ABS || SPF == SPF_NABS) { 156 if (A > B) 157 std::swap(A, B); 158 return hash_combine(Inst->getOpcode(), SPF, A, B); 159 } 160 161 if (CastInst *CI = dyn_cast<CastInst>(Inst)) 162 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0)); 163 164 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst)) 165 return hash_combine(EVI->getOpcode(), EVI->getOperand(0), 166 hash_combine_range(EVI->idx_begin(), EVI->idx_end())); 167 168 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst)) 169 return hash_combine(IVI->getOpcode(), IVI->getOperand(0), 170 IVI->getOperand(1), 171 hash_combine_range(IVI->idx_begin(), IVI->idx_end())); 172 173 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) || 174 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) || 175 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) || 176 isa<ShuffleVectorInst>(Inst)) && 177 "Invalid/unknown instruction"); 178 179 // Mix in the opcode. 180 return hash_combine( 181 Inst->getOpcode(), 182 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end())); 183 } 184 185 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) { 186 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst; 187 188 if (LHS.isSentinel() || RHS.isSentinel()) 189 return LHSI == RHSI; 190 191 if (LHSI->getOpcode() != RHSI->getOpcode()) 192 return false; 193 if (LHSI->isIdenticalToWhenDefined(RHSI)) 194 return true; 195 196 // If we're not strictly identical, we still might be a commutable instruction 197 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) { 198 if (!LHSBinOp->isCommutative()) 199 return false; 200 201 assert(isa<BinaryOperator>(RHSI) && 202 "same opcode, but different instruction type?"); 203 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI); 204 205 // Commuted equality 206 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) && 207 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0); 208 } 209 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) { 210 assert(isa<CmpInst>(RHSI) && 211 "same opcode, but different instruction type?"); 212 CmpInst *RHSCmp = cast<CmpInst>(RHSI); 213 // Commuted equality 214 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) && 215 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) && 216 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate(); 217 } 218 219 // Min/max/abs can occur with commuted operands, non-canonical predicates, 220 // and/or non-canonical operands. 221 Value *LHSA, *LHSB; 222 SelectPatternFlavor LSPF = matchSelectPattern(LHSI, LHSA, LHSB).Flavor; 223 // TODO: We should also detect FP min/max. 224 if (LSPF == SPF_SMIN || LSPF == SPF_SMAX || 225 LSPF == SPF_UMIN || LSPF == SPF_UMAX || 226 LSPF == SPF_ABS || LSPF == SPF_NABS) { 227 Value *RHSA, *RHSB; 228 SelectPatternFlavor RSPF = matchSelectPattern(RHSI, RHSA, RHSB).Flavor; 229 return (LSPF == RSPF && ((LHSA == RHSA && LHSB == RHSB) || 230 (LHSA == RHSB && LHSB == RHSA))); 231 } 232 233 return false; 234 } 235 236 //===----------------------------------------------------------------------===// 237 // CallValue 238 //===----------------------------------------------------------------------===// 239 240 namespace { 241 242 /// \brief Struct representing the available call values in the scoped hash 243 /// table. 244 struct CallValue { 245 Instruction *Inst; 246 247 CallValue(Instruction *I) : Inst(I) { 248 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!"); 249 } 250 251 bool isSentinel() const { 252 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() || 253 Inst == DenseMapInfo<Instruction *>::getTombstoneKey(); 254 } 255 256 static bool canHandle(Instruction *Inst) { 257 // Don't value number anything that returns void. 258 if (Inst->getType()->isVoidTy()) 259 return false; 260 261 CallInst *CI = dyn_cast<CallInst>(Inst); 262 if (!CI || !CI->onlyReadsMemory()) 263 return false; 264 return true; 265 } 266 }; 267 268 } // end anonymous namespace 269 270 namespace llvm { 271 272 template <> struct DenseMapInfo<CallValue> { 273 static inline CallValue getEmptyKey() { 274 return DenseMapInfo<Instruction *>::getEmptyKey(); 275 } 276 277 static inline CallValue getTombstoneKey() { 278 return DenseMapInfo<Instruction *>::getTombstoneKey(); 279 } 280 281 static unsigned getHashValue(CallValue Val); 282 static bool isEqual(CallValue LHS, CallValue RHS); 283 }; 284 285 } // end namespace llvm 286 287 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) { 288 Instruction *Inst = Val.Inst; 289 // Hash all of the operands as pointers and mix in the opcode. 290 return hash_combine( 291 Inst->getOpcode(), 292 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end())); 293 } 294 295 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) { 296 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst; 297 if (LHS.isSentinel() || RHS.isSentinel()) 298 return LHSI == RHSI; 299 return LHSI->isIdenticalTo(RHSI); 300 } 301 302 //===----------------------------------------------------------------------===// 303 // EarlyCSE implementation 304 //===----------------------------------------------------------------------===// 305 306 namespace { 307 308 /// \brief A simple and fast domtree-based CSE pass. 309 /// 310 /// This pass does a simple depth-first walk over the dominator tree, 311 /// eliminating trivially redundant instructions and using instsimplify to 312 /// canonicalize things as it goes. It is intended to be fast and catch obvious 313 /// cases so that instcombine and other passes are more effective. It is 314 /// expected that a later pass of GVN will catch the interesting/hard cases. 315 class EarlyCSE { 316 public: 317 const TargetLibraryInfo &TLI; 318 const TargetTransformInfo &TTI; 319 DominatorTree &DT; 320 AssumptionCache &AC; 321 const SimplifyQuery SQ; 322 MemorySSA *MSSA; 323 std::unique_ptr<MemorySSAUpdater> MSSAUpdater; 324 325 using AllocatorTy = 326 RecyclingAllocator<BumpPtrAllocator, 327 ScopedHashTableVal<SimpleValue, Value *>>; 328 using ScopedHTType = 329 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>, 330 AllocatorTy>; 331 332 /// \brief A scoped hash table of the current values of all of our simple 333 /// scalar expressions. 334 /// 335 /// As we walk down the domtree, we look to see if instructions are in this: 336 /// if so, we replace them with what we find, otherwise we insert them so 337 /// that dominated values can succeed in their lookup. 338 ScopedHTType AvailableValues; 339 340 /// A scoped hash table of the current values of previously encounted memory 341 /// locations. 342 /// 343 /// This allows us to get efficient access to dominating loads or stores when 344 /// we have a fully redundant load. In addition to the most recent load, we 345 /// keep track of a generation count of the read, which is compared against 346 /// the current generation count. The current generation count is incremented 347 /// after every possibly writing memory operation, which ensures that we only 348 /// CSE loads with other loads that have no intervening store. Ordering 349 /// events (such as fences or atomic instructions) increment the generation 350 /// count as well; essentially, we model these as writes to all possible 351 /// locations. Note that atomic and/or volatile loads and stores can be 352 /// present the table; it is the responsibility of the consumer to inspect 353 /// the atomicity/volatility if needed. 354 struct LoadValue { 355 Instruction *DefInst = nullptr; 356 unsigned Generation = 0; 357 int MatchingId = -1; 358 bool IsAtomic = false; 359 bool IsInvariant = false; 360 361 LoadValue() = default; 362 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId, 363 bool IsAtomic, bool IsInvariant) 364 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId), 365 IsAtomic(IsAtomic), IsInvariant(IsInvariant) {} 366 }; 367 368 using LoadMapAllocator = 369 RecyclingAllocator<BumpPtrAllocator, 370 ScopedHashTableVal<Value *, LoadValue>>; 371 using LoadHTType = 372 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>, 373 LoadMapAllocator>; 374 375 LoadHTType AvailableLoads; 376 377 /// \brief A scoped hash table of the current values of read-only call 378 /// values. 379 /// 380 /// It uses the same generation count as loads. 381 using CallHTType = 382 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>; 383 CallHTType AvailableCalls; 384 385 /// \brief This is the current generation of the memory value. 386 unsigned CurrentGeneration = 0; 387 388 /// \brief Set up the EarlyCSE runner for a particular function. 389 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI, 390 const TargetTransformInfo &TTI, DominatorTree &DT, 391 AssumptionCache &AC, MemorySSA *MSSA) 392 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA), 393 MSSAUpdater(llvm::make_unique<MemorySSAUpdater>(MSSA)) {} 394 395 bool run(); 396 397 private: 398 // Almost a POD, but needs to call the constructors for the scoped hash 399 // tables so that a new scope gets pushed on. These are RAII so that the 400 // scope gets popped when the NodeScope is destroyed. 401 class NodeScope { 402 public: 403 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 404 CallHTType &AvailableCalls) 405 : Scope(AvailableValues), LoadScope(AvailableLoads), 406 CallScope(AvailableCalls) {} 407 NodeScope(const NodeScope &) = delete; 408 NodeScope &operator=(const NodeScope &) = delete; 409 410 private: 411 ScopedHTType::ScopeTy Scope; 412 LoadHTType::ScopeTy LoadScope; 413 CallHTType::ScopeTy CallScope; 414 }; 415 416 // Contains all the needed information to create a stack for doing a depth 417 // first traversal of the tree. This includes scopes for values, loads, and 418 // calls as well as the generation. There is a child iterator so that the 419 // children do not need to be store separately. 420 class StackNode { 421 public: 422 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 423 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n, 424 DomTreeNode::iterator child, DomTreeNode::iterator end) 425 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child), 426 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls) 427 {} 428 StackNode(const StackNode &) = delete; 429 StackNode &operator=(const StackNode &) = delete; 430 431 // Accessors. 432 unsigned currentGeneration() { return CurrentGeneration; } 433 unsigned childGeneration() { return ChildGeneration; } 434 void childGeneration(unsigned generation) { ChildGeneration = generation; } 435 DomTreeNode *node() { return Node; } 436 DomTreeNode::iterator childIter() { return ChildIter; } 437 438 DomTreeNode *nextChild() { 439 DomTreeNode *child = *ChildIter; 440 ++ChildIter; 441 return child; 442 } 443 444 DomTreeNode::iterator end() { return EndIter; } 445 bool isProcessed() { return Processed; } 446 void process() { Processed = true; } 447 448 private: 449 unsigned CurrentGeneration; 450 unsigned ChildGeneration; 451 DomTreeNode *Node; 452 DomTreeNode::iterator ChildIter; 453 DomTreeNode::iterator EndIter; 454 NodeScope Scopes; 455 bool Processed = false; 456 }; 457 458 /// \brief Wrapper class to handle memory instructions, including loads, 459 /// stores and intrinsic loads and stores defined by the target. 460 class ParseMemoryInst { 461 public: 462 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI) 463 : Inst(Inst) { 464 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) 465 if (TTI.getTgtMemIntrinsic(II, Info)) 466 IsTargetMemInst = true; 467 } 468 469 bool isLoad() const { 470 if (IsTargetMemInst) return Info.ReadMem; 471 return isa<LoadInst>(Inst); 472 } 473 474 bool isStore() const { 475 if (IsTargetMemInst) return Info.WriteMem; 476 return isa<StoreInst>(Inst); 477 } 478 479 bool isAtomic() const { 480 if (IsTargetMemInst) 481 return Info.Ordering != AtomicOrdering::NotAtomic; 482 return Inst->isAtomic(); 483 } 484 485 bool isUnordered() const { 486 if (IsTargetMemInst) 487 return Info.isUnordered(); 488 489 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 490 return LI->isUnordered(); 491 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 492 return SI->isUnordered(); 493 } 494 // Conservative answer 495 return !Inst->isAtomic(); 496 } 497 498 bool isVolatile() const { 499 if (IsTargetMemInst) 500 return Info.IsVolatile; 501 502 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 503 return LI->isVolatile(); 504 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 505 return SI->isVolatile(); 506 } 507 // Conservative answer 508 return true; 509 } 510 511 bool isInvariantLoad() const { 512 if (auto *LI = dyn_cast<LoadInst>(Inst)) 513 return LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr; 514 return false; 515 } 516 517 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const { 518 return (getPointerOperand() == Inst.getPointerOperand() && 519 getMatchingId() == Inst.getMatchingId()); 520 } 521 522 bool isValid() const { return getPointerOperand() != nullptr; } 523 524 // For regular (non-intrinsic) loads/stores, this is set to -1. For 525 // intrinsic loads/stores, the id is retrieved from the corresponding 526 // field in the MemIntrinsicInfo structure. That field contains 527 // non-negative values only. 528 int getMatchingId() const { 529 if (IsTargetMemInst) return Info.MatchingId; 530 return -1; 531 } 532 533 Value *getPointerOperand() const { 534 if (IsTargetMemInst) return Info.PtrVal; 535 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 536 return LI->getPointerOperand(); 537 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 538 return SI->getPointerOperand(); 539 } 540 return nullptr; 541 } 542 543 bool mayReadFromMemory() const { 544 if (IsTargetMemInst) return Info.ReadMem; 545 return Inst->mayReadFromMemory(); 546 } 547 548 bool mayWriteToMemory() const { 549 if (IsTargetMemInst) return Info.WriteMem; 550 return Inst->mayWriteToMemory(); 551 } 552 553 private: 554 bool IsTargetMemInst = false; 555 MemIntrinsicInfo Info; 556 Instruction *Inst; 557 }; 558 559 bool processNode(DomTreeNode *Node); 560 561 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const { 562 if (auto *LI = dyn_cast<LoadInst>(Inst)) 563 return LI; 564 if (auto *SI = dyn_cast<StoreInst>(Inst)) 565 return SI->getValueOperand(); 566 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported"); 567 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst), 568 ExpectedType); 569 } 570 571 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration, 572 Instruction *EarlierInst, Instruction *LaterInst); 573 574 void removeMSSA(Instruction *Inst) { 575 if (!MSSA) 576 return; 577 // Removing a store here can leave MemorySSA in an unoptimized state by 578 // creating MemoryPhis that have identical arguments and by creating 579 // MemoryUses whose defining access is not an actual clobber. We handle the 580 // phi case eagerly here. The non-optimized MemoryUse case is lazily 581 // updated by MemorySSA getClobberingMemoryAccess. 582 if (MemoryAccess *MA = MSSA->getMemoryAccess(Inst)) { 583 // Optimize MemoryPhi nodes that may become redundant by having all the 584 // same input values once MA is removed. 585 SmallSetVector<MemoryPhi *, 4> PhisToCheck; 586 SmallVector<MemoryAccess *, 8> WorkQueue; 587 WorkQueue.push_back(MA); 588 // Process MemoryPhi nodes in FIFO order using a ever-growing vector since 589 // we shouldn't be processing that many phis and this will avoid an 590 // allocation in almost all cases. 591 for (unsigned I = 0; I < WorkQueue.size(); ++I) { 592 MemoryAccess *WI = WorkQueue[I]; 593 594 for (auto *U : WI->users()) 595 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U)) 596 PhisToCheck.insert(MP); 597 598 MSSAUpdater->removeMemoryAccess(WI); 599 600 for (MemoryPhi *MP : PhisToCheck) { 601 MemoryAccess *FirstIn = MP->getIncomingValue(0); 602 if (llvm::all_of(MP->incoming_values(), 603 [=](Use &In) { return In == FirstIn; })) 604 WorkQueue.push_back(MP); 605 } 606 PhisToCheck.clear(); 607 } 608 } 609 } 610 }; 611 612 } // end anonymous namespace 613 614 /// Determine if the memory referenced by LaterInst is from the same heap 615 /// version as EarlierInst. 616 /// This is currently called in two scenarios: 617 /// 618 /// load p 619 /// ... 620 /// load p 621 /// 622 /// and 623 /// 624 /// x = load p 625 /// ... 626 /// store x, p 627 /// 628 /// in both cases we want to verify that there are no possible writes to the 629 /// memory referenced by p between the earlier and later instruction. 630 bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration, 631 unsigned LaterGeneration, 632 Instruction *EarlierInst, 633 Instruction *LaterInst) { 634 // Check the simple memory generation tracking first. 635 if (EarlierGeneration == LaterGeneration) 636 return true; 637 638 if (!MSSA) 639 return false; 640 641 // If MemorySSA has determined that one of EarlierInst or LaterInst does not 642 // read/write memory, then we can safely return true here. 643 // FIXME: We could be more aggressive when checking doesNotAccessMemory(), 644 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass 645 // by also checking the MemorySSA MemoryAccess on the instruction. Initial 646 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled 647 // with the default optimization pipeline. 648 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst); 649 if (!EarlierMA) 650 return true; 651 auto *LaterMA = MSSA->getMemoryAccess(LaterInst); 652 if (!LaterMA) 653 return true; 654 655 // Since we know LaterDef dominates LaterInst and EarlierInst dominates 656 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between 657 // EarlierInst and LaterInst and neither can any other write that potentially 658 // clobbers LaterInst. 659 MemoryAccess *LaterDef = 660 MSSA->getWalker()->getClobberingMemoryAccess(LaterInst); 661 return MSSA->dominates(LaterDef, EarlierMA); 662 } 663 664 bool EarlyCSE::processNode(DomTreeNode *Node) { 665 bool Changed = false; 666 BasicBlock *BB = Node->getBlock(); 667 668 // If this block has a single predecessor, then the predecessor is the parent 669 // of the domtree node and all of the live out memory values are still current 670 // in this block. If this block has multiple predecessors, then they could 671 // have invalidated the live-out memory values of our parent value. For now, 672 // just be conservative and invalidate memory if this block has multiple 673 // predecessors. 674 if (!BB->getSinglePredecessor()) 675 ++CurrentGeneration; 676 677 // If this node has a single predecessor which ends in a conditional branch, 678 // we can infer the value of the branch condition given that we took this 679 // path. We need the single predecessor to ensure there's not another path 680 // which reaches this block where the condition might hold a different 681 // value. Since we're adding this to the scoped hash table (like any other 682 // def), it will have been popped if we encounter a future merge block. 683 if (BasicBlock *Pred = BB->getSinglePredecessor()) { 684 auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()); 685 if (BI && BI->isConditional()) { 686 auto *CondInst = dyn_cast<Instruction>(BI->getCondition()); 687 if (CondInst && SimpleValue::canHandle(CondInst)) { 688 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB); 689 auto *TorF = (BI->getSuccessor(0) == BB) 690 ? ConstantInt::getTrue(BB->getContext()) 691 : ConstantInt::getFalse(BB->getContext()); 692 AvailableValues.insert(CondInst, TorF); 693 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '" 694 << CondInst->getName() << "' as " << *TorF << " in " 695 << BB->getName() << "\n"); 696 // Replace all dominated uses with the known value. 697 if (unsigned Count = replaceDominatedUsesWith( 698 CondInst, TorF, DT, BasicBlockEdge(Pred, BB))) { 699 Changed = true; 700 NumCSECVP += Count; 701 } 702 } 703 } 704 } 705 706 /// LastStore - Keep track of the last non-volatile store that we saw... for 707 /// as long as there in no instruction that reads memory. If we see a store 708 /// to the same location, we delete the dead store. This zaps trivial dead 709 /// stores which can occur in bitfield code among other things. 710 Instruction *LastStore = nullptr; 711 712 // See if any instructions in the block can be eliminated. If so, do it. If 713 // not, add them to AvailableValues. 714 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 715 Instruction *Inst = &*I++; 716 717 // Dead instructions should just be removed. 718 if (isInstructionTriviallyDead(Inst, &TLI)) { 719 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n'); 720 removeMSSA(Inst); 721 Inst->eraseFromParent(); 722 Changed = true; 723 ++NumSimplify; 724 continue; 725 } 726 727 // Skip assume intrinsics, they don't really have side effects (although 728 // they're marked as such to ensure preservation of control dependencies), 729 // and this pass will not bother with its removal. However, we should mark 730 // its condition as true for all dominated blocks. 731 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) { 732 auto *CondI = 733 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0)); 734 if (CondI && SimpleValue::canHandle(CondI)) { 735 DEBUG(dbgs() << "EarlyCSE considering assumption: " << *Inst << '\n'); 736 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext())); 737 } else 738 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n'); 739 continue; 740 } 741 742 // Skip sideeffect intrinsics, for the same reason as assume intrinsics. 743 if (match(Inst, m_Intrinsic<Intrinsic::sideeffect>())) { 744 DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << *Inst << '\n'); 745 continue; 746 } 747 748 // Skip invariant.start intrinsics since they only read memory, and we can 749 // forward values across it. Also, we dont need to consume the last store 750 // since the semantics of invariant.start allow us to perform DSE of the 751 // last store, if there was a store following invariant.start. Consider: 752 // 753 // store 30, i8* p 754 // invariant.start(p) 755 // store 40, i8* p 756 // We can DSE the store to 30, since the store 40 to invariant location p 757 // causes undefined behaviour. 758 if (match(Inst, m_Intrinsic<Intrinsic::invariant_start>())) 759 continue; 760 761 if (match(Inst, m_Intrinsic<Intrinsic::experimental_guard>())) { 762 if (auto *CondI = 763 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) { 764 if (SimpleValue::canHandle(CondI)) { 765 // Do we already know the actual value of this condition? 766 if (auto *KnownCond = AvailableValues.lookup(CondI)) { 767 // Is the condition known to be true? 768 if (isa<ConstantInt>(KnownCond) && 769 cast<ConstantInt>(KnownCond)->isOne()) { 770 DEBUG(dbgs() << "EarlyCSE removing guard: " << *Inst << '\n'); 771 removeMSSA(Inst); 772 Inst->eraseFromParent(); 773 Changed = true; 774 continue; 775 } else 776 // Use the known value if it wasn't true. 777 cast<CallInst>(Inst)->setArgOperand(0, KnownCond); 778 } 779 // The condition we're on guarding here is true for all dominated 780 // locations. 781 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext())); 782 } 783 } 784 785 // Guard intrinsics read all memory, but don't write any memory. 786 // Accordingly, don't update the generation but consume the last store (to 787 // avoid an incorrect DSE). 788 LastStore = nullptr; 789 continue; 790 } 791 792 // If the instruction can be simplified (e.g. X+0 = X) then replace it with 793 // its simpler value. 794 if (Value *V = SimplifyInstruction(Inst, SQ)) { 795 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n'); 796 bool Killed = false; 797 if (!Inst->use_empty()) { 798 Inst->replaceAllUsesWith(V); 799 Changed = true; 800 } 801 if (isInstructionTriviallyDead(Inst, &TLI)) { 802 removeMSSA(Inst); 803 Inst->eraseFromParent(); 804 Changed = true; 805 Killed = true; 806 } 807 if (Changed) 808 ++NumSimplify; 809 if (Killed) 810 continue; 811 } 812 813 // If this is a simple instruction that we can value number, process it. 814 if (SimpleValue::canHandle(Inst)) { 815 // See if the instruction has an available value. If so, use it. 816 if (Value *V = AvailableValues.lookup(Inst)) { 817 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n'); 818 if (auto *I = dyn_cast<Instruction>(V)) 819 I->andIRFlags(Inst); 820 Inst->replaceAllUsesWith(V); 821 removeMSSA(Inst); 822 Inst->eraseFromParent(); 823 Changed = true; 824 ++NumCSE; 825 continue; 826 } 827 828 // Otherwise, just remember that this value is available. 829 AvailableValues.insert(Inst, Inst); 830 continue; 831 } 832 833 ParseMemoryInst MemInst(Inst, TTI); 834 // If this is a non-volatile load, process it. 835 if (MemInst.isValid() && MemInst.isLoad()) { 836 // (conservatively) we can't peak past the ordering implied by this 837 // operation, but we can add this load to our set of available values 838 if (MemInst.isVolatile() || !MemInst.isUnordered()) { 839 LastStore = nullptr; 840 ++CurrentGeneration; 841 } 842 843 // If we have an available version of this load, and if it is the right 844 // generation or the load is known to be from an invariant location, 845 // replace this instruction. 846 // 847 // If either the dominating load or the current load are invariant, then 848 // we can assume the current load loads the same value as the dominating 849 // load. 850 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand()); 851 if (InVal.DefInst != nullptr && 852 InVal.MatchingId == MemInst.getMatchingId() && 853 // We don't yet handle removing loads with ordering of any kind. 854 !MemInst.isVolatile() && MemInst.isUnordered() && 855 // We can't replace an atomic load with one which isn't also atomic. 856 InVal.IsAtomic >= MemInst.isAtomic() && 857 (InVal.IsInvariant || MemInst.isInvariantLoad() || 858 isSameMemGeneration(InVal.Generation, CurrentGeneration, 859 InVal.DefInst, Inst))) { 860 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType()); 861 if (Op != nullptr) { 862 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst 863 << " to: " << *InVal.DefInst << '\n'); 864 if (!Inst->use_empty()) 865 Inst->replaceAllUsesWith(Op); 866 removeMSSA(Inst); 867 Inst->eraseFromParent(); 868 Changed = true; 869 ++NumCSELoad; 870 continue; 871 } 872 } 873 874 // Otherwise, remember that we have this instruction. 875 AvailableLoads.insert( 876 MemInst.getPointerOperand(), 877 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(), 878 MemInst.isAtomic(), MemInst.isInvariantLoad())); 879 LastStore = nullptr; 880 continue; 881 } 882 883 // If this instruction may read from memory or throw (and potentially read 884 // from memory in the exception handler), forget LastStore. Load/store 885 // intrinsics will indicate both a read and a write to memory. The target 886 // may override this (e.g. so that a store intrinsic does not read from 887 // memory, and thus will be treated the same as a regular store for 888 // commoning purposes). 889 if ((Inst->mayReadFromMemory() || Inst->mayThrow()) && 890 !(MemInst.isValid() && !MemInst.mayReadFromMemory())) 891 LastStore = nullptr; 892 893 // If this is a read-only call, process it. 894 if (CallValue::canHandle(Inst)) { 895 // If we have an available version of this call, and if it is the right 896 // generation, replace this instruction. 897 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst); 898 if (InVal.first != nullptr && 899 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first, 900 Inst)) { 901 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst 902 << " to: " << *InVal.first << '\n'); 903 if (!Inst->use_empty()) 904 Inst->replaceAllUsesWith(InVal.first); 905 removeMSSA(Inst); 906 Inst->eraseFromParent(); 907 Changed = true; 908 ++NumCSECall; 909 continue; 910 } 911 912 // Otherwise, remember that we have this instruction. 913 AvailableCalls.insert( 914 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration)); 915 continue; 916 } 917 918 // A release fence requires that all stores complete before it, but does 919 // not prevent the reordering of following loads 'before' the fence. As a 920 // result, we don't need to consider it as writing to memory and don't need 921 // to advance the generation. We do need to prevent DSE across the fence, 922 // but that's handled above. 923 if (FenceInst *FI = dyn_cast<FenceInst>(Inst)) 924 if (FI->getOrdering() == AtomicOrdering::Release) { 925 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above"); 926 continue; 927 } 928 929 // write back DSE - If we write back the same value we just loaded from 930 // the same location and haven't passed any intervening writes or ordering 931 // operations, we can remove the write. The primary benefit is in allowing 932 // the available load table to remain valid and value forward past where 933 // the store originally was. 934 if (MemInst.isValid() && MemInst.isStore()) { 935 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand()); 936 if (InVal.DefInst && 937 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) && 938 InVal.MatchingId == MemInst.getMatchingId() && 939 // We don't yet handle removing stores with ordering of any kind. 940 !MemInst.isVolatile() && MemInst.isUnordered() && 941 isSameMemGeneration(InVal.Generation, CurrentGeneration, 942 InVal.DefInst, Inst)) { 943 // It is okay to have a LastStore to a different pointer here if MemorySSA 944 // tells us that the load and store are from the same memory generation. 945 // In that case, LastStore should keep its present value since we're 946 // removing the current store. 947 assert((!LastStore || 948 ParseMemoryInst(LastStore, TTI).getPointerOperand() == 949 MemInst.getPointerOperand() || 950 MSSA) && 951 "can't have an intervening store if not using MemorySSA!"); 952 DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n'); 953 removeMSSA(Inst); 954 Inst->eraseFromParent(); 955 Changed = true; 956 ++NumDSE; 957 // We can avoid incrementing the generation count since we were able 958 // to eliminate this store. 959 continue; 960 } 961 } 962 963 // Okay, this isn't something we can CSE at all. Check to see if it is 964 // something that could modify memory. If so, our available memory values 965 // cannot be used so bump the generation count. 966 if (Inst->mayWriteToMemory()) { 967 ++CurrentGeneration; 968 969 if (MemInst.isValid() && MemInst.isStore()) { 970 // We do a trivial form of DSE if there are two stores to the same 971 // location with no intervening loads. Delete the earlier store. 972 // At the moment, we don't remove ordered stores, but do remove 973 // unordered atomic stores. There's no special requirement (for 974 // unordered atomics) about removing atomic stores only in favor of 975 // other atomic stores since we we're going to execute the non-atomic 976 // one anyway and the atomic one might never have become visible. 977 if (LastStore) { 978 ParseMemoryInst LastStoreMemInst(LastStore, TTI); 979 assert(LastStoreMemInst.isUnordered() && 980 !LastStoreMemInst.isVolatile() && 981 "Violated invariant"); 982 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) { 983 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore 984 << " due to: " << *Inst << '\n'); 985 removeMSSA(LastStore); 986 LastStore->eraseFromParent(); 987 Changed = true; 988 ++NumDSE; 989 LastStore = nullptr; 990 } 991 // fallthrough - we can exploit information about this store 992 } 993 994 // Okay, we just invalidated anything we knew about loaded values. Try 995 // to salvage *something* by remembering that the stored value is a live 996 // version of the pointer. It is safe to forward from volatile stores 997 // to non-volatile loads, so we don't have to check for volatility of 998 // the store. 999 AvailableLoads.insert( 1000 MemInst.getPointerOperand(), 1001 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(), 1002 MemInst.isAtomic(), /*IsInvariant=*/false)); 1003 1004 // Remember that this was the last unordered store we saw for DSE. We 1005 // don't yet handle DSE on ordered or volatile stores since we don't 1006 // have a good way to model the ordering requirement for following 1007 // passes once the store is removed. We could insert a fence, but 1008 // since fences are slightly stronger than stores in their ordering, 1009 // it's not clear this is a profitable transform. Another option would 1010 // be to merge the ordering with that of the post dominating store. 1011 if (MemInst.isUnordered() && !MemInst.isVolatile()) 1012 LastStore = Inst; 1013 else 1014 LastStore = nullptr; 1015 } 1016 } 1017 } 1018 1019 return Changed; 1020 } 1021 1022 bool EarlyCSE::run() { 1023 // Note, deque is being used here because there is significant performance 1024 // gains over vector when the container becomes very large due to the 1025 // specific access patterns. For more information see the mailing list 1026 // discussion on this: 1027 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html 1028 std::deque<StackNode *> nodesToProcess; 1029 1030 bool Changed = false; 1031 1032 // Process the root node. 1033 nodesToProcess.push_back(new StackNode( 1034 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration, 1035 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end())); 1036 1037 // Save the current generation. 1038 unsigned LiveOutGeneration = CurrentGeneration; 1039 1040 // Process the stack. 1041 while (!nodesToProcess.empty()) { 1042 // Grab the first item off the stack. Set the current generation, remove 1043 // the node from the stack, and process it. 1044 StackNode *NodeToProcess = nodesToProcess.back(); 1045 1046 // Initialize class members. 1047 CurrentGeneration = NodeToProcess->currentGeneration(); 1048 1049 // Check if the node needs to be processed. 1050 if (!NodeToProcess->isProcessed()) { 1051 // Process the node. 1052 Changed |= processNode(NodeToProcess->node()); 1053 NodeToProcess->childGeneration(CurrentGeneration); 1054 NodeToProcess->process(); 1055 } else if (NodeToProcess->childIter() != NodeToProcess->end()) { 1056 // Push the next child onto the stack. 1057 DomTreeNode *child = NodeToProcess->nextChild(); 1058 nodesToProcess.push_back( 1059 new StackNode(AvailableValues, AvailableLoads, AvailableCalls, 1060 NodeToProcess->childGeneration(), child, child->begin(), 1061 child->end())); 1062 } else { 1063 // It has been processed, and there are no more children to process, 1064 // so delete it and pop it off the stack. 1065 delete NodeToProcess; 1066 nodesToProcess.pop_back(); 1067 } 1068 } // while (!nodes...) 1069 1070 // Reset the current generation. 1071 CurrentGeneration = LiveOutGeneration; 1072 1073 return Changed; 1074 } 1075 1076 PreservedAnalyses EarlyCSEPass::run(Function &F, 1077 FunctionAnalysisManager &AM) { 1078 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1079 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 1080 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1081 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1082 auto *MSSA = 1083 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr; 1084 1085 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA); 1086 1087 if (!CSE.run()) 1088 return PreservedAnalyses::all(); 1089 1090 PreservedAnalyses PA; 1091 PA.preserveSet<CFGAnalyses>(); 1092 PA.preserve<GlobalsAA>(); 1093 if (UseMemorySSA) 1094 PA.preserve<MemorySSAAnalysis>(); 1095 return PA; 1096 } 1097 1098 namespace { 1099 1100 /// \brief A simple and fast domtree-based CSE pass. 1101 /// 1102 /// This pass does a simple depth-first walk over the dominator tree, 1103 /// eliminating trivially redundant instructions and using instsimplify to 1104 /// canonicalize things as it goes. It is intended to be fast and catch obvious 1105 /// cases so that instcombine and other passes are more effective. It is 1106 /// expected that a later pass of GVN will catch the interesting/hard cases. 1107 template<bool UseMemorySSA> 1108 class EarlyCSELegacyCommonPass : public FunctionPass { 1109 public: 1110 static char ID; 1111 1112 EarlyCSELegacyCommonPass() : FunctionPass(ID) { 1113 if (UseMemorySSA) 1114 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry()); 1115 else 1116 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry()); 1117 } 1118 1119 bool runOnFunction(Function &F) override { 1120 if (skipFunction(F)) 1121 return false; 1122 1123 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 1124 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 1125 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1126 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1127 auto *MSSA = 1128 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr; 1129 1130 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA); 1131 1132 return CSE.run(); 1133 } 1134 1135 void getAnalysisUsage(AnalysisUsage &AU) const override { 1136 AU.addRequired<AssumptionCacheTracker>(); 1137 AU.addRequired<DominatorTreeWrapperPass>(); 1138 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1139 AU.addRequired<TargetTransformInfoWrapperPass>(); 1140 if (UseMemorySSA) { 1141 AU.addRequired<MemorySSAWrapperPass>(); 1142 AU.addPreserved<MemorySSAWrapperPass>(); 1143 } 1144 AU.addPreserved<GlobalsAAWrapperPass>(); 1145 AU.setPreservesCFG(); 1146 } 1147 }; 1148 1149 } // end anonymous namespace 1150 1151 using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>; 1152 1153 template<> 1154 char EarlyCSELegacyPass::ID = 0; 1155 1156 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false, 1157 false) 1158 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1159 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1160 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1161 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1162 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false) 1163 1164 using EarlyCSEMemSSALegacyPass = 1165 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>; 1166 1167 template<> 1168 char EarlyCSEMemSSALegacyPass::ID = 0; 1169 1170 FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) { 1171 if (UseMemorySSA) 1172 return new EarlyCSEMemSSALegacyPass(); 1173 else 1174 return new EarlyCSELegacyPass(); 1175 } 1176 1177 INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa", 1178 "Early CSE w/ MemorySSA", false, false) 1179 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1180 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1181 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1182 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1183 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 1184 INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa", 1185 "Early CSE w/ MemorySSA", false, false) 1186