1 //===- MemorySSA.cpp - Memory SSA Builder ---------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the MemorySSA class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Analysis/MemorySSA.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/DenseMapInfo.h" 17 #include "llvm/ADT/DenseSet.h" 18 #include "llvm/ADT/DepthFirstIterator.h" 19 #include "llvm/ADT/Hashing.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/iterator.h" 26 #include "llvm/ADT/iterator_range.h" 27 #include "llvm/Analysis/AliasAnalysis.h" 28 #include "llvm/Analysis/IteratedDominanceFrontier.h" 29 #include "llvm/Analysis/MemoryLocation.h" 30 #include "llvm/Config/llvm-config.h" 31 #include "llvm/IR/AssemblyAnnotationWriter.h" 32 #include "llvm/IR/BasicBlock.h" 33 #include "llvm/IR/Dominators.h" 34 #include "llvm/IR/Function.h" 35 #include "llvm/IR/Instruction.h" 36 #include "llvm/IR/Instructions.h" 37 #include "llvm/IR/IntrinsicInst.h" 38 #include "llvm/IR/Intrinsics.h" 39 #include "llvm/IR/LLVMContext.h" 40 #include "llvm/IR/PassManager.h" 41 #include "llvm/IR/Use.h" 42 #include "llvm/Pass.h" 43 #include "llvm/Support/AtomicOrdering.h" 44 #include "llvm/Support/Casting.h" 45 #include "llvm/Support/CommandLine.h" 46 #include "llvm/Support/Compiler.h" 47 #include "llvm/Support/Debug.h" 48 #include "llvm/Support/ErrorHandling.h" 49 #include "llvm/Support/FormattedStream.h" 50 #include "llvm/Support/raw_ostream.h" 51 #include <algorithm> 52 #include <cassert> 53 #include <iterator> 54 #include <memory> 55 #include <utility> 56 57 using namespace llvm; 58 59 #define DEBUG_TYPE "memoryssa" 60 61 INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false, 62 true) 63 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 64 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 65 INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false, 66 true) 67 68 INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa", 69 "Memory SSA Printer", false, false) 70 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass) 71 INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa", 72 "Memory SSA Printer", false, false) 73 74 static cl::opt<unsigned> MaxCheckLimit( 75 "memssa-check-limit", cl::Hidden, cl::init(100), 76 cl::desc("The maximum number of stores/phis MemorySSA" 77 "will consider trying to walk past (default = 100)")); 78 79 // Always verify MemorySSA if expensive checking is enabled. 80 #ifdef EXPENSIVE_CHECKS 81 bool llvm::VerifyMemorySSA = true; 82 #else 83 bool llvm::VerifyMemorySSA = false; 84 #endif 85 static cl::opt<bool, true> 86 VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA), 87 cl::Hidden, cl::desc("Enable verification of MemorySSA.")); 88 89 namespace llvm { 90 91 /// An assembly annotator class to print Memory SSA information in 92 /// comments. 93 class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter { 94 friend class MemorySSA; 95 96 const MemorySSA *MSSA; 97 98 public: 99 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {} 100 101 void emitBasicBlockStartAnnot(const BasicBlock *BB, 102 formatted_raw_ostream &OS) override { 103 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB)) 104 OS << "; " << *MA << "\n"; 105 } 106 107 void emitInstructionAnnot(const Instruction *I, 108 formatted_raw_ostream &OS) override { 109 if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) 110 OS << "; " << *MA << "\n"; 111 } 112 }; 113 114 } // end namespace llvm 115 116 namespace { 117 118 /// Our current alias analysis API differentiates heavily between calls and 119 /// non-calls, and functions called on one usually assert on the other. 120 /// This class encapsulates the distinction to simplify other code that wants 121 /// "Memory affecting instructions and related data" to use as a key. 122 /// For example, this class is used as a densemap key in the use optimizer. 123 class MemoryLocOrCall { 124 public: 125 bool IsCall = false; 126 127 MemoryLocOrCall(MemoryUseOrDef *MUD) 128 : MemoryLocOrCall(MUD->getMemoryInst()) {} 129 MemoryLocOrCall(const MemoryUseOrDef *MUD) 130 : MemoryLocOrCall(MUD->getMemoryInst()) {} 131 132 MemoryLocOrCall(Instruction *Inst) { 133 if (auto *C = dyn_cast<CallBase>(Inst)) { 134 IsCall = true; 135 Call = C; 136 } else { 137 IsCall = false; 138 // There is no such thing as a memorylocation for a fence inst, and it is 139 // unique in that regard. 140 if (!isa<FenceInst>(Inst)) 141 Loc = MemoryLocation::get(Inst); 142 } 143 } 144 145 explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {} 146 147 const CallBase *getCall() const { 148 assert(IsCall); 149 return Call; 150 } 151 152 MemoryLocation getLoc() const { 153 assert(!IsCall); 154 return Loc; 155 } 156 157 bool operator==(const MemoryLocOrCall &Other) const { 158 if (IsCall != Other.IsCall) 159 return false; 160 161 if (!IsCall) 162 return Loc == Other.Loc; 163 164 if (Call->getCalledValue() != Other.Call->getCalledValue()) 165 return false; 166 167 return Call->arg_size() == Other.Call->arg_size() && 168 std::equal(Call->arg_begin(), Call->arg_end(), 169 Other.Call->arg_begin()); 170 } 171 172 private: 173 union { 174 const CallBase *Call; 175 MemoryLocation Loc; 176 }; 177 }; 178 179 } // end anonymous namespace 180 181 namespace llvm { 182 183 template <> struct DenseMapInfo<MemoryLocOrCall> { 184 static inline MemoryLocOrCall getEmptyKey() { 185 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey()); 186 } 187 188 static inline MemoryLocOrCall getTombstoneKey() { 189 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey()); 190 } 191 192 static unsigned getHashValue(const MemoryLocOrCall &MLOC) { 193 if (!MLOC.IsCall) 194 return hash_combine( 195 MLOC.IsCall, 196 DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc())); 197 198 hash_code hash = 199 hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue( 200 MLOC.getCall()->getCalledValue())); 201 202 for (const Value *Arg : MLOC.getCall()->args()) 203 hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg)); 204 return hash; 205 } 206 207 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) { 208 return LHS == RHS; 209 } 210 }; 211 212 } // end namespace llvm 213 214 /// This does one-way checks to see if Use could theoretically be hoisted above 215 /// MayClobber. This will not check the other way around. 216 /// 217 /// This assumes that, for the purposes of MemorySSA, Use comes directly after 218 /// MayClobber, with no potentially clobbering operations in between them. 219 /// (Where potentially clobbering ops are memory barriers, aliased stores, etc.) 220 static bool areLoadsReorderable(const LoadInst *Use, 221 const LoadInst *MayClobber) { 222 bool VolatileUse = Use->isVolatile(); 223 bool VolatileClobber = MayClobber->isVolatile(); 224 // Volatile operations may never be reordered with other volatile operations. 225 if (VolatileUse && VolatileClobber) 226 return false; 227 // Otherwise, volatile doesn't matter here. From the language reference: 228 // 'optimizers may change the order of volatile operations relative to 229 // non-volatile operations.'" 230 231 // If a load is seq_cst, it cannot be moved above other loads. If its ordering 232 // is weaker, it can be moved above other loads. We just need to be sure that 233 // MayClobber isn't an acquire load, because loads can't be moved above 234 // acquire loads. 235 // 236 // Note that this explicitly *does* allow the free reordering of monotonic (or 237 // weaker) loads of the same address. 238 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent; 239 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(), 240 AtomicOrdering::Acquire); 241 return !(SeqCstUse || MayClobberIsAcquire); 242 } 243 244 namespace { 245 246 struct ClobberAlias { 247 bool IsClobber; 248 Optional<AliasResult> AR; 249 }; 250 251 } // end anonymous namespace 252 253 // Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being 254 // ignored if IsClobber = false. 255 static ClobberAlias instructionClobbersQuery(const MemoryDef *MD, 256 const MemoryLocation &UseLoc, 257 const Instruction *UseInst, 258 AliasAnalysis &AA) { 259 Instruction *DefInst = MD->getMemoryInst(); 260 assert(DefInst && "Defining instruction not actually an instruction"); 261 const auto *UseCall = dyn_cast<CallBase>(UseInst); 262 Optional<AliasResult> AR; 263 264 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) { 265 // These intrinsics will show up as affecting memory, but they are just 266 // markers, mostly. 267 // 268 // FIXME: We probably don't actually want MemorySSA to model these at all 269 // (including creating MemoryAccesses for them): we just end up inventing 270 // clobbers where they don't really exist at all. Please see D43269 for 271 // context. 272 switch (II->getIntrinsicID()) { 273 case Intrinsic::lifetime_start: 274 if (UseCall) 275 return {false, NoAlias}; 276 AR = AA.alias(MemoryLocation(II->getArgOperand(1)), UseLoc); 277 return {AR != NoAlias, AR}; 278 case Intrinsic::lifetime_end: 279 case Intrinsic::invariant_start: 280 case Intrinsic::invariant_end: 281 case Intrinsic::assume: 282 return {false, NoAlias}; 283 default: 284 break; 285 } 286 } 287 288 if (UseCall) { 289 ModRefInfo I = AA.getModRefInfo(DefInst, UseCall); 290 AR = isMustSet(I) ? MustAlias : MayAlias; 291 return {isModOrRefSet(I), AR}; 292 } 293 294 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) 295 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) 296 return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias}; 297 298 ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc); 299 AR = isMustSet(I) ? MustAlias : MayAlias; 300 return {isModSet(I), AR}; 301 } 302 303 static ClobberAlias instructionClobbersQuery(MemoryDef *MD, 304 const MemoryUseOrDef *MU, 305 const MemoryLocOrCall &UseMLOC, 306 AliasAnalysis &AA) { 307 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery 308 // to exist while MemoryLocOrCall is pushed through places. 309 if (UseMLOC.IsCall) 310 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(), 311 AA); 312 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(), 313 AA); 314 } 315 316 // Return true when MD may alias MU, return false otherwise. 317 bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, 318 AliasAnalysis &AA) { 319 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber; 320 } 321 322 namespace { 323 324 struct UpwardsMemoryQuery { 325 // True if our original query started off as a call 326 bool IsCall = false; 327 // The pointer location we started the query with. This will be empty if 328 // IsCall is true. 329 MemoryLocation StartingLoc; 330 // This is the instruction we were querying about. 331 const Instruction *Inst = nullptr; 332 // The MemoryAccess we actually got called with, used to test local domination 333 const MemoryAccess *OriginalAccess = nullptr; 334 Optional<AliasResult> AR = MayAlias; 335 bool SkipSelfAccess = false; 336 337 UpwardsMemoryQuery() = default; 338 339 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access) 340 : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) { 341 if (!IsCall) 342 StartingLoc = MemoryLocation::get(Inst); 343 } 344 }; 345 346 } // end anonymous namespace 347 348 static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc, 349 AliasAnalysis &AA) { 350 Instruction *Inst = MD->getMemoryInst(); 351 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 352 switch (II->getIntrinsicID()) { 353 case Intrinsic::lifetime_end: 354 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc); 355 default: 356 return false; 357 } 358 } 359 return false; 360 } 361 362 static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA, 363 const Instruction *I) { 364 // If the memory can't be changed, then loads of the memory can't be 365 // clobbered. 366 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) || 367 AA.pointsToConstantMemory(cast<LoadInst>(I)-> 368 getPointerOperand())); 369 } 370 371 /// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing 372 /// inbetween `Start` and `ClobberAt` can clobbers `Start`. 373 /// 374 /// This is meant to be as simple and self-contained as possible. Because it 375 /// uses no cache, etc., it can be relatively expensive. 376 /// 377 /// \param Start The MemoryAccess that we want to walk from. 378 /// \param ClobberAt A clobber for Start. 379 /// \param StartLoc The MemoryLocation for Start. 380 /// \param MSSA The MemorySSA instance that Start and ClobberAt belong to. 381 /// \param Query The UpwardsMemoryQuery we used for our search. 382 /// \param AA The AliasAnalysis we used for our search. 383 /// \param AllowImpreciseClobber Always false, unless we do relaxed verify. 384 static void 385 checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt, 386 const MemoryLocation &StartLoc, const MemorySSA &MSSA, 387 const UpwardsMemoryQuery &Query, AliasAnalysis &AA, 388 bool AllowImpreciseClobber = false) { 389 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?"); 390 391 if (MSSA.isLiveOnEntryDef(Start)) { 392 assert(MSSA.isLiveOnEntryDef(ClobberAt) && 393 "liveOnEntry must clobber itself"); 394 return; 395 } 396 397 bool FoundClobber = false; 398 DenseSet<ConstMemoryAccessPair> VisitedPhis; 399 SmallVector<ConstMemoryAccessPair, 8> Worklist; 400 Worklist.emplace_back(Start, StartLoc); 401 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one 402 // is found, complain. 403 while (!Worklist.empty()) { 404 auto MAP = Worklist.pop_back_val(); 405 // All we care about is that nothing from Start to ClobberAt clobbers Start. 406 // We learn nothing from revisiting nodes. 407 if (!VisitedPhis.insert(MAP).second) 408 continue; 409 410 for (const auto *MA : def_chain(MAP.first)) { 411 if (MA == ClobberAt) { 412 if (const auto *MD = dyn_cast<MemoryDef>(MA)) { 413 // instructionClobbersQuery isn't essentially free, so don't use `|=`, 414 // since it won't let us short-circuit. 415 // 416 // Also, note that this can't be hoisted out of the `Worklist` loop, 417 // since MD may only act as a clobber for 1 of N MemoryLocations. 418 FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD); 419 if (!FoundClobber) { 420 ClobberAlias CA = 421 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA); 422 if (CA.IsClobber) { 423 FoundClobber = true; 424 // Not used: CA.AR; 425 } 426 } 427 } 428 break; 429 } 430 431 // We should never hit liveOnEntry, unless it's the clobber. 432 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?"); 433 434 if (const auto *MD = dyn_cast<MemoryDef>(MA)) { 435 // If Start is a Def, skip self. 436 if (MD == Start) 437 continue; 438 439 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) 440 .IsClobber && 441 "Found clobber before reaching ClobberAt!"); 442 continue; 443 } 444 445 if (const auto *MU = dyn_cast<MemoryUse>(MA)) { 446 (void)MU; 447 assert (MU == Start && 448 "Can only find use in def chain if Start is a use"); 449 continue; 450 } 451 452 assert(isa<MemoryPhi>(MA)); 453 Worklist.append( 454 upward_defs_begin({const_cast<MemoryAccess *>(MA), MAP.second}), 455 upward_defs_end()); 456 } 457 } 458 459 // If the verify is done following an optimization, it's possible that 460 // ClobberAt was a conservative clobbering, that we can now infer is not a 461 // true clobbering access. Don't fail the verify if that's the case. 462 // We do have accesses that claim they're optimized, but could be optimized 463 // further. Updating all these can be expensive, so allow it for now (FIXME). 464 if (AllowImpreciseClobber) 465 return; 466 467 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a 468 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point. 469 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) && 470 "ClobberAt never acted as a clobber"); 471 } 472 473 namespace { 474 475 /// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up 476 /// in one class. 477 class ClobberWalker { 478 /// Save a few bytes by using unsigned instead of size_t. 479 using ListIndex = unsigned; 480 481 /// Represents a span of contiguous MemoryDefs, potentially ending in a 482 /// MemoryPhi. 483 struct DefPath { 484 MemoryLocation Loc; 485 // Note that, because we always walk in reverse, Last will always dominate 486 // First. Also note that First and Last are inclusive. 487 MemoryAccess *First; 488 MemoryAccess *Last; 489 Optional<ListIndex> Previous; 490 491 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last, 492 Optional<ListIndex> Previous) 493 : Loc(Loc), First(First), Last(Last), Previous(Previous) {} 494 495 DefPath(const MemoryLocation &Loc, MemoryAccess *Init, 496 Optional<ListIndex> Previous) 497 : DefPath(Loc, Init, Init, Previous) {} 498 }; 499 500 const MemorySSA &MSSA; 501 AliasAnalysis &AA; 502 DominatorTree &DT; 503 UpwardsMemoryQuery *Query; 504 505 // Phi optimization bookkeeping 506 SmallVector<DefPath, 32> Paths; 507 DenseSet<ConstMemoryAccessPair> VisitedPhis; 508 509 /// Find the nearest def or phi that `From` can legally be optimized to. 510 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const { 511 assert(From->getNumOperands() && "Phi with no operands?"); 512 513 BasicBlock *BB = From->getBlock(); 514 MemoryAccess *Result = MSSA.getLiveOnEntryDef(); 515 DomTreeNode *Node = DT.getNode(BB); 516 while ((Node = Node->getIDom())) { 517 auto *Defs = MSSA.getBlockDefs(Node->getBlock()); 518 if (Defs) 519 return &*Defs->rbegin(); 520 } 521 return Result; 522 } 523 524 /// Result of calling walkToPhiOrClobber. 525 struct UpwardsWalkResult { 526 /// The "Result" of the walk. Either a clobber, the last thing we walked, or 527 /// both. Include alias info when clobber found. 528 MemoryAccess *Result; 529 bool IsKnownClobber; 530 Optional<AliasResult> AR; 531 }; 532 533 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last. 534 /// This will update Desc.Last as it walks. It will (optionally) also stop at 535 /// StopAt. 536 /// 537 /// This does not test for whether StopAt is a clobber 538 UpwardsWalkResult 539 walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr, 540 const MemoryAccess *SkipStopAt = nullptr) const { 541 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world"); 542 543 for (MemoryAccess *Current : def_chain(Desc.Last)) { 544 Desc.Last = Current; 545 if (Current == StopAt || Current == SkipStopAt) 546 return {Current, false, MayAlias}; 547 548 if (auto *MD = dyn_cast<MemoryDef>(Current)) { 549 if (MSSA.isLiveOnEntryDef(MD)) 550 return {MD, true, MustAlias}; 551 ClobberAlias CA = 552 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA); 553 if (CA.IsClobber) 554 return {MD, true, CA.AR}; 555 } 556 } 557 558 assert(isa<MemoryPhi>(Desc.Last) && 559 "Ended at a non-clobber that's not a phi?"); 560 return {Desc.Last, false, MayAlias}; 561 } 562 563 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches, 564 ListIndex PriorNode) { 565 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}), 566 upward_defs_end()); 567 for (const MemoryAccessPair &P : UpwardDefs) { 568 PausedSearches.push_back(Paths.size()); 569 Paths.emplace_back(P.second, P.first, PriorNode); 570 } 571 } 572 573 /// Represents a search that terminated after finding a clobber. This clobber 574 /// may or may not be present in the path of defs from LastNode..SearchStart, 575 /// since it may have been retrieved from cache. 576 struct TerminatedPath { 577 MemoryAccess *Clobber; 578 ListIndex LastNode; 579 }; 580 581 /// Get an access that keeps us from optimizing to the given phi. 582 /// 583 /// PausedSearches is an array of indices into the Paths array. Its incoming 584 /// value is the indices of searches that stopped at the last phi optimization 585 /// target. It's left in an unspecified state. 586 /// 587 /// If this returns None, NewPaused is a vector of searches that terminated 588 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state. 589 Optional<TerminatedPath> 590 getBlockingAccess(const MemoryAccess *StopWhere, 591 SmallVectorImpl<ListIndex> &PausedSearches, 592 SmallVectorImpl<ListIndex> &NewPaused, 593 SmallVectorImpl<TerminatedPath> &Terminated) { 594 assert(!PausedSearches.empty() && "No searches to continue?"); 595 596 // BFS vs DFS really doesn't make a difference here, so just do a DFS with 597 // PausedSearches as our stack. 598 while (!PausedSearches.empty()) { 599 ListIndex PathIndex = PausedSearches.pop_back_val(); 600 DefPath &Node = Paths[PathIndex]; 601 602 // If we've already visited this path with this MemoryLocation, we don't 603 // need to do so again. 604 // 605 // NOTE: That we just drop these paths on the ground makes caching 606 // behavior sporadic. e.g. given a diamond: 607 // A 608 // B C 609 // D 610 // 611 // ...If we walk D, B, A, C, we'll only cache the result of phi 612 // optimization for A, B, and D; C will be skipped because it dies here. 613 // This arguably isn't the worst thing ever, since: 614 // - We generally query things in a top-down order, so if we got below D 615 // without needing cache entries for {C, MemLoc}, then chances are 616 // that those cache entries would end up ultimately unused. 617 // - We still cache things for A, so C only needs to walk up a bit. 618 // If this behavior becomes problematic, we can fix without a ton of extra 619 // work. 620 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second) 621 continue; 622 623 const MemoryAccess *SkipStopWhere = nullptr; 624 if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) { 625 assert(isa<MemoryDef>(Query->OriginalAccess)); 626 SkipStopWhere = Query->OriginalAccess; 627 } 628 629 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere, 630 /*SkipStopAt=*/SkipStopWhere); 631 if (Res.IsKnownClobber) { 632 assert(Res.Result != StopWhere && Res.Result != SkipStopWhere); 633 // If this wasn't a cache hit, we hit a clobber when walking. That's a 634 // failure. 635 TerminatedPath Term{Res.Result, PathIndex}; 636 if (!MSSA.dominates(Res.Result, StopWhere)) 637 return Term; 638 639 // Otherwise, it's a valid thing to potentially optimize to. 640 Terminated.push_back(Term); 641 continue; 642 } 643 644 if (Res.Result == StopWhere || Res.Result == SkipStopWhere) { 645 // We've hit our target. Save this path off for if we want to continue 646 // walking. If we are in the mode of skipping the OriginalAccess, and 647 // we've reached back to the OriginalAccess, do not save path, we've 648 // just looped back to self. 649 if (Res.Result != SkipStopWhere) 650 NewPaused.push_back(PathIndex); 651 continue; 652 } 653 654 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber"); 655 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex); 656 } 657 658 return None; 659 } 660 661 template <typename T, typename Walker> 662 struct generic_def_path_iterator 663 : public iterator_facade_base<generic_def_path_iterator<T, Walker>, 664 std::forward_iterator_tag, T *> { 665 generic_def_path_iterator() = default; 666 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {} 667 668 T &operator*() const { return curNode(); } 669 670 generic_def_path_iterator &operator++() { 671 N = curNode().Previous; 672 return *this; 673 } 674 675 bool operator==(const generic_def_path_iterator &O) const { 676 if (N.hasValue() != O.N.hasValue()) 677 return false; 678 return !N.hasValue() || *N == *O.N; 679 } 680 681 private: 682 T &curNode() const { return W->Paths[*N]; } 683 684 Walker *W = nullptr; 685 Optional<ListIndex> N = None; 686 }; 687 688 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>; 689 using const_def_path_iterator = 690 generic_def_path_iterator<const DefPath, const ClobberWalker>; 691 692 iterator_range<def_path_iterator> def_path(ListIndex From) { 693 return make_range(def_path_iterator(this, From), def_path_iterator()); 694 } 695 696 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const { 697 return make_range(const_def_path_iterator(this, From), 698 const_def_path_iterator()); 699 } 700 701 struct OptznResult { 702 /// The path that contains our result. 703 TerminatedPath PrimaryClobber; 704 /// The paths that we can legally cache back from, but that aren't 705 /// necessarily the result of the Phi optimization. 706 SmallVector<TerminatedPath, 4> OtherClobbers; 707 }; 708 709 ListIndex defPathIndex(const DefPath &N) const { 710 // The assert looks nicer if we don't need to do &N 711 const DefPath *NP = &N; 712 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() && 713 "Out of bounds DefPath!"); 714 return NP - &Paths.front(); 715 } 716 717 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths 718 /// that act as legal clobbers. Note that this won't return *all* clobbers. 719 /// 720 /// Phi optimization algorithm tl;dr: 721 /// - Find the earliest def/phi, A, we can optimize to 722 /// - Find if all paths from the starting memory access ultimately reach A 723 /// - If not, optimization isn't possible. 724 /// - Otherwise, walk from A to another clobber or phi, A'. 725 /// - If A' is a def, we're done. 726 /// - If A' is a phi, try to optimize it. 727 /// 728 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path 729 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found. 730 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start, 731 const MemoryLocation &Loc) { 732 assert(Paths.empty() && VisitedPhis.empty() && 733 "Reset the optimization state."); 734 735 Paths.emplace_back(Loc, Start, Phi, None); 736 // Stores how many "valid" optimization nodes we had prior to calling 737 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker. 738 auto PriorPathsSize = Paths.size(); 739 740 SmallVector<ListIndex, 16> PausedSearches; 741 SmallVector<ListIndex, 8> NewPaused; 742 SmallVector<TerminatedPath, 4> TerminatedPaths; 743 744 addSearches(Phi, PausedSearches, 0); 745 746 // Moves the TerminatedPath with the "most dominated" Clobber to the end of 747 // Paths. 748 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) { 749 assert(!Paths.empty() && "Need a path to move"); 750 auto Dom = Paths.begin(); 751 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I) 752 if (!MSSA.dominates(I->Clobber, Dom->Clobber)) 753 Dom = I; 754 auto Last = Paths.end() - 1; 755 if (Last != Dom) 756 std::iter_swap(Last, Dom); 757 }; 758 759 MemoryPhi *Current = Phi; 760 while (true) { 761 assert(!MSSA.isLiveOnEntryDef(Current) && 762 "liveOnEntry wasn't treated as a clobber?"); 763 764 const auto *Target = getWalkTarget(Current); 765 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal 766 // optimization for the prior phi. 767 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) { 768 return MSSA.dominates(P.Clobber, Target); 769 })); 770 771 // FIXME: This is broken, because the Blocker may be reported to be 772 // liveOnEntry, and we'll happily wait for that to disappear (read: never) 773 // For the moment, this is fine, since we do nothing with blocker info. 774 if (Optional<TerminatedPath> Blocker = getBlockingAccess( 775 Target, PausedSearches, NewPaused, TerminatedPaths)) { 776 777 // Find the node we started at. We can't search based on N->Last, since 778 // we may have gone around a loop with a different MemoryLocation. 779 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) { 780 return defPathIndex(N) < PriorPathsSize; 781 }); 782 assert(Iter != def_path_iterator()); 783 784 DefPath &CurNode = *Iter; 785 assert(CurNode.Last == Current); 786 787 // Two things: 788 // A. We can't reliably cache all of NewPaused back. Consider a case 789 // where we have two paths in NewPaused; one of which can't optimize 790 // above this phi, whereas the other can. If we cache the second path 791 // back, we'll end up with suboptimal cache entries. We can handle 792 // cases like this a bit better when we either try to find all 793 // clobbers that block phi optimization, or when our cache starts 794 // supporting unfinished searches. 795 // B. We can't reliably cache TerminatedPaths back here without doing 796 // extra checks; consider a case like: 797 // T 798 // / \ 799 // D C 800 // \ / 801 // S 802 // Where T is our target, C is a node with a clobber on it, D is a 803 // diamond (with a clobber *only* on the left or right node, N), and 804 // S is our start. Say we walk to D, through the node opposite N 805 // (read: ignoring the clobber), and see a cache entry in the top 806 // node of D. That cache entry gets put into TerminatedPaths. We then 807 // walk up to C (N is later in our worklist), find the clobber, and 808 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache 809 // the bottom part of D to the cached clobber, ignoring the clobber 810 // in N. Again, this problem goes away if we start tracking all 811 // blockers for a given phi optimization. 812 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)}; 813 return {Result, {}}; 814 } 815 816 // If there's nothing left to search, then all paths led to valid clobbers 817 // that we got from our cache; pick the nearest to the start, and allow 818 // the rest to be cached back. 819 if (NewPaused.empty()) { 820 MoveDominatedPathToEnd(TerminatedPaths); 821 TerminatedPath Result = TerminatedPaths.pop_back_val(); 822 return {Result, std::move(TerminatedPaths)}; 823 } 824 825 MemoryAccess *DefChainEnd = nullptr; 826 SmallVector<TerminatedPath, 4> Clobbers; 827 for (ListIndex Paused : NewPaused) { 828 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]); 829 if (WR.IsKnownClobber) 830 Clobbers.push_back({WR.Result, Paused}); 831 else 832 // Micro-opt: If we hit the end of the chain, save it. 833 DefChainEnd = WR.Result; 834 } 835 836 if (!TerminatedPaths.empty()) { 837 // If we couldn't find the dominating phi/liveOnEntry in the above loop, 838 // do it now. 839 if (!DefChainEnd) 840 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target))) 841 DefChainEnd = MA; 842 843 // If any of the terminated paths don't dominate the phi we'll try to 844 // optimize, we need to figure out what they are and quit. 845 const BasicBlock *ChainBB = DefChainEnd->getBlock(); 846 for (const TerminatedPath &TP : TerminatedPaths) { 847 // Because we know that DefChainEnd is as "high" as we can go, we 848 // don't need local dominance checks; BB dominance is sufficient. 849 if (DT.dominates(ChainBB, TP.Clobber->getBlock())) 850 Clobbers.push_back(TP); 851 } 852 } 853 854 // If we have clobbers in the def chain, find the one closest to Current 855 // and quit. 856 if (!Clobbers.empty()) { 857 MoveDominatedPathToEnd(Clobbers); 858 TerminatedPath Result = Clobbers.pop_back_val(); 859 return {Result, std::move(Clobbers)}; 860 } 861 862 assert(all_of(NewPaused, 863 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; })); 864 865 // Because liveOnEntry is a clobber, this must be a phi. 866 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd); 867 868 PriorPathsSize = Paths.size(); 869 PausedSearches.clear(); 870 for (ListIndex I : NewPaused) 871 addSearches(DefChainPhi, PausedSearches, I); 872 NewPaused.clear(); 873 874 Current = DefChainPhi; 875 } 876 } 877 878 void verifyOptResult(const OptznResult &R) const { 879 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) { 880 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber); 881 })); 882 } 883 884 void resetPhiOptznState() { 885 Paths.clear(); 886 VisitedPhis.clear(); 887 } 888 889 public: 890 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT) 891 : MSSA(MSSA), AA(AA), DT(DT) {} 892 893 /// Finds the nearest clobber for the given query, optimizing phis if 894 /// possible. 895 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q) { 896 Query = &Q; 897 898 MemoryAccess *Current = Start; 899 // This walker pretends uses don't exist. If we're handed one, silently grab 900 // its def. (This has the nice side-effect of ensuring we never cache uses) 901 if (auto *MU = dyn_cast<MemoryUse>(Start)) 902 Current = MU->getDefiningAccess(); 903 904 DefPath FirstDesc(Q.StartingLoc, Current, Current, None); 905 // Fast path for the overly-common case (no crazy phi optimization 906 // necessary) 907 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc); 908 MemoryAccess *Result; 909 if (WalkResult.IsKnownClobber) { 910 Result = WalkResult.Result; 911 Q.AR = WalkResult.AR; 912 } else { 913 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last), 914 Current, Q.StartingLoc); 915 verifyOptResult(OptRes); 916 resetPhiOptznState(); 917 Result = OptRes.PrimaryClobber.Clobber; 918 } 919 920 #ifdef EXPENSIVE_CHECKS 921 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA); 922 #endif 923 return Result; 924 } 925 926 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); } 927 }; 928 929 struct RenamePassData { 930 DomTreeNode *DTN; 931 DomTreeNode::const_iterator ChildIt; 932 MemoryAccess *IncomingVal; 933 934 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It, 935 MemoryAccess *M) 936 : DTN(D), ChildIt(It), IncomingVal(M) {} 937 938 void swap(RenamePassData &RHS) { 939 std::swap(DTN, RHS.DTN); 940 std::swap(ChildIt, RHS.ChildIt); 941 std::swap(IncomingVal, RHS.IncomingVal); 942 } 943 }; 944 945 } // end anonymous namespace 946 947 namespace llvm { 948 949 class MemorySSA::ClobberWalkerBase { 950 ClobberWalker Walker; 951 MemorySSA *MSSA; 952 953 public: 954 ClobberWalkerBase(MemorySSA *M, AliasAnalysis *A, DominatorTree *D) 955 : Walker(*M, *A, *D), MSSA(M) {} 956 957 MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, 958 const MemoryLocation &); 959 // Second argument (bool), defines whether the clobber search should skip the 960 // original queried access. If true, there will be a follow-up query searching 961 // for a clobber access past "self". Note that the Optimized access is not 962 // updated if a new clobber is found by this SkipSelf search. If this 963 // additional query becomes heavily used we may decide to cache the result. 964 // Walker instantiations will decide how to set the SkipSelf bool. 965 MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, bool); 966 void verify(const MemorySSA *MSSA) { Walker.verify(MSSA); } 967 }; 968 969 /// A MemorySSAWalker that does AA walks to disambiguate accesses. It no 970 /// longer does caching on its own, but the name has been retained for the 971 /// moment. 972 class MemorySSA::CachingWalker final : public MemorySSAWalker { 973 ClobberWalkerBase *Walker; 974 975 public: 976 CachingWalker(MemorySSA *M, ClobberWalkerBase *W) 977 : MemorySSAWalker(M), Walker(W) {} 978 ~CachingWalker() override = default; 979 980 using MemorySSAWalker::getClobberingMemoryAccess; 981 982 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override; 983 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, 984 const MemoryLocation &Loc) override; 985 986 void invalidateInfo(MemoryAccess *MA) override { 987 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) 988 MUD->resetOptimized(); 989 } 990 991 void verify(const MemorySSA *MSSA) override { 992 MemorySSAWalker::verify(MSSA); 993 Walker->verify(MSSA); 994 } 995 }; 996 997 class MemorySSA::SkipSelfWalker final : public MemorySSAWalker { 998 ClobberWalkerBase *Walker; 999 1000 public: 1001 SkipSelfWalker(MemorySSA *M, ClobberWalkerBase *W) 1002 : MemorySSAWalker(M), Walker(W) {} 1003 ~SkipSelfWalker() override = default; 1004 1005 using MemorySSAWalker::getClobberingMemoryAccess; 1006 1007 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override; 1008 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, 1009 const MemoryLocation &Loc) override; 1010 1011 void invalidateInfo(MemoryAccess *MA) override { 1012 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) 1013 MUD->resetOptimized(); 1014 } 1015 1016 void verify(const MemorySSA *MSSA) override { 1017 MemorySSAWalker::verify(MSSA); 1018 Walker->verify(MSSA); 1019 } 1020 }; 1021 1022 } // end namespace llvm 1023 1024 void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal, 1025 bool RenameAllUses) { 1026 // Pass through values to our successors 1027 for (const BasicBlock *S : successors(BB)) { 1028 auto It = PerBlockAccesses.find(S); 1029 // Rename the phi nodes in our successor block 1030 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front())) 1031 continue; 1032 AccessList *Accesses = It->second.get(); 1033 auto *Phi = cast<MemoryPhi>(&Accesses->front()); 1034 if (RenameAllUses) { 1035 int PhiIndex = Phi->getBasicBlockIndex(BB); 1036 assert(PhiIndex != -1 && "Incomplete phi during partial rename"); 1037 Phi->setIncomingValue(PhiIndex, IncomingVal); 1038 } else 1039 Phi->addIncoming(IncomingVal, BB); 1040 } 1041 } 1042 1043 /// Rename a single basic block into MemorySSA form. 1044 /// Uses the standard SSA renaming algorithm. 1045 /// \returns The new incoming value. 1046 MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal, 1047 bool RenameAllUses) { 1048 auto It = PerBlockAccesses.find(BB); 1049 // Skip most processing if the list is empty. 1050 if (It != PerBlockAccesses.end()) { 1051 AccessList *Accesses = It->second.get(); 1052 for (MemoryAccess &L : *Accesses) { 1053 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) { 1054 if (MUD->getDefiningAccess() == nullptr || RenameAllUses) 1055 MUD->setDefiningAccess(IncomingVal); 1056 if (isa<MemoryDef>(&L)) 1057 IncomingVal = &L; 1058 } else { 1059 IncomingVal = &L; 1060 } 1061 } 1062 } 1063 return IncomingVal; 1064 } 1065 1066 /// This is the standard SSA renaming algorithm. 1067 /// 1068 /// We walk the dominator tree in preorder, renaming accesses, and then filling 1069 /// in phi nodes in our successors. 1070 void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal, 1071 SmallPtrSetImpl<BasicBlock *> &Visited, 1072 bool SkipVisited, bool RenameAllUses) { 1073 SmallVector<RenamePassData, 32> WorkStack; 1074 // Skip everything if we already renamed this block and we are skipping. 1075 // Note: You can't sink this into the if, because we need it to occur 1076 // regardless of whether we skip blocks or not. 1077 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second; 1078 if (SkipVisited && AlreadyVisited) 1079 return; 1080 1081 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses); 1082 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses); 1083 WorkStack.push_back({Root, Root->begin(), IncomingVal}); 1084 1085 while (!WorkStack.empty()) { 1086 DomTreeNode *Node = WorkStack.back().DTN; 1087 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt; 1088 IncomingVal = WorkStack.back().IncomingVal; 1089 1090 if (ChildIt == Node->end()) { 1091 WorkStack.pop_back(); 1092 } else { 1093 DomTreeNode *Child = *ChildIt; 1094 ++WorkStack.back().ChildIt; 1095 BasicBlock *BB = Child->getBlock(); 1096 // Note: You can't sink this into the if, because we need it to occur 1097 // regardless of whether we skip blocks or not. 1098 AlreadyVisited = !Visited.insert(BB).second; 1099 if (SkipVisited && AlreadyVisited) { 1100 // We already visited this during our renaming, which can happen when 1101 // being asked to rename multiple blocks. Figure out the incoming val, 1102 // which is the last def. 1103 // Incoming value can only change if there is a block def, and in that 1104 // case, it's the last block def in the list. 1105 if (auto *BlockDefs = getWritableBlockDefs(BB)) 1106 IncomingVal = &*BlockDefs->rbegin(); 1107 } else 1108 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses); 1109 renameSuccessorPhis(BB, IncomingVal, RenameAllUses); 1110 WorkStack.push_back({Child, Child->begin(), IncomingVal}); 1111 } 1112 } 1113 } 1114 1115 /// This handles unreachable block accesses by deleting phi nodes in 1116 /// unreachable blocks, and marking all other unreachable MemoryAccess's as 1117 /// being uses of the live on entry definition. 1118 void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) { 1119 assert(!DT->isReachableFromEntry(BB) && 1120 "Reachable block found while handling unreachable blocks"); 1121 1122 // Make sure phi nodes in our reachable successors end up with a 1123 // LiveOnEntryDef for our incoming edge, even though our block is forward 1124 // unreachable. We could just disconnect these blocks from the CFG fully, 1125 // but we do not right now. 1126 for (const BasicBlock *S : successors(BB)) { 1127 if (!DT->isReachableFromEntry(S)) 1128 continue; 1129 auto It = PerBlockAccesses.find(S); 1130 // Rename the phi nodes in our successor block 1131 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front())) 1132 continue; 1133 AccessList *Accesses = It->second.get(); 1134 auto *Phi = cast<MemoryPhi>(&Accesses->front()); 1135 Phi->addIncoming(LiveOnEntryDef.get(), BB); 1136 } 1137 1138 auto It = PerBlockAccesses.find(BB); 1139 if (It == PerBlockAccesses.end()) 1140 return; 1141 1142 auto &Accesses = It->second; 1143 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) { 1144 auto Next = std::next(AI); 1145 // If we have a phi, just remove it. We are going to replace all 1146 // users with live on entry. 1147 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI)) 1148 UseOrDef->setDefiningAccess(LiveOnEntryDef.get()); 1149 else 1150 Accesses->erase(AI); 1151 AI = Next; 1152 } 1153 } 1154 1155 MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT) 1156 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr), 1157 SkipWalker(nullptr), NextID(0) { 1158 buildMemorySSA(); 1159 } 1160 1161 MemorySSA::~MemorySSA() { 1162 // Drop all our references 1163 for (const auto &Pair : PerBlockAccesses) 1164 for (MemoryAccess &MA : *Pair.second) 1165 MA.dropAllReferences(); 1166 } 1167 1168 MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) { 1169 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr)); 1170 1171 if (Res.second) 1172 Res.first->second = llvm::make_unique<AccessList>(); 1173 return Res.first->second.get(); 1174 } 1175 1176 MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) { 1177 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr)); 1178 1179 if (Res.second) 1180 Res.first->second = llvm::make_unique<DefsList>(); 1181 return Res.first->second.get(); 1182 } 1183 1184 namespace llvm { 1185 1186 /// This class is a batch walker of all MemoryUse's in the program, and points 1187 /// their defining access at the thing that actually clobbers them. Because it 1188 /// is a batch walker that touches everything, it does not operate like the 1189 /// other walkers. This walker is basically performing a top-down SSA renaming 1190 /// pass, where the version stack is used as the cache. This enables it to be 1191 /// significantly more time and memory efficient than using the regular walker, 1192 /// which is walking bottom-up. 1193 class MemorySSA::OptimizeUses { 1194 public: 1195 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA, 1196 DominatorTree *DT) 1197 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) { 1198 Walker = MSSA->getWalker(); 1199 } 1200 1201 void optimizeUses(); 1202 1203 private: 1204 /// This represents where a given memorylocation is in the stack. 1205 struct MemlocStackInfo { 1206 // This essentially is keeping track of versions of the stack. Whenever 1207 // the stack changes due to pushes or pops, these versions increase. 1208 unsigned long StackEpoch; 1209 unsigned long PopEpoch; 1210 // This is the lower bound of places on the stack to check. It is equal to 1211 // the place the last stack walk ended. 1212 // Note: Correctness depends on this being initialized to 0, which densemap 1213 // does 1214 unsigned long LowerBound; 1215 const BasicBlock *LowerBoundBlock; 1216 // This is where the last walk for this memory location ended. 1217 unsigned long LastKill; 1218 bool LastKillValid; 1219 Optional<AliasResult> AR; 1220 }; 1221 1222 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &, 1223 SmallVectorImpl<MemoryAccess *> &, 1224 DenseMap<MemoryLocOrCall, MemlocStackInfo> &); 1225 1226 MemorySSA *MSSA; 1227 MemorySSAWalker *Walker; 1228 AliasAnalysis *AA; 1229 DominatorTree *DT; 1230 }; 1231 1232 } // end namespace llvm 1233 1234 /// Optimize the uses in a given block This is basically the SSA renaming 1235 /// algorithm, with one caveat: We are able to use a single stack for all 1236 /// MemoryUses. This is because the set of *possible* reaching MemoryDefs is 1237 /// the same for every MemoryUse. The *actual* clobbering MemoryDef is just 1238 /// going to be some position in that stack of possible ones. 1239 /// 1240 /// We track the stack positions that each MemoryLocation needs 1241 /// to check, and last ended at. This is because we only want to check the 1242 /// things that changed since last time. The same MemoryLocation should 1243 /// get clobbered by the same store (getModRefInfo does not use invariantness or 1244 /// things like this, and if they start, we can modify MemoryLocOrCall to 1245 /// include relevant data) 1246 void MemorySSA::OptimizeUses::optimizeUsesInBlock( 1247 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch, 1248 SmallVectorImpl<MemoryAccess *> &VersionStack, 1249 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) { 1250 1251 /// If no accesses, nothing to do. 1252 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB); 1253 if (Accesses == nullptr) 1254 return; 1255 1256 // Pop everything that doesn't dominate the current block off the stack, 1257 // increment the PopEpoch to account for this. 1258 while (true) { 1259 assert( 1260 !VersionStack.empty() && 1261 "Version stack should have liveOnEntry sentinel dominating everything"); 1262 BasicBlock *BackBlock = VersionStack.back()->getBlock(); 1263 if (DT->dominates(BackBlock, BB)) 1264 break; 1265 while (VersionStack.back()->getBlock() == BackBlock) 1266 VersionStack.pop_back(); 1267 ++PopEpoch; 1268 } 1269 1270 for (MemoryAccess &MA : *Accesses) { 1271 auto *MU = dyn_cast<MemoryUse>(&MA); 1272 if (!MU) { 1273 VersionStack.push_back(&MA); 1274 ++StackEpoch; 1275 continue; 1276 } 1277 1278 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) { 1279 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true, None); 1280 continue; 1281 } 1282 1283 MemoryLocOrCall UseMLOC(MU); 1284 auto &LocInfo = LocStackInfo[UseMLOC]; 1285 // If the pop epoch changed, it means we've removed stuff from top of 1286 // stack due to changing blocks. We may have to reset the lower bound or 1287 // last kill info. 1288 if (LocInfo.PopEpoch != PopEpoch) { 1289 LocInfo.PopEpoch = PopEpoch; 1290 LocInfo.StackEpoch = StackEpoch; 1291 // If the lower bound was in something that no longer dominates us, we 1292 // have to reset it. 1293 // We can't simply track stack size, because the stack may have had 1294 // pushes/pops in the meantime. 1295 // XXX: This is non-optimal, but only is slower cases with heavily 1296 // branching dominator trees. To get the optimal number of queries would 1297 // be to make lowerbound and lastkill a per-loc stack, and pop it until 1298 // the top of that stack dominates us. This does not seem worth it ATM. 1299 // A much cheaper optimization would be to always explore the deepest 1300 // branch of the dominator tree first. This will guarantee this resets on 1301 // the smallest set of blocks. 1302 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB && 1303 !DT->dominates(LocInfo.LowerBoundBlock, BB)) { 1304 // Reset the lower bound of things to check. 1305 // TODO: Some day we should be able to reset to last kill, rather than 1306 // 0. 1307 LocInfo.LowerBound = 0; 1308 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock(); 1309 LocInfo.LastKillValid = false; 1310 } 1311 } else if (LocInfo.StackEpoch != StackEpoch) { 1312 // If all that has changed is the StackEpoch, we only have to check the 1313 // new things on the stack, because we've checked everything before. In 1314 // this case, the lower bound of things to check remains the same. 1315 LocInfo.PopEpoch = PopEpoch; 1316 LocInfo.StackEpoch = StackEpoch; 1317 } 1318 if (!LocInfo.LastKillValid) { 1319 LocInfo.LastKill = VersionStack.size() - 1; 1320 LocInfo.LastKillValid = true; 1321 LocInfo.AR = MayAlias; 1322 } 1323 1324 // At this point, we should have corrected last kill and LowerBound to be 1325 // in bounds. 1326 assert(LocInfo.LowerBound < VersionStack.size() && 1327 "Lower bound out of range"); 1328 assert(LocInfo.LastKill < VersionStack.size() && 1329 "Last kill info out of range"); 1330 // In any case, the new upper bound is the top of the stack. 1331 unsigned long UpperBound = VersionStack.size() - 1; 1332 1333 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) { 1334 LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " (" 1335 << *(MU->getMemoryInst()) << ")" 1336 << " because there are " 1337 << UpperBound - LocInfo.LowerBound 1338 << " stores to disambiguate\n"); 1339 // Because we did not walk, LastKill is no longer valid, as this may 1340 // have been a kill. 1341 LocInfo.LastKillValid = false; 1342 continue; 1343 } 1344 bool FoundClobberResult = false; 1345 while (UpperBound > LocInfo.LowerBound) { 1346 if (isa<MemoryPhi>(VersionStack[UpperBound])) { 1347 // For phis, use the walker, see where we ended up, go there 1348 Instruction *UseInst = MU->getMemoryInst(); 1349 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst); 1350 // We are guaranteed to find it or something is wrong 1351 while (VersionStack[UpperBound] != Result) { 1352 assert(UpperBound != 0); 1353 --UpperBound; 1354 } 1355 FoundClobberResult = true; 1356 break; 1357 } 1358 1359 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]); 1360 // If the lifetime of the pointer ends at this instruction, it's live on 1361 // entry. 1362 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) { 1363 // Reset UpperBound to liveOnEntryDef's place in the stack 1364 UpperBound = 0; 1365 FoundClobberResult = true; 1366 LocInfo.AR = MustAlias; 1367 break; 1368 } 1369 ClobberAlias CA = instructionClobbersQuery(MD, MU, UseMLOC, *AA); 1370 if (CA.IsClobber) { 1371 FoundClobberResult = true; 1372 LocInfo.AR = CA.AR; 1373 break; 1374 } 1375 --UpperBound; 1376 } 1377 1378 // Note: Phis always have AliasResult AR set to MayAlias ATM. 1379 1380 // At the end of this loop, UpperBound is either a clobber, or lower bound 1381 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill. 1382 if (FoundClobberResult || UpperBound < LocInfo.LastKill) { 1383 // We were last killed now by where we got to 1384 if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound])) 1385 LocInfo.AR = None; 1386 MU->setDefiningAccess(VersionStack[UpperBound], true, LocInfo.AR); 1387 LocInfo.LastKill = UpperBound; 1388 } else { 1389 // Otherwise, we checked all the new ones, and now we know we can get to 1390 // LastKill. 1391 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true, LocInfo.AR); 1392 } 1393 LocInfo.LowerBound = VersionStack.size() - 1; 1394 LocInfo.LowerBoundBlock = BB; 1395 } 1396 } 1397 1398 /// Optimize uses to point to their actual clobbering definitions. 1399 void MemorySSA::OptimizeUses::optimizeUses() { 1400 SmallVector<MemoryAccess *, 16> VersionStack; 1401 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo; 1402 VersionStack.push_back(MSSA->getLiveOnEntryDef()); 1403 1404 unsigned long StackEpoch = 1; 1405 unsigned long PopEpoch = 1; 1406 // We perform a non-recursive top-down dominator tree walk. 1407 for (const auto *DomNode : depth_first(DT->getRootNode())) 1408 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack, 1409 LocStackInfo); 1410 } 1411 1412 void MemorySSA::placePHINodes( 1413 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) { 1414 // Determine where our MemoryPhi's should go 1415 ForwardIDFCalculator IDFs(*DT); 1416 IDFs.setDefiningBlocks(DefiningBlocks); 1417 SmallVector<BasicBlock *, 32> IDFBlocks; 1418 IDFs.calculate(IDFBlocks); 1419 1420 // Now place MemoryPhi nodes. 1421 for (auto &BB : IDFBlocks) 1422 createMemoryPhi(BB); 1423 } 1424 1425 void MemorySSA::buildMemorySSA() { 1426 // We create an access to represent "live on entry", for things like 1427 // arguments or users of globals, where the memory they use is defined before 1428 // the beginning of the function. We do not actually insert it into the IR. 1429 // We do not define a live on exit for the immediate uses, and thus our 1430 // semantics do *not* imply that something with no immediate uses can simply 1431 // be removed. 1432 BasicBlock &StartingPoint = F.getEntryBlock(); 1433 LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr, 1434 &StartingPoint, NextID++)); 1435 1436 // We maintain lists of memory accesses per-block, trading memory for time. We 1437 // could just look up the memory access for every possible instruction in the 1438 // stream. 1439 SmallPtrSet<BasicBlock *, 32> DefiningBlocks; 1440 // Go through each block, figure out where defs occur, and chain together all 1441 // the accesses. 1442 for (BasicBlock &B : F) { 1443 bool InsertIntoDef = false; 1444 AccessList *Accesses = nullptr; 1445 DefsList *Defs = nullptr; 1446 for (Instruction &I : B) { 1447 MemoryUseOrDef *MUD = createNewAccess(&I); 1448 if (!MUD) 1449 continue; 1450 1451 if (!Accesses) 1452 Accesses = getOrCreateAccessList(&B); 1453 Accesses->push_back(MUD); 1454 if (isa<MemoryDef>(MUD)) { 1455 InsertIntoDef = true; 1456 if (!Defs) 1457 Defs = getOrCreateDefsList(&B); 1458 Defs->push_back(*MUD); 1459 } 1460 } 1461 if (InsertIntoDef) 1462 DefiningBlocks.insert(&B); 1463 } 1464 placePHINodes(DefiningBlocks); 1465 1466 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get 1467 // filled in with all blocks. 1468 SmallPtrSet<BasicBlock *, 16> Visited; 1469 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited); 1470 1471 CachingWalker *Walker = getWalkerImpl(); 1472 1473 OptimizeUses(this, Walker, AA, DT).optimizeUses(); 1474 1475 // Mark the uses in unreachable blocks as live on entry, so that they go 1476 // somewhere. 1477 for (auto &BB : F) 1478 if (!Visited.count(&BB)) 1479 markUnreachableAsLiveOnEntry(&BB); 1480 } 1481 1482 MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); } 1483 1484 MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() { 1485 if (Walker) 1486 return Walker.get(); 1487 1488 if (!WalkerBase) 1489 WalkerBase = llvm::make_unique<ClobberWalkerBase>(this, AA, DT); 1490 1491 Walker = llvm::make_unique<CachingWalker>(this, WalkerBase.get()); 1492 return Walker.get(); 1493 } 1494 1495 MemorySSAWalker *MemorySSA::getSkipSelfWalker() { 1496 if (SkipWalker) 1497 return SkipWalker.get(); 1498 1499 if (!WalkerBase) 1500 WalkerBase = llvm::make_unique<ClobberWalkerBase>(this, AA, DT); 1501 1502 SkipWalker = llvm::make_unique<SkipSelfWalker>(this, WalkerBase.get()); 1503 return SkipWalker.get(); 1504 } 1505 1506 1507 // This is a helper function used by the creation routines. It places NewAccess 1508 // into the access and defs lists for a given basic block, at the given 1509 // insertion point. 1510 void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess, 1511 const BasicBlock *BB, 1512 InsertionPlace Point) { 1513 auto *Accesses = getOrCreateAccessList(BB); 1514 if (Point == Beginning) { 1515 // If it's a phi node, it goes first, otherwise, it goes after any phi 1516 // nodes. 1517 if (isa<MemoryPhi>(NewAccess)) { 1518 Accesses->push_front(NewAccess); 1519 auto *Defs = getOrCreateDefsList(BB); 1520 Defs->push_front(*NewAccess); 1521 } else { 1522 auto AI = find_if_not( 1523 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); }); 1524 Accesses->insert(AI, NewAccess); 1525 if (!isa<MemoryUse>(NewAccess)) { 1526 auto *Defs = getOrCreateDefsList(BB); 1527 auto DI = find_if_not( 1528 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); }); 1529 Defs->insert(DI, *NewAccess); 1530 } 1531 } 1532 } else { 1533 Accesses->push_back(NewAccess); 1534 if (!isa<MemoryUse>(NewAccess)) { 1535 auto *Defs = getOrCreateDefsList(BB); 1536 Defs->push_back(*NewAccess); 1537 } 1538 } 1539 BlockNumberingValid.erase(BB); 1540 } 1541 1542 void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB, 1543 AccessList::iterator InsertPt) { 1544 auto *Accesses = getWritableBlockAccesses(BB); 1545 bool WasEnd = InsertPt == Accesses->end(); 1546 Accesses->insert(AccessList::iterator(InsertPt), What); 1547 if (!isa<MemoryUse>(What)) { 1548 auto *Defs = getOrCreateDefsList(BB); 1549 // If we got asked to insert at the end, we have an easy job, just shove it 1550 // at the end. If we got asked to insert before an existing def, we also get 1551 // an iterator. If we got asked to insert before a use, we have to hunt for 1552 // the next def. 1553 if (WasEnd) { 1554 Defs->push_back(*What); 1555 } else if (isa<MemoryDef>(InsertPt)) { 1556 Defs->insert(InsertPt->getDefsIterator(), *What); 1557 } else { 1558 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt)) 1559 ++InsertPt; 1560 // Either we found a def, or we are inserting at the end 1561 if (InsertPt == Accesses->end()) 1562 Defs->push_back(*What); 1563 else 1564 Defs->insert(InsertPt->getDefsIterator(), *What); 1565 } 1566 } 1567 BlockNumberingValid.erase(BB); 1568 } 1569 1570 void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) { 1571 // Keep it in the lookup tables, remove from the lists 1572 removeFromLists(What, false); 1573 1574 // Note that moving should implicitly invalidate the optimized state of a 1575 // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a 1576 // MemoryDef. 1577 if (auto *MD = dyn_cast<MemoryDef>(What)) 1578 MD->resetOptimized(); 1579 What->setBlock(BB); 1580 } 1581 1582 // Move What before Where in the IR. The end result is that What will belong to 1583 // the right lists and have the right Block set, but will not otherwise be 1584 // correct. It will not have the right defining access, and if it is a def, 1585 // things below it will not properly be updated. 1586 void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB, 1587 AccessList::iterator Where) { 1588 prepareForMoveTo(What, BB); 1589 insertIntoListsBefore(What, BB, Where); 1590 } 1591 1592 void MemorySSA::moveTo(MemoryAccess *What, BasicBlock *BB, 1593 InsertionPlace Point) { 1594 if (isa<MemoryPhi>(What)) { 1595 assert(Point == Beginning && 1596 "Can only move a Phi at the beginning of the block"); 1597 // Update lookup table entry 1598 ValueToMemoryAccess.erase(What->getBlock()); 1599 bool Inserted = ValueToMemoryAccess.insert({BB, What}).second; 1600 (void)Inserted; 1601 assert(Inserted && "Cannot move a Phi to a block that already has one"); 1602 } 1603 1604 prepareForMoveTo(What, BB); 1605 insertIntoListsForBlock(What, BB, Point); 1606 } 1607 1608 MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) { 1609 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB"); 1610 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++); 1611 // Phi's always are placed at the front of the block. 1612 insertIntoListsForBlock(Phi, BB, Beginning); 1613 ValueToMemoryAccess[BB] = Phi; 1614 return Phi; 1615 } 1616 1617 MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I, 1618 MemoryAccess *Definition, 1619 const MemoryUseOrDef *Template) { 1620 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI"); 1621 MemoryUseOrDef *NewAccess = createNewAccess(I, Template); 1622 assert( 1623 NewAccess != nullptr && 1624 "Tried to create a memory access for a non-memory touching instruction"); 1625 NewAccess->setDefiningAccess(Definition); 1626 return NewAccess; 1627 } 1628 1629 // Return true if the instruction has ordering constraints. 1630 // Note specifically that this only considers stores and loads 1631 // because others are still considered ModRef by getModRefInfo. 1632 static inline bool isOrdered(const Instruction *I) { 1633 if (auto *SI = dyn_cast<StoreInst>(I)) { 1634 if (!SI->isUnordered()) 1635 return true; 1636 } else if (auto *LI = dyn_cast<LoadInst>(I)) { 1637 if (!LI->isUnordered()) 1638 return true; 1639 } 1640 return false; 1641 } 1642 1643 /// Helper function to create new memory accesses 1644 MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I, 1645 const MemoryUseOrDef *Template) { 1646 // The assume intrinsic has a control dependency which we model by claiming 1647 // that it writes arbitrarily. Ignore that fake memory dependency here. 1648 // FIXME: Replace this special casing with a more accurate modelling of 1649 // assume's control dependency. 1650 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 1651 if (II->getIntrinsicID() == Intrinsic::assume) 1652 return nullptr; 1653 1654 bool Def, Use; 1655 if (Template) { 1656 Def = dyn_cast_or_null<MemoryDef>(Template) != nullptr; 1657 Use = dyn_cast_or_null<MemoryUse>(Template) != nullptr; 1658 #if !defined(NDEBUG) 1659 ModRefInfo ModRef = AA->getModRefInfo(I, None); 1660 bool DefCheck, UseCheck; 1661 DefCheck = isModSet(ModRef) || isOrdered(I); 1662 UseCheck = isRefSet(ModRef); 1663 assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template"); 1664 #endif 1665 } else { 1666 // Find out what affect this instruction has on memory. 1667 ModRefInfo ModRef = AA->getModRefInfo(I, None); 1668 // The isOrdered check is used to ensure that volatiles end up as defs 1669 // (atomics end up as ModRef right now anyway). Until we separate the 1670 // ordering chain from the memory chain, this enables people to see at least 1671 // some relative ordering to volatiles. Note that getClobberingMemoryAccess 1672 // will still give an answer that bypasses other volatile loads. TODO: 1673 // Separate memory aliasing and ordering into two different chains so that 1674 // we can precisely represent both "what memory will this read/write/is 1675 // clobbered by" and "what instructions can I move this past". 1676 Def = isModSet(ModRef) || isOrdered(I); 1677 Use = isRefSet(ModRef); 1678 } 1679 1680 // It's possible for an instruction to not modify memory at all. During 1681 // construction, we ignore them. 1682 if (!Def && !Use) 1683 return nullptr; 1684 1685 MemoryUseOrDef *MUD; 1686 if (Def) 1687 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++); 1688 else 1689 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent()); 1690 ValueToMemoryAccess[I] = MUD; 1691 return MUD; 1692 } 1693 1694 /// Returns true if \p Replacer dominates \p Replacee . 1695 bool MemorySSA::dominatesUse(const MemoryAccess *Replacer, 1696 const MemoryAccess *Replacee) const { 1697 if (isa<MemoryUseOrDef>(Replacee)) 1698 return DT->dominates(Replacer->getBlock(), Replacee->getBlock()); 1699 const auto *MP = cast<MemoryPhi>(Replacee); 1700 // For a phi node, the use occurs in the predecessor block of the phi node. 1701 // Since we may occur multiple times in the phi node, we have to check each 1702 // operand to ensure Replacer dominates each operand where Replacee occurs. 1703 for (const Use &Arg : MP->operands()) { 1704 if (Arg.get() != Replacee && 1705 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg))) 1706 return false; 1707 } 1708 return true; 1709 } 1710 1711 /// Properly remove \p MA from all of MemorySSA's lookup tables. 1712 void MemorySSA::removeFromLookups(MemoryAccess *MA) { 1713 assert(MA->use_empty() && 1714 "Trying to remove memory access that still has uses"); 1715 BlockNumbering.erase(MA); 1716 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) 1717 MUD->setDefiningAccess(nullptr); 1718 // Invalidate our walker's cache if necessary 1719 if (!isa<MemoryUse>(MA)) 1720 Walker->invalidateInfo(MA); 1721 1722 Value *MemoryInst; 1723 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) 1724 MemoryInst = MUD->getMemoryInst(); 1725 else 1726 MemoryInst = MA->getBlock(); 1727 1728 auto VMA = ValueToMemoryAccess.find(MemoryInst); 1729 if (VMA->second == MA) 1730 ValueToMemoryAccess.erase(VMA); 1731 } 1732 1733 /// Properly remove \p MA from all of MemorySSA's lists. 1734 /// 1735 /// Because of the way the intrusive list and use lists work, it is important to 1736 /// do removal in the right order. 1737 /// ShouldDelete defaults to true, and will cause the memory access to also be 1738 /// deleted, not just removed. 1739 void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) { 1740 BasicBlock *BB = MA->getBlock(); 1741 // The access list owns the reference, so we erase it from the non-owning list 1742 // first. 1743 if (!isa<MemoryUse>(MA)) { 1744 auto DefsIt = PerBlockDefs.find(BB); 1745 std::unique_ptr<DefsList> &Defs = DefsIt->second; 1746 Defs->remove(*MA); 1747 if (Defs->empty()) 1748 PerBlockDefs.erase(DefsIt); 1749 } 1750 1751 // The erase call here will delete it. If we don't want it deleted, we call 1752 // remove instead. 1753 auto AccessIt = PerBlockAccesses.find(BB); 1754 std::unique_ptr<AccessList> &Accesses = AccessIt->second; 1755 if (ShouldDelete) 1756 Accesses->erase(MA); 1757 else 1758 Accesses->remove(MA); 1759 1760 if (Accesses->empty()) { 1761 PerBlockAccesses.erase(AccessIt); 1762 BlockNumberingValid.erase(BB); 1763 } 1764 } 1765 1766 void MemorySSA::print(raw_ostream &OS) const { 1767 MemorySSAAnnotatedWriter Writer(this); 1768 F.print(OS, &Writer); 1769 } 1770 1771 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1772 LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); } 1773 #endif 1774 1775 void MemorySSA::verifyMemorySSA() const { 1776 verifyDefUses(F); 1777 verifyDomination(F); 1778 verifyOrdering(F); 1779 verifyDominationNumbers(F); 1780 Walker->verify(this); 1781 verifyClobberSanity(F); 1782 } 1783 1784 /// Check sanity of the clobbering instruction for access MA. 1785 void MemorySSA::checkClobberSanityAccess(const MemoryAccess *MA) const { 1786 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) { 1787 if (!MUD->isOptimized()) 1788 return; 1789 auto *I = MUD->getMemoryInst(); 1790 auto Loc = MemoryLocation::getOrNone(I); 1791 if (Loc == None) 1792 return; 1793 auto *Clobber = MUD->getOptimized(); 1794 UpwardsMemoryQuery Q(I, MUD); 1795 checkClobberSanity(MUD, Clobber, *Loc, *this, Q, *AA, true); 1796 } 1797 } 1798 1799 void MemorySSA::verifyClobberSanity(const Function &F) const { 1800 #if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS) 1801 for (const BasicBlock &BB : F) { 1802 const AccessList *Accesses = getBlockAccesses(&BB); 1803 if (!Accesses) 1804 continue; 1805 for (const MemoryAccess &MA : *Accesses) 1806 checkClobberSanityAccess(&MA); 1807 } 1808 #endif 1809 } 1810 1811 /// Verify that all of the blocks we believe to have valid domination numbers 1812 /// actually have valid domination numbers. 1813 void MemorySSA::verifyDominationNumbers(const Function &F) const { 1814 #ifndef NDEBUG 1815 if (BlockNumberingValid.empty()) 1816 return; 1817 1818 SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid; 1819 for (const BasicBlock &BB : F) { 1820 if (!ValidBlocks.count(&BB)) 1821 continue; 1822 1823 ValidBlocks.erase(&BB); 1824 1825 const AccessList *Accesses = getBlockAccesses(&BB); 1826 // It's correct to say an empty block has valid numbering. 1827 if (!Accesses) 1828 continue; 1829 1830 // Block numbering starts at 1. 1831 unsigned long LastNumber = 0; 1832 for (const MemoryAccess &MA : *Accesses) { 1833 auto ThisNumberIter = BlockNumbering.find(&MA); 1834 assert(ThisNumberIter != BlockNumbering.end() && 1835 "MemoryAccess has no domination number in a valid block!"); 1836 1837 unsigned long ThisNumber = ThisNumberIter->second; 1838 assert(ThisNumber > LastNumber && 1839 "Domination numbers should be strictly increasing!"); 1840 LastNumber = ThisNumber; 1841 } 1842 } 1843 1844 assert(ValidBlocks.empty() && 1845 "All valid BasicBlocks should exist in F -- dangling pointers?"); 1846 #endif 1847 } 1848 1849 /// Verify that the order and existence of MemoryAccesses matches the 1850 /// order and existence of memory affecting instructions. 1851 void MemorySSA::verifyOrdering(Function &F) const { 1852 #ifndef NDEBUG 1853 // Walk all the blocks, comparing what the lookups think and what the access 1854 // lists think, as well as the order in the blocks vs the order in the access 1855 // lists. 1856 SmallVector<MemoryAccess *, 32> ActualAccesses; 1857 SmallVector<MemoryAccess *, 32> ActualDefs; 1858 for (BasicBlock &B : F) { 1859 const AccessList *AL = getBlockAccesses(&B); 1860 const auto *DL = getBlockDefs(&B); 1861 MemoryAccess *Phi = getMemoryAccess(&B); 1862 if (Phi) { 1863 ActualAccesses.push_back(Phi); 1864 ActualDefs.push_back(Phi); 1865 } 1866 1867 for (Instruction &I : B) { 1868 MemoryAccess *MA = getMemoryAccess(&I); 1869 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) && 1870 "We have memory affecting instructions " 1871 "in this block but they are not in the " 1872 "access list or defs list"); 1873 if (MA) { 1874 ActualAccesses.push_back(MA); 1875 if (isa<MemoryDef>(MA)) 1876 ActualDefs.push_back(MA); 1877 } 1878 } 1879 // Either we hit the assert, really have no accesses, or we have both 1880 // accesses and an access list. 1881 // Same with defs. 1882 if (!AL && !DL) 1883 continue; 1884 assert(AL->size() == ActualAccesses.size() && 1885 "We don't have the same number of accesses in the block as on the " 1886 "access list"); 1887 assert((DL || ActualDefs.size() == 0) && 1888 "Either we should have a defs list, or we should have no defs"); 1889 assert((!DL || DL->size() == ActualDefs.size()) && 1890 "We don't have the same number of defs in the block as on the " 1891 "def list"); 1892 auto ALI = AL->begin(); 1893 auto AAI = ActualAccesses.begin(); 1894 while (ALI != AL->end() && AAI != ActualAccesses.end()) { 1895 assert(&*ALI == *AAI && "Not the same accesses in the same order"); 1896 ++ALI; 1897 ++AAI; 1898 } 1899 ActualAccesses.clear(); 1900 if (DL) { 1901 auto DLI = DL->begin(); 1902 auto ADI = ActualDefs.begin(); 1903 while (DLI != DL->end() && ADI != ActualDefs.end()) { 1904 assert(&*DLI == *ADI && "Not the same defs in the same order"); 1905 ++DLI; 1906 ++ADI; 1907 } 1908 } 1909 ActualDefs.clear(); 1910 } 1911 #endif 1912 } 1913 1914 /// Verify the domination properties of MemorySSA by checking that each 1915 /// definition dominates all of its uses. 1916 void MemorySSA::verifyDomination(Function &F) const { 1917 #ifndef NDEBUG 1918 for (BasicBlock &B : F) { 1919 // Phi nodes are attached to basic blocks 1920 if (MemoryPhi *MP = getMemoryAccess(&B)) 1921 for (const Use &U : MP->uses()) 1922 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses"); 1923 1924 for (Instruction &I : B) { 1925 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I)); 1926 if (!MD) 1927 continue; 1928 1929 for (const Use &U : MD->uses()) 1930 assert(dominates(MD, U) && "Memory Def does not dominate it's uses"); 1931 } 1932 } 1933 #endif 1934 } 1935 1936 /// Verify the def-use lists in MemorySSA, by verifying that \p Use 1937 /// appears in the use list of \p Def. 1938 void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const { 1939 #ifndef NDEBUG 1940 // The live on entry use may cause us to get a NULL def here 1941 if (!Def) 1942 assert(isLiveOnEntryDef(Use) && 1943 "Null def but use not point to live on entry def"); 1944 else 1945 assert(is_contained(Def->users(), Use) && 1946 "Did not find use in def's use list"); 1947 #endif 1948 } 1949 1950 /// Verify the immediate use information, by walking all the memory 1951 /// accesses and verifying that, for each use, it appears in the 1952 /// appropriate def's use list 1953 void MemorySSA::verifyDefUses(Function &F) const { 1954 #ifndef NDEBUG 1955 for (BasicBlock &B : F) { 1956 // Phi nodes are attached to basic blocks 1957 if (MemoryPhi *Phi = getMemoryAccess(&B)) { 1958 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance( 1959 pred_begin(&B), pred_end(&B))) && 1960 "Incomplete MemoryPhi Node"); 1961 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) { 1962 verifyUseInDefs(Phi->getIncomingValue(I), Phi); 1963 assert(find(predecessors(&B), Phi->getIncomingBlock(I)) != 1964 pred_end(&B) && 1965 "Incoming phi block not a block predecessor"); 1966 } 1967 } 1968 1969 for (Instruction &I : B) { 1970 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) { 1971 verifyUseInDefs(MA->getDefiningAccess(), MA); 1972 } 1973 } 1974 } 1975 #endif 1976 } 1977 1978 /// Perform a local numbering on blocks so that instruction ordering can be 1979 /// determined in constant time. 1980 /// TODO: We currently just number in order. If we numbered by N, we could 1981 /// allow at least N-1 sequences of insertBefore or insertAfter (and at least 1982 /// log2(N) sequences of mixed before and after) without needing to invalidate 1983 /// the numbering. 1984 void MemorySSA::renumberBlock(const BasicBlock *B) const { 1985 // The pre-increment ensures the numbers really start at 1. 1986 unsigned long CurrentNumber = 0; 1987 const AccessList *AL = getBlockAccesses(B); 1988 assert(AL != nullptr && "Asking to renumber an empty block"); 1989 for (const auto &I : *AL) 1990 BlockNumbering[&I] = ++CurrentNumber; 1991 BlockNumberingValid.insert(B); 1992 } 1993 1994 /// Determine, for two memory accesses in the same block, 1995 /// whether \p Dominator dominates \p Dominatee. 1996 /// \returns True if \p Dominator dominates \p Dominatee. 1997 bool MemorySSA::locallyDominates(const MemoryAccess *Dominator, 1998 const MemoryAccess *Dominatee) const { 1999 const BasicBlock *DominatorBlock = Dominator->getBlock(); 2000 2001 assert((DominatorBlock == Dominatee->getBlock()) && 2002 "Asking for local domination when accesses are in different blocks!"); 2003 // A node dominates itself. 2004 if (Dominatee == Dominator) 2005 return true; 2006 2007 // When Dominatee is defined on function entry, it is not dominated by another 2008 // memory access. 2009 if (isLiveOnEntryDef(Dominatee)) 2010 return false; 2011 2012 // When Dominator is defined on function entry, it dominates the other memory 2013 // access. 2014 if (isLiveOnEntryDef(Dominator)) 2015 return true; 2016 2017 if (!BlockNumberingValid.count(DominatorBlock)) 2018 renumberBlock(DominatorBlock); 2019 2020 unsigned long DominatorNum = BlockNumbering.lookup(Dominator); 2021 // All numbers start with 1 2022 assert(DominatorNum != 0 && "Block was not numbered properly"); 2023 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee); 2024 assert(DominateeNum != 0 && "Block was not numbered properly"); 2025 return DominatorNum < DominateeNum; 2026 } 2027 2028 bool MemorySSA::dominates(const MemoryAccess *Dominator, 2029 const MemoryAccess *Dominatee) const { 2030 if (Dominator == Dominatee) 2031 return true; 2032 2033 if (isLiveOnEntryDef(Dominatee)) 2034 return false; 2035 2036 if (Dominator->getBlock() != Dominatee->getBlock()) 2037 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock()); 2038 return locallyDominates(Dominator, Dominatee); 2039 } 2040 2041 bool MemorySSA::dominates(const MemoryAccess *Dominator, 2042 const Use &Dominatee) const { 2043 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) { 2044 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee); 2045 // The def must dominate the incoming block of the phi. 2046 if (UseBB != Dominator->getBlock()) 2047 return DT->dominates(Dominator->getBlock(), UseBB); 2048 // If the UseBB and the DefBB are the same, compare locally. 2049 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee)); 2050 } 2051 // If it's not a PHI node use, the normal dominates can already handle it. 2052 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser())); 2053 } 2054 2055 const static char LiveOnEntryStr[] = "liveOnEntry"; 2056 2057 void MemoryAccess::print(raw_ostream &OS) const { 2058 switch (getValueID()) { 2059 case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS); 2060 case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS); 2061 case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS); 2062 } 2063 llvm_unreachable("invalid value id"); 2064 } 2065 2066 void MemoryDef::print(raw_ostream &OS) const { 2067 MemoryAccess *UO = getDefiningAccess(); 2068 2069 auto printID = [&OS](MemoryAccess *A) { 2070 if (A && A->getID()) 2071 OS << A->getID(); 2072 else 2073 OS << LiveOnEntryStr; 2074 }; 2075 2076 OS << getID() << " = MemoryDef("; 2077 printID(UO); 2078 OS << ")"; 2079 2080 if (isOptimized()) { 2081 OS << "->"; 2082 printID(getOptimized()); 2083 2084 if (Optional<AliasResult> AR = getOptimizedAccessType()) 2085 OS << " " << *AR; 2086 } 2087 } 2088 2089 void MemoryPhi::print(raw_ostream &OS) const { 2090 bool First = true; 2091 OS << getID() << " = MemoryPhi("; 2092 for (const auto &Op : operands()) { 2093 BasicBlock *BB = getIncomingBlock(Op); 2094 MemoryAccess *MA = cast<MemoryAccess>(Op); 2095 if (!First) 2096 OS << ','; 2097 else 2098 First = false; 2099 2100 OS << '{'; 2101 if (BB->hasName()) 2102 OS << BB->getName(); 2103 else 2104 BB->printAsOperand(OS, false); 2105 OS << ','; 2106 if (unsigned ID = MA->getID()) 2107 OS << ID; 2108 else 2109 OS << LiveOnEntryStr; 2110 OS << '}'; 2111 } 2112 OS << ')'; 2113 } 2114 2115 void MemoryUse::print(raw_ostream &OS) const { 2116 MemoryAccess *UO = getDefiningAccess(); 2117 OS << "MemoryUse("; 2118 if (UO && UO->getID()) 2119 OS << UO->getID(); 2120 else 2121 OS << LiveOnEntryStr; 2122 OS << ')'; 2123 2124 if (Optional<AliasResult> AR = getOptimizedAccessType()) 2125 OS << " " << *AR; 2126 } 2127 2128 void MemoryAccess::dump() const { 2129 // Cannot completely remove virtual function even in release mode. 2130 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2131 print(dbgs()); 2132 dbgs() << "\n"; 2133 #endif 2134 } 2135 2136 char MemorySSAPrinterLegacyPass::ID = 0; 2137 2138 MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) { 2139 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry()); 2140 } 2141 2142 void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const { 2143 AU.setPreservesAll(); 2144 AU.addRequired<MemorySSAWrapperPass>(); 2145 } 2146 2147 bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) { 2148 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA(); 2149 MSSA.print(dbgs()); 2150 if (VerifyMemorySSA) 2151 MSSA.verifyMemorySSA(); 2152 return false; 2153 } 2154 2155 AnalysisKey MemorySSAAnalysis::Key; 2156 2157 MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F, 2158 FunctionAnalysisManager &AM) { 2159 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 2160 auto &AA = AM.getResult<AAManager>(F); 2161 return MemorySSAAnalysis::Result(llvm::make_unique<MemorySSA>(F, &AA, &DT)); 2162 } 2163 2164 PreservedAnalyses MemorySSAPrinterPass::run(Function &F, 2165 FunctionAnalysisManager &AM) { 2166 OS << "MemorySSA for function: " << F.getName() << "\n"; 2167 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS); 2168 2169 return PreservedAnalyses::all(); 2170 } 2171 2172 PreservedAnalyses MemorySSAVerifierPass::run(Function &F, 2173 FunctionAnalysisManager &AM) { 2174 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA(); 2175 2176 return PreservedAnalyses::all(); 2177 } 2178 2179 char MemorySSAWrapperPass::ID = 0; 2180 2181 MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) { 2182 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry()); 2183 } 2184 2185 void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); } 2186 2187 void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 2188 AU.setPreservesAll(); 2189 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 2190 AU.addRequiredTransitive<AAResultsWrapperPass>(); 2191 } 2192 2193 bool MemorySSAWrapperPass::runOnFunction(Function &F) { 2194 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2195 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 2196 MSSA.reset(new MemorySSA(F, &AA, &DT)); 2197 return false; 2198 } 2199 2200 void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); } 2201 2202 void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const { 2203 MSSA->print(OS); 2204 } 2205 2206 MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {} 2207 2208 /// Walk the use-def chains starting at \p StartingAccess and find 2209 /// the MemoryAccess that actually clobbers Loc. 2210 /// 2211 /// \returns our clobbering memory access 2212 MemoryAccess *MemorySSA::ClobberWalkerBase::getClobberingMemoryAccessBase( 2213 MemoryAccess *StartingAccess, const MemoryLocation &Loc) { 2214 if (isa<MemoryPhi>(StartingAccess)) 2215 return StartingAccess; 2216 2217 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess); 2218 if (MSSA->isLiveOnEntryDef(StartingUseOrDef)) 2219 return StartingUseOrDef; 2220 2221 Instruction *I = StartingUseOrDef->getMemoryInst(); 2222 2223 // Conservatively, fences are always clobbers, so don't perform the walk if we 2224 // hit a fence. 2225 if (!isa<CallBase>(I) && I->isFenceLike()) 2226 return StartingUseOrDef; 2227 2228 UpwardsMemoryQuery Q; 2229 Q.OriginalAccess = StartingUseOrDef; 2230 Q.StartingLoc = Loc; 2231 Q.Inst = I; 2232 Q.IsCall = false; 2233 2234 // Unlike the other function, do not walk to the def of a def, because we are 2235 // handed something we already believe is the clobbering access. 2236 // We never set SkipSelf to true in Q in this method. 2237 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef) 2238 ? StartingUseOrDef->getDefiningAccess() 2239 : StartingUseOrDef; 2240 2241 MemoryAccess *Clobber = Walker.findClobber(DefiningAccess, Q); 2242 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is "); 2243 LLVM_DEBUG(dbgs() << *StartingUseOrDef << "\n"); 2244 LLVM_DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is "); 2245 LLVM_DEBUG(dbgs() << *Clobber << "\n"); 2246 return Clobber; 2247 } 2248 2249 MemoryAccess * 2250 MemorySSA::ClobberWalkerBase::getClobberingMemoryAccessBase(MemoryAccess *MA, 2251 bool SkipSelf) { 2252 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA); 2253 // If this is a MemoryPhi, we can't do anything. 2254 if (!StartingAccess) 2255 return MA; 2256 2257 bool IsOptimized = false; 2258 2259 // If this is an already optimized use or def, return the optimized result. 2260 // Note: Currently, we store the optimized def result in a separate field, 2261 // since we can't use the defining access. 2262 if (StartingAccess->isOptimized()) { 2263 if (!SkipSelf || !isa<MemoryDef>(StartingAccess)) 2264 return StartingAccess->getOptimized(); 2265 IsOptimized = true; 2266 } 2267 2268 const Instruction *I = StartingAccess->getMemoryInst(); 2269 // We can't sanely do anything with a fence, since they conservatively clobber 2270 // all memory, and have no locations to get pointers from to try to 2271 // disambiguate. 2272 if (!isa<CallBase>(I) && I->isFenceLike()) 2273 return StartingAccess; 2274 2275 UpwardsMemoryQuery Q(I, StartingAccess); 2276 2277 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) { 2278 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef(); 2279 StartingAccess->setOptimized(LiveOnEntry); 2280 StartingAccess->setOptimizedAccessType(None); 2281 return LiveOnEntry; 2282 } 2283 2284 MemoryAccess *OptimizedAccess; 2285 if (!IsOptimized) { 2286 // Start with the thing we already think clobbers this location 2287 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess(); 2288 2289 // At this point, DefiningAccess may be the live on entry def. 2290 // If it is, we will not get a better result. 2291 if (MSSA->isLiveOnEntryDef(DefiningAccess)) { 2292 StartingAccess->setOptimized(DefiningAccess); 2293 StartingAccess->setOptimizedAccessType(None); 2294 return DefiningAccess; 2295 } 2296 2297 OptimizedAccess = Walker.findClobber(DefiningAccess, Q); 2298 StartingAccess->setOptimized(OptimizedAccess); 2299 if (MSSA->isLiveOnEntryDef(OptimizedAccess)) 2300 StartingAccess->setOptimizedAccessType(None); 2301 else if (Q.AR == MustAlias) 2302 StartingAccess->setOptimizedAccessType(MustAlias); 2303 } else 2304 OptimizedAccess = StartingAccess->getOptimized(); 2305 2306 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is "); 2307 LLVM_DEBUG(dbgs() << *StartingAccess << "\n"); 2308 LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is "); 2309 LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n"); 2310 2311 MemoryAccess *Result; 2312 if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) && 2313 isa<MemoryDef>(StartingAccess)) { 2314 assert(isa<MemoryDef>(Q.OriginalAccess)); 2315 Q.SkipSelfAccess = true; 2316 Result = Walker.findClobber(OptimizedAccess, Q); 2317 } else 2318 Result = OptimizedAccess; 2319 2320 LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf); 2321 LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n"); 2322 2323 return Result; 2324 } 2325 2326 MemoryAccess * 2327 MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) { 2328 return Walker->getClobberingMemoryAccessBase(MA, false); 2329 } 2330 2331 MemoryAccess * 2332 MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA, 2333 const MemoryLocation &Loc) { 2334 return Walker->getClobberingMemoryAccessBase(MA, Loc); 2335 } 2336 2337 MemoryAccess * 2338 MemorySSA::SkipSelfWalker::getClobberingMemoryAccess(MemoryAccess *MA) { 2339 return Walker->getClobberingMemoryAccessBase(MA, true); 2340 } 2341 2342 MemoryAccess * 2343 MemorySSA::SkipSelfWalker::getClobberingMemoryAccess(MemoryAccess *MA, 2344 const MemoryLocation &Loc) { 2345 return Walker->getClobberingMemoryAccessBase(MA, Loc); 2346 } 2347 2348 MemoryAccess * 2349 DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) { 2350 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA)) 2351 return Use->getDefiningAccess(); 2352 return MA; 2353 } 2354 2355 MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess( 2356 MemoryAccess *StartingAccess, const MemoryLocation &) { 2357 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess)) 2358 return Use->getDefiningAccess(); 2359 return StartingAccess; 2360 } 2361 2362 void MemoryPhi::deleteMe(DerivedUser *Self) { 2363 delete static_cast<MemoryPhi *>(Self); 2364 } 2365 2366 void MemoryDef::deleteMe(DerivedUser *Self) { 2367 delete static_cast<MemoryDef *>(Self); 2368 } 2369 2370 void MemoryUse::deleteMe(DerivedUser *Self) { 2371 delete static_cast<MemoryUse *>(Self); 2372 } 2373