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