1 //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass performs a simple dominator tree walk that eliminates trivially 10 // redundant instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar/EarlyCSE.h" 15 #include "llvm/ADT/DenseMapInfo.h" 16 #include "llvm/ADT/Hashing.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/ScopedHashTable.h" 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AssumptionCache.h" 23 #include "llvm/Analysis/GlobalsModRef.h" 24 #include "llvm/Analysis/GuardUtils.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/Statepoint.h" 45 #include "llvm/IR/Type.h" 46 #include "llvm/IR/Use.h" 47 #include "llvm/IR/Value.h" 48 #include "llvm/InitializePasses.h" 49 #include "llvm/Pass.h" 50 #include "llvm/Support/Allocator.h" 51 #include "llvm/Support/AtomicOrdering.h" 52 #include "llvm/Support/Casting.h" 53 #include "llvm/Support/Debug.h" 54 #include "llvm/Support/DebugCounter.h" 55 #include "llvm/Support/RecyclingAllocator.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include "llvm/Transforms/Scalar.h" 58 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 59 #include "llvm/Transforms/Utils/GuardUtils.h" 60 #include "llvm/Transforms/Utils/Local.h" 61 #include <cassert> 62 #include <deque> 63 #include <memory> 64 #include <utility> 65 66 using namespace llvm; 67 using namespace llvm::PatternMatch; 68 69 #define DEBUG_TYPE "early-cse" 70 71 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd"); 72 STATISTIC(NumCSE, "Number of instructions CSE'd"); 73 STATISTIC(NumCSECVP, "Number of compare instructions CVP'd"); 74 STATISTIC(NumCSELoad, "Number of load instructions CSE'd"); 75 STATISTIC(NumCSECall, "Number of call instructions CSE'd"); 76 STATISTIC(NumDSE, "Number of trivial dead stores removed"); 77 78 DEBUG_COUNTER(CSECounter, "early-cse", 79 "Controls which instructions are removed"); 80 81 static cl::opt<unsigned> EarlyCSEMssaOptCap( 82 "earlycse-mssa-optimization-cap", cl::init(500), cl::Hidden, 83 cl::desc("Enable imprecision in EarlyCSE in pathological cases, in exchange " 84 "for faster compile. Caps the MemorySSA clobbering calls.")); 85 86 static cl::opt<bool> EarlyCSEDebugHash( 87 "earlycse-debug-hash", cl::init(false), cl::Hidden, 88 cl::desc("Perform extra assertion checking to verify that SimpleValue's hash " 89 "function is well-behaved w.r.t. its isEqual predicate")); 90 91 //===----------------------------------------------------------------------===// 92 // SimpleValue 93 //===----------------------------------------------------------------------===// 94 95 namespace { 96 97 /// Struct representing the available values in the scoped hash table. 98 struct SimpleValue { 99 Instruction *Inst; 100 101 SimpleValue(Instruction *I) : Inst(I) { 102 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!"); 103 } 104 105 bool isSentinel() const { 106 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() || 107 Inst == DenseMapInfo<Instruction *>::getTombstoneKey(); 108 } 109 110 static bool canHandle(Instruction *Inst) { 111 // This can only handle non-void readnone functions. 112 if (CallInst *CI = dyn_cast<CallInst>(Inst)) 113 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy(); 114 return isa<CastInst>(Inst) || isa<UnaryOperator>(Inst) || 115 isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) || 116 isa<CmpInst>(Inst) || isa<SelectInst>(Inst) || 117 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) || 118 isa<ShuffleVectorInst>(Inst) || isa<ExtractValueInst>(Inst) || 119 isa<InsertValueInst>(Inst) || isa<FreezeInst>(Inst); 120 } 121 }; 122 123 } // end anonymous namespace 124 125 namespace llvm { 126 127 template <> struct DenseMapInfo<SimpleValue> { 128 static inline SimpleValue getEmptyKey() { 129 return DenseMapInfo<Instruction *>::getEmptyKey(); 130 } 131 132 static inline SimpleValue getTombstoneKey() { 133 return DenseMapInfo<Instruction *>::getTombstoneKey(); 134 } 135 136 static unsigned getHashValue(SimpleValue Val); 137 static bool isEqual(SimpleValue LHS, SimpleValue RHS); 138 }; 139 140 } // end namespace llvm 141 142 /// Match a 'select' including an optional 'not's of the condition. 143 static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond, Value *&A, 144 Value *&B, 145 SelectPatternFlavor &Flavor) { 146 // Return false if V is not even a select. 147 if (!match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B)))) 148 return false; 149 150 // Look through a 'not' of the condition operand by swapping A/B. 151 Value *CondNot; 152 if (match(Cond, m_Not(m_Value(CondNot)))) { 153 Cond = CondNot; 154 std::swap(A, B); 155 } 156 157 // Match canonical forms of abs/nabs/min/max. We are not using ValueTracking's 158 // more powerful matchSelectPattern() because it may rely on instruction flags 159 // such as "nsw". That would be incompatible with the current hashing 160 // mechanism that may remove flags to increase the likelihood of CSE. 161 162 // These are the canonical forms of abs(X) and nabs(X) created by instcombine: 163 // %N = sub i32 0, %X 164 // %C = icmp slt i32 %X, 0 165 // %ABS = select i1 %C, i32 %N, i32 %X 166 // 167 // %N = sub i32 0, %X 168 // %C = icmp slt i32 %X, 0 169 // %NABS = select i1 %C, i32 %X, i32 %N 170 Flavor = SPF_UNKNOWN; 171 CmpInst::Predicate Pred; 172 if (match(Cond, m_ICmp(Pred, m_Specific(B), m_ZeroInt())) && 173 Pred == ICmpInst::ICMP_SLT && match(A, m_Neg(m_Specific(B)))) { 174 // ABS: B < 0 ? -B : B 175 Flavor = SPF_ABS; 176 return true; 177 } 178 if (match(Cond, m_ICmp(Pred, m_Specific(A), m_ZeroInt())) && 179 Pred == ICmpInst::ICMP_SLT && match(B, m_Neg(m_Specific(A)))) { 180 // NABS: A < 0 ? A : -A 181 Flavor = SPF_NABS; 182 return true; 183 } 184 185 if (!match(Cond, m_ICmp(Pred, m_Specific(A), m_Specific(B)))) { 186 // Check for commuted variants of min/max by swapping predicate. 187 // If we do not match the standard or commuted patterns, this is not a 188 // recognized form of min/max, but it is still a select, so return true. 189 if (!match(Cond, m_ICmp(Pred, m_Specific(B), m_Specific(A)))) 190 return true; 191 Pred = ICmpInst::getSwappedPredicate(Pred); 192 } 193 194 // Check for inverted variants of min/max by swapping operands. 195 switch (Pred) { 196 case CmpInst::ICMP_ULE: 197 case CmpInst::ICMP_UGE: 198 case CmpInst::ICMP_SLE: 199 case CmpInst::ICMP_SGE: 200 Pred = CmpInst::getInversePredicate(Pred); 201 std::swap(A, B); 202 break; 203 default: 204 break; 205 } 206 207 switch (Pred) { 208 case CmpInst::ICMP_UGT: Flavor = SPF_UMAX; break; 209 case CmpInst::ICMP_ULT: Flavor = SPF_UMIN; break; 210 case CmpInst::ICMP_SGT: Flavor = SPF_SMAX; break; 211 case CmpInst::ICMP_SLT: Flavor = SPF_SMIN; break; 212 default: break; 213 } 214 215 return true; 216 } 217 218 static unsigned getHashValueImpl(SimpleValue Val) { 219 Instruction *Inst = Val.Inst; 220 // Hash in all of the operands as pointers. 221 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) { 222 Value *LHS = BinOp->getOperand(0); 223 Value *RHS = BinOp->getOperand(1); 224 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1)) 225 std::swap(LHS, RHS); 226 227 return hash_combine(BinOp->getOpcode(), LHS, RHS); 228 } 229 230 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) { 231 // Compares can be commuted by swapping the comparands and 232 // updating the predicate. Choose the form that has the 233 // comparands in sorted order, or in the case of a tie, the 234 // one with the lower predicate. 235 Value *LHS = CI->getOperand(0); 236 Value *RHS = CI->getOperand(1); 237 CmpInst::Predicate Pred = CI->getPredicate(); 238 CmpInst::Predicate SwappedPred = CI->getSwappedPredicate(); 239 if (std::tie(LHS, Pred) > std::tie(RHS, SwappedPred)) { 240 std::swap(LHS, RHS); 241 Pred = SwappedPred; 242 } 243 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS); 244 } 245 246 // Hash general selects to allow matching commuted true/false operands. 247 SelectPatternFlavor SPF; 248 Value *Cond, *A, *B; 249 if (matchSelectWithOptionalNotCond(Inst, Cond, A, B, SPF)) { 250 // Hash min/max/abs (cmp + select) to allow for commuted operands. 251 // Min/max may also have non-canonical compare predicate (eg, the compare for 252 // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the 253 // compare. 254 // TODO: We should also detect FP min/max. 255 if (SPF == SPF_SMIN || SPF == SPF_SMAX || 256 SPF == SPF_UMIN || SPF == SPF_UMAX) { 257 if (A > B) 258 std::swap(A, B); 259 return hash_combine(Inst->getOpcode(), SPF, A, B); 260 } 261 if (SPF == SPF_ABS || SPF == SPF_NABS) { 262 // ABS/NABS always puts the input in A and its negation in B. 263 return hash_combine(Inst->getOpcode(), SPF, A, B); 264 } 265 266 // Hash general selects to allow matching commuted true/false operands. 267 268 // If we do not have a compare as the condition, just hash in the condition. 269 CmpInst::Predicate Pred; 270 Value *X, *Y; 271 if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y)))) 272 return hash_combine(Inst->getOpcode(), Cond, A, B); 273 274 // Similar to cmp normalization (above) - canonicalize the predicate value: 275 // select (icmp Pred, X, Y), A, B --> select (icmp InvPred, X, Y), B, A 276 if (CmpInst::getInversePredicate(Pred) < Pred) { 277 Pred = CmpInst::getInversePredicate(Pred); 278 std::swap(A, B); 279 } 280 return hash_combine(Inst->getOpcode(), Pred, X, Y, A, B); 281 } 282 283 if (CastInst *CI = dyn_cast<CastInst>(Inst)) 284 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0)); 285 286 if (FreezeInst *FI = dyn_cast<FreezeInst>(Inst)) 287 return hash_combine(FI->getOpcode(), FI->getOperand(0)); 288 289 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst)) 290 return hash_combine(EVI->getOpcode(), EVI->getOperand(0), 291 hash_combine_range(EVI->idx_begin(), EVI->idx_end())); 292 293 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst)) 294 return hash_combine(IVI->getOpcode(), IVI->getOperand(0), 295 IVI->getOperand(1), 296 hash_combine_range(IVI->idx_begin(), IVI->idx_end())); 297 298 assert((isa<CallInst>(Inst) || isa<GetElementPtrInst>(Inst) || 299 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) || 300 isa<ShuffleVectorInst>(Inst) || isa<UnaryOperator>(Inst) || 301 isa<FreezeInst>(Inst)) && 302 "Invalid/unknown instruction"); 303 304 // Handle intrinsics with commutative operands. 305 // TODO: Extend this to handle intrinsics with >2 operands where the 1st 306 // 2 operands are commutative. 307 auto *II = dyn_cast<IntrinsicInst>(Inst); 308 if (II && II->isCommutative() && II->getNumArgOperands() == 2) { 309 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 310 if (LHS > RHS) 311 std::swap(LHS, RHS); 312 return hash_combine(II->getOpcode(), LHS, RHS); 313 } 314 315 // Mix in the opcode. 316 return hash_combine( 317 Inst->getOpcode(), 318 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end())); 319 } 320 321 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) { 322 #ifndef NDEBUG 323 // If -earlycse-debug-hash was specified, return a constant -- this 324 // will force all hashing to collide, so we'll exhaustively search 325 // the table for a match, and the assertion in isEqual will fire if 326 // there's a bug causing equal keys to hash differently. 327 if (EarlyCSEDebugHash) 328 return 0; 329 #endif 330 return getHashValueImpl(Val); 331 } 332 333 static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS) { 334 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst; 335 336 if (LHS.isSentinel() || RHS.isSentinel()) 337 return LHSI == RHSI; 338 339 if (LHSI->getOpcode() != RHSI->getOpcode()) 340 return false; 341 if (LHSI->isIdenticalToWhenDefined(RHSI)) 342 return true; 343 344 // If we're not strictly identical, we still might be a commutable instruction 345 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) { 346 if (!LHSBinOp->isCommutative()) 347 return false; 348 349 assert(isa<BinaryOperator>(RHSI) && 350 "same opcode, but different instruction type?"); 351 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI); 352 353 // Commuted equality 354 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) && 355 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0); 356 } 357 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) { 358 assert(isa<CmpInst>(RHSI) && 359 "same opcode, but different instruction type?"); 360 CmpInst *RHSCmp = cast<CmpInst>(RHSI); 361 // Commuted equality 362 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) && 363 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) && 364 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate(); 365 } 366 367 // TODO: Extend this for >2 args by matching the trailing N-2 args. 368 auto *LII = dyn_cast<IntrinsicInst>(LHSI); 369 auto *RII = dyn_cast<IntrinsicInst>(RHSI); 370 if (LII && RII && LII->getIntrinsicID() == RII->getIntrinsicID() && 371 LII->isCommutative() && LII->getNumArgOperands() == 2) { 372 return LII->getArgOperand(0) == RII->getArgOperand(1) && 373 LII->getArgOperand(1) == RII->getArgOperand(0); 374 } 375 376 // Min/max/abs can occur with commuted operands, non-canonical predicates, 377 // and/or non-canonical operands. 378 // Selects can be non-trivially equivalent via inverted conditions and swaps. 379 SelectPatternFlavor LSPF, RSPF; 380 Value *CondL, *CondR, *LHSA, *RHSA, *LHSB, *RHSB; 381 if (matchSelectWithOptionalNotCond(LHSI, CondL, LHSA, LHSB, LSPF) && 382 matchSelectWithOptionalNotCond(RHSI, CondR, RHSA, RHSB, RSPF)) { 383 if (LSPF == RSPF) { 384 // TODO: We should also detect FP min/max. 385 if (LSPF == SPF_SMIN || LSPF == SPF_SMAX || 386 LSPF == SPF_UMIN || LSPF == SPF_UMAX) 387 return ((LHSA == RHSA && LHSB == RHSB) || 388 (LHSA == RHSB && LHSB == RHSA)); 389 390 if (LSPF == SPF_ABS || LSPF == SPF_NABS) { 391 // Abs results are placed in a defined order by matchSelectPattern. 392 return LHSA == RHSA && LHSB == RHSB; 393 } 394 395 // select Cond, A, B <--> select not(Cond), B, A 396 if (CondL == CondR && LHSA == RHSA && LHSB == RHSB) 397 return true; 398 } 399 400 // If the true/false operands are swapped and the conditions are compares 401 // with inverted predicates, the selects are equal: 402 // select (icmp Pred, X, Y), A, B <--> select (icmp InvPred, X, Y), B, A 403 // 404 // This also handles patterns with a double-negation in the sense of not + 405 // inverse, because we looked through a 'not' in the matching function and 406 // swapped A/B: 407 // select (cmp Pred, X, Y), A, B <--> select (not (cmp InvPred, X, Y)), B, A 408 // 409 // This intentionally does NOT handle patterns with a double-negation in 410 // the sense of not + not, because doing so could result in values 411 // comparing 412 // as equal that hash differently in the min/max/abs cases like: 413 // select (cmp slt, X, Y), X, Y <--> select (not (not (cmp slt, X, Y))), X, Y 414 // ^ hashes as min ^ would not hash as min 415 // In the context of the EarlyCSE pass, however, such cases never reach 416 // this code, as we simplify the double-negation before hashing the second 417 // select (and so still succeed at CSEing them). 418 if (LHSA == RHSB && LHSB == RHSA) { 419 CmpInst::Predicate PredL, PredR; 420 Value *X, *Y; 421 if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) && 422 match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) && 423 CmpInst::getInversePredicate(PredL) == PredR) 424 return true; 425 } 426 } 427 428 return false; 429 } 430 431 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) { 432 // These comparisons are nontrivial, so assert that equality implies 433 // hash equality (DenseMap demands this as an invariant). 434 bool Result = isEqualImpl(LHS, RHS); 435 assert(!Result || (LHS.isSentinel() && LHS.Inst == RHS.Inst) || 436 getHashValueImpl(LHS) == getHashValueImpl(RHS)); 437 return Result; 438 } 439 440 //===----------------------------------------------------------------------===// 441 // CallValue 442 //===----------------------------------------------------------------------===// 443 444 namespace { 445 446 /// Struct representing the available call values in the scoped hash 447 /// table. 448 struct CallValue { 449 Instruction *Inst; 450 451 CallValue(Instruction *I) : Inst(I) { 452 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!"); 453 } 454 455 bool isSentinel() const { 456 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() || 457 Inst == DenseMapInfo<Instruction *>::getTombstoneKey(); 458 } 459 460 static bool canHandle(Instruction *Inst) { 461 // Don't value number anything that returns void. 462 if (Inst->getType()->isVoidTy()) 463 return false; 464 465 CallInst *CI = dyn_cast<CallInst>(Inst); 466 if (!CI || !CI->onlyReadsMemory()) 467 return false; 468 return true; 469 } 470 }; 471 472 } // end anonymous namespace 473 474 namespace llvm { 475 476 template <> struct DenseMapInfo<CallValue> { 477 static inline CallValue getEmptyKey() { 478 return DenseMapInfo<Instruction *>::getEmptyKey(); 479 } 480 481 static inline CallValue getTombstoneKey() { 482 return DenseMapInfo<Instruction *>::getTombstoneKey(); 483 } 484 485 static unsigned getHashValue(CallValue Val); 486 static bool isEqual(CallValue LHS, CallValue RHS); 487 }; 488 489 } // end namespace llvm 490 491 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) { 492 Instruction *Inst = Val.Inst; 493 494 // gc.relocate is 'special' call: its second and third operands are 495 // not real values, but indices into statepoint's argument list. 496 // Get values they point to. 497 if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(Inst)) 498 return hash_combine(GCR->getOpcode(), GCR->getOperand(0), 499 GCR->getBasePtr(), GCR->getDerivedPtr()); 500 501 // Hash all of the operands as pointers and mix in the opcode. 502 return hash_combine( 503 Inst->getOpcode(), 504 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end())); 505 } 506 507 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) { 508 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst; 509 if (LHS.isSentinel() || RHS.isSentinel()) 510 return LHSI == RHSI; 511 512 // See comment above in `getHashValue()`. 513 if (const GCRelocateInst *GCR1 = dyn_cast<GCRelocateInst>(LHSI)) 514 if (const GCRelocateInst *GCR2 = dyn_cast<GCRelocateInst>(RHSI)) 515 return GCR1->getOperand(0) == GCR2->getOperand(0) && 516 GCR1->getBasePtr() == GCR2->getBasePtr() && 517 GCR1->getDerivedPtr() == GCR2->getDerivedPtr(); 518 519 return LHSI->isIdenticalTo(RHSI); 520 } 521 522 //===----------------------------------------------------------------------===// 523 // EarlyCSE implementation 524 //===----------------------------------------------------------------------===// 525 526 namespace { 527 528 /// A simple and fast domtree-based CSE pass. 529 /// 530 /// This pass does a simple depth-first walk over the dominator tree, 531 /// eliminating trivially redundant instructions and using instsimplify to 532 /// canonicalize things as it goes. It is intended to be fast and catch obvious 533 /// cases so that instcombine and other passes are more effective. It is 534 /// expected that a later pass of GVN will catch the interesting/hard cases. 535 class EarlyCSE { 536 public: 537 const TargetLibraryInfo &TLI; 538 const TargetTransformInfo &TTI; 539 DominatorTree &DT; 540 AssumptionCache &AC; 541 const SimplifyQuery SQ; 542 MemorySSA *MSSA; 543 std::unique_ptr<MemorySSAUpdater> MSSAUpdater; 544 545 using AllocatorTy = 546 RecyclingAllocator<BumpPtrAllocator, 547 ScopedHashTableVal<SimpleValue, Value *>>; 548 using ScopedHTType = 549 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>, 550 AllocatorTy>; 551 552 /// A scoped hash table of the current values of all of our simple 553 /// scalar expressions. 554 /// 555 /// As we walk down the domtree, we look to see if instructions are in this: 556 /// if so, we replace them with what we find, otherwise we insert them so 557 /// that dominated values can succeed in their lookup. 558 ScopedHTType AvailableValues; 559 560 /// A scoped hash table of the current values of previously encountered 561 /// memory locations. 562 /// 563 /// This allows us to get efficient access to dominating loads or stores when 564 /// we have a fully redundant load. In addition to the most recent load, we 565 /// keep track of a generation count of the read, which is compared against 566 /// the current generation count. The current generation count is incremented 567 /// after every possibly writing memory operation, which ensures that we only 568 /// CSE loads with other loads that have no intervening store. Ordering 569 /// events (such as fences or atomic instructions) increment the generation 570 /// count as well; essentially, we model these as writes to all possible 571 /// locations. Note that atomic and/or volatile loads and stores can be 572 /// present the table; it is the responsibility of the consumer to inspect 573 /// the atomicity/volatility if needed. 574 struct LoadValue { 575 Instruction *DefInst = nullptr; 576 unsigned Generation = 0; 577 int MatchingId = -1; 578 bool IsAtomic = false; 579 580 LoadValue() = default; 581 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId, 582 bool IsAtomic) 583 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId), 584 IsAtomic(IsAtomic) {} 585 }; 586 587 using LoadMapAllocator = 588 RecyclingAllocator<BumpPtrAllocator, 589 ScopedHashTableVal<Value *, LoadValue>>; 590 using LoadHTType = 591 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>, 592 LoadMapAllocator>; 593 594 LoadHTType AvailableLoads; 595 596 // A scoped hash table mapping memory locations (represented as typed 597 // addresses) to generation numbers at which that memory location became 598 // (henceforth indefinitely) invariant. 599 using InvariantMapAllocator = 600 RecyclingAllocator<BumpPtrAllocator, 601 ScopedHashTableVal<MemoryLocation, unsigned>>; 602 using InvariantHTType = 603 ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>, 604 InvariantMapAllocator>; 605 InvariantHTType AvailableInvariants; 606 607 /// A scoped hash table of the current values of read-only call 608 /// values. 609 /// 610 /// It uses the same generation count as loads. 611 using CallHTType = 612 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>; 613 CallHTType AvailableCalls; 614 615 /// This is the current generation of the memory value. 616 unsigned CurrentGeneration = 0; 617 618 /// Set up the EarlyCSE runner for a particular function. 619 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI, 620 const TargetTransformInfo &TTI, DominatorTree &DT, 621 AssumptionCache &AC, MemorySSA *MSSA) 622 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA), 623 MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {} 624 625 bool run(); 626 627 private: 628 unsigned ClobberCounter = 0; 629 // Almost a POD, but needs to call the constructors for the scoped hash 630 // tables so that a new scope gets pushed on. These are RAII so that the 631 // scope gets popped when the NodeScope is destroyed. 632 class NodeScope { 633 public: 634 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 635 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls) 636 : Scope(AvailableValues), LoadScope(AvailableLoads), 637 InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {} 638 NodeScope(const NodeScope &) = delete; 639 NodeScope &operator=(const NodeScope &) = delete; 640 641 private: 642 ScopedHTType::ScopeTy Scope; 643 LoadHTType::ScopeTy LoadScope; 644 InvariantHTType::ScopeTy InvariantScope; 645 CallHTType::ScopeTy CallScope; 646 }; 647 648 // Contains all the needed information to create a stack for doing a depth 649 // first traversal of the tree. This includes scopes for values, loads, and 650 // calls as well as the generation. There is a child iterator so that the 651 // children do not need to be store separately. 652 class StackNode { 653 public: 654 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads, 655 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls, 656 unsigned cg, DomTreeNode *n, DomTreeNode::const_iterator child, 657 DomTreeNode::const_iterator end) 658 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child), 659 EndIter(end), 660 Scopes(AvailableValues, AvailableLoads, AvailableInvariants, 661 AvailableCalls) 662 {} 663 StackNode(const StackNode &) = delete; 664 StackNode &operator=(const StackNode &) = delete; 665 666 // Accessors. 667 unsigned currentGeneration() { return CurrentGeneration; } 668 unsigned childGeneration() { return ChildGeneration; } 669 void childGeneration(unsigned generation) { ChildGeneration = generation; } 670 DomTreeNode *node() { return Node; } 671 DomTreeNode::const_iterator childIter() { return ChildIter; } 672 673 DomTreeNode *nextChild() { 674 DomTreeNode *child = *ChildIter; 675 ++ChildIter; 676 return child; 677 } 678 679 DomTreeNode::const_iterator end() { return EndIter; } 680 bool isProcessed() { return Processed; } 681 void process() { Processed = true; } 682 683 private: 684 unsigned CurrentGeneration; 685 unsigned ChildGeneration; 686 DomTreeNode *Node; 687 DomTreeNode::const_iterator ChildIter; 688 DomTreeNode::const_iterator EndIter; 689 NodeScope Scopes; 690 bool Processed = false; 691 }; 692 693 /// Wrapper class to handle memory instructions, including loads, 694 /// stores and intrinsic loads and stores defined by the target. 695 class ParseMemoryInst { 696 public: 697 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI) 698 : Inst(Inst) { 699 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) 700 if (TTI.getTgtMemIntrinsic(II, Info)) 701 IsTargetMemInst = true; 702 } 703 704 bool isLoad() const { 705 if (IsTargetMemInst) return Info.ReadMem; 706 return isa<LoadInst>(Inst); 707 } 708 709 bool isStore() const { 710 if (IsTargetMemInst) return Info.WriteMem; 711 return isa<StoreInst>(Inst); 712 } 713 714 bool isAtomic() const { 715 if (IsTargetMemInst) 716 return Info.Ordering != AtomicOrdering::NotAtomic; 717 return Inst->isAtomic(); 718 } 719 720 bool isUnordered() const { 721 if (IsTargetMemInst) 722 return Info.isUnordered(); 723 724 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 725 return LI->isUnordered(); 726 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 727 return SI->isUnordered(); 728 } 729 // Conservative answer 730 return !Inst->isAtomic(); 731 } 732 733 bool isVolatile() const { 734 if (IsTargetMemInst) 735 return Info.IsVolatile; 736 737 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 738 return LI->isVolatile(); 739 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 740 return SI->isVolatile(); 741 } 742 // Conservative answer 743 return true; 744 } 745 746 bool isInvariantLoad() const { 747 if (auto *LI = dyn_cast<LoadInst>(Inst)) 748 return LI->hasMetadata(LLVMContext::MD_invariant_load); 749 return false; 750 } 751 752 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const { 753 return (getPointerOperand() == Inst.getPointerOperand() && 754 getMatchingId() == Inst.getMatchingId()); 755 } 756 757 bool isValid() const { return getPointerOperand() != nullptr; } 758 759 // For regular (non-intrinsic) loads/stores, this is set to -1. For 760 // intrinsic loads/stores, the id is retrieved from the corresponding 761 // field in the MemIntrinsicInfo structure. That field contains 762 // non-negative values only. 763 int getMatchingId() const { 764 if (IsTargetMemInst) return Info.MatchingId; 765 return -1; 766 } 767 768 Value *getPointerOperand() const { 769 if (IsTargetMemInst) return Info.PtrVal; 770 return getLoadStorePointerOperand(Inst); 771 } 772 773 bool mayReadFromMemory() const { 774 if (IsTargetMemInst) return Info.ReadMem; 775 return Inst->mayReadFromMemory(); 776 } 777 778 bool mayWriteToMemory() const { 779 if (IsTargetMemInst) return Info.WriteMem; 780 return Inst->mayWriteToMemory(); 781 } 782 783 private: 784 bool IsTargetMemInst = false; 785 MemIntrinsicInfo Info; 786 Instruction *Inst; 787 }; 788 789 bool processNode(DomTreeNode *Node); 790 791 bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI, 792 const BasicBlock *BB, const BasicBlock *Pred); 793 794 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const { 795 if (auto *LI = dyn_cast<LoadInst>(Inst)) 796 return LI; 797 if (auto *SI = dyn_cast<StoreInst>(Inst)) 798 return SI->getValueOperand(); 799 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported"); 800 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst), 801 ExpectedType); 802 } 803 804 /// Return true if the instruction is known to only operate on memory 805 /// provably invariant in the given "generation". 806 bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt); 807 808 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration, 809 Instruction *EarlierInst, Instruction *LaterInst); 810 811 void removeMSSA(Instruction &Inst) { 812 if (!MSSA) 813 return; 814 if (VerifyMemorySSA) 815 MSSA->verifyMemorySSA(); 816 // Removing a store here can leave MemorySSA in an unoptimized state by 817 // creating MemoryPhis that have identical arguments and by creating 818 // MemoryUses whose defining access is not an actual clobber. The phi case 819 // is handled by MemorySSA when passing OptimizePhis = true to 820 // removeMemoryAccess. The non-optimized MemoryUse case is lazily updated 821 // by MemorySSA's getClobberingMemoryAccess. 822 MSSAUpdater->removeMemoryAccess(&Inst, true); 823 } 824 }; 825 826 } // end anonymous namespace 827 828 /// Determine if the memory referenced by LaterInst is from the same heap 829 /// version as EarlierInst. 830 /// This is currently called in two scenarios: 831 /// 832 /// load p 833 /// ... 834 /// load p 835 /// 836 /// and 837 /// 838 /// x = load p 839 /// ... 840 /// store x, p 841 /// 842 /// in both cases we want to verify that there are no possible writes to the 843 /// memory referenced by p between the earlier and later instruction. 844 bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration, 845 unsigned LaterGeneration, 846 Instruction *EarlierInst, 847 Instruction *LaterInst) { 848 // Check the simple memory generation tracking first. 849 if (EarlierGeneration == LaterGeneration) 850 return true; 851 852 if (!MSSA) 853 return false; 854 855 // If MemorySSA has determined that one of EarlierInst or LaterInst does not 856 // read/write memory, then we can safely return true here. 857 // FIXME: We could be more aggressive when checking doesNotAccessMemory(), 858 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass 859 // by also checking the MemorySSA MemoryAccess on the instruction. Initial 860 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled 861 // with the default optimization pipeline. 862 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst); 863 if (!EarlierMA) 864 return true; 865 auto *LaterMA = MSSA->getMemoryAccess(LaterInst); 866 if (!LaterMA) 867 return true; 868 869 // Since we know LaterDef dominates LaterInst and EarlierInst dominates 870 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between 871 // EarlierInst and LaterInst and neither can any other write that potentially 872 // clobbers LaterInst. 873 MemoryAccess *LaterDef; 874 if (ClobberCounter < EarlyCSEMssaOptCap) { 875 LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst); 876 ClobberCounter++; 877 } else 878 LaterDef = LaterMA->getDefiningAccess(); 879 880 return MSSA->dominates(LaterDef, EarlierMA); 881 } 882 883 bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) { 884 // A location loaded from with an invariant_load is assumed to *never* change 885 // within the visible scope of the compilation. 886 if (auto *LI = dyn_cast<LoadInst>(I)) 887 if (LI->hasMetadata(LLVMContext::MD_invariant_load)) 888 return true; 889 890 auto MemLocOpt = MemoryLocation::getOrNone(I); 891 if (!MemLocOpt) 892 // "target" intrinsic forms of loads aren't currently known to 893 // MemoryLocation::get. TODO 894 return false; 895 MemoryLocation MemLoc = *MemLocOpt; 896 if (!AvailableInvariants.count(MemLoc)) 897 return false; 898 899 // Is the generation at which this became invariant older than the 900 // current one? 901 return AvailableInvariants.lookup(MemLoc) <= GenAt; 902 } 903 904 bool EarlyCSE::handleBranchCondition(Instruction *CondInst, 905 const BranchInst *BI, const BasicBlock *BB, 906 const BasicBlock *Pred) { 907 assert(BI->isConditional() && "Should be a conditional branch!"); 908 assert(BI->getCondition() == CondInst && "Wrong condition?"); 909 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB); 910 auto *TorF = (BI->getSuccessor(0) == BB) 911 ? ConstantInt::getTrue(BB->getContext()) 912 : ConstantInt::getFalse(BB->getContext()); 913 auto MatchBinOp = [](Instruction *I, unsigned Opcode) { 914 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I)) 915 return BOp->getOpcode() == Opcode; 916 return false; 917 }; 918 // If the condition is AND operation, we can propagate its operands into the 919 // true branch. If it is OR operation, we can propagate them into the false 920 // branch. 921 unsigned PropagateOpcode = 922 (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or; 923 924 bool MadeChanges = false; 925 SmallVector<Instruction *, 4> WorkList; 926 SmallPtrSet<Instruction *, 4> Visited; 927 WorkList.push_back(CondInst); 928 while (!WorkList.empty()) { 929 Instruction *Curr = WorkList.pop_back_val(); 930 931 AvailableValues.insert(Curr, TorF); 932 LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '" 933 << Curr->getName() << "' as " << *TorF << " in " 934 << BB->getName() << "\n"); 935 if (!DebugCounter::shouldExecute(CSECounter)) { 936 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 937 } else { 938 // Replace all dominated uses with the known value. 939 if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT, 940 BasicBlockEdge(Pred, BB))) { 941 NumCSECVP += Count; 942 MadeChanges = true; 943 } 944 } 945 946 if (MatchBinOp(Curr, PropagateOpcode)) 947 for (auto &Op : cast<BinaryOperator>(Curr)->operands()) 948 if (Instruction *OPI = dyn_cast<Instruction>(Op)) 949 if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second) 950 WorkList.push_back(OPI); 951 } 952 953 return MadeChanges; 954 } 955 956 bool EarlyCSE::processNode(DomTreeNode *Node) { 957 bool Changed = false; 958 BasicBlock *BB = Node->getBlock(); 959 960 // If this block has a single predecessor, then the predecessor is the parent 961 // of the domtree node and all of the live out memory values are still current 962 // in this block. If this block has multiple predecessors, then they could 963 // have invalidated the live-out memory values of our parent value. For now, 964 // just be conservative and invalidate memory if this block has multiple 965 // predecessors. 966 if (!BB->getSinglePredecessor()) 967 ++CurrentGeneration; 968 969 // If this node has a single predecessor which ends in a conditional branch, 970 // we can infer the value of the branch condition given that we took this 971 // path. We need the single predecessor to ensure there's not another path 972 // which reaches this block where the condition might hold a different 973 // value. Since we're adding this to the scoped hash table (like any other 974 // def), it will have been popped if we encounter a future merge block. 975 if (BasicBlock *Pred = BB->getSinglePredecessor()) { 976 auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()); 977 if (BI && BI->isConditional()) { 978 auto *CondInst = dyn_cast<Instruction>(BI->getCondition()); 979 if (CondInst && SimpleValue::canHandle(CondInst)) 980 Changed |= handleBranchCondition(CondInst, BI, BB, Pred); 981 } 982 } 983 984 /// LastStore - Keep track of the last non-volatile store that we saw... for 985 /// as long as there in no instruction that reads memory. If we see a store 986 /// to the same location, we delete the dead store. This zaps trivial dead 987 /// stores which can occur in bitfield code among other things. 988 Instruction *LastStore = nullptr; 989 990 // See if any instructions in the block can be eliminated. If so, do it. If 991 // not, add them to AvailableValues. 992 for (Instruction &Inst : make_early_inc_range(BB->getInstList())) { 993 // Dead instructions should just be removed. 994 if (isInstructionTriviallyDead(&Inst, &TLI)) { 995 LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << Inst << '\n'); 996 if (!DebugCounter::shouldExecute(CSECounter)) { 997 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 998 continue; 999 } 1000 1001 salvageKnowledge(&Inst, &AC); 1002 salvageDebugInfo(Inst); 1003 removeMSSA(Inst); 1004 Inst.eraseFromParent(); 1005 Changed = true; 1006 ++NumSimplify; 1007 continue; 1008 } 1009 1010 // Skip assume intrinsics, they don't really have side effects (although 1011 // they're marked as such to ensure preservation of control dependencies), 1012 // and this pass will not bother with its removal. However, we should mark 1013 // its condition as true for all dominated blocks. 1014 if (match(&Inst, m_Intrinsic<Intrinsic::assume>())) { 1015 auto *CondI = 1016 dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0)); 1017 if (CondI && SimpleValue::canHandle(CondI)) { 1018 LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << Inst 1019 << '\n'); 1020 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext())); 1021 } else 1022 LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << Inst << '\n'); 1023 continue; 1024 } 1025 1026 // Skip sideeffect intrinsics, for the same reason as assume intrinsics. 1027 if (match(&Inst, m_Intrinsic<Intrinsic::sideeffect>())) { 1028 LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << Inst << '\n'); 1029 continue; 1030 } 1031 1032 // We can skip all invariant.start intrinsics since they only read memory, 1033 // and we can forward values across it. For invariant starts without 1034 // invariant ends, we can use the fact that the invariantness never ends to 1035 // start a scope in the current generaton which is true for all future 1036 // generations. Also, we dont need to consume the last store since the 1037 // semantics of invariant.start allow us to perform DSE of the last 1038 // store, if there was a store following invariant.start. Consider: 1039 // 1040 // store 30, i8* p 1041 // invariant.start(p) 1042 // store 40, i8* p 1043 // We can DSE the store to 30, since the store 40 to invariant location p 1044 // causes undefined behaviour. 1045 if (match(&Inst, m_Intrinsic<Intrinsic::invariant_start>())) { 1046 // If there are any uses, the scope might end. 1047 if (!Inst.use_empty()) 1048 continue; 1049 MemoryLocation MemLoc = 1050 MemoryLocation::getForArgument(&cast<CallInst>(Inst), 1, TLI); 1051 // Don't start a scope if we already have a better one pushed 1052 if (!AvailableInvariants.count(MemLoc)) 1053 AvailableInvariants.insert(MemLoc, CurrentGeneration); 1054 continue; 1055 } 1056 1057 if (isGuard(&Inst)) { 1058 if (auto *CondI = 1059 dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0))) { 1060 if (SimpleValue::canHandle(CondI)) { 1061 // Do we already know the actual value of this condition? 1062 if (auto *KnownCond = AvailableValues.lookup(CondI)) { 1063 // Is the condition known to be true? 1064 if (isa<ConstantInt>(KnownCond) && 1065 cast<ConstantInt>(KnownCond)->isOne()) { 1066 LLVM_DEBUG(dbgs() 1067 << "EarlyCSE removing guard: " << Inst << '\n'); 1068 salvageKnowledge(&Inst, &AC); 1069 removeMSSA(Inst); 1070 Inst.eraseFromParent(); 1071 Changed = true; 1072 continue; 1073 } else 1074 // Use the known value if it wasn't true. 1075 cast<CallInst>(Inst).setArgOperand(0, KnownCond); 1076 } 1077 // The condition we're on guarding here is true for all dominated 1078 // locations. 1079 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext())); 1080 } 1081 } 1082 1083 // Guard intrinsics read all memory, but don't write any memory. 1084 // Accordingly, don't update the generation but consume the last store (to 1085 // avoid an incorrect DSE). 1086 LastStore = nullptr; 1087 continue; 1088 } 1089 1090 // If the instruction can be simplified (e.g. X+0 = X) then replace it with 1091 // its simpler value. 1092 if (Value *V = SimplifyInstruction(&Inst, SQ)) { 1093 LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << Inst << " to: " << *V 1094 << '\n'); 1095 if (!DebugCounter::shouldExecute(CSECounter)) { 1096 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1097 } else { 1098 bool Killed = false; 1099 if (!Inst.use_empty()) { 1100 Inst.replaceAllUsesWith(V); 1101 Changed = true; 1102 } 1103 if (isInstructionTriviallyDead(&Inst, &TLI)) { 1104 salvageKnowledge(&Inst, &AC); 1105 removeMSSA(Inst); 1106 Inst.eraseFromParent(); 1107 Changed = true; 1108 Killed = true; 1109 } 1110 if (Changed) 1111 ++NumSimplify; 1112 if (Killed) 1113 continue; 1114 } 1115 } 1116 1117 // If this is a simple instruction that we can value number, process it. 1118 if (SimpleValue::canHandle(&Inst)) { 1119 // See if the instruction has an available value. If so, use it. 1120 if (Value *V = AvailableValues.lookup(&Inst)) { 1121 LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << Inst << " to: " << *V 1122 << '\n'); 1123 if (!DebugCounter::shouldExecute(CSECounter)) { 1124 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1125 continue; 1126 } 1127 if (auto *I = dyn_cast<Instruction>(V)) 1128 I->andIRFlags(&Inst); 1129 Inst.replaceAllUsesWith(V); 1130 salvageKnowledge(&Inst, &AC); 1131 removeMSSA(Inst); 1132 Inst.eraseFromParent(); 1133 Changed = true; 1134 ++NumCSE; 1135 continue; 1136 } 1137 1138 // Otherwise, just remember that this value is available. 1139 AvailableValues.insert(&Inst, &Inst); 1140 continue; 1141 } 1142 1143 ParseMemoryInst MemInst(&Inst, TTI); 1144 // If this is a non-volatile load, process it. 1145 if (MemInst.isValid() && MemInst.isLoad()) { 1146 // (conservatively) we can't peak past the ordering implied by this 1147 // operation, but we can add this load to our set of available values 1148 if (MemInst.isVolatile() || !MemInst.isUnordered()) { 1149 LastStore = nullptr; 1150 ++CurrentGeneration; 1151 } 1152 1153 if (MemInst.isInvariantLoad()) { 1154 // If we pass an invariant load, we know that memory location is 1155 // indefinitely constant from the moment of first dereferenceability. 1156 // We conservatively treat the invariant_load as that moment. If we 1157 // pass a invariant load after already establishing a scope, don't 1158 // restart it since we want to preserve the earliest point seen. 1159 auto MemLoc = MemoryLocation::get(&Inst); 1160 if (!AvailableInvariants.count(MemLoc)) 1161 AvailableInvariants.insert(MemLoc, CurrentGeneration); 1162 } 1163 1164 // If we have an available version of this load, and if it is the right 1165 // generation or the load is known to be from an invariant location, 1166 // replace this instruction. 1167 // 1168 // If either the dominating load or the current load are invariant, then 1169 // we can assume the current load loads the same value as the dominating 1170 // load. 1171 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand()); 1172 if (InVal.DefInst != nullptr && 1173 InVal.MatchingId == MemInst.getMatchingId() && 1174 // We don't yet handle removing loads with ordering of any kind. 1175 !MemInst.isVolatile() && MemInst.isUnordered() && 1176 // We can't replace an atomic load with one which isn't also atomic. 1177 InVal.IsAtomic >= MemInst.isAtomic() && 1178 (isOperatingOnInvariantMemAt(&Inst, InVal.Generation) || 1179 isSameMemGeneration(InVal.Generation, CurrentGeneration, 1180 InVal.DefInst, &Inst))) { 1181 Value *Op = getOrCreateResult(InVal.DefInst, Inst.getType()); 1182 if (Op != nullptr) { 1183 LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << Inst 1184 << " to: " << *InVal.DefInst << '\n'); 1185 if (!DebugCounter::shouldExecute(CSECounter)) { 1186 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1187 continue; 1188 } 1189 if (!Inst.use_empty()) 1190 Inst.replaceAllUsesWith(Op); 1191 salvageKnowledge(&Inst, &AC); 1192 removeMSSA(Inst); 1193 Inst.eraseFromParent(); 1194 Changed = true; 1195 ++NumCSELoad; 1196 continue; 1197 } 1198 } 1199 1200 // Otherwise, remember that we have this instruction. 1201 AvailableLoads.insert(MemInst.getPointerOperand(), 1202 LoadValue(&Inst, CurrentGeneration, 1203 MemInst.getMatchingId(), 1204 MemInst.isAtomic())); 1205 LastStore = nullptr; 1206 continue; 1207 } 1208 1209 // If this instruction may read from memory or throw (and potentially read 1210 // from memory in the exception handler), forget LastStore. Load/store 1211 // intrinsics will indicate both a read and a write to memory. The target 1212 // may override this (e.g. so that a store intrinsic does not read from 1213 // memory, and thus will be treated the same as a regular store for 1214 // commoning purposes). 1215 if ((Inst.mayReadFromMemory() || Inst.mayThrow()) && 1216 !(MemInst.isValid() && !MemInst.mayReadFromMemory())) 1217 LastStore = nullptr; 1218 1219 // If this is a read-only call, process it. 1220 if (CallValue::canHandle(&Inst)) { 1221 // If we have an available version of this call, and if it is the right 1222 // generation, replace this instruction. 1223 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(&Inst); 1224 if (InVal.first != nullptr && 1225 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first, 1226 &Inst)) { 1227 LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << Inst 1228 << " to: " << *InVal.first << '\n'); 1229 if (!DebugCounter::shouldExecute(CSECounter)) { 1230 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1231 continue; 1232 } 1233 if (!Inst.use_empty()) 1234 Inst.replaceAllUsesWith(InVal.first); 1235 salvageKnowledge(&Inst, &AC); 1236 removeMSSA(Inst); 1237 Inst.eraseFromParent(); 1238 Changed = true; 1239 ++NumCSECall; 1240 continue; 1241 } 1242 1243 // Otherwise, remember that we have this instruction. 1244 AvailableCalls.insert(&Inst, std::make_pair(&Inst, CurrentGeneration)); 1245 continue; 1246 } 1247 1248 // A release fence requires that all stores complete before it, but does 1249 // not prevent the reordering of following loads 'before' the fence. As a 1250 // result, we don't need to consider it as writing to memory and don't need 1251 // to advance the generation. We do need to prevent DSE across the fence, 1252 // but that's handled above. 1253 if (auto *FI = dyn_cast<FenceInst>(&Inst)) 1254 if (FI->getOrdering() == AtomicOrdering::Release) { 1255 assert(Inst.mayReadFromMemory() && "relied on to prevent DSE above"); 1256 continue; 1257 } 1258 1259 // write back DSE - If we write back the same value we just loaded from 1260 // the same location and haven't passed any intervening writes or ordering 1261 // operations, we can remove the write. The primary benefit is in allowing 1262 // the available load table to remain valid and value forward past where 1263 // the store originally was. 1264 if (MemInst.isValid() && MemInst.isStore()) { 1265 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand()); 1266 if (InVal.DefInst && 1267 InVal.DefInst == getOrCreateResult(&Inst, InVal.DefInst->getType()) && 1268 InVal.MatchingId == MemInst.getMatchingId() && 1269 // We don't yet handle removing stores with ordering of any kind. 1270 !MemInst.isVolatile() && MemInst.isUnordered() && 1271 (isOperatingOnInvariantMemAt(&Inst, InVal.Generation) || 1272 isSameMemGeneration(InVal.Generation, CurrentGeneration, 1273 InVal.DefInst, &Inst))) { 1274 // It is okay to have a LastStore to a different pointer here if MemorySSA 1275 // tells us that the load and store are from the same memory generation. 1276 // In that case, LastStore should keep its present value since we're 1277 // removing the current store. 1278 assert((!LastStore || 1279 ParseMemoryInst(LastStore, TTI).getPointerOperand() == 1280 MemInst.getPointerOperand() || 1281 MSSA) && 1282 "can't have an intervening store if not using MemorySSA!"); 1283 LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << Inst << '\n'); 1284 if (!DebugCounter::shouldExecute(CSECounter)) { 1285 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1286 continue; 1287 } 1288 salvageKnowledge(&Inst, &AC); 1289 removeMSSA(Inst); 1290 Inst.eraseFromParent(); 1291 Changed = true; 1292 ++NumDSE; 1293 // We can avoid incrementing the generation count since we were able 1294 // to eliminate this store. 1295 continue; 1296 } 1297 } 1298 1299 // Okay, this isn't something we can CSE at all. Check to see if it is 1300 // something that could modify memory. If so, our available memory values 1301 // cannot be used so bump the generation count. 1302 if (Inst.mayWriteToMemory()) { 1303 ++CurrentGeneration; 1304 1305 if (MemInst.isValid() && MemInst.isStore()) { 1306 // We do a trivial form of DSE if there are two stores to the same 1307 // location with no intervening loads. Delete the earlier store. 1308 // At the moment, we don't remove ordered stores, but do remove 1309 // unordered atomic stores. There's no special requirement (for 1310 // unordered atomics) about removing atomic stores only in favor of 1311 // other atomic stores since we were going to execute the non-atomic 1312 // one anyway and the atomic one might never have become visible. 1313 if (LastStore) { 1314 ParseMemoryInst LastStoreMemInst(LastStore, TTI); 1315 assert(LastStoreMemInst.isUnordered() && 1316 !LastStoreMemInst.isVolatile() && 1317 "Violated invariant"); 1318 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) { 1319 LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore 1320 << " due to: " << Inst << '\n'); 1321 if (!DebugCounter::shouldExecute(CSECounter)) { 1322 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n"); 1323 } else { 1324 salvageKnowledge(&Inst, &AC); 1325 removeMSSA(*LastStore); 1326 LastStore->eraseFromParent(); 1327 Changed = true; 1328 ++NumDSE; 1329 LastStore = nullptr; 1330 } 1331 } 1332 // fallthrough - we can exploit information about this store 1333 } 1334 1335 // Okay, we just invalidated anything we knew about loaded values. Try 1336 // to salvage *something* by remembering that the stored value is a live 1337 // version of the pointer. It is safe to forward from volatile stores 1338 // to non-volatile loads, so we don't have to check for volatility of 1339 // the store. 1340 AvailableLoads.insert(MemInst.getPointerOperand(), 1341 LoadValue(&Inst, CurrentGeneration, 1342 MemInst.getMatchingId(), 1343 MemInst.isAtomic())); 1344 1345 // Remember that this was the last unordered store we saw for DSE. We 1346 // don't yet handle DSE on ordered or volatile stores since we don't 1347 // have a good way to model the ordering requirement for following 1348 // passes once the store is removed. We could insert a fence, but 1349 // since fences are slightly stronger than stores in their ordering, 1350 // it's not clear this is a profitable transform. Another option would 1351 // be to merge the ordering with that of the post dominating store. 1352 if (MemInst.isUnordered() && !MemInst.isVolatile()) 1353 LastStore = &Inst; 1354 else 1355 LastStore = nullptr; 1356 } 1357 } 1358 } 1359 1360 return Changed; 1361 } 1362 1363 bool EarlyCSE::run() { 1364 // Note, deque is being used here because there is significant performance 1365 // gains over vector when the container becomes very large due to the 1366 // specific access patterns. For more information see the mailing list 1367 // discussion on this: 1368 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html 1369 std::deque<StackNode *> nodesToProcess; 1370 1371 bool Changed = false; 1372 1373 // Process the root node. 1374 nodesToProcess.push_back(new StackNode( 1375 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls, 1376 CurrentGeneration, DT.getRootNode(), 1377 DT.getRootNode()->begin(), DT.getRootNode()->end())); 1378 1379 assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it."); 1380 1381 // Process the stack. 1382 while (!nodesToProcess.empty()) { 1383 // Grab the first item off the stack. Set the current generation, remove 1384 // the node from the stack, and process it. 1385 StackNode *NodeToProcess = nodesToProcess.back(); 1386 1387 // Initialize class members. 1388 CurrentGeneration = NodeToProcess->currentGeneration(); 1389 1390 // Check if the node needs to be processed. 1391 if (!NodeToProcess->isProcessed()) { 1392 // Process the node. 1393 Changed |= processNode(NodeToProcess->node()); 1394 NodeToProcess->childGeneration(CurrentGeneration); 1395 NodeToProcess->process(); 1396 } else if (NodeToProcess->childIter() != NodeToProcess->end()) { 1397 // Push the next child onto the stack. 1398 DomTreeNode *child = NodeToProcess->nextChild(); 1399 nodesToProcess.push_back( 1400 new StackNode(AvailableValues, AvailableLoads, AvailableInvariants, 1401 AvailableCalls, NodeToProcess->childGeneration(), 1402 child, child->begin(), child->end())); 1403 } else { 1404 // It has been processed, and there are no more children to process, 1405 // so delete it and pop it off the stack. 1406 delete NodeToProcess; 1407 nodesToProcess.pop_back(); 1408 } 1409 } // while (!nodes...) 1410 1411 return Changed; 1412 } 1413 1414 PreservedAnalyses EarlyCSEPass::run(Function &F, 1415 FunctionAnalysisManager &AM) { 1416 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1417 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 1418 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1419 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1420 auto *MSSA = 1421 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr; 1422 1423 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA); 1424 1425 if (!CSE.run()) 1426 return PreservedAnalyses::all(); 1427 1428 PreservedAnalyses PA; 1429 PA.preserveSet<CFGAnalyses>(); 1430 PA.preserve<GlobalsAA>(); 1431 if (UseMemorySSA) 1432 PA.preserve<MemorySSAAnalysis>(); 1433 return PA; 1434 } 1435 1436 namespace { 1437 1438 /// A simple and fast domtree-based CSE pass. 1439 /// 1440 /// This pass does a simple depth-first walk over the dominator tree, 1441 /// eliminating trivially redundant instructions and using instsimplify to 1442 /// canonicalize things as it goes. It is intended to be fast and catch obvious 1443 /// cases so that instcombine and other passes are more effective. It is 1444 /// expected that a later pass of GVN will catch the interesting/hard cases. 1445 template<bool UseMemorySSA> 1446 class EarlyCSELegacyCommonPass : public FunctionPass { 1447 public: 1448 static char ID; 1449 1450 EarlyCSELegacyCommonPass() : FunctionPass(ID) { 1451 if (UseMemorySSA) 1452 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry()); 1453 else 1454 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry()); 1455 } 1456 1457 bool runOnFunction(Function &F) override { 1458 if (skipFunction(F)) 1459 return false; 1460 1461 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 1462 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 1463 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1464 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1465 auto *MSSA = 1466 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr; 1467 1468 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA); 1469 1470 return CSE.run(); 1471 } 1472 1473 void getAnalysisUsage(AnalysisUsage &AU) const override { 1474 AU.addRequired<AssumptionCacheTracker>(); 1475 AU.addRequired<DominatorTreeWrapperPass>(); 1476 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1477 AU.addRequired<TargetTransformInfoWrapperPass>(); 1478 if (UseMemorySSA) { 1479 AU.addRequired<AAResultsWrapperPass>(); 1480 AU.addRequired<MemorySSAWrapperPass>(); 1481 AU.addPreserved<MemorySSAWrapperPass>(); 1482 } 1483 AU.addPreserved<GlobalsAAWrapperPass>(); 1484 AU.addPreserved<AAResultsWrapperPass>(); 1485 AU.setPreservesCFG(); 1486 } 1487 }; 1488 1489 } // end anonymous namespace 1490 1491 using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>; 1492 1493 template<> 1494 char EarlyCSELegacyPass::ID = 0; 1495 1496 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false, 1497 false) 1498 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1499 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1500 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1501 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1502 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false) 1503 1504 using EarlyCSEMemSSALegacyPass = 1505 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>; 1506 1507 template<> 1508 char EarlyCSEMemSSALegacyPass::ID = 0; 1509 1510 FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) { 1511 if (UseMemorySSA) 1512 return new EarlyCSEMemSSALegacyPass(); 1513 else 1514 return new EarlyCSELegacyPass(); 1515 } 1516 1517 INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa", 1518 "Early CSE w/ MemorySSA", false, false) 1519 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1520 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1521 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1522 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1523 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1524 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 1525 INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa", 1526 "Early CSE w/ MemorySSA", false, false) 1527