LLVM 24.0.0git
MemoryDependenceAnalysis.cpp
Go to the documentation of this file.
1//===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===//
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 an analysis that determines, for a given memory
10// operation, what preceding memory operations it depends on. It builds on
11// alias analysis information, and tries to provide a lazy, caching interface to
12// a common kind of alias information query.
13//
14//===----------------------------------------------------------------------===//
15
17#include "AnalysisOptions.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/Statistic.h"
25#include "llvm/Analysis/Loads.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/InstrTypes.h"
35#include "llvm/IR/Instruction.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Metadata.h"
40#include "llvm/IR/Module.h"
42#include "llvm/IR/Type.h"
43#include "llvm/IR/Use.h"
44#include "llvm/IR/Value.h"
46#include "llvm/Pass.h"
50#include "llvm/Support/Debug.h"
51#include <algorithm>
52#include <cassert>
53#include <iterator>
54#include <utility>
55
56using namespace llvm;
57
58#define DEBUG_TYPE "memdep"
59
60STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
61STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
62STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
63
64STATISTIC(NumCacheNonLocalPtr,
65 "Number of fully cached non-local ptr responses");
66STATISTIC(NumCacheDirtyNonLocalPtr,
67 "Number of cached, but dirty, non-local ptr responses");
68STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses");
69STATISTIC(NumCacheCompleteNonLocalPtr,
70 "Number of block queries that were completely cached");
71
72// Limit on the number of memdep results to process.
73static const unsigned int NumResultsLimit = 100;
74
75/// This is a helper function that removes Val from 'Inst's set in ReverseMap.
76///
77/// If the set becomes empty, remove Inst's entry.
78template <typename KeyTy>
79static void
81 Instruction *Inst, KeyTy Val) {
83 ReverseMap.find(Inst);
84 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
85 bool Found = InstIt->second.erase(Val);
86 assert(Found && "Invalid reverse map!");
87 (void)Found;
88 if (InstIt->second.empty())
89 ReverseMap.erase(InstIt);
90}
91
92/// If the given instruction references a specific memory location, fill in Loc
93/// with the details, otherwise set Loc.Ptr to null.
94///
95/// Returns a ModRefInfo value describing the general behavior of the
96/// instruction.
98 const TargetLibraryInfo &TLI) {
99 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
100 if (LI->isUnordered()) {
102 return ModRefInfo::Ref;
103 }
104 if (LI->getOrdering() == AtomicOrdering::Monotonic) {
106 return ModRefInfo::ModRef;
107 }
109 return ModRefInfo::ModRef;
110 }
111
112 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
113 if (SI->isUnordered()) {
115 return ModRefInfo::Mod;
116 }
117 if (SI->getOrdering() == AtomicOrdering::Monotonic) {
119 return ModRefInfo::ModRef;
120 }
122 return ModRefInfo::ModRef;
123 }
124
125 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
127 return ModRefInfo::ModRef;
128 }
129
130 if (const CallBase *CB = dyn_cast<CallBase>(Inst)) {
131 if (Value *FreedOp = getFreedOperand(CB, &TLI)) {
132 // calls to free() deallocate the entire structure
133 Loc = MemoryLocation::getAfter(FreedOp);
134 return ModRefInfo::Mod;
135 }
136 }
137
138 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
139 switch (II->getIntrinsicID()) {
140 case Intrinsic::lifetime_start:
141 case Intrinsic::lifetime_end:
143 // These intrinsics don't really modify the memory, but returning Mod
144 // will allow them to be handled conservatively.
145 return ModRefInfo::Mod;
146 case Intrinsic::invariant_start:
148 // These intrinsics don't really modify the memory, but returning Mod
149 // will allow them to be handled conservatively.
150 return ModRefInfo::Mod;
151 case Intrinsic::invariant_end:
153 // These intrinsics don't really modify the memory, but returning Mod
154 // will allow them to be handled conservatively.
155 return ModRefInfo::Mod;
156 case Intrinsic::masked_load:
158 return ModRefInfo::Ref;
159 case Intrinsic::masked_store:
161 return ModRefInfo::Mod;
162 default:
163 break;
164 }
165 }
166
167 // Otherwise, just do the coarse-grained thing that always works.
168 if (Inst->mayWriteToMemory())
169 return ModRefInfo::ModRef;
170 if (Inst->mayReadFromMemory())
171 return ModRefInfo::Ref;
173}
174
175/// Private helper for finding the local dependencies of a call site.
176MemDepResult MemoryDependenceResults::getCallDependencyFrom(
177 CallBase *Call, bool isReadOnlyCall, BasicBlock::iterator ScanIt,
178 BasicBlock *BB) {
179 unsigned Limit = getDefaultBlockScanLimit();
180 bool IsInvariantLoad = Call->hasMetadata(LLVMContext::MD_invariant_load);
181
182 // Walk backwards through the block, looking for dependencies.
183 while (ScanIt != BB->begin()) {
184 Instruction *Inst = &*--ScanIt;
185
186 // Limit the amount of scanning we do so we don't end up with quadratic
187 // running time on extreme testcases.
188 --Limit;
189 if (!Limit)
191
192 // If this inst is a memory op, get the pointer it accessed
193 MemoryLocation Loc;
194 ModRefInfo MR = GetLocation(Inst, Loc, TLI);
195 if (Loc.Ptr) {
196 // A simple instruction.
197 if (isModOrRefSet(AA.getModRefInfo(Call, Loc))) {
198 if (IsInvariantLoad)
199 continue;
200 return MemDepResult::getClobber(Inst);
201 }
202 continue;
203 }
204
205 if (auto *CallB = dyn_cast<CallBase>(Inst)) {
206 bool IsIdenticalReadOnlyCall = isReadOnlyCall && !isModSet(MR) &&
208
209 // An identical earlier invariant load-like call is an available value
210 // even if AA sees both calls as reading the same memory.
211 if (IsInvariantLoad && IsIdenticalReadOnlyCall)
212 return MemDepResult::getDef(Inst);
213
214 // If these two calls do not interfere, look past it.
215 if (isNoModRef(AA.getModRefInfo(Call, CallB))) {
216 // If the two calls are the same, return Inst as a Def, so that
217 // Call can be found redundant and eliminated.
218 if (IsIdenticalReadOnlyCall)
219 return MemDepResult::getDef(Inst);
220
221 // Otherwise if the two calls don't interact (e.g. CallB is readnone)
222 // keep scanning.
223 continue;
224 } else if (IsInvariantLoad) {
225 continue;
226 } else {
227 return MemDepResult::getClobber(Inst);
228 }
229 }
230
231 // If we could not obtain a pointer for the instruction and the instruction
232 // touches memory then assume that this is a dependency.
233 if (isModOrRefSet(MR))
234 return MemDepResult::getClobber(Inst);
235 }
236
237 // No dependence found. If this is the entry block of the function, it is
238 // unknown, otherwise it is non-local.
239 if (BB != &BB->getParent()->getEntryBlock())
242}
243
245 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
246 BasicBlock *BB, Instruction *QueryInst, unsigned *Limit,
247 BatchAAResults &BatchAA) {
248 MemDepResult InvariantGroupDependency = MemDepResult::getUnknown();
249 if (QueryInst != nullptr) {
250 if (auto *LI = dyn_cast<LoadInst>(QueryInst)) {
251 InvariantGroupDependency = getInvariantGroupPointerDependency(LI, BB);
252
253 if (InvariantGroupDependency.isDef())
254 return InvariantGroupDependency;
255 }
256 }
258 MemLoc, isLoad, ScanIt, BB, QueryInst, Limit, BatchAA);
259 if (SimpleDep.isDef())
260 return SimpleDep;
261 // Non-local invariant group dependency indicates there is non local Def
262 // (it only returns nonLocal if it finds nonLocal def), which is better than
263 // local clobber and everything else.
264 if (InvariantGroupDependency.isNonLocal())
265 return InvariantGroupDependency;
266
267 assert(InvariantGroupDependency.isUnknown() &&
268 "InvariantGroupDependency should be only unknown at this point");
269 return SimpleDep;
270}
271
273 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
274 BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) {
275 BatchAAResults BatchAA(AA, &EEA);
276 return getPointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst, Limit,
277 BatchAA);
278}
279
282 BasicBlock *BB) {
283
284 if (!LI->hasMetadata(LLVMContext::MD_invariant_group))
286
287 // Take the ptr operand after all casts and geps 0. This way we can search
288 // cast graph down only.
289 Value *LoadOperand = LI->getPointerOperand()->stripPointerCasts();
290
291 // It's is not safe to walk the use list of constant, because function
292 // passes aren't allowed to look outside their functions.
293 // FIXME: this could be fixed by filtering instructions from outside
294 // of current function.
295 if (isa<Constant>(LoadOperand))
297
298 Instruction *ClosestDependency = nullptr;
299 // Order of instructions in uses list is unpredictible. In order to always
300 // get the same result, we will look for the closest dominance.
301 auto GetClosestDependency = [this](Instruction *Best, Instruction *Other) {
302 assert(Other && "Must call it with not null instruction");
303 if (Best == nullptr || DT.dominates(Best, Other))
304 return Other;
305 return Best;
306 };
307
308 for (const Use &Us : LoadOperand->uses()) {
309 auto *U = dyn_cast<Instruction>(Us.getUser());
310 if (!U || U == LI || !DT.dominates(U, LI))
311 continue;
312
313 // If we hit load/store with the same invariant.group metadata (and the
314 // same pointer operand) we can assume that value pointed by pointer
315 // operand didn't change.
316 if ((isa<LoadInst>(U) ||
317 (isa<StoreInst>(U) &&
318 cast<StoreInst>(U)->getPointerOperand() == LoadOperand)) &&
319 U->hasMetadata(LLVMContext::MD_invariant_group))
320 ClosestDependency = GetClosestDependency(ClosestDependency, U);
321 }
322
323 if (!ClosestDependency)
325 if (ClosestDependency->getParent() == BB)
326 return MemDepResult::getDef(ClosestDependency);
327 // Def(U) can't be returned here because it is non-local. If local
328 // dependency won't be found then return nonLocal counting that the
329 // user will call getNonLocalPointerDependency, which will return cached
330 // result.
331 NonLocalDefsCache.try_emplace(
332 LI, NonLocalDepResult(ClosestDependency->getParent(),
333 MemDepResult::getDef(ClosestDependency), nullptr));
334 ReverseNonLocalDefsCache[ClosestDependency].insert(LI);
336}
337
339 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
340 BasicBlock *BB, Instruction *QueryInst, unsigned *Limit,
341 BatchAAResults &BatchAA) {
342 bool isInvariantLoad = false;
343 Align MemLocAlign =
345
346 unsigned DefaultLimit = getDefaultBlockScanLimit();
347 if (!Limit)
348 Limit = &DefaultLimit;
349
350 // We must be careful with atomic accesses, as they may allow another thread
351 // to touch this location, clobbering it. We are conservative: if the
352 // QueryInst is not a simple (non-atomic) memory access, we automatically
353 // return getClobber.
354 // If it is simple, we know based on the results of
355 // "Compiler testing via a theory of sound optimisations in the C11/C++11
356 // memory model" in PLDI 2013, that a non-atomic location can only be
357 // clobbered between a pair of a release and an acquire action, with no
358 // access to the location in between.
359 // Here is an example for giving the general intuition behind this rule.
360 // In the following code:
361 // store x 0;
362 // release action; [1]
363 // acquire action; [4]
364 // %val = load x;
365 // It is unsafe to replace %val by 0 because another thread may be running:
366 // acquire action; [2]
367 // store x 42;
368 // release action; [3]
369 // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
370 // being 42. A key property of this program however is that if either
371 // 1 or 4 were missing, there would be a race between the store of 42
372 // either the store of 0 or the load (making the whole program racy).
373 // The paper mentioned above shows that the same property is respected
374 // by every program that can detect any optimization of that kind: either
375 // it is racy (undefined) or there is a release followed by an acquire
376 // between the pair of accesses under consideration.
377
378 // If the load is invariant, we "know" that it doesn't alias *any* write. We
379 // do want to respect mustalias results since defs are useful for value
380 // forwarding, but any mayalias write can be assumed to be noalias.
381 // Arguably, this logic should be pushed inside AliasAnalysis itself.
382 if (isLoad && QueryInst) {
383 isInvariantLoad = QueryInst->hasMetadata(LLVMContext::MD_invariant_load);
384 if (LoadInst *LI = dyn_cast<LoadInst>(QueryInst))
385 MemLocAlign = LI->getAlign();
386 }
387
388 // True for volatile instruction.
389 // For Load/Store return true if atomic ordering is stronger than AO,
390 // for other instruction just true if it can read or write to memory.
391 auto isComplexForReordering = [](Instruction * I, AtomicOrdering AO)->bool {
392 if (I->isVolatile())
393 return true;
394 if (auto *LI = dyn_cast<LoadInst>(I))
395 return isStrongerThan(LI->getOrdering(), AO);
396 if (auto *SI = dyn_cast<StoreInst>(I))
397 return isStrongerThan(SI->getOrdering(), AO);
398 return I->mayReadOrWriteMemory();
399 };
400
401 // Walk backwards through the basic block, looking for dependencies.
402 while (ScanIt != BB->begin()) {
403 Instruction *Inst = &*--ScanIt;
404
405 // Limit the amount of scanning we do so we don't end up with quadratic
406 // running time on extreme testcases.
407 --*Limit;
408 if (!*Limit)
410
412 // If we reach a lifetime begin or end marker, then the query ends here
413 // because the value is undefined.
414 Intrinsic::ID ID = II->getIntrinsicID();
415 switch (ID) {
416 case Intrinsic::lifetime_start: {
417 MemoryLocation ArgLoc = MemoryLocation::getAfter(II->getArgOperand(0));
418 AliasResult R = BatchAA.alias(ArgLoc, MemLoc);
419 if (R == AliasResult::MustAlias)
420 return MemDepResult::getDef(II);
421 if (R == AliasResult::NoAlias)
422 continue;
423 // A partial overlap must act as a barrier.
425 }
426 case Intrinsic::masked_load:
427 case Intrinsic::masked_store: {
429 /*ModRefInfo MR =*/ GetLocation(II, Loc, TLI);
430 AliasResult R = BatchAA.alias(Loc, MemLoc);
431 if (R == AliasResult::NoAlias)
432 continue;
433 if (R == AliasResult::MustAlias)
434 return MemDepResult::getDef(II);
435 if (ID == Intrinsic::masked_load)
436 continue;
438 }
439 }
440 }
441
442 // Values depend on loads if the pointers are must aliased. This means
443 // that a load depends on another must aliased load from the same value.
444 // One exception is atomic loads: a value can depend on an atomic load that
445 // it does not alias with when this atomic load indicates that another
446 // thread may be accessing the location.
447 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
448 // While volatile access cannot be eliminated, they do not have to clobber
449 // non-aliasing locations, as normal accesses, for example, can be safely
450 // reordered with volatile accesses.
451 if (LI->isVolatile()) {
452 if (!QueryInst)
453 // Original QueryInst *may* be volatile
454 return MemDepResult::getClobber(LI);
455 if (QueryInst->isVolatile())
456 // Ordering required if QueryInst is itself volatile
457 return MemDepResult::getClobber(LI);
458 // Otherwise, volatile doesn't imply any special ordering
459 }
460
461 // Atomic loads have complications involved.
462 // A Monotonic (or higher) load is OK if the query inst is itself not
463 // atomic.
464 // FIXME: This is overly conservative.
465 if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) {
466 if (!QueryInst ||
467 isComplexForReordering(QueryInst, AtomicOrdering::NotAtomic))
468 return MemDepResult::getClobber(LI);
469 if (LI->getOrdering() != AtomicOrdering::Monotonic)
470 return MemDepResult::getClobber(LI);
471 }
472
474
475 // If we found a pointer, check if it could be the same as our pointer.
476 AliasResult R = BatchAA.alias(LoadLoc, MemLoc);
477
478 if (R == AliasResult::NoAlias)
479 continue;
480
481 if (isLoad) {
482 // Must aliased loads are defs of each other.
483 if (R == AliasResult::MustAlias)
484 return MemDepResult::getDef(Inst);
485
486 // If we have a partial alias, then return this as a clobber for the
487 // client to handle.
488 if (R == AliasResult::PartialAlias && R.hasOffset()) {
489 ClobberOffsets[LI] = R.getOffset();
490 return MemDepResult::getClobber(Inst);
491 }
492
493 // Random may-alias loads don't depend on each other without a
494 // dependence.
495 continue;
496 }
497
498 // Stores don't alias loads from read-only memory.
499 if (!isModSet(BatchAA.getModRefInfoMask(LoadLoc)))
500 continue;
501
502 // Stores depend on may/must aliased loads.
503 return MemDepResult::getDef(Inst);
504 }
505
506 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
507 // Atomic stores have complications involved.
508 // A Monotonic store is OK if the query inst is itself not atomic.
509 // FIXME: This is overly conservative.
510 if (!SI->isUnordered() && SI->isAtomic()) {
511 if (!QueryInst ||
512 isComplexForReordering(QueryInst, AtomicOrdering::Unordered))
514 // Ok, if we are here the guard above guarantee us that
515 // QueryInst is a non-atomic or unordered load/store.
516 // SI is atomic with monotonic or release semantic (seq_cst for store
517 // is actually a release semantic plus total order over other seq_cst
518 // instructions, as soon as QueryInst is not seq_cst we can consider it
519 // as simple release semantic).
520 // Monotonic and Release semantic allows re-ordering before store
521 // so we are safe to go further and check the aliasing. It will prohibit
522 // re-ordering in case locations are may or must alias.
523 }
524
525 // While volatile access cannot be eliminated, they do not have to clobber
526 // non-aliasing locations, as normal accesses can for example be reordered
527 // with volatile accesses.
528 if (SI->isVolatile())
529 if (!QueryInst || QueryInst->isVolatile())
531
532 // If alias analysis can tell that this store is guaranteed to not modify
533 // the query pointer, ignore it. Use getModRefInfo to handle cases where
534 // the query pointer points to constant memory etc.
535 if (!isModOrRefSet(BatchAA.getModRefInfo(SI, MemLoc)))
536 continue;
537
538 // Ok, this store might clobber the query pointer. Check to see if it is
539 // a must alias: in this case, we want to return this as a def.
540 // FIXME: Use ModRefInfo::Must bit from getModRefInfo call above.
542
543 // If we found a pointer, check if it could be the same as our pointer.
544 AliasResult R = BatchAA.alias(StoreLoc, MemLoc);
545
546 if (R == AliasResult::NoAlias)
547 continue;
548 if (R == AliasResult::MustAlias)
549 return MemDepResult::getDef(Inst);
550 if (isInvariantLoad)
551 continue;
552 if (isStorePreservingMemoryLocation(SI, MemLoc, MemLocAlign, BatchAA,
553 *Limit))
554 continue;
555 return MemDepResult::getClobber(Inst);
556 }
557
558 // If this is an allocation, and if we know that the accessed pointer is to
559 // the allocation, return Def. This means that there is no dependence and
560 // the access can be optimized based on that. For example, a load could
561 // turn into undef. Note that we can bypass the allocation itself when
562 // looking for a clobber in many cases; that's an alias property and is
563 // handled by BasicAA.
564 if (isa<AllocaInst>(Inst) || isNoAliasCall(Inst)) {
565 const Value *AccessPtr = getUnderlyingObject(MemLoc.Ptr);
566 if (AccessPtr == Inst || BatchAA.isMustAlias(Inst, AccessPtr))
567 return MemDepResult::getDef(Inst);
568 }
569
570 // If we found a select instruction for MemLoc pointer, return it as Def
571 // dependency.
572 if (isa<SelectInst>(Inst) && MemLoc.Ptr == Inst)
573 return MemDepResult::getDef(Inst);
574
575 if (isInvariantLoad)
576 continue;
577
578 // A release fence requires that all stores complete before it, but does
579 // not prevent the reordering of following loads or stores 'before' the
580 // fence. As a result, we look past it when finding a dependency for
581 // loads. DSE uses this to find preceding stores to delete and thus we
582 // can't bypass the fence if the query instruction is a store.
583 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
584 if (isLoad && FI->getOrdering() == AtomicOrdering::Release)
585 continue;
586
587 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
588 switch (BatchAA.getModRefInfo(Inst, MemLoc)) {
590 // If the call has no effect on the queried pointer, just ignore it.
591 continue;
592 case ModRefInfo::Mod:
593 return MemDepResult::getClobber(Inst);
594 case ModRefInfo::Ref:
595 // If the call is known to never store to the pointer, and if this is a
596 // load query, we can safely ignore it (scan past it).
597 if (isLoad)
598 continue;
599 [[fallthrough]];
600 default:
601 // Otherwise, there is a potential dependence. Return a clobber.
602 return MemDepResult::getClobber(Inst);
603 }
604 }
605
606 // No dependence found. If this is the entry block of the function, it is
607 // unknown, otherwise it is non-local.
608 if (BB != &BB->getParent()->getEntryBlock())
611}
612
614 ClobberOffsets.clear();
615 Instruction *ScanPos = QueryInst;
616
617 // Check for a cached result
618 MemDepResult &LocalCache = LocalDeps[QueryInst];
619
620 // If the cached entry is non-dirty, just return it. Note that this depends
621 // on MemDepResult's default constructing to 'dirty'.
622 if (!LocalCache.isDirty())
623 return LocalCache;
624
625 // Otherwise, if we have a dirty entry, we know we can start the scan at that
626 // instruction, which may save us some work.
627 if (Instruction *Inst = LocalCache.getInst()) {
628 ScanPos = Inst;
629
630 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
631 }
632
633 BasicBlock *QueryParent = QueryInst->getParent();
634
635 // Do the scan.
636 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
637 // No dependence found. If this is the entry block of the function, it is
638 // unknown, otherwise it is non-local.
639 if (QueryParent != &QueryParent->getParent()->getEntryBlock())
640 LocalCache = MemDepResult::getNonLocal();
641 else
642 LocalCache = MemDepResult::getNonFuncLocal();
643 } else {
644 MemoryLocation MemLoc;
645 ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI);
646 if (MemLoc.Ptr) {
647 // If we can do a pointer scan, make it happen.
648 bool isLoad = !isModSet(MR);
649 if (auto *II = dyn_cast<IntrinsicInst>(QueryInst))
650 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
651
652 LocalCache =
653 getPointerDependencyFrom(MemLoc, isLoad, ScanPos->getIterator(),
654 QueryParent, QueryInst, nullptr);
655 } else if (auto *QueryCall = dyn_cast<CallBase>(QueryInst)) {
656 bool isReadOnly = AA.onlyReadsMemory(QueryCall);
657 LocalCache = getCallDependencyFrom(QueryCall, isReadOnly,
658 ScanPos->getIterator(), QueryParent);
659 } else
660 // Non-memory instruction.
661 LocalCache = MemDepResult::getUnknown();
662 }
663
664 // Remember the result!
665 if (Instruction *I = LocalCache.getInst())
666 ReverseLocalDeps[I].insert(QueryInst);
667
668 return LocalCache;
669}
670
671#ifndef NDEBUG
672/// This method is used when -debug is specified to verify that cache arrays
673/// are properly kept sorted.
675 int Count = -1) {
676 if (Count == -1)
677 Count = Cache.size();
678 assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) &&
679 "Cache isn't sorted!");
680}
681#endif
682
685 assert(getDependency(QueryCall).isNonLocal() &&
686 "getNonLocalCallDependency should only be used on calls with "
687 "non-local deps!");
688 PerInstNLInfo &CacheP = NonLocalDepsMap[QueryCall];
689 NonLocalDepInfo &Cache = CacheP.first;
690
691 // This is the set of blocks that need to be recomputed. In the cached case,
692 // this can happen due to instructions being deleted etc. In the uncached
693 // case, this starts out as the set of predecessors we care about.
695
696 if (!Cache.empty()) {
697 // Okay, we have a cache entry. If we know it is not dirty, just return it
698 // with no computation.
699 if (!CacheP.second) {
700 ++NumCacheNonLocal;
701 return Cache;
702 }
703
704 // If we already have a partially computed set of results, scan them to
705 // determine what is dirty, seeding our initial DirtyBlocks worklist.
706 for (auto &Entry : Cache)
707 if (Entry.getResult().isDirty())
708 DirtyBlocks.push_back(Entry.getBB());
709
710 // Sort the cache so that we can do fast binary search lookups below.
711 llvm::sort(Cache);
712
713 ++NumCacheDirtyNonLocal;
714 } else {
715 // Seed DirtyBlocks with each of the preds of QueryInst's block.
716 BasicBlock *QueryBB = QueryCall->getParent();
717 append_range(DirtyBlocks, PredCache.get(QueryBB));
718 ++NumUncacheNonLocal;
719 }
720
721 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
722 bool isReadonlyCall = AA.onlyReadsMemory(QueryCall);
723
725
726 unsigned NumSortedEntries = Cache.size();
727 LLVM_DEBUG(AssertSorted(Cache));
728
729 // Iterate while we still have blocks to update.
730 while (!DirtyBlocks.empty()) {
731 BasicBlock *DirtyBB = DirtyBlocks.pop_back_val();
732
733 // Already processed this block?
734 if (!Visited.insert(DirtyBB).second)
735 continue;
736
737 // Do a binary search to see if we already have an entry for this block in
738 // the cache set. If so, find it.
739 LLVM_DEBUG(AssertSorted(Cache, NumSortedEntries));
740 NonLocalDepInfo::iterator Entry =
741 std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries,
742 NonLocalDepEntry(DirtyBB));
743 if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
744 --Entry;
745
746 NonLocalDepEntry *ExistingResult = nullptr;
747 if (Entry != Cache.begin() + NumSortedEntries &&
748 Entry->getBB() == DirtyBB) {
749 // If we already have an entry, and if it isn't already dirty, the block
750 // is done.
751 if (!Entry->getResult().isDirty())
752 continue;
753
754 // Otherwise, remember this slot so we can update the value.
755 ExistingResult = &*Entry;
756 }
757
758 // If the dirty entry has a pointer, start scanning from it so we don't have
759 // to rescan the entire block.
760 BasicBlock::iterator ScanPos = DirtyBB->end();
761 if (ExistingResult) {
762 if (Instruction *Inst = ExistingResult->getResult().getInst()) {
763 ScanPos = Inst->getIterator();
764 // We're removing QueryInst's use of Inst.
765 RemoveFromReverseMap<Instruction *>(ReverseNonLocalDeps, Inst,
766 QueryCall);
767 }
768 }
769
770 // Find out if this block has a local dependency for QueryInst.
771 MemDepResult Dep;
772
773 if (ScanPos != DirtyBB->begin()) {
774 Dep = getCallDependencyFrom(QueryCall, isReadonlyCall, ScanPos, DirtyBB);
775 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
776 // No dependence found. If this is the entry block of the function, it is
777 // a clobber, otherwise it is unknown.
779 } else {
781 }
782
783 // If we had a dirty entry for the block, update it. Otherwise, just add
784 // a new entry.
785 if (ExistingResult)
786 ExistingResult->setResult(Dep);
787 else
788 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
789
790 // If the block has a dependency (i.e. it isn't completely transparent to
791 // the value), remember the association!
792 if (!Dep.isNonLocal()) {
793 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
794 // update this when we remove instructions.
795 if (Instruction *Inst = Dep.getInst())
796 ReverseNonLocalDeps[Inst].insert(QueryCall);
797 } else {
798
799 // If the block *is* completely transparent to the load, we need to check
800 // the predecessors of this block. Add them to our worklist.
801 append_range(DirtyBlocks, PredCache.get(DirtyBB));
802 }
803 }
804
805 return Cache;
806}
807
810 const MemoryLocation Loc = MemoryLocation::get(QueryInst);
811 bool isLoad = isa<LoadInst>(QueryInst);
812 BasicBlock *FromBB = QueryInst->getParent();
813 assert(FromBB);
814
815 assert(Loc.Ptr->getType()->isPointerTy() &&
816 "Can't get pointer deps of a non-pointer!");
817 Result.clear();
818 {
819 // Check if there is cached Def with invariant.group.
820 auto NonLocalDefIt = NonLocalDefsCache.find(QueryInst);
821 if (NonLocalDefIt != NonLocalDefsCache.end()) {
822 Result.push_back(NonLocalDefIt->second);
824 ReverseNonLocalDefsCache, NonLocalDefIt->second.getResult().getInst(),
825 QueryInst);
826 NonLocalDefsCache.erase(NonLocalDefIt);
827 return;
828 }
829 }
830 // This routine does not expect to deal with volatile instructions.
831 // Doing so would require piping through the QueryInst all the way through.
832 // TODO: volatiles can't be elided, but they can be reordered with other
833 // non-volatile accesses.
834
835 // We currently give up on any instruction which is ordered, but we do handle
836 // atomic instructions which are unordered.
837 // TODO: Handle ordered instructions
838 auto isOrdered = [](Instruction *Inst) {
839 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
840 return !LI->isUnordered();
841 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
842 return !SI->isUnordered();
843 }
844 return false;
845 };
846 if (QueryInst->isVolatile() || isOrdered(QueryInst)) {
847 Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
848 const_cast<Value *>(Loc.Ptr)));
849 return;
850 }
851 const DataLayout &DL = FromBB->getDataLayout();
852 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC);
853
854 // NonLocalPointerDepVisited is the set of blocks we've inspected, and the
855 // pointer we consider in each block. Because of critical edges, we currently
856 // bail out if querying a block with multiple different pointers. This can
857 // happen during PHI translation.
858 ++NonLocalPointerDepEpoch;
859 assert(NonLocalPointerDepEpoch > 0 &&
860 "NonLocalPointerDepVisitedEpoch overflow");
861 NonLocalPointerDepVisited.resize(FromBB->getParent()->getMaxBlockNumber());
862 if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
863 Result, true))
864 return;
865 Result.clear();
866 Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
867 const_cast<Value *>(Loc.Ptr)));
868}
869
870/// Compute the memdep value for BB with Pointer/PointeeSize using either
871/// cached information in Cache or by doing a lookup (which may use dirty cache
872/// info if available).
873///
874/// If we do a lookup, add the result to the cache.
875MemDepResult MemoryDependenceResults::getNonLocalInfoForBlock(
876 Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad,
877 BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries,
878 BatchAAResults &BatchAA) {
879
880 bool isInvariantLoad = false;
881
882 if (QueryInst)
883 isInvariantLoad = QueryInst->hasMetadata(LLVMContext::MD_invariant_load);
884
885 // Do a binary search to see if we already have an entry for this block in
886 // the cache set. If so, find it.
887 NonLocalDepInfo::iterator Entry = std::upper_bound(
888 Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB));
889 if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB)
890 --Entry;
891
892 NonLocalDepEntry *ExistingResult = nullptr;
893 if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB)
894 ExistingResult = &*Entry;
895
896 // Use cached result for invariant load only if there is no dependency for non
897 // invariant load. In this case invariant load can not have any dependency as
898 // well.
899 if (ExistingResult && isInvariantLoad &&
900 !ExistingResult->getResult().isNonFuncLocal())
901 ExistingResult = nullptr;
902
903 // If we have a cached entry, and it is non-dirty, use it as the value for
904 // this dependency.
905 if (ExistingResult && !ExistingResult->getResult().isDirty()) {
906 ++NumCacheNonLocalPtr;
907 return ExistingResult->getResult();
908 }
909
910 // Otherwise, we have to scan for the value. If we have a dirty cache
911 // entry, start scanning from its position, otherwise we scan from the end
912 // of the block.
913 BasicBlock::iterator ScanPos = BB->end();
914 if (ExistingResult && ExistingResult->getResult().getInst()) {
915 assert(ExistingResult->getResult().getInst()->getParent() == BB &&
916 "Instruction invalidated?");
917 ++NumCacheDirtyNonLocalPtr;
918 ScanPos = ExistingResult->getResult().getInst()->getIterator();
919
920 // Eliminating the dirty entry from 'Cache', so update the reverse info.
921 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
922 RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey);
923 } else {
924 ++NumUncacheNonLocalPtr;
925 }
926
927 // Scan the block for the dependency.
928 MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB,
929 QueryInst, nullptr, BatchAA);
930
931 // Don't cache results for invariant load.
932 if (isInvariantLoad)
933 return Dep;
934
935 // If we had a dirty entry for the block, update it. Otherwise, just add
936 // a new entry.
937 if (ExistingResult)
938 ExistingResult->setResult(Dep);
939 else
940 Cache->push_back(NonLocalDepEntry(BB, Dep));
941
942 // If the block has a dependency (i.e. it isn't completely transparent to
943 // the value), remember the reverse association because we just added it
944 // to Cache!
945 if (!Dep.isLocal())
946 return Dep;
947
948 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
949 // update MemDep when we remove instructions.
950 Instruction *Inst = Dep.getInst();
951 assert(Inst && "Didn't depend on anything?");
952 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
953 ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
954 return Dep;
955}
956
957/// Sort the NonLocalDepInfo cache, given a certain number of elements in the
958/// array that are already properly ordered.
959///
960/// This is optimized for the case when only a few entries are added.
961static void
963 unsigned NumSortedEntries) {
964
965 // If only one entry, don't sort.
966 if (Cache.size() < 2)
967 return;
968
969 unsigned s = Cache.size() - NumSortedEntries;
970
971 // If the cache is already sorted, don't sort it again.
972 if (s == 0)
973 return;
974
975 // If no entry is sorted, sort the whole cache.
976 if (NumSortedEntries == 0) {
977 llvm::sort(Cache);
978 return;
979 }
980
981 // If the number of unsorted entires is small and the cache size is big, using
982 // insertion sort is faster. Here use Log2_32 to quickly choose the sort
983 // method.
984 if (s < Log2_32(Cache.size())) {
985 while (s > 0) {
986 NonLocalDepEntry Val = Cache.back();
987 Cache.pop_back();
988 MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
989 std::upper_bound(Cache.begin(), Cache.end() - s + 1, Val);
990 Cache.insert(Entry, Val);
991 s--;
992 }
993 } else {
994 llvm::sort(Cache);
995 }
996}
997
998void MemoryDependenceResults::setNonLocalPointerDepVisited(BasicBlock *BB,
999 Value *V) {
1000 NonLocalPointerDepVisited[BB->getNumber()] = {V, NonLocalPointerDepEpoch};
1001}
1002
1003bool MemoryDependenceResults::isNonLocalPointerDepVisited(
1004 BasicBlock *BB) const {
1005 return NonLocalPointerDepVisited[BB->getNumber()].second ==
1006 NonLocalPointerDepEpoch;
1007}
1008
1009Value *
1010MemoryDependenceResults::lookupNonLocalPointerDepVisited(BasicBlock *BB) const {
1011 assert(isNonLocalPointerDepVisited(BB) &&
1012 "Visited value requested for unseen block");
1013 return NonLocalPointerDepVisited[BB->getNumber()].first;
1014}
1015
1016/// Perform a dependency query based on pointer/pointeesize starting at the end
1017/// of StartBB.
1018///
1019/// Add any clobber/def results to the results vector and keep track of which
1020/// blocks are visited in 'NonLocalPointerDepVisited'.
1021///
1022/// This has special behavior for the first block queries (when SkipFirstBlock
1023/// is true). In this special case, it ignores the contents of the specified
1024/// block and starts returning dependence info for its predecessors.
1025///
1026/// This function returns true on success, or false to indicate that it could
1027/// not compute dependence information for some reason. This should be treated
1028/// as a clobber dependence on the first instruction in the predecessor block.
1029bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
1030 Instruction *QueryInst, const PHITransAddr &Pointer,
1031 const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
1032 SmallVectorImpl<NonLocalDepResult> &Result, bool SkipFirstBlock,
1033 bool IsIncomplete) {
1034 // Look up the cached info for Pointer.
1035 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
1036
1037 // Set up a temporary NLPI value. If the map doesn't yet have an entry for
1038 // CacheKey, this value will be inserted as the associated value. Otherwise,
1039 // it'll be ignored, and we'll have to check to see if the cached size and
1040 // aa tags are consistent with the current query.
1041 NonLocalPointerInfo InitialNLPI;
1042 InitialNLPI.Size = Loc.Size;
1043 InitialNLPI.AATags = Loc.AATags;
1044
1045 bool isInvariantLoad = false;
1046 if (QueryInst)
1047 isInvariantLoad = QueryInst->hasMetadata(LLVMContext::MD_invariant_load);
1048
1049 // Get the NLPI for CacheKey, inserting one into the map if it doesn't
1050 // already have one.
1051 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
1052 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
1053 NonLocalPointerInfo *CacheInfo = &Pair.first->second;
1054
1055 // If we already have a cache entry for this CacheKey, we may need to do some
1056 // work to reconcile the cache entry and the current query.
1057 // Invariant loads don't participate in caching. Thus no need to reconcile.
1058 if (!isInvariantLoad && !Pair.second) {
1059 if (CacheInfo->Size != Loc.Size) {
1060 // The query's Size is not equal to the cached one. Throw out the cached
1061 // data and proceed with the query with the new size.
1062 CacheInfo->Pair = BBSkipFirstBlockPair();
1063 CacheInfo->Size = Loc.Size;
1064 for (auto &Entry : CacheInfo->NonLocalDeps)
1065 if (Instruction *Inst = Entry.getResult().getInst())
1066 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1067 CacheInfo->NonLocalDeps.clear();
1068 // The cache is cleared (in the above line) so we will have lost
1069 // information about blocks we have already visited. We therefore must
1070 // assume that the cache information is incomplete.
1071 IsIncomplete = true;
1072 }
1073
1074 // If the query's AATags are inconsistent with the cached one,
1075 // conservatively throw out the cached data and restart the query with
1076 // no tag if needed.
1077 if (CacheInfo->AATags != Loc.AATags) {
1078 if (CacheInfo->AATags) {
1079 CacheInfo->Pair = BBSkipFirstBlockPair();
1080 CacheInfo->AATags = AAMDNodes();
1081 for (auto &Entry : CacheInfo->NonLocalDeps)
1082 if (Instruction *Inst = Entry.getResult().getInst())
1083 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
1084 CacheInfo->NonLocalDeps.clear();
1085 // The cache is cleared (in the above line) so we will have lost
1086 // information about blocks we have already visited. We therefore must
1087 // assume that the cache information is incomplete.
1088 IsIncomplete = true;
1089 }
1090 if (Loc.AATags)
1091 return getNonLocalPointerDepFromBB(
1092 QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result,
1093 SkipFirstBlock, IsIncomplete);
1094 }
1095 }
1096
1097 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
1098
1099 // If we have valid cached information for exactly the block we are
1100 // investigating, just return it with no recomputation.
1101 // Don't use cached information for invariant loads since it is valid for
1102 // non-invariant loads only.
1103 if (!IsIncomplete && !isInvariantLoad &&
1104 CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
1105 // We have a fully cached result for this query then we can just return the
1106 // cached results and populate the visited set. However, we have to verify
1107 // that we don't already have conflicting results for these blocks. Check
1108 // to ensure that if a block in the results set is in the visited set that
1109 // it was for the same pointer query.
1110 for (auto &Entry : *Cache) {
1111 if (!isNonLocalPointerDepVisited(Entry.getBB()))
1112 continue;
1113 Value *Prev = lookupNonLocalPointerDepVisited(Entry.getBB());
1114 if (Prev == Pointer.getAddr())
1115 continue;
1116
1117 // We have a pointer mismatch in a block. Just return false, saying
1118 // that something was clobbered in this result. We could also do a
1119 // non-fully cached query, but there is little point in doing this.
1120 return false;
1121 }
1122
1123 Value *Addr = Pointer.getAddr();
1124 for (auto &Entry : *Cache) {
1125 setNonLocalPointerDepVisited(Entry.getBB(), Addr);
1126 if (Entry.getResult().isNonLocal()) {
1127 continue;
1128 }
1129
1130 if (DT.isReachableFromEntry(Entry.getBB())) {
1131 Result.push_back(
1132 NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr));
1133 }
1134 }
1135 ++NumCacheCompleteNonLocalPtr;
1136 return true;
1137 }
1138
1139 // If the size of this cache has surpassed the global limit, stop here.
1140 if (Cache->size() > Opts.memdep_cache_global_limit)
1141 return false;
1142
1143 // Otherwise, either this is a new block, a block with an invalid cache
1144 // pointer or one that we're about to invalidate by putting more info into
1145 // it than its valid cache info. If empty and not explicitly indicated as
1146 // incomplete, the result will be valid cache info, otherwise it isn't.
1147 //
1148 // Invariant loads don't affect cache in any way thus no need to update
1149 // CacheInfo as well.
1150 if (!isInvariantLoad) {
1151 if (!IsIncomplete && Cache->empty())
1152 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1153 else
1154 CacheInfo->Pair = BBSkipFirstBlockPair();
1155 }
1156
1158 Worklist.push_back(StartBB);
1159
1160 // PredList used inside loop.
1162
1163 // Keep track of the entries that we know are sorted. Previously cached
1164 // entries will all be sorted. The entries we add we only sort on demand (we
1165 // don't insert every element into its sorted position). We know that we
1166 // won't get any reuse from currently inserted values, because we don't
1167 // revisit blocks after we insert info for them.
1168 unsigned NumSortedEntries = Cache->size();
1169 unsigned WorklistEntries = Opts.memdep_block_number_limit;
1170 bool GotWorklistLimit = false;
1171 LLVM_DEBUG(AssertSorted(*Cache));
1172
1173 BatchAAResults BatchAA(AA, &EEA);
1174 while (!Worklist.empty()) {
1175 BasicBlock *BB = Worklist.pop_back_val();
1176
1177 // If we do process a large number of blocks it becomes very expensive and
1178 // likely it isn't worth worrying about
1179 if (Result.size() > NumResultsLimit) {
1180 // Sort it now (if needed) so that recursive invocations of
1181 // getNonLocalPointerDepFromBB and other routines that could reuse the
1182 // cache value will only see properly sorted cache arrays.
1183 if (Cache && NumSortedEntries != Cache->size()) {
1184 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1185 }
1186 // Since we bail out, the "Cache" set won't contain all of the
1187 // results for the query. This is ok (we can still use it to accelerate
1188 // specific block queries) but we can't do the fastpath "return all
1189 // results from the set". Clear out the indicator for this.
1190 CacheInfo->Pair = BBSkipFirstBlockPair();
1191 return false;
1192 }
1193
1194 // Skip the first block if we have it.
1195 if (!SkipFirstBlock) {
1196 // Analyze the dependency of *Pointer in FromBB. See if we already have
1197 // been here.
1198 assert(isNonLocalPointerDepVisited(BB) &&
1199 "Should check 'visited' before adding to WL");
1200
1201 // Get the dependency info for Pointer in BB. If we have cached
1202 // information, we will use it, otherwise we compute it.
1203 LLVM_DEBUG(AssertSorted(*Cache, NumSortedEntries));
1204 MemDepResult Dep = getNonLocalInfoForBlock(
1205 QueryInst, Loc, isLoad, BB, Cache, NumSortedEntries, BatchAA);
1206
1207 // If we got a Def or Clobber, add this to the list of results.
1208 if (!Dep.isNonLocal()) {
1209 if (DT.isReachableFromEntry(BB)) {
1210 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1211 continue;
1212 }
1213 }
1214 }
1215
1216 // If 'Pointer' is an instruction defined in this block, then we need to do
1217 // phi translation to change it into a value live in the predecessor block.
1218 // If not, we just add the predecessors to the worklist and scan them with
1219 // the same Pointer.
1220 if (!Pointer.needsPHITranslationFromBlock(BB)) {
1221 SkipFirstBlock = false;
1222 SmallVector<BasicBlock *, 16> NewBlocks;
1223 for (BasicBlock *Pred : PredCache.get(BB)) {
1224 // Verify that we haven't looked at this block yet.
1225 if (!isNonLocalPointerDepVisited(Pred)) {
1226 setNonLocalPointerDepVisited(Pred, Pointer.getAddr());
1227 // First time we've looked at *PI.
1228 NewBlocks.push_back(Pred);
1229 continue;
1230 }
1231 Value *Prev = lookupNonLocalPointerDepVisited(Pred);
1232 // If we have seen this block before, but it was with a different
1233 // pointer then we have a phi translation failure and we have to treat
1234 // this as a clobber.
1235 if (Prev != Pointer.getAddr()) {
1236 // Make sure to clean up the Visited map before continuing on to
1237 // PredTranslationFailure.
1238 for (auto *NewBlock : NewBlocks)
1239 setNonLocalPointerDepVisited(NewBlock, nullptr);
1240 goto PredTranslationFailure;
1241 }
1242 }
1243 if (NewBlocks.size() > WorklistEntries) {
1244 // Make sure to clean up the Visited map before continuing on to
1245 // PredTranslationFailure.
1246 for (auto *NewBlock : NewBlocks)
1247 setNonLocalPointerDepVisited(NewBlock, nullptr);
1248 GotWorklistLimit = true;
1249 goto PredTranslationFailure;
1250 }
1251 WorklistEntries -= NewBlocks.size();
1252 Worklist.append(NewBlocks.begin(), NewBlocks.end());
1253 continue;
1254 }
1255
1256 // We do need to do phi translation, if we know ahead of time we can't phi
1257 // translate this value, don't even try.
1258 if (!Pointer.isPotentiallyPHITranslatable())
1259 goto PredTranslationFailure;
1260
1261 // We may have added values to the cache list before this PHI translation.
1262 // If so, we haven't done anything to ensure that the cache remains sorted.
1263 // Sort it now (if needed) so that recursive invocations of
1264 // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1265 // value will only see properly sorted cache arrays.
1266 if (Cache && NumSortedEntries != Cache->size()) {
1267 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1268 NumSortedEntries = Cache->size();
1269 }
1270 Cache = nullptr;
1271
1272 PredList.clear();
1273 for (BasicBlock *Pred : PredCache.get(BB)) {
1274 PredList.push_back(std::make_pair(Pred, Pointer));
1275
1276 // Get the PHI translated pointer in this predecessor. This can fail if
1277 // not translatable, in which case the getAddr() returns null.
1278 PHITransAddr &PredPointer = PredList.back().second;
1279 Value *PredPtrVal =
1280 PredPointer.translateValue(BB, Pred, &DT, /*MustDominate=*/false);
1281
1282 // Check to see if we have already visited this pred block with another
1283 // pointer. If so, we can't do this lookup. This failure can occur
1284 // with PHI translation when a critical edge exists and the PHI node in
1285 // the successor translates to a pointer value different than the
1286 // pointer the block was first analyzed with.
1287 if (!isNonLocalPointerDepVisited(Pred)) {
1288 setNonLocalPointerDepVisited(Pred, PredPtrVal);
1289 continue;
1290 }
1291 Value *PrevVal = lookupNonLocalPointerDepVisited(Pred);
1292
1293 // We found the pred; take it off the list of preds to visit.
1294 PredList.pop_back();
1295
1296 // If the predecessor was visited with PredPtr, then we already did
1297 // the analysis and can ignore it.
1298 if (PrevVal == PredPtrVal)
1299 continue;
1300
1301 // Otherwise, the block was previously analyzed with a different
1302 // pointer. We can't represent the result of this case, so we just
1303 // treat this as a phi translation failure.
1304
1305 // Make sure to clean up the Visited map before continuing on to
1306 // PredTranslationFailure.
1307 for (const auto &Pred : PredList)
1308 setNonLocalPointerDepVisited(Pred.first, nullptr);
1309
1310 goto PredTranslationFailure;
1311 }
1312
1313 // Actually process results here; this need to be a separate loop to avoid
1314 // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1315 // any results for. (getNonLocalPointerDepFromBB will modify our
1316 // datastructures in ways the code after the PredTranslationFailure label
1317 // doesn't expect.)
1318 for (auto &I : PredList) {
1319 BasicBlock *Pred = I.first;
1320 PHITransAddr &PredPointer = I.second;
1321 Value *PredPtrVal = PredPointer.getAddr();
1322
1323 bool CanTranslate = true;
1324 // If PHI translation was unable to find an available pointer in this
1325 // predecessor, then we have to assume that the pointer is clobbered in
1326 // that predecessor. We can still do PRE of the load, which would insert
1327 // a computation of the pointer in this predecessor.
1328 if (!PredPtrVal) {
1329 // If translation failed but the (partially) translated address
1330 // expression depends on a select instruction, try to translate both
1331 // sides of that select. The select instruction is recovered from the
1332 // failed `PredPointer` (the phi has already been resolved to the
1333 // select there), but the two sides must be translated from the
1334 // original, untranslated `Pointer`.
1335 if (SelectInst *Sel = PredPointer.getSelect()) {
1336 SelectAddr::SelectAddrs SelAddrs =
1337 PHITransAddr(Pointer).translateValue(BB, Pred, &DT,
1338 Sel->getCondition());
1339 if (SelAddrs.first && SelAddrs.second) {
1340 Result.push_back(NonLocalDepResult(Pred, MemDepResult::getSelect(),
1341 SelectAddr(Sel, SelAddrs)));
1342 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1343 NLPI.Pair = BBSkipFirstBlockPair();
1344 continue;
1345 }
1346 }
1347 CanTranslate = false;
1348 }
1349
1350 // FIXME: it is entirely possible that PHI translating will end up with
1351 // the same value. Consider PHI translating something like:
1352 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need*
1353 // to recurse here, pedantically speaking.
1354
1355 // If getNonLocalPointerDepFromBB fails here, that means the cached
1356 // result conflicted with the Visited list; we have to conservatively
1357 // assume it is unknown, but this also does not block PRE of the load.
1358 if (!CanTranslate ||
1359 !getNonLocalPointerDepFromBB(QueryInst, PredPointer,
1360 Loc.getWithNewPtr(PredPtrVal), isLoad,
1361 Pred, Result)) {
1362 // Add the entry to the Result list.
1363 NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1364 Result.push_back(Entry);
1365
1366 // Since we had a phi translation failure, the cache for CacheKey won't
1367 // include all of the entries that we need to immediately satisfy future
1368 // queries. Mark this in NonLocalPointerDeps by setting the
1369 // BBSkipFirstBlockPair pointer to null. This requires reuse of the
1370 // cached value to do more work but not miss the phi trans failure.
1371 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
1372 NLPI.Pair = BBSkipFirstBlockPair();
1373 continue;
1374 }
1375 }
1376
1377 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1378 CacheInfo = &NonLocalPointerDeps[CacheKey];
1379 Cache = &CacheInfo->NonLocalDeps;
1380 NumSortedEntries = Cache->size();
1381
1382 // Since we did phi translation, the "Cache" set won't contain all of the
1383 // results for the query. This is ok (we can still use it to accelerate
1384 // specific block queries) but we can't do the fastpath "return all
1385 // results from the set" Clear out the indicator for this.
1386 CacheInfo->Pair = BBSkipFirstBlockPair();
1387 SkipFirstBlock = false;
1388 continue;
1389
1390 PredTranslationFailure:
1391 // The following code is "failure"; we can't produce a sane translation
1392 // for the given block. It assumes that we haven't modified any of
1393 // our datastructures while processing the current block.
1394
1395 if (!Cache) {
1396 // Refresh the CacheInfo/Cache pointer if it got invalidated.
1397 CacheInfo = &NonLocalPointerDeps[CacheKey];
1398 Cache = &CacheInfo->NonLocalDeps;
1399 NumSortedEntries = Cache->size();
1400 }
1401
1402 // Since we failed phi translation, the "Cache" set won't contain all of the
1403 // results for the query. This is ok (we can still use it to accelerate
1404 // specific block queries) but we can't do the fastpath "return all
1405 // results from the set". Clear out the indicator for this.
1406 CacheInfo->Pair = BBSkipFirstBlockPair();
1407
1408 // If *nothing* works, mark the pointer as unknown.
1409 //
1410 // If this is the magic first block, return this as a clobber of the whole
1411 // incoming value. Since we can't phi translate to one of the predecessors,
1412 // we have to bail out.
1413 if (SkipFirstBlock)
1414 return false;
1415
1416 // Results of invariant loads are not cached thus no need to update cached
1417 // information.
1418 if (!isInvariantLoad) {
1419 for (NonLocalDepEntry &I : llvm::reverse(*Cache)) {
1420 if (I.getBB() != BB)
1421 continue;
1422
1423 assert((GotWorklistLimit || I.getResult().isNonLocal() ||
1424 !DT.isReachableFromEntry(BB)) &&
1425 "Should only be here with transparent block");
1426
1427 I.setResult(MemDepResult::getUnknown());
1428
1429
1430 break;
1431 }
1432 }
1433 (void)GotWorklistLimit;
1434 // Go ahead and report unknown dependence.
1435 Result.push_back(
1436 NonLocalDepResult(BB, MemDepResult::getUnknown(), Pointer.getAddr()));
1437 }
1438
1439 // Okay, we're done now. If we added new values to the cache, re-sort it.
1440 SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1441 LLVM_DEBUG(AssertSorted(*Cache));
1442 return true;
1443}
1444
1445/// If P exists in CachedNonLocalPointerInfo or NonLocalDefsCache, remove it.
1446void MemoryDependenceResults::removeCachedNonLocalPointerDependencies(
1447 ValueIsLoadPair P) {
1448
1449 // Most of the time this cache is empty.
1450 if (!NonLocalDefsCache.empty()) {
1451 auto it = NonLocalDefsCache.find(P.getPointer());
1452 if (it != NonLocalDefsCache.end()) {
1453 RemoveFromReverseMap(ReverseNonLocalDefsCache,
1454 it->second.getResult().getInst(), P.getPointer());
1455 NonLocalDefsCache.erase(it);
1456 }
1457
1458 if (auto *I = dyn_cast<Instruction>(P.getPointer())) {
1459 auto toRemoveIt = ReverseNonLocalDefsCache.find(I);
1460 if (toRemoveIt != ReverseNonLocalDefsCache.end()) {
1461 for (const auto *Entry : toRemoveIt->second) {
1462 [[maybe_unused]] bool Removed = NonLocalDefsCache.erase(Entry);
1463 assert(Removed && "Reverse non-local def map out of sync?");
1464 }
1465 ReverseNonLocalDefsCache.erase(toRemoveIt);
1466 }
1467 }
1468 }
1469
1470 CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P);
1471 if (It == NonLocalPointerDeps.end())
1472 return;
1473
1474 // Remove all of the entries in the BB->val map. This involves removing
1475 // instructions from the reverse map.
1476 NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1477
1478 for (const NonLocalDepEntry &DE : PInfo) {
1479 Instruction *Target = DE.getResult().getInst();
1480 if (!Target)
1481 continue; // Ignore non-local dep results.
1482 assert(Target->getParent() == DE.getBB());
1483
1484 // Eliminating the dirty entry from 'Cache', so update the reverse info.
1485 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1486 }
1487
1488 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1489 NonLocalPointerDeps.erase(It);
1490}
1491
1493 // If Ptr isn't really a pointer, just ignore it.
1494 if (!Ptr->getType()->isPointerTy())
1495 return;
1496 // Flush store info for the pointer.
1497 removeCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1498 // Flush load info for the pointer.
1499 removeCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1500}
1501
1503 PredCache.clear();
1504}
1505
1507 EEA.removeInstruction(RemInst);
1508
1509 // Walk through the Non-local dependencies, removing this one as the value
1510 // for any cached queries.
1511 NonLocalDepMapType::iterator NLDI = NonLocalDepsMap.find(RemInst);
1512 if (NLDI != NonLocalDepsMap.end()) {
1513 NonLocalDepInfo &BlockMap = NLDI->second.first;
1514 for (auto &Entry : BlockMap)
1515 if (Instruction *Inst = Entry.getResult().getInst())
1516 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1517 NonLocalDepsMap.erase(NLDI);
1518 }
1519
1520 // If we have a cached local dependence query for this instruction, remove it.
1521 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1522 if (LocalDepEntry != LocalDeps.end()) {
1523 // Remove us from DepInst's reverse set now that the local dep info is gone.
1524 if (Instruction *Inst = LocalDepEntry->second.getInst())
1525 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1526
1527 // Remove this local dependency info.
1528 LocalDeps.erase(LocalDepEntry);
1529 }
1530
1531 // If we have any cached dependencies on this instruction, remove
1532 // them.
1533
1534 // If the instruction is a pointer, remove it from both the load info and the
1535 // store info.
1536 if (RemInst->getType()->isPointerTy()) {
1537 removeCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1538 removeCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1539 } else {
1540 // Otherwise, if the instructions is in the map directly, it must be a load.
1541 // Remove it.
1542 auto toRemoveIt = NonLocalDefsCache.find(RemInst);
1543 if (toRemoveIt != NonLocalDefsCache.end()) {
1544 assert(isa<LoadInst>(RemInst) &&
1545 "only load instructions should be added directly");
1546 Instruction *DepV = toRemoveIt->second.getResult().getInst();
1547 RemoveFromReverseMap<const Value *>(ReverseNonLocalDefsCache, DepV,
1548 RemInst);
1549 NonLocalDefsCache.erase(toRemoveIt);
1550 }
1551 }
1552
1553 auto ReverseNonLocalDefIt = ReverseNonLocalDefsCache.find(RemInst);
1554 if (ReverseNonLocalDefIt != ReverseNonLocalDefsCache.end()) {
1555 for (const Value *QueryInst : ReverseNonLocalDefIt->second) {
1556 [[maybe_unused]] bool Removed = NonLocalDefsCache.erase(QueryInst);
1557 assert(Removed && "Reverse non-local def map out of sync?");
1558 }
1559 ReverseNonLocalDefsCache.erase(ReverseNonLocalDefIt);
1560 }
1561
1562 // Loop over all of the things that depend on the instruction we're removing.
1564
1565 // If we find RemInst as a clobber or Def in any of the maps for other values,
1566 // we need to replace its entry with a dirty version of the instruction after
1567 // it. If RemInst is a terminator, we use a null dirty value.
1568 //
1569 // Using a dirty version of the instruction after RemInst saves having to scan
1570 // the entire block to get to this point.
1571 MemDepResult NewDirtyVal;
1572 if (!RemInst->isTerminator())
1573 NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator());
1574
1575 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1576 if (ReverseDepIt != ReverseLocalDeps.end()) {
1577 // RemInst can't be the terminator if it has local stuff depending on it.
1578 assert(!ReverseDepIt->second.empty() && !RemInst->isTerminator() &&
1579 "Nothing can locally depend on a terminator");
1580
1581 for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
1582 assert(InstDependingOnRemInst != RemInst &&
1583 "Already removed our local dep info");
1584
1585 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1586
1587 // Make sure to remember that new things depend on NewDepInst.
1588 assert(NewDirtyVal.getInst() &&
1589 "There is no way something else can have "
1590 "a local dep on this if it is a terminator!");
1591 ReverseDepsToAdd.push_back(
1592 std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst));
1593 }
1594
1595 ReverseLocalDeps.erase(ReverseDepIt);
1596
1597 // Add new reverse deps after scanning the set, to avoid invalidating the
1598 // 'ReverseDeps' reference.
1599 while (!ReverseDepsToAdd.empty()) {
1600 ReverseLocalDeps[ReverseDepsToAdd.back().first].insert(
1601 ReverseDepsToAdd.back().second);
1602 ReverseDepsToAdd.pop_back();
1603 }
1604 }
1605
1606 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1607 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1608 for (Instruction *I : ReverseDepIt->second) {
1609 assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
1610
1611 PerInstNLInfo &INLD = NonLocalDepsMap[I];
1612 // The information is now dirty!
1613 INLD.second = true;
1614
1615 for (auto &Entry : INLD.first) {
1616 if (Entry.getResult().getInst() != RemInst)
1617 continue;
1618
1619 // Convert to a dirty entry for the subsequent instruction.
1620 Entry.setResult(NewDirtyVal);
1621
1622 if (Instruction *NextI = NewDirtyVal.getInst())
1623 ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
1624 }
1625 }
1626
1627 ReverseNonLocalDeps.erase(ReverseDepIt);
1628
1629 // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1630 while (!ReverseDepsToAdd.empty()) {
1631 ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert(
1632 ReverseDepsToAdd.back().second);
1633 ReverseDepsToAdd.pop_back();
1634 }
1635 }
1636
1637 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1638 // value in the NonLocalPointerDeps info.
1639 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1640 ReverseNonLocalPtrDeps.find(RemInst);
1641 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1643 ReversePtrDepsToAdd;
1644
1645 for (ValueIsLoadPair P : ReversePtrDepIt->second) {
1646 assert(P.getPointer() != RemInst &&
1647 "Already removed NonLocalPointerDeps info for RemInst");
1648
1649 auto &NLPD = NonLocalPointerDeps[P];
1650
1651 NonLocalDepInfo &NLPDI = NLPD.NonLocalDeps;
1652
1653 // The cache is not valid for any specific block anymore.
1654 NLPD.Pair = BBSkipFirstBlockPair();
1655
1656 // Update any entries for RemInst to use the instruction after it.
1657 for (auto &Entry : NLPDI) {
1658 if (Entry.getResult().getInst() != RemInst)
1659 continue;
1660
1661 // Convert to a dirty entry for the subsequent instruction.
1662 Entry.setResult(NewDirtyVal);
1663
1664 if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1665 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1666 }
1667
1668 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its
1669 // subsequent value may invalidate the sortedness.
1670 llvm::sort(NLPDI);
1671 }
1672
1673 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1674
1675 while (!ReversePtrDepsToAdd.empty()) {
1676 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert(
1677 ReversePtrDepsToAdd.back().second);
1678 ReversePtrDepsToAdd.pop_back();
1679 }
1680 }
1681
1682 assert(!NonLocalDepsMap.count(RemInst) && "RemInst got reinserted?");
1683 LLVM_DEBUG(verifyRemoved(RemInst));
1684}
1685
1686/// Verify that the specified instruction does not occur in our internal data
1687/// structures.
1688///
1689/// This function verifies by asserting in debug builds.
1690void MemoryDependenceResults::verifyRemoved(Instruction *D) const {
1691#ifndef NDEBUG
1692 for (const auto &DepKV : LocalDeps) {
1693 assert(DepKV.first != D && "Inst occurs in data structures");
1694 assert(DepKV.second.getInst() != D && "Inst occurs in data structures");
1695 }
1696
1697 for (const auto &DepKV : NonLocalPointerDeps) {
1698 assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key");
1699 for (const auto &Entry : DepKV.second.NonLocalDeps)
1700 assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value");
1701 }
1702
1703 for (const auto &DepKV : NonLocalDepsMap) {
1704 assert(DepKV.first != D && "Inst occurs in data structures");
1705 const PerInstNLInfo &INLD = DepKV.second;
1706 for (const auto &Entry : INLD.first)
1707 assert(Entry.getResult().getInst() != D &&
1708 "Inst occurs in data structures");
1709 }
1710
1711 for (const auto &DepKV : ReverseLocalDeps) {
1712 assert(DepKV.first != D && "Inst occurs in data structures");
1713 for (Instruction *Inst : DepKV.second)
1714 assert(Inst != D && "Inst occurs in data structures");
1715 }
1716
1717 for (const auto &DepKV : ReverseNonLocalDeps) {
1718 assert(DepKV.first != D && "Inst occurs in data structures");
1719 for (Instruction *Inst : DepKV.second)
1720 assert(Inst != D && "Inst occurs in data structures");
1721 }
1722
1723 for (const auto &DepKV : ReverseNonLocalPtrDeps) {
1724 assert(DepKV.first != D && "Inst occurs in rev NLPD map");
1725
1726 for (ValueIsLoadPair P : DepKV.second)
1727 assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) &&
1728 "Inst occurs in ReverseNonLocalPtrDeps map");
1729 }
1730#endif
1731}
1732
1733AnalysisKey MemoryDependenceAnalysis::Key;
1734
1736
1739 auto &AA = AM.getResult<AAManager>(F);
1740 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1741 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1742 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1744 AA, AC, TLI, DT,
1745 DefaultBlockScanLimit.value_or(
1746 getAnalysisOptions(F).memdep_block_scan_limit));
1747}
1748
1750
1752 "Memory Dependence Analysis", false, true)
1758 "Memory Dependence Analysis", false, true)
1759
1761
1763
1765 MemDep.reset();
1766}
1767
1775
1777 AssumptionCache &AC,
1778 const TargetLibraryInfo &TLI,
1779 DominatorTree &DT,
1780 unsigned DefaultBlockScanLimit)
1781 : Opts(getAnalysisOptions(*DT.getRoot()->getParent())), AA(AA), AC(AC),
1782 TLI(TLI), DT(DT), EEA(DT), DefaultBlockScanLimit(DefaultBlockScanLimit) {}
1783
1785 FunctionAnalysisManager::Invalidator &Inv) {
1786 // Check whether our analysis is preserved.
1787 auto PAC = PA.getChecker<MemoryDependenceAnalysis>();
1788 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
1789 // If not, give up now.
1790 return true;
1791
1792 // Check whether the analyses we depend on became invalid for any reason.
1793 if (Inv.invalidate<AAManager>(F, PA) ||
1794 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
1795 Inv.invalidate<DominatorTreeAnalysis>(F, PA))
1796 return true;
1797
1798 // Otherwise this analysis result remains valid.
1799 return false;
1800}
1801
1803 return DefaultBlockScanLimit;
1804}
1805
1807 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1808 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1809 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1810 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1811 MemDep.emplace(AA, AC, TLI, DT,
1812 getAnalysisOptions(F).memdep_block_scan_limit);
1813 return false;
1814}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isLoad(int Opcode)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
static const Function * getParent(const Value *V)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static DeltaTreeNode * getRoot(void *Root)
This file defines the DenseMap class.
Module.h This file contains the declarations for the Module class.
This defines the Use class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const unsigned int NumResultsLimit
static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc, const TargetLibraryInfo &TLI)
If the given instruction references a specific memory location, fill in Loc with the details,...
static void RemoveFromReverseMap(DenseMap< Instruction *, SmallPtrSet< KeyTy, 4 > > &ReverseMap, Instruction *Inst, KeyTy Val)
This is a helper function that removes Val from 'Inst's set in ReverseMap.
static void SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache, unsigned NumSortedEntries)
Sort the NonLocalDepInfo cache, given a certain number of elements in the array that are already prop...
static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache, int Count=-1)
This method is used when -debug is specified to verify that cache arrays are properly kept sorted.
This file provides utility analysis objects describing memory locations.
static bool isOrdered(const Instruction *I)
This file contains the declarations for metadata subclasses.
static bool isInvariantLoad(const Instruction *I, const Value *Ptr, const bool IsKernelFn)
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
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 defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
The possible results of an alias query.
@ NoAlias
The two locations do not alias at all.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
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.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
unsigned getNumber() const
Definition BasicBlock.h:95
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool empty() const
Definition DenseMap.h:716
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:678
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
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
An instruction for ordering other memory operations.
FunctionPass(char &pid)
Definition Pass.h:314
const BasicBlock & getEntryBlock() const
Definition Function.h:794
unsigned getMaxBlockNumber() const
Return a value larger than the largest block number.
Definition Function.h:813
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
bool isTerminator() const
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
LLVM_ABI bool isVolatile() const LLVM_READONLY
Return true if this instruction has a volatile memory access.
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
Value * getPointerOperand()
A memory dependence query can return one of three different answers.
bool isNonLocal() const
Tests if this MemDepResult represents a query that is transparent to the start of the block,...
static MemDepResult getNonLocal()
bool isNonFuncLocal() const
Tests if this MemDepResult represents a query that is transparent to the start of the function.
static MemDepResult getSelect()
static MemDepResult getClobber(Instruction *Inst)
bool isDef() const
Tests if this MemDepResult represents a query that is an instruction definition dependency.
static MemDepResult getUnknown()
bool isLocal() const
Tests if this MemDepResult represents a valid local query (Clobber/Def).
bool isUnknown() const
Tests if this MemDepResult represents a query which cannot and/or will not be computed.
static MemDepResult getNonFuncLocal()
static MemDepResult getDef(Instruction *Inst)
get methods: These are static ctor methods for creating various MemDepResult kinds.
Instruction * getInst() const
If this is a normal dependency, returns the instruction that is depended on.
An analysis that produces MemoryDependenceResults for a function.
LLVM_ABI MemoryDependenceResults run(Function &F, FunctionAnalysisManager &AM)
Provides a lazy, caching interface for making common memory aliasing information queries,...
LLVM_ABI MemDepResult getSimplePointerDependencyFrom(const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt, BasicBlock *BB, Instruction *QueryInst, unsigned *Limit, BatchAAResults &BatchAA)
std::vector< NonLocalDepEntry > NonLocalDepInfo
LLVM_ABI void invalidateCachedPredecessors()
Clears the PredIteratorCache info.
LLVM_ABI void invalidateCachedPointerInfo(Value *Ptr)
Invalidates cached information about the specified pointer, because it may be too conservative in mem...
LLVM_ABI MemDepResult getPointerDependencyFrom(const MemoryLocation &Loc, bool isLoad, BasicBlock::iterator ScanIt, BasicBlock *BB, Instruction *QueryInst=nullptr, unsigned *Limit=nullptr)
Returns the instruction on which a memory location depends.
LLVM_ABI void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
LLVM_ABI MemoryDependenceResults(AAResults &AA, AssumptionCache &AC, const TargetLibraryInfo &TLI, DominatorTree &DT, unsigned DefaultBlockScanLimit)
LLVM_ABI MemDepResult getInvariantGroupPointerDependency(LoadInst *LI, BasicBlock *BB)
This analysis looks for other loads and stores with invariant.group metadata and the same pointer ope...
LLVM_ABI unsigned getDefaultBlockScanLimit() const
Some methods limit the number of instructions they will examine.
LLVM_ABI MemDepResult getDependency(Instruction *QueryInst)
Returns the instruction on which a memory operation depends.
LLVM_ABI const NonLocalDepInfo & getNonLocalCallDependency(CallBase *QueryCall)
Perform a full dependency query for the specified call, returning the set of blocks that the value is...
LLVM_ABI void getNonLocalPointerDependency(Instruction *QueryInst, SmallVectorImpl< NonLocalDepResult > &Result)
Perform a full dependency query for an access to the QueryInst's specified memory location,...
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation in the new PM.
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance.
bool runOnFunction(Function &) override
Pass Implementation stuff. This doesn't do any analysis eagerly.
void getAnalysisUsage(AnalysisUsage &AU) const override
Does not modify anything. It uses Value Numbering and Alias Analysis.
void releaseMemory() override
Clean up memory in between runs.
Representation for a specific memory location.
MemoryLocation getWithoutAATags() const
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
static MemoryLocation getAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location after Ptr, while remaining within the underlying objec...
MemoryLocation getWithNewPtr(const Value *NewPtr) const
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
const Value * Ptr
The address of the start of the location.
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
This is an entry in the NonLocalDepInfo cache.
void setResult(const MemDepResult &R)
const MemDepResult & getResult() const
This is a result from a NonLocal dependence query.
PHITransAddr - An address value which tracks and handles phi translation.
LLVM_ABI Value * translateValue(BasicBlock *CurBB, BasicBlock *PredBB, const DominatorTree *DT, bool MustDominate)
translateValue - PHI translate the current address up the CFG from CurBB to Pred, updating our state ...
LLVM_ABI SelectInst * getSelect() const
If the address expression depends on a select instruction (possibly through casts or GEPs),...
Value * getAddr() const
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
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
std::pair< Value *, Value * > SelectAddrs
size_type size() const
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.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:986
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:708
iterator_range< use_iterator > uses()
Definition Value.h:382
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
Abstract Attribute helper functions.
Definition Attributor.h:164
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool isStorePreservingMemoryLocation(const StoreInst *SI, const MemoryLocation &MemLoc, Align MemLocAlign, BatchAAResults &AA, unsigned ScanLimit)
Check whether SI, which may alias MemLoc, can be safely skipped.
Definition Loads.cpp:843
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
bool isStrongerThanUnordered(AtomicOrdering AO)
LLVM_ABI bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ Other
Any other memory.
Definition ModRef.h:68
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool isNoModRef(const ModRefInfo MRI)
Definition ModRef.h:40
bool isStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice,...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29