LLVM 24.0.0git
MemorySSA.cpp
Go to the documentation of this file.
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
14#include "AnalysisOptions.h"
15#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/iterator.h"
27#include "llvm/Analysis/Loads.h"
30#include "llvm/Config/llvm-config.h"
32#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/Instruction.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Operator.h"
40#include "llvm/IR/PassManager.h"
41#include "llvm/IR/Use.h"
43#include "llvm/Pass.h"
48#include "llvm/Support/Debug.h"
53#include <algorithm>
54#include <cassert>
55#include <iterator>
56#include <memory>
57#include <utility>
58
59using namespace llvm;
60
61#define DEBUG_TYPE "memoryssa"
62
63INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
64 true)
68 true)
69
70// Always verify MemorySSA if expensive checking is enabled.
71#ifdef EXPENSIVE_CHECKS
72bool llvm::VerifyMemorySSA = true;
73#else
75#endif
76
79 cl::Hidden, cl::desc("Enable verification of MemorySSA."));
80
81const static char LiveOnEntryStr[] = "liveOnEntry";
82
83namespace {
84
85/// An assembly annotator class to print Memory SSA information in
86/// comments.
87class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
88 const MemorySSA *MSSA;
89
90public:
91 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
92
93 void emitBasicBlockStartAnnot(const BasicBlock *BB,
94 formatted_raw_ostream &OS) override {
95 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
96 OS << "; " << *MA << "\n";
97 }
98
99 void emitInstructionAnnot(const Instruction *I,
100 formatted_raw_ostream &OS) override {
101 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
102 OS << "; " << *MA << "\n";
103 }
104};
105
106/// An assembly annotator class to print Memory SSA information in
107/// comments.
108class MemorySSAWalkerAnnotatedWriter : public AssemblyAnnotationWriter {
109 MemorySSA *MSSA;
110 MemorySSAWalker *Walker;
111 BatchAAResults BAA;
112
113public:
114 MemorySSAWalkerAnnotatedWriter(MemorySSA *M)
115 : MSSA(M), Walker(M->getWalker()), BAA(M->getAA()) {}
116
117 void emitBasicBlockStartAnnot(const BasicBlock *BB,
118 formatted_raw_ostream &OS) override {
119 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
120 OS << "; " << *MA << "\n";
121 }
122
123 void emitInstructionAnnot(const Instruction *I,
124 formatted_raw_ostream &OS) override {
125 if (MemoryAccess *MA = MSSA->getMemoryAccess(I)) {
126 MemoryAccess *Clobber = Walker->getClobberingMemoryAccess(MA, BAA);
127 OS << "; " << *MA;
128 if (Clobber) {
129 OS << " - clobbered by ";
130 if (MSSA->isLiveOnEntryDef(Clobber))
131 OS << LiveOnEntryStr;
132 else
133 OS << *Clobber;
134 }
135 OS << "\n";
136 }
137 }
138};
139
140} // namespace
141
142/// This does one-way checks to see if Use could theoretically be hoisted above
143/// MayClobber. This will not check the other way around.
144///
145/// This assumes that, for the purposes of MemorySSA, Use comes directly after
146/// MayClobber, with no potentially clobbering operations in between them.
147/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
149 const LoadInst *MayClobber) {
150 bool VolatileUse = Use->isVolatile();
151 bool VolatileClobber = MayClobber->isVolatile();
152 // Volatile operations may never be reordered with other volatile operations.
153 if (VolatileUse && VolatileClobber)
154 return false;
155 // Otherwise, volatile doesn't matter here. From the language reference:
156 // 'optimizers may change the order of volatile operations relative to
157 // non-volatile operations.'"
158
159 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
160 // is weaker, it can be moved above other loads. We just need to be sure that
161 // MayClobber isn't an acquire load, because loads can't be moved above
162 // acquire loads.
163 //
164 // Note that this explicitly *does* allow the free reordering of monotonic (or
165 // weaker) loads of the same address.
166 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
167 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
169 return !(SeqCstUse || MayClobberIsAcquire);
170}
171
172template <typename AliasAnalysisType>
173static bool
175 const Instruction *UseInst, AliasAnalysisType &AA) {
176 Instruction *DefInst = MD->getMemoryInst();
177 assert(DefInst && "Defining instruction not actually an instruction");
178
179 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
180 // These intrinsics will show up as affecting memory, but they are just
181 // markers, mostly.
182 //
183 // FIXME: We probably don't actually want MemorySSA to model these at all
184 // (including creating MemoryAccesses for them): we just end up inventing
185 // clobbers where they don't really exist at all. Please see D43269 for
186 // context.
187 switch (II->getIntrinsicID()) {
188 case Intrinsic::allow_runtime_check:
189 case Intrinsic::allow_ubsan_check:
190 case Intrinsic::invariant_start:
191 case Intrinsic::invariant_end:
192 case Intrinsic::assume:
193 case Intrinsic::experimental_noalias_scope_decl:
194 case Intrinsic::pseudoprobe:
195 return false;
196 default:
197 break;
198 }
199 }
200
201 if (auto *CB = dyn_cast_or_null<CallBase>(UseInst)) {
202 ModRefInfo I = AA.getModRefInfo(DefInst, CB);
203 return isModSet(I);
204 }
205
206 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
207 if (auto *UseLoad = dyn_cast_or_null<LoadInst>(UseInst))
208 return !areLoadsReorderable(UseLoad, DefLoad);
209
210 ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
211 return isModSet(I);
212}
213
214// Return true when MD may alias MU, return false otherwise.
216 AliasAnalysis &AA) {
217 Instruction *UseInst = MU->getMemoryInst();
218 MemoryLocation UseLoc =
219 MemoryLocation::getOrNone(UseInst).value_or(MemoryLocation());
220 return instructionClobbersQuery(MD, UseLoc, UseInst, AA);
221}
222
223namespace {
224
225struct UpwardsMemoryQuery {
226 // True if our original query started off as a call
227 bool IsCall = false;
228 // The pointer location we started the query with. This will be empty if
229 // IsCall is true.
230 MemoryLocation StartingLoc;
231 // This is the instruction we were querying about.
232 const Instruction *Inst = nullptr;
233 // The MemoryAccess we actually got called with, used to test local domination
234 const MemoryAccess *OriginalAccess = nullptr;
235 bool SkipSelfAccess = false;
236
237 UpwardsMemoryQuery() = default;
238
239 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
240 : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
241 if (!IsCall)
242 StartingLoc = MemoryLocation::get(Inst);
243 }
244};
245
246} // end anonymous namespace
247
248template <typename AliasAnalysisType>
249static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
250 const Instruction *I) {
251 // If the memory can't be changed, then loads of the memory can't be
252 // clobbered.
253 if (I->hasMetadata(LLVMContext::MD_invariant_load))
254 return true;
255 if (auto *LI = dyn_cast<LoadInst>(I))
256 return !isModSet(AA.getModRefInfoMask(MemoryLocation::get(LI)));
257 return false;
258}
259
260/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
261/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
262///
263/// This is meant to be as simple and self-contained as possible. Because it
264/// uses no cache, etc., it can be relatively expensive.
265///
266/// \param Start The MemoryAccess that we want to walk from.
267/// \param ClobberAt A clobber for Start.
268/// \param StartLoc The MemoryLocation for Start.
269/// \param MSSA The MemorySSA instance that Start and ClobberAt belong to.
270/// \param Query The UpwardsMemoryQuery we used for our search.
271/// \param AA The AliasAnalysis we used for our search.
272/// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
273
274[[maybe_unused]] static void
276 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
277 const UpwardsMemoryQuery &Query, BatchAAResults &AA,
278 bool AllowImpreciseClobber = false) {
279 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
280
281 if (MSSA.isLiveOnEntryDef(Start)) {
282 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
283 "liveOnEntry must clobber itself");
284 return;
285 }
286
287 bool FoundClobber = false;
288 DenseSet<UpwardDefsElem> VisitedPhis;
290 Worklist.push_back({Start, StartLoc, /*MayBeCrossIteration=*/false});
291 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
292 // is found, complain.
293 while (!Worklist.empty()) {
294 auto MAP = Worklist.pop_back_val();
295 // All we care about is that nothing from Start to ClobberAt clobbers Start.
296 // We learn nothing from revisiting nodes.
297 if (!VisitedPhis.insert(MAP).second)
298 continue;
299
300 for (auto *MA : def_chain(MAP.MA)) {
301 if (MA == ClobberAt) {
302 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
303 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
304 // since it won't let us short-circuit.
305 //
306 // Also, note that this can't be hoisted out of the `Worklist` loop,
307 // since MD may only act as a clobber for 1 of N MemoryLocations.
308 FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
309 if (!FoundClobber) {
310 BatchAACrossIterationScope _(AA, MAP.MayBeCrossIteration);
311 if (instructionClobbersQuery(MD, MAP.Loc, Query.Inst, AA))
312 FoundClobber = true;
313 }
314 }
315 break;
316 }
317
318 // We should never hit liveOnEntry, unless it's the clobber.
319 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
320
321 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
322 // If Start is a Def, skip self.
323 if (MD == Start)
324 continue;
325
326 BatchAACrossIterationScope _(AA, MAP.MayBeCrossIteration);
327 assert(!instructionClobbersQuery(MD, MAP.Loc, Query.Inst, AA) &&
328 "Found clobber before reaching ClobberAt!");
329 continue;
330 }
331
332 if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
333 (void)MU;
334 assert (MU == Start &&
335 "Can only find use in def chain if Start is a use");
336 continue;
337 }
338
340
341 // Add reachable phi predecessors
342 for (auto ItB = upward_defs_begin({MA, MAP.Loc, MAP.MayBeCrossIteration},
343 MSSA.getDomTree()),
344 ItE = upward_defs_end();
345 ItB != ItE; ++ItB)
346 if (MSSA.getDomTree().isReachableFromEntry(ItB.getPhiArgBlock()))
347 Worklist.emplace_back(*ItB);
348 }
349 }
350
351 // If the verify is done following an optimization, it's possible that
352 // ClobberAt was a conservative clobbering, that we can now infer is not a
353 // true clobbering access. Don't fail the verify if that's the case.
354 // We do have accesses that claim they're optimized, but could be optimized
355 // further. Updating all these can be expensive, so allow it for now (FIXME).
356 if (AllowImpreciseClobber)
357 return;
358
359 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
360 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
361 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
362 "ClobberAt never acted as a clobber");
363}
364
365namespace {
366
367/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
368/// in one class.
369class ClobberWalker {
370 /// Save a few bytes by using unsigned instead of size_t.
371 using ListIndex = unsigned;
372
373 /// Represents a span of contiguous MemoryDefs, potentially ending in a
374 /// MemoryPhi.
375 struct DefPath {
376 MemoryLocation Loc;
377 // Note that, because we always walk in reverse, Last will always dominate
378 // First. Also note that First and Last are inclusive.
379 MemoryAccess *First;
380 MemoryAccess *Last;
381 std::optional<ListIndex> Previous;
382 bool MayBeCrossIteration;
383
384 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
385 bool MayBeCrossIteration, std::optional<ListIndex> Previous)
386 : Loc(Loc), First(First), Last(Last), Previous(Previous),
387 MayBeCrossIteration(MayBeCrossIteration) {}
388
389 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
390 bool MayBeCrossIteration, std::optional<ListIndex> Previous)
391 : DefPath(Loc, Init, Init, MayBeCrossIteration, Previous) {}
392 };
393
394 const MemorySSA &MSSA;
395 DominatorTree &DT;
396 BatchAAResults *AA;
397 UpwardsMemoryQuery *Query;
398 unsigned *UpwardWalkLimit;
399
400 // Phi optimization bookkeeping:
401 // List of DefPath to process during the current phi optimization walk.
403 // List of visited <Access, Location> pairs; we can skip paths already
404 // visited with the same memory location.
405 DenseSet<UpwardDefsElem> VisitedPhis;
406
407 /// Find the nearest def or phi that `From` can legally be optimized to.
408 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
409 assert(From->getNumOperands() && "Phi with no operands?");
410
411 BasicBlock *BB = From->getBlock();
412 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
413 DomTreeNode *Node = DT.getNode(BB);
414 while ((Node = Node->getIDom())) {
415 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
416 if (Defs)
417 return &*Defs->rbegin();
418 }
419 return Result;
420 }
421
422 /// Result of calling walkToPhiOrClobber.
423 struct UpwardsWalkResult {
424 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
425 /// both. Include alias info when clobber found.
426 MemoryAccess *Result;
427 bool IsKnownClobber;
428 };
429
430 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
431 /// This will update Desc.Last as it walks. It will (optionally) also stop at
432 /// StopAt.
433 ///
434 /// This does not test for whether StopAt is a clobber
435 UpwardsWalkResult
436 walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
437 const MemoryAccess *SkipStopAt = nullptr) const {
438 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
439 assert(UpwardWalkLimit && "Need a valid walk limit");
440 bool LimitAlreadyReached = false;
441 // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
442 // it to 1. This will not do any alias() calls. It either returns in the
443 // first iteration in the loop below, or is set back to 0 if all def chains
444 // are free of MemoryDefs.
445 if (!*UpwardWalkLimit) {
446 *UpwardWalkLimit = 1;
447 LimitAlreadyReached = true;
448 }
449
450 for (MemoryAccess *Current : def_chain(Desc.Last)) {
451 Desc.Last = Current;
452 if (Current == StopAt || Current == SkipStopAt)
453 return {Current, false};
454
455 if (auto *MD = dyn_cast<MemoryDef>(Current)) {
456 if (MSSA.isLiveOnEntryDef(MD))
457 return {MD, true};
458
459 if (!--*UpwardWalkLimit)
460 return {Current, true};
461
462 BatchAACrossIterationScope _(*AA, Desc.MayBeCrossIteration);
463 if (instructionClobbersQuery(MD, Desc.Loc, Query->Inst, *AA))
464 return {MD, true};
465 }
466 }
467
468 if (LimitAlreadyReached)
469 *UpwardWalkLimit = 0;
470
471 assert(isa<MemoryPhi>(Desc.Last) &&
472 "Ended at a non-clobber that's not a phi?");
473 return {Desc.Last, false};
474 }
475
476 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
477 ListIndex PriorNode, bool MayBeCrossIteration) {
478 auto UpwardDefsBegin =
479 upward_defs_begin({Phi, Paths[PriorNode].Loc, MayBeCrossIteration}, DT);
480 auto UpwardDefs = make_range(UpwardDefsBegin, upward_defs_end());
481 for (const UpwardDefsElem &E : UpwardDefs) {
482 PausedSearches.push_back(Paths.size());
483 Paths.emplace_back(E.Loc, E.MA, E.MayBeCrossIteration, PriorNode);
484 }
485 }
486
487 /// Represents a search that terminated after finding a clobber. This clobber
488 /// may or may not be present in the path of defs from LastNode..SearchStart,
489 /// since it may have been retrieved from cache.
490 struct TerminatedPath {
491 MemoryAccess *Clobber;
492 ListIndex LastNode;
493 };
494
495 /// Get an access that keeps us from optimizing to the given phi.
496 ///
497 /// PausedSearches is an array of indices into the Paths array. Its incoming
498 /// value is the indices of searches that stopped at the last phi optimization
499 /// target. It's left in an unspecified state.
500 ///
501 /// If this returns std::nullopt, NewPaused is a vector of searches that
502 /// terminated at StopWhere. Otherwise, NewPaused is left in an unspecified
503 /// state.
504 std::optional<TerminatedPath>
505 getBlockingAccess(const MemoryAccess *StopWhere,
506 SmallVectorImpl<ListIndex> &PausedSearches,
507 SmallVectorImpl<ListIndex> &NewPaused,
508 SmallVectorImpl<TerminatedPath> &Terminated) {
509 assert(!PausedSearches.empty() && "No searches to continue?");
510
511 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
512 // PausedSearches as our stack.
513 while (!PausedSearches.empty()) {
514 ListIndex PathIndex = PausedSearches.pop_back_val();
515 DefPath &Node = Paths[PathIndex];
516
517 // If we've already visited this path with this MemoryLocation, we don't
518 // need to do so again.
519 //
520 // NOTE: That we just drop these paths on the ground makes caching
521 // behavior sporadic. e.g. given a diamond:
522 // A
523 // B C
524 // D
525 //
526 // ...If we walk D, B, A, C, we'll only cache the result of phi
527 // optimization for A, B, and D; C will be skipped because it dies here.
528 // This arguably isn't the worst thing ever, since:
529 // - We generally query things in a top-down order, so if we got below D
530 // without needing cache entries for {C, MemLoc}, then chances are
531 // that those cache entries would end up ultimately unused.
532 // - We still cache things for A, so C only needs to walk up a bit.
533 // If this behavior becomes problematic, we can fix without a ton of extra
534 // work.
535 if (!VisitedPhis.insert({Node.Last, Node.Loc, Node.MayBeCrossIteration})
536 .second)
537 continue;
538
539 const MemoryAccess *SkipStopWhere = nullptr;
540 if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
541 assert(isa<MemoryDef>(Query->OriginalAccess));
542 SkipStopWhere = Query->OriginalAccess;
543 }
544
545 UpwardsWalkResult Res = walkToPhiOrClobber(Node,
546 /*StopAt=*/StopWhere,
547 /*SkipStopAt=*/SkipStopWhere);
548 if (Res.IsKnownClobber) {
549 assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
550
551 // If this wasn't a cache hit, we hit a clobber when walking. That's a
552 // failure.
553 TerminatedPath Term{Res.Result, PathIndex};
554 if (!MSSA.dominates(Res.Result, StopWhere))
555 return Term;
556
557 // Otherwise, it's a valid thing to potentially optimize to.
558 Terminated.push_back(Term);
559 continue;
560 }
561
562 if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
563 // We've hit our target. Save this path off for if we want to continue
564 // walking. If we are in the mode of skipping the OriginalAccess, and
565 // we've reached back to the OriginalAccess, do not save path, we've
566 // just looped back to self.
567 if (Res.Result != SkipStopWhere)
568 NewPaused.push_back(PathIndex);
569 continue;
570 }
571
572 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
573 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex,
574 Node.MayBeCrossIteration);
575 }
576
577 return std::nullopt;
578 }
579
580 template <typename T, typename Walker>
581 struct generic_def_path_iterator
582 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
583 std::forward_iterator_tag, T *> {
584 generic_def_path_iterator() = default;
585 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
586
587 T &operator*() const { return curNode(); }
588
589 generic_def_path_iterator &operator++() {
590 N = curNode().Previous;
591 return *this;
592 }
593
594 bool operator==(const generic_def_path_iterator &O) const {
595 if (N.has_value() != O.N.has_value())
596 return false;
597 return !N || *N == *O.N;
598 }
599
600 private:
601 T &curNode() const { return W->Paths[*N]; }
602
603 Walker *W = nullptr;
604 std::optional<ListIndex> N;
605 };
606
607 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
608
609 iterator_range<def_path_iterator> def_path(ListIndex From) {
610 return make_range(def_path_iterator(this, From), def_path_iterator());
611 }
612
613 struct OptznResult {
614 /// The path that contains our result.
615 TerminatedPath PrimaryClobber;
616 /// The paths that we can legally cache back from, but that aren't
617 /// necessarily the result of the Phi optimization.
618 SmallVector<TerminatedPath, 4> OtherClobbers;
619 };
620
621 ListIndex defPathIndex(const DefPath &N) const {
622 // The assert looks nicer if we don't need to do &N
623 const DefPath *NP = &N;
624 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
625 "Out of bounds DefPath!");
626 return NP - &Paths.front();
627 }
628
629 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
630 /// that act as legal clobbers. Note that this won't return *all* clobbers.
631 ///
632 /// Phi optimization algorithm tl;dr:
633 /// - Find the earliest def/phi, A, we can optimize to
634 /// - Find if all paths from the starting memory access ultimately reach A
635 /// - If not, optimization isn't possible.
636 /// - Otherwise, walk from A to another clobber or phi, A'.
637 /// - If A' is a def, we're done.
638 /// - If A' is a phi, try to optimize it.
639 ///
640 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
641 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
642 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
643 const MemoryLocation &Loc) {
644 assert(Paths.empty() && VisitedPhis.empty() &&
645 "Reset the optimization state.");
646
647 Paths.emplace_back(Loc, Start, Phi, /*MayBeCrossIteration=*/false,
648 std::nullopt);
649 // Stores how many "valid" optimization nodes we had prior to calling
650 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
651 auto PriorPathsSize = Paths.size();
652
653 SmallVector<ListIndex, 16> PausedSearches;
655 SmallVector<TerminatedPath, 4> TerminatedPaths;
656
657 addSearches(Phi, PausedSearches, 0, /*MayBeCrossIteration=*/false);
658
659 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
660 // Paths.
661 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
662 assert(!Paths.empty() && "Need a path to move");
663 auto Dom = Paths.begin();
664 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
665 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
666 Dom = I;
667 auto Last = Paths.end() - 1;
668 if (Last != Dom)
669 std::iter_swap(Last, Dom);
670 };
671
672 MemoryPhi *Current = Phi;
673 while (true) {
674 assert(!MSSA.isLiveOnEntryDef(Current) &&
675 "liveOnEntry wasn't treated as a clobber?");
676
677 const auto *Target = getWalkTarget(Current);
678 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
679 // optimization for the prior phi.
680 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
681 return MSSA.dominates(P.Clobber, Target);
682 }));
683
684 // FIXME: This is broken, because the Blocker may be reported to be
685 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
686 // For the moment, this is fine, since we do nothing with blocker info.
687 if (std::optional<TerminatedPath> Blocker = getBlockingAccess(
688 Target, PausedSearches, NewPaused, TerminatedPaths)) {
689
690 // Find the node we started at. We can't search based on N->Last, since
691 // we may have gone around a loop with a different MemoryLocation.
692 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
693 return defPathIndex(N) < PriorPathsSize;
694 });
695 assert(Iter != def_path_iterator());
696
697 DefPath &CurNode = *Iter;
698 assert(CurNode.Last == Current);
699
700 // Two things:
701 // A. We can't reliably cache all of NewPaused back. Consider a case
702 // where we have two paths in NewPaused; one of which can't optimize
703 // above this phi, whereas the other can. If we cache the second path
704 // back, we'll end up with suboptimal cache entries. We can handle
705 // cases like this a bit better when we either try to find all
706 // clobbers that block phi optimization, or when our cache starts
707 // supporting unfinished searches.
708 // B. We can't reliably cache TerminatedPaths back here without doing
709 // extra checks; consider a case like:
710 // T
711 // / \
712 // D C
713 // \ /
714 // S
715 // Where T is our target, C is a node with a clobber on it, D is a
716 // diamond (with a clobber *only* on the left or right node, N), and
717 // S is our start. Say we walk to D, through the node opposite N
718 // (read: ignoring the clobber), and see a cache entry in the top
719 // node of D. That cache entry gets put into TerminatedPaths. We then
720 // walk up to C (N is later in our worklist), find the clobber, and
721 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
722 // the bottom part of D to the cached clobber, ignoring the clobber
723 // in N. Again, this problem goes away if we start tracking all
724 // blockers for a given phi optimization.
725 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
726 return {Result, {}};
727 }
728
729 // If there's nothing left to search, then all paths led to valid clobbers
730 // that we got from our cache; pick the nearest to the start, and allow
731 // the rest to be cached back.
732 if (NewPaused.empty()) {
733 MoveDominatedPathToEnd(TerminatedPaths);
734 TerminatedPath Result = TerminatedPaths.pop_back_val();
735 return {Result, std::move(TerminatedPaths)};
736 }
737
738 MemoryAccess *DefChainEnd = nullptr;
740 for (ListIndex Paused : NewPaused) {
741 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
742 if (WR.IsKnownClobber)
743 Clobbers.push_back({WR.Result, Paused});
744 else
745 // Micro-opt: If we hit the end of the chain, save it.
746 DefChainEnd = WR.Result;
747 }
748
749 if (!TerminatedPaths.empty()) {
750 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
751 // do it now.
752 if (!DefChainEnd)
753 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
754 DefChainEnd = MA;
755 assert(DefChainEnd && "Failed to find dominating phi/liveOnEntry");
756
757 // If any of the terminated paths don't dominate the phi we'll try to
758 // optimize, we need to figure out what they are and quit.
759 const BasicBlock *ChainBB = DefChainEnd->getBlock();
760 for (const TerminatedPath &TP : TerminatedPaths) {
761 // Because we know that DefChainEnd is as "high" as we can go, we
762 // don't need local dominance checks; BB dominance is sufficient.
763 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
764 Clobbers.push_back(TP);
765 }
766 }
767
768 // If we have clobbers in the def chain, find the one closest to Current
769 // and quit.
770 if (!Clobbers.empty()) {
771 MoveDominatedPathToEnd(Clobbers);
772 TerminatedPath Result = Clobbers.pop_back_val();
773 return {Result, std::move(Clobbers)};
774 }
775
776 assert(all_of(NewPaused,
777 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
778
779 // Because liveOnEntry is a clobber, this must be a phi.
780 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
781
782 PriorPathsSize = Paths.size();
783 PausedSearches.clear();
784 for (ListIndex I : NewPaused)
785 addSearches(DefChainPhi, PausedSearches, I,
786 Paths[I].MayBeCrossIteration);
787 NewPaused.clear();
788
789 Current = DefChainPhi;
790 }
791 }
792
793 void verifyOptResult(const OptznResult &R) const {
794 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
795 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
796 }));
797 }
798
799 void resetPhiOptznState() {
800 Paths.clear();
801 VisitedPhis.clear();
802 }
803
804public:
805 ClobberWalker(const MemorySSA &MSSA, DominatorTree &DT)
806 : MSSA(MSSA), DT(DT) {}
807
808 /// Finds the nearest clobber for the given query, optimizing phis if
809 /// possible.
810 MemoryAccess *findClobber(BatchAAResults &BAA, MemoryAccess *Start,
811 UpwardsMemoryQuery &Q, unsigned &UpWalkLimit) {
812 AA = &BAA;
813 Query = &Q;
814 UpwardWalkLimit = &UpWalkLimit;
815 // Starting limit must be > 0.
816 if (!UpWalkLimit)
817 UpWalkLimit++;
818
819 MemoryAccess *Current = Start;
820 // This walker pretends uses don't exist. If we're handed one, silently grab
821 // its def. (This has the nice side-effect of ensuring we never cache uses)
822 if (auto *MU = dyn_cast<MemoryUse>(Start))
823 Current = MU->getDefiningAccess();
824
825 DefPath FirstDesc(Q.StartingLoc, Current, Current,
826 /*MayBeCrossIteration=*/false, std::nullopt);
827 // Fast path for the overly-common case (no crazy phi optimization
828 // necessary)
829 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
830 MemoryAccess *Result;
831 if (WalkResult.IsKnownClobber) {
832 Result = WalkResult.Result;
833 } else {
834 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
835 Current, Q.StartingLoc);
836 verifyOptResult(OptRes);
837 resetPhiOptznState();
838 Result = OptRes.PrimaryClobber.Clobber;
839 }
840
841#ifdef EXPENSIVE_CHECKS
842 if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
843 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, BAA);
844#endif
845 return Result;
846 }
847};
848
849struct RenamePassData {
850 DomTreeNode *DTN;
851 DomTreeNode::const_iterator ChildIt;
852 MemoryAccess *IncomingVal;
853
854 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
855 MemoryAccess *M)
856 : DTN(D), ChildIt(It), IncomingVal(M) {}
857
858 void swap(RenamePassData &RHS) {
859 std::swap(DTN, RHS.DTN);
860 std::swap(ChildIt, RHS.ChildIt);
861 std::swap(IncomingVal, RHS.IncomingVal);
862 }
863};
864
865} // end anonymous namespace
866
867namespace llvm {
868
870 ClobberWalker Walker;
871 MemorySSA *MSSA;
872
873public:
874 ClobberWalkerBase(MemorySSA *M, DominatorTree *D) : Walker(*M, *D), MSSA(M) {}
875
877 const MemoryLocation &,
878 BatchAAResults &, unsigned &);
879 // Third argument (bool), defines whether the clobber search should skip the
880 // original queried access. If true, there will be a follow-up query searching
881 // for a clobber access past "self". Note that the Optimized access is not
882 // updated if a new clobber is found by this SkipSelf search. If this
883 // additional query becomes heavily used we may decide to cache the result.
884 // Walker instantiations will decide how to set the SkipSelf bool.
886 unsigned &, bool);
887};
888
889/// A MemorySSAWalker that does AA walks to disambiguate accesses. It no
890/// longer does caching on its own, but the name has been retained for the
891/// moment.
893 ClobberWalkerBase *Walker;
894
895public:
898 ~CachingWalker() override = default;
899
901
903 unsigned &UWL) {
904 return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL, false);
905 }
907 const MemoryLocation &Loc,
908 BatchAAResults &BAA, unsigned &UWL) {
909 return Walker->getClobberingMemoryAccessBase(MA, Loc, BAA, UWL);
910 }
911
913 BatchAAResults &BAA) override {
914 unsigned UpwardWalkLimit = MSSA->Opts.memssa_check_limit;
915 return getClobberingMemoryAccess(MA, BAA, UpwardWalkLimit);
916 }
918 const MemoryLocation &Loc,
919 BatchAAResults &BAA) override {
920 unsigned UpwardWalkLimit = MSSA->Opts.memssa_check_limit;
921 return getClobberingMemoryAccess(MA, Loc, BAA, UpwardWalkLimit);
922 }
923
924 void invalidateInfo(MemoryAccess *MA) override {
925 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
926 MUD->resetOptimized();
927 }
928};
929
931 ClobberWalkerBase *Walker;
932
933public:
936 ~SkipSelfWalker() override = default;
937
939
941 unsigned &UWL) {
942 return Walker->getClobberingMemoryAccessBase(MA, BAA, UWL, true);
943 }
945 const MemoryLocation &Loc,
946 BatchAAResults &BAA, unsigned &UWL) {
947 return Walker->getClobberingMemoryAccessBase(MA, Loc, BAA, UWL);
948 }
949
951 BatchAAResults &BAA) override {
952 unsigned UpwardWalkLimit = MSSA->Opts.memssa_check_limit;
953 return getClobberingMemoryAccess(MA, BAA, UpwardWalkLimit);
954 }
956 const MemoryLocation &Loc,
957 BatchAAResults &BAA) override {
958 unsigned UpwardWalkLimit = MSSA->Opts.memssa_check_limit;
959 return getClobberingMemoryAccess(MA, Loc, BAA, UpwardWalkLimit);
960 }
961
962 void invalidateInfo(MemoryAccess *MA) override {
963 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
964 MUD->resetOptimized();
965 }
966};
967
968} // end namespace llvm
969
970void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
971 bool RenameAllUses) {
972 // Pass through values to our successors
973 for (const BasicBlock *S : successors(BB)) {
975 // Rename the phi nodes in our successor block
976 if (!Accesses || !isa<MemoryPhi>(Accesses->front()))
977 continue;
978 auto *Phi = cast<MemoryPhi>(&Accesses->front());
979 if (RenameAllUses) {
980 bool ReplacementDone = false;
981 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
982 if (Phi->getIncomingBlock(I) == BB) {
983 Phi->setIncomingValue(I, IncomingVal);
984 ReplacementDone = true;
985 }
986 (void) ReplacementDone;
987 assert(ReplacementDone && "Incomplete phi during partial rename");
988 } else
989 Phi->addIncoming(IncomingVal, BB);
990 }
991}
992
993/// Rename a single basic block into MemorySSA form.
994/// Uses the standard SSA renaming algorithm.
995/// \returns The new incoming value.
996MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
997 bool RenameAllUses) {
998 // Skip most processing if the list is empty.
1000 for (MemoryAccess &L : *Accesses) {
1001 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1002 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
1003 MUD->setDefiningAccess(IncomingVal);
1004 if (isa<MemoryDef>(&L))
1005 IncomingVal = &L;
1006 } else {
1007 IncomingVal = &L;
1008 }
1009 }
1010 }
1011 return IncomingVal;
1012}
1013
1014/// This is the standard SSA renaming algorithm.
1015///
1016/// We walk the dominator tree in preorder, renaming accesses, and then filling
1017/// in phi nodes in our successors.
1018void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
1020 bool SkipVisited, bool RenameAllUses) {
1021 assert(Root && "Trying to rename accesses in an unreachable block");
1022
1024 // Skip everything if we already renamed this block and we are skipping.
1025 // Note: You can't sink this into the if, because we need it to occur
1026 // regardless of whether we skip blocks or not.
1027 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
1028 if (SkipVisited && AlreadyVisited)
1029 return;
1030
1031 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
1032 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
1033 WorkStack.push_back({Root, Root->begin(), IncomingVal});
1034
1035 while (!WorkStack.empty()) {
1036 DomTreeNode *Node = WorkStack.back().DTN;
1037 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1038 IncomingVal = WorkStack.back().IncomingVal;
1039
1040 if (ChildIt == Node->end()) {
1041 WorkStack.pop_back();
1042 } else {
1043 DomTreeNode *Child = *ChildIt;
1044 ++WorkStack.back().ChildIt;
1045 BasicBlock *BB = Child->getBlock();
1046 // Note: You can't sink this into the if, because we need it to occur
1047 // regardless of whether we skip blocks or not.
1048 AlreadyVisited = !Visited.insert(BB).second;
1049 if (SkipVisited && AlreadyVisited) {
1050 // We already visited this during our renaming, which can happen when
1051 // being asked to rename multiple blocks. Figure out the incoming val,
1052 // which is the last def.
1053 // Incoming value can only change if there is a block def, and in that
1054 // case, it's the last block def in the list.
1055 if (auto *BlockDefs = getBlockDefs(BB))
1056 IncomingVal = &*BlockDefs->rbegin();
1057 } else
1058 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1059 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
1060 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1061 }
1062 }
1063}
1064
1065/// This handles unreachable block accesses by deleting phi nodes in
1066/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1067/// being uses of the live on entry definition.
1068void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1069 assert(!DT->isReachableFromEntry(BB) &&
1070 "Reachable block found while handling unreachable blocks");
1071
1072 // Make sure phi nodes in our reachable successors end up with a
1073 // LiveOnEntryDef for our incoming edge, even though our block is forward
1074 // unreachable. We could just disconnect these blocks from the CFG fully,
1075 // but we do not right now.
1076 for (const BasicBlock *S : successors(BB)) {
1077 if (!DT->isReachableFromEntry(S))
1078 continue;
1080 // Rename the phi nodes in our successor block
1081 if (!Accesses || !isa<MemoryPhi>(Accesses->front()))
1082 continue;
1083 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1084 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1085 }
1086
1088 if (!Accesses)
1089 return;
1090
1091 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1092 auto Next = std::next(AI);
1093 // If we have a phi, just remove it. We are going to replace all
1094 // users with live on entry.
1095 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1096 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1097 else
1098 Accesses->erase(AI);
1099 AI = Next;
1100 }
1101}
1102
1104 : Opts(getAnalysisOptions(Func)), DT(DT), F(&Func),
1105 BlockNumberEpoch(Func.getBlockNumberEpoch()), LiveOnEntryDef(nullptr),
1106 Walker(nullptr), SkipWalker(nullptr) {
1107 // Build MemorySSA using a batch alias analysis. This reuses the internal
1108 // state that AA collects during an alias()/getModRefInfo() call. This is
1109 // safe because there are no CFG changes while building MemorySSA and can
1110 // significantly reduce the time spent by the compiler in AA, because we will
1111 // make queries about all the instructions in the Function.
1112 assert(AA && "No alias analysis?");
1113 BatchAAResults BatchAA(*AA);
1114 buildMemorySSA(BatchAA, iterator_range(F->begin(), F->end()));
1115 // Intentionally leave AA to nullptr while building so we don't accidentally
1116 // use non-batch AliasAnalysis.
1117 this->AA = AA;
1118 // Also create the walker here.
1119 getWalker();
1120}
1121
1123 : Opts(getAnalysisOptions(L)), DT(DT), L(&L),
1124 BlockNumberEpoch(L.getHeader()->getParent()->getBlockNumberEpoch()),
1125 LiveOnEntryDef(nullptr), Walker(nullptr), SkipWalker(nullptr) {
1126 // Build MemorySSA using a batch alias analysis. This reuses the internal
1127 // state that AA collects during an alias()/getModRefInfo() call. This is
1128 // safe because there are no CFG changes while building MemorySSA and can
1129 // significantly reduce the time spent by the compiler in AA, because we will
1130 // make queries about all the instructions in the Function.
1131 assert(AA && "No alias analysis?");
1132 BatchAAResults BatchAA(*AA);
1133 buildMemorySSA(
1134 BatchAA, map_range(L.blocks(), [](const BasicBlock *BB) -> BasicBlock & {
1135 return *const_cast<BasicBlock *>(BB);
1136 }));
1137 // Intentionally leave AA to nullptr while building so we don't accidentally
1138 // use non-batch AliasAnalysis.
1139 this->AA = AA;
1140 // Also create the walker here.
1141 getWalker();
1142}
1143
1145 // Drop all our references
1146 for (const BlockInfo &Info : PerBlock)
1147 if (Info.Accesses)
1148 for (MemoryAccess &MA : *Info.Accesses)
1149 MA.dropAllReferences();
1150}
1151
1152MemorySSA::BlockInfo &MemorySSA::getOrCreateBlockInfo(const BasicBlock *BB) {
1153 unsigned N = getBlockIndex(BB);
1154 if (N >= PerBlock.size())
1155 PerBlock.resize(BB->getParent()->getMaxBlockNumber());
1156 return PerBlock[N];
1157}
1158
1159template <typename ListT>
1160ListT *MemorySSA::getOrCreateList(ListPtr<ListT> &List) {
1161 if (!List)
1162 List.reset(new (UseOrDefAllocator) ListT());
1163 return List.get();
1164}
1165
1166void MemorySSA::placePHINodes(
1167 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
1168 // Determine where our MemoryPhi's should go
1169 ForwardIDFCalculator IDFs(*DT);
1170 IDFs.setDefiningBlocks(DefiningBlocks);
1172 IDFs.calculate(IDFBlocks);
1173
1174 // Now place MemoryPhi nodes.
1175 for (auto &BB : IDFBlocks)
1176 createMemoryPhi(BB);
1177}
1178
1179/// Allocate a MemoryUse or MemoryDef from \p Allocator, with its operands in
1180/// front of it like User::operator new.
1181template <typename AccessT, typename AllocatorT, typename... ArgTs>
1182static AccessT *allocateUseOrDef(AllocatorT &Allocator, ArgTs &&...Args) {
1183 size_t OpsSize = sizeof(Use) * OperandTraits<AccessT>::operands(nullptr);
1184 char *Mem = static_cast<char *>(
1185 Allocator.Allocate(OpsSize + sizeof(AccessT), alignof(AccessT)));
1186 return ::new (Mem + OpsSize) AccessT(std::forward<ArgTs>(Args)...);
1187}
1188
1189template <typename IterT>
1190void MemorySSA::buildMemorySSA(BatchAAResults &BAA, IterT Blocks) {
1191 // We create an access to represent "live on entry", for things like
1192 // arguments or users of globals, where the memory they use is defined before
1193 // the beginning of the function. We do not actually insert it into the IR.
1194 // We do not define a live on exit for the immediate uses, and thus our
1195 // semantics do *not* imply that something with no immediate uses can simply
1196 // be removed.
1197 BasicBlock &StartingPoint = *Blocks.begin();
1198 LiveOnEntryDef.reset(
1199 allocateUseOrDef<MemoryDef>(UseOrDefAllocator, StartingPoint.getContext(),
1200 nullptr, nullptr, &StartingPoint, NextID++));
1201
1202 // We maintain lists of memory accesses per-block, trading memory for time. We
1203 // could just look up the memory access for every possible instruction in the
1204 // stream.
1205 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
1206 // Go through each block, figure out where defs occur, and chain together all
1207 // the accesses.
1208 for (BasicBlock &B : Blocks) {
1209 bool InsertIntoDef = false;
1210 AccessList *Accesses = nullptr;
1211 DefsList *Defs = nullptr;
1212 for (Instruction &I : B) {
1213 MemoryUseOrDef *MUD = createNewAccess(&I, &BAA);
1214 if (!MUD)
1215 continue;
1216
1217 if (!Accesses)
1218 Accesses = getOrCreateList(getOrCreateBlockInfo(&B).Accesses);
1219 Accesses->push_back(MUD);
1220 if (isa<MemoryDef>(MUD)) {
1221 InsertIntoDef = true;
1222 if (!Defs)
1223 Defs = getOrCreateList(getOrCreateBlockInfo(&B).Defs);
1224 Defs->push_back(*MUD);
1225 }
1226 }
1227 if (InsertIntoDef)
1228 DefiningBlocks.insert(&B);
1229 }
1230 placePHINodes(DefiningBlocks);
1231
1232 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1233 // filled in with all blocks.
1234 SmallPtrSet<BasicBlock *, 16> Visited;
1235 if (L) {
1236 // Only building MemorySSA for a single loop. placePHINodes may have
1237 // inserted a MemoryPhi in the loop's preheader. As this is outside the
1238 // scope of the loop, set them to LiveOnEntry.
1239 if (auto *P = getMemoryAccess(L->getLoopPreheader())) {
1240 for (Use &U : make_early_inc_range(P->uses()))
1241 U.set(LiveOnEntryDef.get());
1243 }
1244 // Now rename accesses in the loop. Populate Visited with the exit blocks of
1245 // the loop, to limit the scope of the renaming.
1246 SmallVector<BasicBlock *> ExitBlocks;
1247 L->getExitBlocks(ExitBlocks);
1248 Visited.insert_range(ExitBlocks);
1249 renamePass(DT->getNode(L->getLoopPreheader()), LiveOnEntryDef.get(),
1250 Visited);
1251 } else {
1252 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1253 }
1254
1255 // Mark the uses in unreachable blocks as live on entry, so that they go
1256 // somewhere.
1257 for (auto &BB : Blocks)
1258 if (!Visited.count(&BB))
1259 markUnreachableAsLiveOnEntry(&BB);
1260}
1261
1262MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1263
1264MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
1265 if (Walker)
1266 return Walker.get();
1267
1268 if (!WalkerBase)
1269 WalkerBase = std::make_unique<ClobberWalkerBase>(this, DT);
1270
1271 Walker = std::make_unique<CachingWalker>(this, WalkerBase.get());
1272 return Walker.get();
1273}
1274
1276 if (SkipWalker)
1277 return SkipWalker.get();
1278
1279 if (!WalkerBase)
1280 WalkerBase = std::make_unique<ClobberWalkerBase>(this, DT);
1281
1282 SkipWalker = std::make_unique<SkipSelfWalker>(this, WalkerBase.get());
1283 return SkipWalker.get();
1284 }
1285
1286
1287// This is a helper function used by the creation routines. It places NewAccess
1288// into the access and defs lists for a given basic block, at the given
1289// insertion point.
1291 const BasicBlock *BB,
1292 InsertionPlace Point) {
1293 BlockInfo &Info = getOrCreateBlockInfo(BB);
1294 AccessList *Accesses = getOrCreateList(Info.Accesses);
1295 if (Point == Beginning) {
1296 // If it's a phi node, it goes first, otherwise, it goes after any phi
1297 // nodes.
1298 if (isa<MemoryPhi>(NewAccess)) {
1299 Accesses->push_front(NewAccess);
1300 getOrCreateList(Info.Defs)->push_front(*NewAccess);
1301 } else {
1302 auto AI = find_if_not(
1303 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1304 Accesses->insert(AI, NewAccess);
1305 if (!isa<MemoryUse>(NewAccess)) {
1306 DefsList *Defs = getOrCreateList(Info.Defs);
1307 auto DI = find_if_not(
1308 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1309 Defs->insert(DI, *NewAccess);
1310 }
1311 }
1312 } else {
1313 Accesses->push_back(NewAccess);
1314 if (!isa<MemoryUse>(NewAccess))
1315 getOrCreateList(Info.Defs)->push_back(*NewAccess);
1316 }
1317 BlockNumberingValid.erase(BB);
1318}
1319
1322 BlockInfo &Info = PerBlock[getBlockIndex(BB)];
1323 AccessList *Accesses = Info.Accesses.get();
1324 bool WasEnd = InsertPt == Accesses->end();
1325 Accesses->insert(AccessList::iterator(InsertPt), What);
1326 if (!isa<MemoryUse>(What)) {
1327 DefsList *Defs = getOrCreateList(Info.Defs);
1328 // If we got asked to insert at the end, we have an easy job, just shove it
1329 // at the end. If we got asked to insert before an existing def, we also get
1330 // an iterator. If we got asked to insert before a use, we have to hunt for
1331 // the next def.
1332 if (WasEnd) {
1333 Defs->push_back(*What);
1334 } else if (isa<MemoryDef>(InsertPt)) {
1335 Defs->insert(InsertPt->getDefsIterator(), *What);
1336 } else {
1337 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1338 ++InsertPt;
1339 // Either we found a def, or we are inserting at the end
1340 if (InsertPt == Accesses->end())
1341 Defs->push_back(*What);
1342 else
1343 Defs->insert(InsertPt->getDefsIterator(), *What);
1344 }
1345 }
1346 BlockNumberingValid.erase(BB);
1347}
1348
1349void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) {
1350 // Keep it in the lookup tables, remove from the lists
1351 removeFromLists(What, false);
1352
1353 // Note that moving should implicitly invalidate the optimized state of a
1354 // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a
1355 // MemoryDef.
1356 if (auto *MD = dyn_cast<MemoryDef>(What))
1357 MD->resetOptimized();
1358 What->setBlock(BB);
1359}
1360
1361// Move What before Where in the IR. The end result is that What will belong to
1362// the right lists and have the right Block set, but will not otherwise be
1363// correct. It will not have the right defining access, and if it is a def,
1364// things below it will not properly be updated.
1366 AccessList::iterator Where) {
1367 prepareForMoveTo(What, BB);
1368 insertIntoListsBefore(What, BB, Where);
1369}
1370
1372 InsertionPlace Point) {
1373 if (isa<MemoryPhi>(What)) {
1374 assert(Point == Beginning &&
1375 "Can only move a Phi at the beginning of the block");
1376 // Update lookup table entry
1377 ValueToMemoryAccess.erase(What->getBlock());
1378 bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
1379 (void)Inserted;
1380 assert(Inserted && "Cannot move a Phi to a block that already has one");
1381 }
1382
1383 prepareForMoveTo(What, BB);
1384 insertIntoListsForBlock(What, BB, Point);
1385}
1386
1387MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1388 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1389 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1390 // Phi's always are placed at the front of the block.
1392 ValueToMemoryAccess[BB] = Phi;
1393 return Phi;
1394}
1395
1397 MemoryAccess *Definition,
1398 const MemoryUseOrDef *Template,
1399 bool CreationMustSucceed) {
1400 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1401 MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template);
1402 if (CreationMustSucceed)
1403 assert(NewAccess != nullptr && "Tried to create a memory access for a "
1404 "non-memory touching instruction");
1405 if (NewAccess) {
1406 assert((!Definition || !isa<MemoryUse>(Definition)) &&
1407 "A use cannot be a defining access");
1408 NewAccess->setDefiningAccess(Definition);
1409 }
1410 return NewAccess;
1411}
1412
1413// Return true if the instruction has ordering constraints.
1414// Note specifically that this only considers stores and loads
1415// because others are still considered ModRef by getModRefInfo.
1416static inline bool isOrdered(const Instruction *I) {
1417 if (auto *SI = dyn_cast<StoreInst>(I)) {
1418 if (!SI->isUnordered())
1419 return true;
1420 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1421 if (!LI->isUnordered())
1422 return true;
1423 }
1424 return false;
1425}
1426
1427/// Helper function to create new memory accesses
1428template <typename AliasAnalysisType>
1429MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
1430 AliasAnalysisType *AAP,
1431 const MemoryUseOrDef *Template) {
1432 // The assume intrinsic has a control dependency which we model by claiming
1433 // that it writes arbitrarily. Debuginfo intrinsics may be considered
1434 // clobbers when we have a nonstandard AA pipeline. Ignore these fake memory
1435 // dependencies here.
1436 // FIXME: Replace this special casing with a more accurate modelling of
1437 // assume's control dependency.
1438 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1439 switch (II->getIntrinsicID()) {
1440 default:
1441 break;
1442 case Intrinsic::allow_runtime_check:
1443 case Intrinsic::allow_ubsan_check:
1444 case Intrinsic::assume:
1445 case Intrinsic::experimental_noalias_scope_decl:
1446 case Intrinsic::pseudoprobe:
1447 return nullptr;
1448 }
1449 }
1450
1451 // Using a nonstandard AA pipelines might leave us with unexpected modref
1452 // results for I, so add a check to not model instructions that may not read
1453 // from or write to memory. This is necessary for correctness.
1454 if (!I->mayReadFromMemory() && !I->mayWriteToMemory())
1455 return nullptr;
1456
1457 bool Def, Use;
1458 if (Template) {
1461#if !defined(NDEBUG)
1462 ModRefInfo ModRef = AAP->getModRefInfo(I, std::nullopt);
1463 bool DefCheck, UseCheck;
1464 DefCheck = isModSet(ModRef) || isOrdered(I);
1465 UseCheck = isRefSet(ModRef);
1466 // Memory accesses should only be reduced and can not be increased since AA
1467 // just might return better results as a result of some transformations.
1468 assert((Def == DefCheck || !DefCheck) &&
1469 "Memory accesses should only be reduced");
1470 if (!Def && Use != UseCheck) {
1471 // New Access should not have more power than template access
1472 assert(!UseCheck && "Invalid template");
1473 }
1474#endif
1475 } else {
1476 // Find out what affect this instruction has on memory.
1477 ModRefInfo ModRef = AAP->getModRefInfo(I, std::nullopt);
1478 // The isOrdered check is used to ensure that volatiles end up as defs
1479 // (atomics end up as ModRef right now anyway). Until we separate the
1480 // ordering chain from the memory chain, this enables people to see at least
1481 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1482 // will still give an answer that bypasses other volatile loads. TODO:
1483 // Separate memory aliasing and ordering into two different chains so that
1484 // we can precisely represent both "what memory will this read/write/is
1485 // clobbered by" and "what instructions can I move this past".
1486 Def = isModSet(ModRef) || isOrdered(I);
1487 Use = isRefSet(ModRef);
1488 }
1489
1490 // It's possible for an instruction to not modify memory at all. During
1491 // construction, we ignore them.
1492 if (!Def && !Use)
1493 return nullptr;
1494
1495 MemoryUseOrDef *MUD;
1496 if (Def) {
1497 MUD = allocateUseOrDef<MemoryDef>(UseOrDefAllocator, I->getContext(),
1498 nullptr, I, I->getParent(), NextID++);
1499 } else {
1500 MUD = allocateUseOrDef<MemoryUse>(UseOrDefAllocator, I->getContext(),
1501 nullptr, I, I->getParent());
1503 MemoryAccess *LiveOnEntry = getLiveOnEntryDef();
1504 MUD->setOptimized(LiveOnEntry);
1505 }
1506 }
1507 ValueToMemoryAccess[I] = MUD;
1508 return MUD;
1509}
1510
1511/// Properly remove \p MA from all of MemorySSA's lookup tables.
1513 assert(MA->use_empty() &&
1514 "Trying to remove memory access that still has uses");
1515 BlockNumbering.erase(MA);
1516 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1517 MUD->setDefiningAccess(nullptr);
1518 // Invalidate our walker's cache if necessary
1519 if (!isa<MemoryUse>(MA))
1521
1522 Value *MemoryInst;
1523 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1524 MemoryInst = MUD->getMemoryInst();
1525 else
1526 MemoryInst = MA->getBlock();
1527
1528 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1529 if (VMA->second == MA)
1530 ValueToMemoryAccess.erase(VMA);
1531}
1532
1533/// Properly remove \p MA from all of MemorySSA's lists.
1534///
1535/// Because of the way the intrusive list and use lists work, it is important to
1536/// do removal in the right order.
1537/// ShouldDelete defaults to true, and will cause the memory access to also be
1538/// deleted, not just removed.
1539void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
1540 BasicBlock *BB = MA->getBlock();
1541 BlockInfo &Info = PerBlock[getBlockIndex(BB)];
1542 // The access list owns the reference, so we erase it from the non-owning list
1543 // first.
1544 if (!isa<MemoryUse>(MA)) {
1545 Info.Defs->remove(*MA);
1546 if (Info.Defs->empty())
1547 Info.Defs.reset();
1548 }
1549
1550 // The erase call here will delete it. If we don't want it deleted, we call
1551 // remove instead.
1552 if (ShouldDelete)
1553 Info.Accesses->erase(MA);
1554 else
1555 Info.Accesses->remove(MA);
1556
1557 if (Info.Accesses->empty()) {
1558 Info.Accesses.reset();
1559 BlockNumberingValid.erase(BB);
1560 }
1561}
1562
1564 MemorySSAAnnotatedWriter Writer(this);
1565 Function *F = this->F;
1566 if (L)
1567 F = L->getHeader()->getParent();
1568 F->print(OS, &Writer);
1569}
1570
1571#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1573#endif
1574
1576#if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS)
1578#endif
1579
1580#ifndef NDEBUG
1581 if (F) {
1582 auto Blocks = iterator_range(F->begin(), F->end());
1585 if (VL == VerificationLevel::Full)
1586 verifyPrevDefInPhis(Blocks);
1587 } else {
1588 assert(L && "must either have loop or function");
1589 auto Blocks =
1590 map_range(L->blocks(), [](const BasicBlock *BB) -> BasicBlock & {
1591 return *const_cast<BasicBlock *>(BB);
1592 });
1595 if (VL == VerificationLevel::Full)
1596 verifyPrevDefInPhis(Blocks);
1597 }
1598#endif
1599 // Previously, the verification used to also verify that the clobberingAccess
1600 // cached by MemorySSA is the same as the clobberingAccess found at a later
1601 // query to AA. This does not hold true in general due to the current fragility
1602 // of BasicAA which has arbitrary caps on the things it analyzes before giving
1603 // up. As a result, transformations that are correct, will lead to BasicAA
1604 // returning different Alias answers before and after that transformation.
1605 // Invalidating MemorySSA is not an option, as the results in BasicAA can be so
1606 // random, in the worst case we'd need to rebuild MemorySSA from scratch after
1607 // every transformation, which defeats the purpose of using it. For such an
1608 // example, see test4 added in D51960.
1609}
1610
1611template <typename IterT>
1612void MemorySSA::verifyPrevDefInPhis(IterT Blocks) const {
1613 for (const BasicBlock &BB : Blocks) {
1614 if (MemoryPhi *Phi = getMemoryAccess(&BB)) {
1615 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
1616 auto *Pred = Phi->getIncomingBlock(I);
1617 auto *IncAcc = Phi->getIncomingValue(I);
1618 // If Pred has no unreachable predecessors, get last def looking at
1619 // IDoms. If, while walkings IDoms, any of these has an unreachable
1620 // predecessor, then the incoming def can be any access.
1621 if (auto *DTNode = DT->getNode(Pred)) {
1622 while (DTNode) {
1623 if (auto *DefList = getBlockDefs(DTNode->getBlock())) {
1624 auto *LastAcc = &*(--DefList->end());
1625 assert(LastAcc == IncAcc &&
1626 "Incorrect incoming access into phi.");
1627 (void)IncAcc;
1628 (void)LastAcc;
1629 break;
1630 }
1631 DTNode = DTNode->getIDom();
1632 }
1633 } else {
1634 // If Pred has unreachable predecessors, but has at least a Def, the
1635 // incoming access can be the last Def in Pred, or it could have been
1636 // optimized to LoE. After an update, though, the LoE may have been
1637 // replaced by another access, so IncAcc may be any access.
1638 // If Pred has unreachable predecessors and no Defs, incoming access
1639 // should be LoE; However, after an update, it may be any access.
1640 }
1641 }
1642 }
1643 }
1644}
1645
1646/// Verify that all of the blocks we believe to have valid domination numbers
1647/// actually have valid domination numbers.
1648template <typename IterT>
1649void MemorySSA::verifyDominationNumbers(IterT Blocks) const {
1650 if (BlockNumberingValid.empty())
1651 return;
1652
1653 SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid;
1654 for (const BasicBlock &BB : Blocks) {
1655 if (!ValidBlocks.count(&BB))
1656 continue;
1657
1658 ValidBlocks.erase(&BB);
1659
1660 const AccessList *Accesses = getBlockAccesses(&BB);
1661 // It's correct to say an empty block has valid numbering.
1662 if (!Accesses)
1663 continue;
1664
1665 // Block numbering starts at 1.
1666 unsigned long LastNumber = 0;
1667 for (const MemoryAccess &MA : *Accesses) {
1668 auto ThisNumberIter = BlockNumbering.find(&MA);
1669 assert(ThisNumberIter != BlockNumbering.end() &&
1670 "MemoryAccess has no domination number in a valid block!");
1671
1672 unsigned long ThisNumber = ThisNumberIter->second;
1673 assert(ThisNumber > LastNumber &&
1674 "Domination numbers should be strictly increasing!");
1675 (void)LastNumber;
1676 LastNumber = ThisNumber;
1677 }
1678 }
1679
1680 assert(ValidBlocks.empty() &&
1681 "All valid BasicBlocks should exist in F -- dangling pointers?");
1682}
1683
1684/// Verify ordering: the order and existence of MemoryAccesses matches the
1685/// order and existence of memory affecting instructions.
1686/// Verify domination: each definition dominates all of its uses.
1687/// Verify def-uses: the immediate use information - walk all the memory
1688/// accesses and verifying that, for each use, it appears in the appropriate
1689/// def's use list
1690template <typename IterT>
1692 VerificationLevel VL) const {
1693 // Walk all the blocks, comparing what the lookups think and what the access
1694 // lists think, as well as the order in the blocks vs the order in the access
1695 // lists.
1696 SmallVector<MemoryAccess *, 32> ActualAccesses;
1698 for (BasicBlock &B : Blocks) {
1699 const AccessList *AL = getBlockAccesses(&B);
1700 const auto *DL = getBlockDefs(&B);
1701 MemoryPhi *Phi = getMemoryAccess(&B);
1702 if (Phi) {
1703 // Verify ordering.
1704 ActualAccesses.push_back(Phi);
1705 ActualDefs.push_back(Phi);
1706 // Verify domination
1707 for (const Use &U : Phi->uses()) {
1708 assert(dominates(Phi, U) && "Memory PHI does not dominate it's uses");
1709 (void)U;
1710 }
1711 // Verify def-uses for full verify.
1712 if (VL == VerificationLevel::Full) {
1713 assert(Phi->getNumOperands() == pred_size(&B) &&
1714 "Incomplete MemoryPhi Node");
1715 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
1716 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
1717 assert(is_contained(predecessors(&B), Phi->getIncomingBlock(I)) &&
1718 "Incoming phi block not a block predecessor");
1719 }
1720 }
1721 }
1722
1723 for (Instruction &I : B) {
1725 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1726 "We have memory affecting instructions "
1727 "in this block but they are not in the "
1728 "access list or defs list");
1729 if (MA) {
1730 // Verify ordering.
1731 ActualAccesses.push_back(MA);
1732 if (MemoryAccess *MD = dyn_cast<MemoryDef>(MA)) {
1733 // Verify ordering.
1734 ActualDefs.push_back(MA);
1735 // Verify domination.
1736 for (const Use &U : MD->uses()) {
1737 assert(dominates(MD, U) &&
1738 "Memory Def does not dominate it's uses");
1739 (void)U;
1740 }
1741 }
1742 // Verify def-uses for full verify.
1743 if (VL == VerificationLevel::Full)
1744 verifyUseInDefs(MA->getDefiningAccess(), MA);
1745 }
1746 }
1747 // Either we hit the assert, really have no accesses, or we have both
1748 // accesses and an access list. Same with defs.
1749 if (!AL && !DL)
1750 continue;
1751 // Verify ordering.
1752 assert(AL->size() == ActualAccesses.size() &&
1753 "We don't have the same number of accesses in the block as on the "
1754 "access list");
1755 assert((DL || ActualDefs.size() == 0) &&
1756 "Either we should have a defs list, or we should have no defs");
1757 assert((!DL || DL->size() == ActualDefs.size()) &&
1758 "We don't have the same number of defs in the block as on the "
1759 "def list");
1760 auto ALI = AL->begin();
1761 auto AAI = ActualAccesses.begin();
1762 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1763 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1764 ++ALI;
1765 ++AAI;
1766 }
1767 ActualAccesses.clear();
1768 if (DL) {
1769 auto DLI = DL->begin();
1770 auto ADI = ActualDefs.begin();
1771 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1772 assert(&*DLI == *ADI && "Not the same defs in the same order");
1773 ++DLI;
1774 ++ADI;
1775 }
1776 }
1777 ActualDefs.clear();
1778 }
1779}
1780
1781/// Verify the def-use lists in MemorySSA, by verifying that \p Use
1782/// appears in the use list of \p Def.
1783void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
1784 // The live on entry use may cause us to get a NULL def here
1785 if (!Def)
1787 "Null def but use not point to live on entry def");
1788 else
1789 assert(is_contained(Def->users(), Use) &&
1790 "Did not find use in def's use list");
1791}
1792
1793/// Perform a local numbering on blocks so that instruction ordering can be
1794/// determined in constant time.
1795/// TODO: We currently just number in order. If we numbered by N, we could
1796/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1797/// log2(N) sequences of mixed before and after) without needing to invalidate
1798/// the numbering.
1799void MemorySSA::renumberBlock(const BasicBlock *B) const {
1800 // The pre-increment ensures the numbers really start at 1.
1801 unsigned long CurrentNumber = 0;
1802 const AccessList *AL = getBlockAccesses(B);
1803 assert(AL != nullptr && "Asking to renumber an empty block");
1804 for (const auto &I : *AL)
1805 BlockNumbering[&I] = ++CurrentNumber;
1806 BlockNumberingValid.insert(B);
1807}
1808
1809/// Determine, for two memory accesses in the same block,
1810/// whether \p Dominator dominates \p Dominatee.
1811/// \returns True if \p Dominator dominates \p Dominatee.
1813 const MemoryAccess *Dominatee) const {
1814 const BasicBlock *DominatorBlock = Dominator->getBlock();
1815
1816 assert((DominatorBlock == Dominatee->getBlock()) &&
1817 "Asking for local domination when accesses are in different blocks!");
1818 // A node dominates itself.
1819 if (Dominatee == Dominator)
1820 return true;
1821
1822 // When Dominatee is defined on function entry, it is not dominated by another
1823 // memory access.
1824 if (isLiveOnEntryDef(Dominatee))
1825 return false;
1826
1827 // When Dominator is defined on function entry, it dominates the other memory
1828 // access.
1829 if (isLiveOnEntryDef(Dominator))
1830 return true;
1831
1832 if (!BlockNumberingValid.count(DominatorBlock))
1833 renumberBlock(DominatorBlock);
1834
1835 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1836 // All numbers start with 1
1837 assert(DominatorNum != 0 && "Block was not numbered properly");
1838 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1839 assert(DominateeNum != 0 && "Block was not numbered properly");
1840 return DominatorNum < DominateeNum;
1841}
1842
1844 const MemoryAccess *Dominatee) const {
1845 if (Dominator == Dominatee)
1846 return true;
1847
1848 if (isLiveOnEntryDef(Dominatee))
1849 return false;
1850
1851 if (Dominator->getBlock() != Dominatee->getBlock())
1852 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1853 return locallyDominates(Dominator, Dominatee);
1854}
1855
1857 const Use &Dominatee) const {
1858 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1859 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1860 // The def must dominate the incoming block of the phi.
1861 if (UseBB != Dominator->getBlock())
1862 return DT->dominates(Dominator->getBlock(), UseBB);
1863 // If the UseBB and the DefBB are the same, compare locally.
1864 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1865 }
1866 // If it's not a PHI node use, the normal dominates can already handle it.
1867 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1868}
1869
1871 switch (getValueID()) {
1872 case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
1873 case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
1874 case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
1875 }
1876 llvm_unreachable("invalid value id");
1877}
1878
1881
1882 auto printID = [&OS](MemoryAccess *A) {
1883 if (A && A->getID())
1884 OS << A->getID();
1885 else
1886 OS << LiveOnEntryStr;
1887 };
1888
1889 OS << getID() << " = MemoryDef(";
1890 printID(UO);
1891 OS << ")";
1892
1893 if (isOptimized()) {
1894 OS << "->";
1895 printID(getOptimized());
1896 }
1897}
1898
1900 ListSeparator LS(",");
1901 OS << getID() << " = MemoryPhi(";
1902 for (const auto &Op : operands()) {
1905
1906 OS << LS << '{';
1907 if (BB->hasName())
1908 OS << BB->getName();
1909 else
1910 BB->printAsOperand(OS, false);
1911 OS << ',';
1912 if (unsigned ID = MA->getID())
1913 OS << ID;
1914 else
1915 OS << LiveOnEntryStr;
1916 OS << '}';
1917 }
1918 OS << ')';
1919}
1920
1923 OS << "MemoryUse(";
1924 if (UO && UO->getID())
1925 OS << UO->getID();
1926 else
1927 OS << LiveOnEntryStr;
1928 OS << ')';
1929}
1930
1932// Cannot completely remove virtual function even in release mode.
1933#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1934 print(dbgs());
1935 dbgs() << "\n";
1936#endif
1937}
1938
1940private:
1941 const Function &F;
1942 MemorySSAAnnotatedWriter MSSAWriter;
1943
1944public:
1946 : F(F), MSSAWriter(&MSSA) {}
1947
1948 const Function *getFunction() { return &F; }
1949 MemorySSAAnnotatedWriter &getWriter() { return MSSAWriter; }
1950};
1951
1952namespace llvm {
1953
1954template <>
1957 return &(CFGInfo->getFunction()->getEntryBlock());
1958 }
1959
1960 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
1962
1964 return nodes_iterator(CFGInfo->getFunction()->begin());
1965 }
1966
1968 return nodes_iterator(CFGInfo->getFunction()->end());
1969 }
1970
1971 static size_t size(DOTFuncMSSAInfo *CFGInfo) {
1972 return CFGInfo->getFunction()->size();
1973 }
1974};
1975
1976template <>
1978
1979 DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {}
1980
1981 static std::string getGraphName(DOTFuncMSSAInfo *CFGInfo) {
1982 return "MSSA CFG for '" + CFGInfo->getFunction()->getName().str() +
1983 "' function";
1984 }
1985
1986 std::string getNodeLabel(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo) {
1988 Node, nullptr,
1989 [CFGInfo](raw_string_ostream &OS, const BasicBlock &BB) -> void {
1990 BB.print(OS, &CFGInfo->getWriter(), true, true);
1991 },
1992 [](std::string &S, unsigned &I, unsigned Idx) -> void {
1993 std::string Str = S.substr(I, Idx - I);
1994 StringRef SR = Str;
1995 if (SR.count(" = MemoryDef(") || SR.count(" = MemoryPhi(") ||
1996 SR.count("MemoryUse("))
1997 return;
1999 });
2000 }
2001
2006
2007 /// Display the raw branch weights from PGO.
2009 DOTFuncMSSAInfo *CFGInfo) {
2010 return "";
2011 }
2012
2014 DOTFuncMSSAInfo *CFGInfo) {
2015 return getNodeLabel(Node, CFGInfo).find(';') != std::string::npos
2016 ? "style=filled, fillcolor=lightpink"
2017 : "";
2018 }
2019};
2020
2021} // namespace llvm
2022
2023AnalysisKey MemorySSAAnalysis::Key;
2024
2027 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2028 auto &AA = AM.getResult<AAManager>(F);
2029 return MemorySSAAnalysis::Result(std::make_unique<MemorySSA>(F, &AA, &DT));
2030}
2031
2033 Function &F, const PreservedAnalyses &PA,
2034 FunctionAnalysisManager::Invalidator &Inv) {
2035 auto PAC = PA.getChecker<MemorySSAAnalysis>();
2036 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
2037 Inv.invalidate<AAManager>(F, PA) ||
2038 Inv.invalidate<DominatorTreeAnalysis>(F, PA);
2039}
2040
2043 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2044 StringRef DotCFGMSSA = getAnalysisOptions(F).dot_cfg_mssa;
2045 if (!DotCFGMSSA.empty()) {
2046 DOTFuncMSSAInfo CFGInfo(F, MSSA);
2047 WriteGraph(&CFGInfo, "", false, "MSSA", DotCFGMSSA.str());
2048 } else {
2049 OS << "MemorySSA for function: " << F.getName() << "\n";
2050 MSSA.print(OS);
2051 }
2052
2053 return PreservedAnalyses::all();
2054}
2055
2058 auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
2059 OS << "MemorySSA (walker) for function: " << F.getName() << "\n";
2060 MemorySSAWalkerAnnotatedWriter Writer(&MSSA);
2061 F.print(OS, &Writer);
2062
2063 return PreservedAnalyses::all();
2064}
2065
2068 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
2069
2070 return PreservedAnalyses::all();
2071}
2072
2074
2076
2078
2084
2086 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2087 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2088 MSSA.reset(new MemorySSA(F, &AA, &DT));
2089 return false;
2090}
2091
2093 if (VerifyMemorySSA)
2094 MSSA->verifyMemorySSA();
2095}
2096
2098 MSSA->print(OS);
2099}
2100
2102
2103/// Walk the use-def chains starting at \p StartingAccess and find
2104/// the MemoryAccess that actually clobbers Loc.
2105///
2106/// \returns our clobbering memory access
2108 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
2109 BatchAAResults &BAA, unsigned &UpwardWalkLimit) {
2110 assert(!isa<MemoryUse>(StartingAccess) && "Use cannot be defining access");
2111
2112 // If location is undefined, conservatively return starting access.
2113 if (Loc.Ptr == nullptr)
2114 return StartingAccess;
2115
2116 Instruction *I = nullptr;
2117 if (auto *StartingUseOrDef = dyn_cast<MemoryUseOrDef>(StartingAccess)) {
2118 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2119 return StartingUseOrDef;
2120
2121 I = StartingUseOrDef->getMemoryInst();
2122
2123 // Conservatively, fences are always clobbers, so don't perform the walk if
2124 // we hit a fence.
2125 if (!isa<CallBase>(I) && I->isFenceLike())
2126 return StartingUseOrDef;
2127 }
2128
2129 UpwardsMemoryQuery Q;
2130 Q.OriginalAccess = StartingAccess;
2131 Q.StartingLoc = Loc;
2132 Q.Inst = nullptr;
2133 Q.IsCall = false;
2134
2135 // Unlike the other function, do not walk to the def of a def, because we are
2136 // handed something we already believe is the clobbering access.
2137 // We never set SkipSelf to true in Q in this method.
2138 MemoryAccess *Clobber =
2139 Walker.findClobber(BAA, StartingAccess, Q, UpwardWalkLimit);
2140 LLVM_DEBUG({
2141 dbgs() << "Clobber starting at access " << *StartingAccess << "\n";
2142 if (I)
2143 dbgs() << " for instruction " << *I << "\n";
2144 dbgs() << " is " << *Clobber << "\n";
2145 });
2146 return Clobber;
2147}
2148
2149static const Instruction *
2151 if (!I.hasMetadata(LLVMContext::MD_invariant_group) || I.isVolatile())
2152 return nullptr;
2153
2154 // We consider bitcasts and zero GEPs to be the same pointer value. Start by
2155 // stripping bitcasts and zero GEPs, then we will recursively look at loads
2156 // and stores through bitcasts and zero GEPs.
2157 Value *PointerOperand = getLoadStorePointerOperand(&I)->stripPointerCasts();
2158
2159 // It's not safe to walk the use list of a global value because function
2160 // passes aren't allowed to look outside their functions.
2161 // FIXME: this could be fixed by filtering instructions from outside of
2162 // current function.
2163 if (isa<Constant>(PointerOperand))
2164 return nullptr;
2165
2166 const Instruction *MostDominatingInstruction = &I;
2167
2168 for (const User *Us : PointerOperand->users()) {
2169 auto *U = dyn_cast<Instruction>(Us);
2170 if (!U || U == &I || !DT.dominates(U, MostDominatingInstruction))
2171 continue;
2172
2173 // If we hit a load/store with an invariant.group metadata and the same
2174 // pointer operand, we can assume that value pointed to by the pointer
2175 // operand didn't change.
2176 if (U->hasMetadata(LLVMContext::MD_invariant_group) &&
2177 getLoadStorePointerOperand(U) == PointerOperand && !U->isVolatile()) {
2178 MostDominatingInstruction = U;
2179 }
2180 }
2181
2182 return MostDominatingInstruction == &I ? nullptr : MostDominatingInstruction;
2183}
2184
2186 MemoryAccess *MA, BatchAAResults &BAA, unsigned &UpwardWalkLimit,
2187 bool SkipSelf) {
2188 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2189 // If this is a MemoryPhi, we can't do anything.
2190 if (!StartingAccess)
2191 return MA;
2192
2194 *StartingAccess->getMemoryInst(), MSSA->getDomTree())) {
2196
2197 auto *ClobberMA = MSSA->getMemoryAccess(I);
2198 assert(ClobberMA);
2199 if (isa<MemoryUse>(ClobberMA))
2200 return ClobberMA->getDefiningAccess();
2201 return ClobberMA;
2202 }
2203
2204 bool IsOptimized = false;
2205
2206 // If this is an already optimized use or def, return the optimized result.
2207 // Note: Currently, we store the optimized def result in a separate field,
2208 // since we can't use the defining access.
2209 if (StartingAccess->isOptimized()) {
2210 if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
2211 return StartingAccess->getOptimized();
2212 IsOptimized = true;
2213 }
2214
2215 const Instruction *I = StartingAccess->getMemoryInst();
2216 // We can't sanely do anything with a fence, since they conservatively clobber
2217 // all memory, and have no locations to get pointers from to try to
2218 // disambiguate.
2219 if (!isa<CallBase>(I) && I->isFenceLike())
2220 return StartingAccess;
2221
2222 UpwardsMemoryQuery Q(I, StartingAccess);
2223
2225 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2226 StartingAccess->setOptimized(LiveOnEntry);
2227 return LiveOnEntry;
2228 }
2229
2230 MemoryAccess *OptimizedAccess;
2231 if (!IsOptimized) {
2232 // Start with the thing we already think clobbers this location
2233 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2234
2235 // At this point, DefiningAccess may be the live on entry def.
2236 // If it is, we will not get a better result.
2237 if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
2238 StartingAccess->setOptimized(DefiningAccess);
2239 return DefiningAccess;
2240 }
2241
2242 OptimizedAccess =
2243 Walker.findClobber(BAA, DefiningAccess, Q, UpwardWalkLimit);
2244 StartingAccess->setOptimized(OptimizedAccess);
2245 } else
2246 OptimizedAccess = StartingAccess->getOptimized();
2247
2248 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2249 LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
2250 LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
2251 LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
2252
2253 MemoryAccess *Result;
2254 if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) &&
2255 isa<MemoryDef>(StartingAccess) && UpwardWalkLimit) {
2256 assert(isa<MemoryDef>(Q.OriginalAccess));
2257 Q.SkipSelfAccess = true;
2258 Result = Walker.findClobber(BAA, OptimizedAccess, Q, UpwardWalkLimit);
2259 } else
2260 Result = OptimizedAccess;
2261
2262 LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2263 LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
2264
2265 return Result;
2266}
2267
2268MemoryAccess *
2270 BatchAAResults &) {
2271 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2272 return Use->getDefiningAccess();
2273 return MA;
2274}
2275
2277 MemoryAccess *StartingAccess, const MemoryLocation &, BatchAAResults &) {
2278 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2279 return Use->getDefiningAccess();
2280 return StartingAccess;
2281}
2282
2283void MemoryPhi::deleteMe(DerivedUser *Self) {
2284 delete static_cast<MemoryPhi *>(Self);
2285}
2286
2287void MemoryDef::deleteMe(DerivedUser *Self) {
2288 static_cast<MemoryDef *>(Self)->~MemoryDef();
2289}
2290
2291void MemoryUse::deleteMe(DerivedUser *Self) {
2292 static_cast<MemoryUse *>(Self)->~MemoryUse();
2293}
2294
2295bool upward_defs_iterator::IsGuaranteedLoopInvariant(const Value *Ptr) const {
2296 auto IsGuaranteedLoopInvariantBase = [](const Value *Ptr) {
2297 Ptr = Ptr->stripPointerCasts();
2298 if (!isa<Instruction>(Ptr))
2299 return true;
2300 return isa<AllocaInst>(Ptr);
2301 };
2302
2303 Ptr = Ptr->stripPointerCasts();
2304 if (auto *I = dyn_cast<Instruction>(Ptr)) {
2305 if (I->getParent()->isEntryBlock())
2306 return true;
2307 }
2308 if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
2309 return IsGuaranteedLoopInvariantBase(GEP->getPointerOperand()) &&
2310 GEP->hasAllConstantIndices();
2311 }
2312 return IsGuaranteedLoopInvariantBase(Ptr);
2313}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
DXIL Forward Handle Accesses
DXIL Resource Access
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
early cse Early CSE w MemorySSA
Hexagon Common GEP
#define _
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
static bool instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc, const Instruction *UseInst, AliasAnalysisType &AA)
static void checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt, const MemoryLocation &StartLoc, const MemorySSA &MSSA, const UpwardsMemoryQuery &Query, BatchAAResults &AA, bool AllowImpreciseClobber=false)
Verifies that Start is clobbered by ClobberAt, and that nothing inbetween Start and ClobberAt can clo...
static AccessT * allocateUseOrDef(AllocatorT &Allocator, ArgTs &&...Args)
Allocate a MemoryUse or MemoryDef from Allocator, with its operands in front of it like User::operato...
static cl::opt< bool, true > VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA), cl::Hidden, cl::desc("Enable verification of MemorySSA."))
static const char LiveOnEntryStr[]
Definition MemorySSA.cpp:81
static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA, const Instruction *I)
static bool areLoadsReorderable(const LoadInst *Use, const LoadInst *MayClobber)
This does one-way checks to see if Use could theoretically be hoisted above MayClobber.
static const Instruction * getInvariantGroupClobberingInstruction(Instruction &I, DominatorTree &DT)
static bool isOrdered(const Instruction *I)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
#define T
static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS)
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
Basic Register Allocator
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
DOTFuncMSSAInfo(const Function &F, MemorySSA &MSSA)
const Function * getFunction()
MemorySSAAnnotatedWriter & getWriter()
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
LLVM Basic Block Representation.
Definition BasicBlock.h:61
LLVM_ABI BasicBlock::iterator erase(BasicBlock::iterator FromIt, BasicBlock::iterator ToIt)
Erases a range of instructions from FromIt to (not including) ToIt.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
LLVM_ABI void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the basic block to an output stream with an optional AssemblyAnnotationWriter.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
Temporarily set the cross iteration mode on a BatchAA instance.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Extension point for the Value hierarchy.
Definition DerivedUser.h:26
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *, BatchAAResults &) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
iterator begin() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass(char &pid)
Definition Pass.h:314
unsigned getMaxBlockNumber() const
Return a value larger than the largest block number.
Definition Function.h:822
iterator begin()
Definition Function.h:847
size_t size() const
Definition Function.h:852
iterator end()
Definition Function.h:849
Module * getParent()
Get the module that this global value is contained inside of...
A wrapper class for inspecting calls to intrinsic functions.
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI void dump() const
MemoryAccess(const MemoryAccess &)=delete
friend class MemoryUse
Definition MemorySSA.h:216
friend class MemoryPhi
Definition MemorySSA.h:214
friend class MemoryDef
Definition MemorySSA.h:213
BasicBlock * getBlock() const
Definition MemorySSA.h:168
LLVM_ABI void print(raw_ostream &OS) const
unsigned getID() const
Used for debugging and tracking things about MemoryAccesses.
Definition MemorySSA.h:653
void setBlock(BasicBlock *BB)
Used by MemorySSA to change the block of a MemoryAccess when it is moved.
Definition MemorySSA.h:221
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition MemorySSA.h:372
LLVM_ABI void print(raw_ostream &OS) const
MemoryAccess * getOptimized() const
Definition MemorySSA.h:394
unsigned getID() const
Definition MemorySSA.h:409
bool isOptimized() const
Definition MemorySSA.h:398
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
Represents phi nodes for memory accesses.
Definition MemorySSA.h:476
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
Definition MemorySSA.h:539
LLVM_ABI void print(raw_ostream &OS) const
unsigned getID() const
Definition MemorySSA.h:624
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:930
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static LLVM_ABI bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This is the generic walker interface for walkers of MemorySSA.
Definition MemorySSA.h:1012
friend class MemorySSA
Definition MemorySSA.h:1092
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition MemorySSA.h:1041
LLVM_ABI MemorySSAWalker(MemorySSA *)
virtual void invalidateInfo(MemoryAccess *)
Given a memory access, invalidate anything this walker knows about that access.
Definition MemorySSA.h:1089
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:981
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
A MemorySSAWalker that does AA walks to disambiguate accesses.
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA, unsigned &UWL)
void invalidateInfo(MemoryAccess *MA) override
Given a memory access, invalidate anything this walker knows about that access.
~CachingWalker() override=default
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA, unsigned &UWL)
CachingWalker(MemorySSA *M, ClobberWalkerBase *W)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA) override
Given a potentially clobbering memory access and a new location, calling this will give you the neare...
ClobberWalkerBase(MemorySSA *M, DominatorTree *D)
MemoryAccess * getClobberingMemoryAccessBase(MemoryAccess *, BatchAAResults &, unsigned &, bool)
MemoryAccess * getClobberingMemoryAccessBase(MemoryAccess *, const MemoryLocation &, BatchAAResults &, unsigned &)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA) override
Given a potentially clobbering memory access and a new location, calling this will give you the neare...
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc, BatchAAResults &BAA, unsigned &UWL)
~SkipSelfWalker() override=default
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA, unsigned &UWL)
SkipSelfWalker(MemorySSA *M, ClobberWalkerBase *W)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, BatchAAResults &BAA) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
void invalidateInfo(MemoryAccess *MA) override
Given a memory access, invalidate anything this walker knows about that access.
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:692
LLVM_ABI void dump() const
simple_ilist< MemoryAccess, ilist_tag< MSSAHelpers::DefsOnlyTag > > DefsList
Definition MemorySSA.h:744
LLVM_ABI void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where)
void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal, SmallPtrSetImpl< BasicBlock * > &Visited)
Definition MemorySSA.h:805
DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
Definition MemorySSA.h:755
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
LLVM_ABI MemorySSA(Function &, AliasAnalysis *, DominatorTree *)
iplist< MemoryAccess, ilist_tag< MSSAHelpers::AllAccessTag > > AccessList
Definition MemorySSA.h:743
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Definition MemorySSA.h:748
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
void verifyOrderingDominationAndDefUses(IterT Blocks, VerificationLevel=VerificationLevel::Fast) const
Verify ordering: the order and existence of MemoryAccesses matches the order and existence of memory ...
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
LLVM_ABI void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *, InsertionPlace)
LLVM_ABI MemorySSAWalker * getWalker()
InsertionPlace
Used in various insertion functions to specify whether we are talking about the beginning or end of a...
Definition MemorySSA.h:781
LLVM_ABI void insertIntoListsBefore(MemoryAccess *, const BasicBlock *, AccessList::iterator)
LLVM_ABI MemoryUseOrDef * createDefinedAccess(Instruction *, MemoryAccess *, const MemoryUseOrDef *Template=nullptr, bool CreationMustSucceed=true)
DominatorTree & getDomTree() const
Definition MemorySSA.h:718
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:710
MemoryAccess * getLiveOnEntryDef() const
Definition MemorySSA.h:734
LLVM_ABI void removeFromLookups(MemoryAccess *)
Properly remove MA from all of MemorySSA's lookup tables.
void verifyDominationNumbers(IterT Blocks) const
Verify that all of the blocks we believe to have valid domination numbers actually have valid dominat...
void verifyPrevDefInPhis(IterT Blocks) const
LLVM_ABI bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
LLVM_ABI void removeFromLists(MemoryAccess *, bool ShouldDelete=true)
Properly remove MA from all of MemorySSA's lists.
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:730
LLVM_ABI ~MemorySSA()
LLVM_ABI void print(raw_ostream &) const
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:256
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Definition MemorySSA.h:266
void setDefiningAccess(MemoryAccess *DMA, bool Optimized=false)
Definition MemorySSA.h:299
void setOptimized(MemoryAccess *)
Sets the optimized use for a MemoryDef.
Definition MemorySSA.h:673
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
Definition MemorySSA.h:263
LLVM_ABI void print(raw_ostream &OS) const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the module to an output stream with an optional AssemblyAnnotationWriter.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
size_t count(char C) const
Return the number of occurrences of C in the string.
Definition StringRef.h:463
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
void dropAllReferences()
Drop all references to operands.
Definition User.h:324
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:428
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
typename base_list_type::iterator iterator
Definition ilist.h:121
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
iterator insert(iterator I, reference Node)
Insert a node by reference; never copies.
void push_back(reference Node)
Insert a node at the back; never copies.
reverse_iterator rbegin()
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LocationClass< Ty > location(Ty &L)
@ Init
Initialization function, sets up the coroutine frame.
Definition CodeView.h:644
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APInt operator*(APInt a, uint64_t RHS)
Definition APInt.h:2261
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
auto pred_size(const MachineBasicBlock *BB)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
Op::Description Desc
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
iterator_range< def_chain_iterator< T > > def_chain(T MA, MemoryAccess *UpTo=nullptr)
Definition MemorySSA.h:1374
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
auto find_if_not(R &&Range, UnaryPredicate P)
Definition STLExtras.h:1793
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isAtLeastOrStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:74
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
IDFCalculator< false > ForwardIDFCalculator
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
upward_defs_iterator upward_defs_end()
Definition MemorySSA.h:1328
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Instruction::const_succ_iterator const_succ_iterator
Definition CFG.h:127
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
upward_defs_iterator upward_defs_begin(const UpwardDefsElem &Pair, DominatorTree &DT)
Definition MemorySSA.h:1323
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define MAP(n)
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
std::string getEdgeAttributes(const BasicBlock *Node, const_succ_iterator I, DOTFuncMSSAInfo *CFGInfo)
Display the raw branch weights from PGO.
std::string getNodeAttributes(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo)
static std::string getEdgeSourceLabel(const BasicBlock *Node, const_succ_iterator I)
std::string getNodeLabel(const BasicBlock *Node, DOTFuncMSSAInfo *CFGInfo)
static std::string getGraphName(DOTFuncMSSAInfo *CFGInfo)
static std::string getEdgeSourceLabel(const void *, EdgeIter)
getEdgeSourceLabel - If you want to label the edge source itself, implement this method.
pointer_iterator< Function::const_iterator > nodes_iterator
static size_t size(DOTFuncMSSAInfo *CFGInfo)
static NodeRef getEntryNode(DOTFuncMSSAInfo *CFGInfo)
static nodes_iterator nodes_begin(DOTFuncMSSAInfo *CFGInfo)
static nodes_iterator nodes_end(DOTFuncMSSAInfo *CFGInfo)
typename DOTFuncMSSAInfo *::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:94
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Compile-time customization of User operands.
Definition User.h:42