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