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