1//===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
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 defines the primary stateless implementation of the
10// Alias Analysis interface that implements identities (two different
11// globals cannot alias, etc), but does no stateful analysis.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/BasicAliasAnalysis.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/AssumptionCache.h"
23#include "llvm/Analysis/CFG.h"
24#include "llvm/Analysis/CaptureTracking.h"
25#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/MemoryLocation.h"
27#include "llvm/Analysis/TargetLibraryInfo.h"
28#include "llvm/Analysis/ValueTracking.h"
29#include "llvm/IR/Argument.h"
30#include "llvm/IR/Attributes.h"
31#include "llvm/IR/Constant.h"
32#include "llvm/IR/ConstantRange.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/CycleInfo.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/DerivedTypes.h"
37#include "llvm/IR/Dominators.h"
38#include "llvm/IR/Function.h"
39#include "llvm/IR/GetElementPtrTypeIterator.h"
40#include "llvm/IR/GlobalAlias.h"
41#include "llvm/IR/GlobalVariable.h"
42#include "llvm/IR/InstrTypes.h"
43#include "llvm/IR/Instruction.h"
44#include "llvm/IR/Instructions.h"
45#include "llvm/IR/IntrinsicInst.h"
46#include "llvm/IR/Intrinsics.h"
47#include "llvm/IR/Operator.h"
48#include "llvm/IR/PatternMatch.h"
49#include "llvm/IR/Type.h"
50#include "llvm/IR/User.h"
51#include "llvm/IR/Value.h"
52#include "llvm/InitializePasses.h"
53#include "llvm/Pass.h"
54#include "llvm/Support/Casting.h"
55#include "llvm/Support/CommandLine.h"
56#include "llvm/Support/Compiler.h"
57#include "llvm/Support/KnownBits.h"
58#include "llvm/Support/SaveAndRestore.h"
59#include <cassert>
60#include <cstdint>
61#include <cstdlib>
62#include <optional>
63#include <utility>
64
65#define DEBUG_TYPE "basicaa"
66
67using namespace llvm;
68
69/// Enable analysis of recursive PHI nodes.
70static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden,
71 cl::init(Val: true));
72
73static cl::opt<bool> EnableSeparateStorageAnalysis("basic-aa-separate-storage",
74 cl::Hidden, cl::init(Val: true));
75
76/// SearchLimitReached / SearchTimes shows how often the limit of
77/// to decompose GEPs is reached. It will affect the precision
78/// of basic alias analysis.
79STATISTIC(SearchLimitReached, "Number of times the limit to "
80 "decompose GEPs is reached");
81STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
82
83bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
84 FunctionAnalysisManager::Invalidator &Inv) {
85 // We don't care if this analysis itself is preserved, it has no state. But
86 // we need to check that the analyses it depends on have been. Note that we
87 // may be created without handles to some analyses and in that case don't
88 // depend on them.
89 if (Inv.invalidate<AssumptionAnalysis>(IR&: Fn, PA) ||
90 (DT_ && Inv.invalidate<DominatorTreeAnalysis>(IR&: Fn, PA)) ||
91 Inv.invalidate<TargetLibraryAnalysis>(IR&: Fn, PA))
92 return true;
93
94 // Otherwise this analysis result remains valid.
95 return false;
96}
97
98//===----------------------------------------------------------------------===//
99// Useful predicates
100//===----------------------------------------------------------------------===//
101
102/// Returns the size of the object specified by V or UnknownSize if unknown.
103static std::optional<TypeSize> getObjectSize(const Value *V,
104 const DataLayout &DL,
105 const TargetLibraryInfo &TLI,
106 bool NullIsValidLoc,
107 bool RoundToAlign = false) {
108 ObjectSizeOpts Opts;
109 Opts.RoundToAlign = RoundToAlign;
110 Opts.NullIsUnknownSize = NullIsValidLoc;
111 if (std::optional<TypeSize> Size = getBaseObjectSize(Ptr: V, DL, TLI: &TLI, Opts)) {
112 // FIXME: Remove this check, only exists to preserve previous behavior.
113 if (Size->isScalable())
114 return std::nullopt;
115 return Size;
116 }
117 return std::nullopt;
118}
119
120/// Return the minimal extent from \p V to the end of the underlying object,
121/// assuming the result is used in an aliasing query. E.g., we do use the query
122/// location size and the fact that null pointers cannot alias here.
123static TypeSize getMinimalExtentFrom(const Value &V,
124 const LocationSize &LocSize,
125 const DataLayout &DL,
126 bool NullIsValidLoc) {
127 // If we have dereferenceability information we know a lower bound for the
128 // extent as accesses for a lower offset would be valid. We need to exclude
129 // the "or null" part if null is a valid pointer. We can ignore frees, as an
130 // access after free would be undefined behavior.
131 bool CanBeNull;
132 uint64_t DerefBytes =
133 V.getPointerDereferenceableBytes(DL, CanBeNull, /*CanBeFreed=*/nullptr);
134 DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
135 // If queried with a precise location size, we assume that location size to be
136 // accessed, thus valid.
137 if (LocSize.isPrecise())
138 DerefBytes = std::max(a: DerefBytes, b: LocSize.getValue().getKnownMinValue());
139 return TypeSize::getFixed(ExactSize: DerefBytes);
140}
141
142/// Returns true if we can prove that the object specified by V is smaller than
143/// the minimal extent accessed from OtherV with size OtherSize. Bails out early
144/// unless the root object is passed as the first parameter.
145static bool isObjectSmallerThan(const Value *V, const Value &OtherV,
146 LocationSize OtherSize, const DataLayout &DL,
147 const TargetLibraryInfo &TLI,
148 bool NullIsValidLoc) {
149 // Note that the meanings of the "object" are slightly different in the
150 // following contexts:
151 // c1: llvm::getObjectSize()
152 // c2: llvm.objectsize() intrinsic
153 // c3: isObjectSmallerThan()
154 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
155 // refers to the "entire object".
156 //
157 // Consider this example:
158 // char *p = (char*)malloc(100)
159 // char *q = p+80;
160 //
161 // In the context of c1 and c2, the "object" pointed by q refers to the
162 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
163 //
164 // In the context of c3, the "object" refers to the chunk of memory being
165 // allocated. So, the "object" has 100 bytes, and q points to the middle the
166 // "object". However, unless p, the root object, is passed as the first
167 // parameter, the call to isIdentifiedObject() makes isObjectSmallerThan()
168 // bail out early.
169 if (!isIdentifiedObject(V))
170 return false;
171
172 // This function needs to use the aligned object size because we allow
173 // reads a bit past the end given sufficient alignment.
174 std::optional<TypeSize> ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
175 /*RoundToAlign*/ true);
176 if (!ObjectSize)
177 return false;
178
179 TypeSize Size = getMinimalExtentFrom(V: OtherV, LocSize: OtherSize, DL, NullIsValidLoc);
180 return TypeSize::isKnownLT(LHS: *ObjectSize, RHS: Size);
181}
182
183/// Returns true if we can prove that the object specified by V has size Size.
184static bool isObjectSize(const Value *V, TypeSize Size, const DataLayout &DL,
185 const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
186 std::optional<TypeSize> ObjectSize =
187 getObjectSize(V, DL, TLI, NullIsValidLoc);
188 return ObjectSize && *ObjectSize == Size;
189}
190
191/// Return true if both V1 and V2 are VScale
192static bool areBothVScale(const Value *V1, const Value *V2) {
193 return PatternMatch::match(V: V1, P: PatternMatch::m_VScale()) &&
194 PatternMatch::match(V: V2, P: PatternMatch::m_VScale());
195}
196
197//===----------------------------------------------------------------------===//
198// CaptureAnalysis implementations
199//===----------------------------------------------------------------------===//
200
201CaptureAnalysis::~CaptureAnalysis() = default;
202
203CaptureComponents SimpleCaptureAnalysis::getCapturesBefore(
204 const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) {
205 if (!isIdentifiedFunctionLocal(V: Object))
206 return CaptureComponents::Provenance;
207
208 auto [CacheIt, Inserted] = IsCapturedCache.try_emplace(Key: Object);
209 if (Inserted)
210 CacheIt->second = PointerMayBeCaptured(
211 V: Object, Mask: CaptureComponents::Provenance,
212 StopFn: [](CaptureComponents CC) { return capturesFullProvenance(CC); });
213
214 return ReturnCaptures ? CacheIt->second.WithRet : CacheIt->second.WithoutRet;
215}
216
217static bool isNotInCycle(const Instruction *I, const DominatorTree *DT,
218 const LoopInfo *LI, const CycleInfo *CI) {
219 if (CI)
220 return !CI->getCycle(Block: I->getParent());
221
222 BasicBlock *BB = const_cast<BasicBlock *>(I->getParent());
223 SmallVector<BasicBlock *> Succs(successors(BB));
224 return Succs.empty() ||
225 !isPotentiallyReachableFromMany(Worklist&: Succs, StopBB: BB, ExclusionSet: nullptr, DT, LI);
226}
227
228CaptureComponents EarliestEscapeAnalysis::getCapturesBefore(
229 const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) {
230 if (!isIdentifiedFunctionLocal(V: Object))
231 return CaptureComponents::Provenance;
232
233 auto Iter = EarliestEscapes.try_emplace(Key: Object);
234 if (Iter.second) {
235 auto [EarliestInst, Res] = FindEarliestCapture(
236 V: Object, F&: *DT.getRoot()->getParent(), DT, Mask: CaptureComponents::Provenance);
237 if (EarliestInst)
238 Inst2Obj[EarliestInst].push_back(NewVal: Object);
239 Iter.first->second = {EarliestInst, Res};
240 }
241
242 if (ReturnCaptures) {
243 assert(!I && "Context instruction not supported if ReturnCaptures");
244 return Iter.first->second.second.WithRet;
245 }
246
247 auto IsNotCapturedBefore = [&]() {
248 // No capturing instruction.
249 Instruction *CaptureInst = Iter.first->second.first;
250 if (!CaptureInst)
251 return true;
252
253 // No context instruction means any use is capturing.
254 if (!I)
255 return false;
256
257 // Handle longjmp during re-entry.
258 if (callsReturnsTwiceFn())
259 return false;
260
261 if (I == CaptureInst) {
262 if (OrAt)
263 return false;
264 return isNotInCycle(I, DT: &DT, LI, CI);
265 }
266
267 return !isPotentiallyReachable(From: CaptureInst, To: I, ExclusionSet: nullptr, DT: &DT, LI, CI);
268 };
269 if (IsNotCapturedBefore())
270 return CaptureComponents::None;
271 return Iter.first->second.second.WithoutRet;
272}
273
274bool EarliestEscapeAnalysis::callsReturnsTwiceFn() {
275 if (!CallsReturnsTwiceFn)
276 CallsReturnsTwiceFn =
277 DT.getRoot()->getParent()->callsFunctionThatReturnsTwice();
278 return *CallsReturnsTwiceFn;
279}
280
281void EarliestEscapeAnalysis::removeInstruction(Instruction *I) {
282 auto Iter = Inst2Obj.find(Val: I);
283 if (Iter != Inst2Obj.end()) {
284 for (const Value *Obj : Iter->second)
285 EarliestEscapes.erase(Val: Obj);
286 Inst2Obj.erase(Val: I);
287 }
288}
289
290//===----------------------------------------------------------------------===//
291// GetElementPtr Instruction Decomposition and Analysis
292//===----------------------------------------------------------------------===//
293
294namespace {
295/// Represents zext(sext(trunc(V))).
296struct CastedValue {
297 const Value *V;
298 unsigned ZExtBits = 0;
299 unsigned SExtBits = 0;
300 unsigned TruncBits = 0;
301 /// Whether trunc(V) is non-negative.
302 bool IsNonNegative = false;
303
304 explicit CastedValue(const Value *V) : V(V) {}
305 explicit CastedValue(const Value *V, unsigned ZExtBits, unsigned SExtBits,
306 unsigned TruncBits, bool IsNonNegative)
307 : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits), TruncBits(TruncBits),
308 IsNonNegative(IsNonNegative) {}
309
310 unsigned getBitWidth() const {
311 return V->getType()->getPrimitiveSizeInBits() - TruncBits + ZExtBits +
312 SExtBits;
313 }
314
315 CastedValue withValue(const Value *NewV, bool PreserveNonNeg) const {
316 return CastedValue(NewV, ZExtBits, SExtBits, TruncBits,
317 IsNonNegative && PreserveNonNeg);
318 }
319
320 /// Replace V with zext(NewV)
321 CastedValue withZExtOfValue(const Value *NewV, bool ZExtNonNegative) const {
322 unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
323 NewV->getType()->getPrimitiveSizeInBits();
324 if (ExtendBy <= TruncBits)
325 // zext<nneg>(trunc(zext(NewV))) == zext<nneg>(trunc(NewV))
326 // The nneg can be preserved on the outer zext here.
327 return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy,
328 IsNonNegative);
329
330 // zext(sext(zext(NewV))) == zext(zext(zext(NewV)))
331 ExtendBy -= TruncBits;
332 // zext<nneg>(zext(NewV)) == zext(NewV)
333 // zext(zext<nneg>(NewV)) == zext<nneg>(NewV)
334 // The nneg can be preserved from the inner zext here but must be dropped
335 // from the outer.
336 return CastedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0, 0,
337 ZExtNonNegative);
338 }
339
340 /// Replace V with sext(NewV)
341 CastedValue withSExtOfValue(const Value *NewV) const {
342 unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
343 NewV->getType()->getPrimitiveSizeInBits();
344 if (ExtendBy <= TruncBits)
345 // zext<nneg>(trunc(sext(NewV))) == zext<nneg>(trunc(NewV))
346 // The nneg can be preserved on the outer zext here
347 return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy,
348 IsNonNegative);
349
350 // zext(sext(sext(NewV)))
351 ExtendBy -= TruncBits;
352 // zext<nneg>(sext(sext(NewV))) = zext<nneg>(sext(NewV))
353 // The nneg can be preserved on the outer zext here
354 return CastedValue(NewV, ZExtBits, SExtBits + ExtendBy, 0, IsNonNegative);
355 }
356
357 APInt evaluateWith(APInt N) const {
358 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
359 "Incompatible bit width");
360 if (TruncBits) N = N.trunc(width: N.getBitWidth() - TruncBits);
361 if (SExtBits) N = N.sext(width: N.getBitWidth() + SExtBits);
362 if (ZExtBits) N = N.zext(width: N.getBitWidth() + ZExtBits);
363 return N;
364 }
365
366 ConstantRange evaluateWith(ConstantRange N) const {
367 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
368 "Incompatible bit width");
369 if (TruncBits) N = N.truncate(BitWidth: N.getBitWidth() - TruncBits);
370 if (IsNonNegative && !N.isAllNonNegative())
371 N = N.intersectWith(
372 CR: ConstantRange(APInt::getZero(numBits: N.getBitWidth()),
373 APInt::getSignedMinValue(numBits: N.getBitWidth())));
374 if (SExtBits) N = N.signExtend(BitWidth: N.getBitWidth() + SExtBits);
375 if (ZExtBits) N = N.zeroExtend(BitWidth: N.getBitWidth() + ZExtBits);
376 return N;
377 }
378
379 KnownBits evaluateWith(KnownBits K) const {
380 assert(K.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
381 "Incompatible bit width");
382 if (TruncBits)
383 K = K.trunc(BitWidth: K.getBitWidth() - TruncBits);
384 if (SExtBits)
385 K = K.sext(BitWidth: K.getBitWidth() + SExtBits);
386 if (ZExtBits)
387 K = K.zext(BitWidth: K.getBitWidth() + ZExtBits);
388 return K;
389 }
390
391 bool canDistributeOver(bool NUW, bool NSW) const {
392 // zext(x op<nuw> y) == zext(x) op<nuw> zext(y)
393 // sext(x op<nsw> y) == sext(x) op<nsw> sext(y)
394 // trunc(x op y) == trunc(x) op trunc(y)
395 return (!ZExtBits || NUW) && (!SExtBits || NSW);
396 }
397
398 bool hasSameCastsAs(const CastedValue &Other) const {
399 if (V->getType() != Other.V->getType())
400 return false;
401
402 if (ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits &&
403 TruncBits == Other.TruncBits)
404 return true;
405 // If either CastedValue has a nneg zext then the sext/zext bits are
406 // interchangable for that value.
407 if (IsNonNegative || Other.IsNonNegative)
408 return (ZExtBits + SExtBits == Other.ZExtBits + Other.SExtBits &&
409 TruncBits == Other.TruncBits);
410 return false;
411 }
412};
413
414/// Represents zext(sext(trunc(V))) * Scale + Offset.
415struct LinearExpression {
416 CastedValue Val;
417 APInt Scale;
418 APInt Offset;
419
420 /// True if all operations in this expression are NUW.
421 bool IsNUW;
422 /// True if all operations in this expression are NSW.
423 bool IsNSW;
424
425 LinearExpression(const CastedValue &Val, const APInt &Scale,
426 const APInt &Offset, bool IsNUW, bool IsNSW)
427 : Val(Val), Scale(Scale), Offset(Offset), IsNUW(IsNUW), IsNSW(IsNSW) {}
428
429 LinearExpression(const CastedValue &Val)
430 : Val(Val), IsNUW(true), IsNSW(true) {
431 unsigned BitWidth = Val.getBitWidth();
432 Scale = APInt(BitWidth, 1);
433 Offset = APInt(BitWidth, 0);
434 }
435
436 LinearExpression mul(const APInt &Other, bool MulIsNUW, bool MulIsNSW) const {
437 // The check for zero offset is necessary, because generally
438 // (X +nsw Y) *nsw Z does not imply (X *nsw Z) +nsw (Y *nsw Z).
439 bool NSW = IsNSW && (Other.isOne() || (MulIsNSW && Offset.isZero()));
440 bool NUW = IsNUW && (Other.isOne() || MulIsNUW);
441 return LinearExpression(Val, Scale * Other, Offset * Other, NUW, NSW);
442 }
443};
444}
445
446/// Analyzes the specified value as a linear expression: "A*V + B", where A and
447/// B are constant integers.
448static LinearExpression GetLinearExpression(
449 const CastedValue &Val, const DataLayout &DL, unsigned Depth,
450 AssumptionCache *AC, DominatorTree *DT) {
451 // Limit our recursion depth.
452 if (Depth == 6)
453 return Val;
454
455 if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val: Val.V))
456 return LinearExpression(Val, APInt(Val.getBitWidth(), 0),
457 Val.evaluateWith(N: Const->getValue()), true, true);
458
459 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val: Val.V)) {
460 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Val: BOp->getOperand(i_nocapture: 1))) {
461 APInt RHS = Val.evaluateWith(N: RHSC->getValue());
462 // The only non-OBO case we deal with is or, and only limited to the
463 // case where it is both nuw and nsw.
464 bool NUW = true, NSW = true;
465 if (isa<OverflowingBinaryOperator>(Val: BOp)) {
466 NUW &= BOp->hasNoUnsignedWrap();
467 NSW &= BOp->hasNoSignedWrap();
468 }
469 if (!Val.canDistributeOver(NUW, NSW))
470 return Val;
471
472 // While we can distribute over trunc, we cannot preserve nowrap flags
473 // in that case.
474 if (Val.TruncBits)
475 NUW = NSW = false;
476
477 LinearExpression E(Val);
478 switch (BOp->getOpcode()) {
479 default:
480 // We don't understand this instruction, so we can't decompose it any
481 // further.
482 return Val;
483 case Instruction::Or:
484 // X|C == X+C if it is disjoint. Otherwise we can't analyze it.
485 if (!cast<PossiblyDisjointInst>(Val: BOp)->isDisjoint())
486 return Val;
487
488 [[fallthrough]];
489 case Instruction::Add: {
490 E = GetLinearExpression(Val: Val.withValue(NewV: BOp->getOperand(i_nocapture: 0), PreserveNonNeg: false), DL,
491 Depth: Depth + 1, AC, DT);
492 E.Offset += RHS;
493 E.IsNUW &= NUW;
494 E.IsNSW &= NSW;
495 break;
496 }
497 case Instruction::Sub: {
498 E = GetLinearExpression(Val: Val.withValue(NewV: BOp->getOperand(i_nocapture: 0), PreserveNonNeg: false), DL,
499 Depth: Depth + 1, AC, DT);
500 E.Offset -= RHS;
501 E.IsNUW = false; // sub nuw x, y is not add nuw x, -y.
502 E.IsNSW &= NSW;
503 break;
504 }
505 case Instruction::Mul:
506 E = GetLinearExpression(Val: Val.withValue(NewV: BOp->getOperand(i_nocapture: 0), PreserveNonNeg: false), DL,
507 Depth: Depth + 1, AC, DT)
508 .mul(Other: RHS, MulIsNUW: NUW, MulIsNSW: NSW);
509 break;
510 case Instruction::Shl:
511 // We're trying to linearize an expression of the kind:
512 // shl i8 -128, 36
513 // where the shift count exceeds the bitwidth of the type.
514 // We can't decompose this further (the expression would return
515 // a poison value).
516 if (RHS.getLimitedValue() > Val.getBitWidth())
517 return Val;
518
519 E = GetLinearExpression(Val: Val.withValue(NewV: BOp->getOperand(i_nocapture: 0), PreserveNonNeg: NSW), DL,
520 Depth: Depth + 1, AC, DT);
521 E.Offset <<= RHS.getLimitedValue();
522 E.Scale <<= RHS.getLimitedValue();
523 E.IsNUW &= NUW;
524 E.IsNSW &= NSW;
525 break;
526 }
527 return E;
528 }
529 }
530
531 if (const auto *ZExt = dyn_cast<ZExtInst>(Val: Val.V))
532 return GetLinearExpression(
533 Val: Val.withZExtOfValue(NewV: ZExt->getOperand(i_nocapture: 0), ZExtNonNegative: ZExt->hasNonNeg()), DL,
534 Depth: Depth + 1, AC, DT);
535
536 if (isa<SExtInst>(Val: Val.V))
537 return GetLinearExpression(
538 Val: Val.withSExtOfValue(NewV: cast<CastInst>(Val: Val.V)->getOperand(i_nocapture: 0)),
539 DL, Depth: Depth + 1, AC, DT);
540
541 return Val;
542}
543
544namespace {
545// A linear transformation of a Value; this class represents
546// ZExt(SExt(Trunc(V, TruncBits), SExtBits), ZExtBits) * Scale.
547struct VariableGEPIndex {
548 CastedValue Val;
549 APInt Scale;
550
551 // Context instruction to use when querying information about this index.
552 const Instruction *CtxI;
553
554 /// True if all operations in this expression are NSW.
555 bool IsNSW;
556
557 /// True if the index should be subtracted rather than added. We don't simply
558 /// negate the Scale, to avoid losing the NSW flag: X - INT_MIN*1 may be
559 /// non-wrapping, while X + INT_MIN*(-1) wraps.
560 bool IsNegated;
561
562 bool hasNegatedScaleOf(const VariableGEPIndex &Other) const {
563 if (IsNegated == Other.IsNegated)
564 return Scale == -Other.Scale;
565 return Scale == Other.Scale;
566 }
567
568 void dump() const {
569 print(OS&: dbgs());
570 dbgs() << "\n";
571 }
572 void print(raw_ostream &OS) const {
573 OS << "(V=" << Val.V->getName()
574 << ", zextbits=" << Val.ZExtBits
575 << ", sextbits=" << Val.SExtBits
576 << ", truncbits=" << Val.TruncBits
577 << ", scale=" << Scale
578 << ", nsw=" << IsNSW
579 << ", negated=" << IsNegated << ")";
580 }
581};
582}
583
584// Represents the internal structure of a GEP, decomposed into a base pointer,
585// constant offsets, and variable scaled indices.
586struct BasicAAResult::DecomposedGEP {
587 // Base pointer of the GEP
588 const Value *Base;
589 // Total constant offset from base.
590 APInt Offset;
591 // Scaled variable (non-constant) indices.
592 SmallVector<VariableGEPIndex, 4> VarIndices;
593 // Nowrap flags common to all GEP operations involved in expression.
594 GEPNoWrapFlags NWFlags = GEPNoWrapFlags::all();
595
596 void dump() const {
597 print(OS&: dbgs());
598 dbgs() << "\n";
599 }
600 void print(raw_ostream &OS) const {
601 OS << ", inbounds=" << (NWFlags.isInBounds() ? "1" : "0")
602 << ", nuw=" << (NWFlags.hasNoUnsignedWrap() ? "1" : "0")
603 << "(DecomposedGEP Base=" << Base->getName() << ", Offset=" << Offset
604 << ", VarIndices=[";
605 for (size_t i = 0; i < VarIndices.size(); i++) {
606 if (i != 0)
607 OS << ", ";
608 VarIndices[i].print(OS);
609 }
610 OS << "])";
611 }
612};
613
614// Results of analyzing variable GEP indices for offset-based disambiguation.
615struct BasicAAResult::VariableGEPOffsetInfo {
616 APInt GCD;
617 ConstantRange OffsetRange;
618 SmallVector<KnownBits, 4> VarIndexKnownBits;
619};
620
621/// If V is a symbolic pointer expression, decompose it into a base pointer
622/// with a constant offset and a number of scaled symbolic offsets.
623///
624/// The scaled symbolic offsets (represented by pairs of a Value* and a scale
625/// in the VarIndices vector) are Value*'s that are known to be scaled by the
626/// specified amount, but which may have other unrepresented high bits. As
627/// such, the gep cannot necessarily be reconstructed from its decomposed form.
628BasicAAResult::DecomposedGEP
629BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL,
630 AssumptionCache *AC, DominatorTree *DT) {
631 // Limit recursion depth to limit compile time in crazy cases.
632 unsigned MaxLookup = MaxLookupSearchDepth;
633 SearchTimes++;
634 const Instruction *CtxI = dyn_cast<Instruction>(Val: V);
635
636 unsigned IndexSize = DL.getIndexTypeSizeInBits(Ty: V->getType());
637 DecomposedGEP Decomposed;
638 Decomposed.Offset = APInt(IndexSize, 0);
639 do {
640 // See if this is a bitcast or GEP.
641 const Operator *Op = dyn_cast<Operator>(Val: V);
642 if (!Op) {
643 // The only non-operator case we can handle are GlobalAliases.
644 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Val: V)) {
645 if (!GA->isInterposable()) {
646 V = GA->getAliasee();
647 continue;
648 }
649 }
650 Decomposed.Base = V;
651 return Decomposed;
652 }
653
654 if (Op->getOpcode() == Instruction::BitCast ||
655 Op->getOpcode() == Instruction::AddrSpaceCast) {
656 Value *NewV = Op->getOperand(i: 0);
657 auto *NewVTy = NewV->getType();
658 // Don't look through casts to non-scalar-pointer types or address spaces
659 // with differing index widths.
660 if (!isa<PointerType>(Val: NewVTy) ||
661 DL.getIndexTypeSizeInBits(Ty: NewVTy) != IndexSize) {
662 Decomposed.Base = V;
663 return Decomposed;
664 }
665 V = NewV;
666 continue;
667 }
668
669 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Val: Op);
670 if (!GEPOp) {
671 if (const auto *PHI = dyn_cast<PHINode>(Val: V)) {
672 // Look through single-arg phi nodes created by LCSSA.
673 if (PHI->getNumIncomingValues() == 1) {
674 V = PHI->getIncomingValue(i: 0);
675 continue;
676 }
677 } else if (const auto *Call = dyn_cast<CallBase>(Val: V)) {
678 // CaptureTracking can know about special capturing properties of some
679 // intrinsics like launder.invariant.group, that can't be expressed with
680 // the attributes, but have properties like returning aliasing pointer.
681 // Because some analysis may assume that nocaptured pointer is not
682 // returned from some special intrinsic (because function would have to
683 // be marked with returns attribute), it is crucial to use this function
684 // because it should be in sync with CaptureTracking. Not using it may
685 // cause weird miscompilations where 2 aliasing pointers are assumed to
686 // noalias.
687 // Pass MustPreserveOffset=true so we exclude llvm.ptrmask, which can
688 // change the byte offset by clearing low bits and would otherwise
689 // corrupt the symbolic offset we are accumulating in `Decomposed`.
690 if (auto *RP = getArgumentAliasingToReturnedPointer(
691 Call, /*MustPreserveOffset=*/true)) {
692 V = RP;
693 continue;
694 }
695 }
696
697 Decomposed.Base = V;
698 return Decomposed;
699 }
700
701 // Track the common nowrap flags for all GEPs we see.
702 Decomposed.NWFlags &= GEPOp->getNoWrapFlags();
703
704 assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized");
705
706 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
707 gep_type_iterator GTI = gep_type_begin(GEP: GEPOp);
708 for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
709 I != E; ++I, ++GTI) {
710 const Value *Index = *I;
711 // Compute the (potentially symbolic) offset in bytes for this index.
712 if (StructType *STy = GTI.getStructTypeOrNull()) {
713 // For a struct, add the member offset.
714 unsigned FieldNo = cast<ConstantInt>(Val: Index)->getZExtValue();
715 if (FieldNo == 0)
716 continue;
717
718 Decomposed.Offset += DL.getStructLayout(Ty: STy)->getElementOffset(Idx: FieldNo);
719 continue;
720 }
721
722 // For an array/pointer, add the element offset, explicitly scaled.
723 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Val: Index)) {
724 if (CIdx->isZero())
725 continue;
726
727 // Don't attempt to analyze GEPs if the scalable index is not zero.
728 TypeSize AllocTypeSize = GTI.getSequentialElementStride(DL);
729 if (AllocTypeSize.isScalable()) {
730 Decomposed.Base = V;
731 return Decomposed;
732 }
733
734 Decomposed.Offset += AllocTypeSize.getFixedValue() *
735 CIdx->getValue().sextOrTrunc(width: IndexSize);
736 continue;
737 }
738
739 TypeSize AllocTypeSize = GTI.getSequentialElementStride(DL);
740 if (AllocTypeSize.isScalable()) {
741 Decomposed.Base = V;
742 return Decomposed;
743 }
744
745 // If the integer type is smaller than the index size, it is implicitly
746 // sign extended or truncated to index size.
747 bool NUSW = GEPOp->hasNoUnsignedSignedWrap();
748 bool NUW = GEPOp->hasNoUnsignedWrap();
749 bool NonNeg = NUSW && NUW;
750 unsigned Width = Index->getType()->getIntegerBitWidth();
751 unsigned SExtBits = IndexSize > Width ? IndexSize - Width : 0;
752 unsigned TruncBits = IndexSize < Width ? Width - IndexSize : 0;
753 LinearExpression LE = GetLinearExpression(
754 Val: CastedValue(Index, 0, SExtBits, TruncBits, NonNeg), DL, Depth: 0, AC, DT);
755
756 // Scale by the type size.
757 unsigned TypeSize = AllocTypeSize.getFixedValue();
758 LE = LE.mul(Other: APInt(IndexSize, TypeSize), MulIsNUW: NUW, MulIsNSW: NUSW);
759 Decomposed.Offset += LE.Offset;
760 APInt Scale = LE.Scale;
761 if (!LE.IsNUW)
762 Decomposed.NWFlags = Decomposed.NWFlags.withoutNoUnsignedWrap();
763
764 // If we already had an occurrence of this index variable, merge this
765 // scale into it. For example, we want to handle:
766 // A[x][x] -> x*16 + x*4 -> x*20
767 // This also ensures that 'x' only appears in the index list once.
768 for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
769 if ((Decomposed.VarIndices[i].Val.V == LE.Val.V ||
770 areBothVScale(V1: Decomposed.VarIndices[i].Val.V, V2: LE.Val.V)) &&
771 Decomposed.VarIndices[i].Val.hasSameCastsAs(Other: LE.Val)) {
772 Scale += Decomposed.VarIndices[i].Scale;
773 // We cannot guarantee no-wrap for the merge.
774 LE.IsNSW = LE.IsNUW = false;
775 Decomposed.VarIndices.erase(CI: Decomposed.VarIndices.begin() + i);
776 break;
777 }
778 }
779
780 if (!!Scale) {
781 VariableGEPIndex Entry = {.Val: LE.Val, .Scale: Scale, .CtxI: CtxI, .IsNSW: LE.IsNSW,
782 /* IsNegated */ false};
783 Decomposed.VarIndices.push_back(Elt: Entry);
784 }
785 }
786
787 // Analyze the base pointer next.
788 V = GEPOp->getOperand(i_nocapture: 0);
789 } while (--MaxLookup);
790
791 // If the chain of expressions is too deep, just return early.
792 Decomposed.Base = V;
793 SearchLimitReached++;
794 return Decomposed;
795}
796
797ModRefInfo BasicAAResult::getModRefInfoMask(const MemoryLocation &Loc,
798 AAQueryInfo &AAQI,
799 bool IgnoreLocals) {
800 assert(Visited.empty() && "Visited must be cleared after use!");
801 llvm::scope_exit _([&] { Visited.clear(); });
802
803 unsigned MaxLookup = 8;
804 SmallVector<const Value *, 16> Worklist;
805 Worklist.push_back(Elt: Loc.Ptr);
806 ModRefInfo Result = ModRefInfo::NoModRef;
807
808 do {
809 const Value *V = getUnderlyingObject(V: Worklist.pop_back_val());
810 if (!Visited.insert(Ptr: V).second)
811 continue;
812
813 // Ignore allocas if we were instructed to do so.
814 if (IgnoreLocals && isa<AllocaInst>(Val: V))
815 continue;
816
817 // If the location points to memory that is known to be invariant for
818 // the life of the underlying SSA value, then we can exclude Mod from
819 // the set of valid memory effects.
820 //
821 // An argument that is marked readonly and noalias is known to be
822 // invariant while that function is executing.
823 if (const Argument *Arg = dyn_cast<Argument>(Val: V)) {
824 if (Arg->hasNoAliasAttr() && Arg->onlyReadsMemory()) {
825 Result |= ModRefInfo::Ref;
826 continue;
827 }
828 }
829
830 // A global constant can't be mutated.
831 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: V)) {
832 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
833 // global to be marked constant in some modules and non-constant in
834 // others. GV may even be a declaration, not a definition.
835 if (!GV->isConstant())
836 return ModRefInfo::ModRef;
837 continue;
838 }
839
840 // If both select values point to local memory, then so does the select.
841 if (const SelectInst *SI = dyn_cast<SelectInst>(Val: V)) {
842 Worklist.push_back(Elt: SI->getTrueValue());
843 Worklist.push_back(Elt: SI->getFalseValue());
844 continue;
845 }
846
847 // If all values incoming to a phi node point to local memory, then so does
848 // the phi.
849 if (const PHINode *PN = dyn_cast<PHINode>(Val: V)) {
850 // Don't bother inspecting phi nodes with many operands.
851 if (PN->getNumIncomingValues() > MaxLookup)
852 return ModRefInfo::ModRef;
853 append_range(C&: Worklist, R: PN->incoming_values());
854 continue;
855 }
856
857 // Otherwise be conservative.
858 return ModRefInfo::ModRef;
859 } while (!Worklist.empty() && --MaxLookup);
860
861 // If we hit the maximum number of instructions to examine, be conservative.
862 if (!Worklist.empty())
863 return ModRefInfo::ModRef;
864
865 return Result;
866}
867
868static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
869 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: Call);
870 return II && II->getIntrinsicID() == IID;
871}
872
873/// Returns the behavior when calling the given call site.
874MemoryEffects BasicAAResult::getMemoryEffects(const CallBase *Call,
875 AAQueryInfo &AAQI) {
876 MemoryEffects Min = Call->getAttributes().getMemoryEffects();
877
878 if (const Function *F = dyn_cast<Function>(Val: Call->getCalledOperand())) {
879 MemoryEffects FuncME = AAQI.AAR.getMemoryEffects(F);
880 // Operand bundles on the call may also read or write memory, in addition
881 // to the behavior of the called function.
882 if (Call->hasReadingOperandBundles())
883 FuncME |= MemoryEffects::readOnly();
884 if (Call->hasClobberingOperandBundles())
885 FuncME |= MemoryEffects::writeOnly();
886 if (Call->isVolatile()) {
887 // Volatile operations also access inaccessible memory.
888 FuncME |= MemoryEffects::inaccessibleMemOnly();
889 }
890 Min &= FuncME;
891 }
892
893 return Min;
894}
895
896/// Returns the behavior when calling the given function. For use when the call
897/// site is not known.
898MemoryEffects BasicAAResult::getMemoryEffects(const Function *F) {
899 switch (F->getIntrinsicID()) {
900 case Intrinsic::experimental_guard:
901 case Intrinsic::experimental_deoptimize:
902 // These intrinsics can read arbitrary memory, and additionally modref
903 // inaccessible memory to model control dependence.
904 return MemoryEffects::readOnly() |
905 MemoryEffects::inaccessibleMemOnly(MR: ModRefInfo::ModRef);
906 }
907
908 return F->getMemoryEffects();
909}
910
911ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,
912 unsigned ArgIdx) {
913 if (Call->doesNotAccessMemory(OpNo: ArgIdx))
914 return ModRefInfo::NoModRef;
915
916 if (Call->onlyWritesMemory(OpNo: ArgIdx))
917 return ModRefInfo::Mod;
918
919 if (Call->onlyReadsMemory(OpNo: ArgIdx))
920 return ModRefInfo::Ref;
921
922 return ModRefInfo::ModRef;
923}
924
925#ifndef NDEBUG
926static const Function *getParent(const Value *V) {
927 if (const Instruction *inst = dyn_cast<Instruction>(V)) {
928 if (!inst->getParent())
929 return nullptr;
930 return inst->getParent()->getParent();
931 }
932
933 if (const Argument *arg = dyn_cast<Argument>(V))
934 return arg->getParent();
935
936 return nullptr;
937}
938
939static bool notDifferentParent(const Value *O1, const Value *O2) {
940
941 const Function *F1 = getParent(O1);
942 const Function *F2 = getParent(O2);
943
944 return !F1 || !F2 || F1 == F2;
945}
946#endif
947
948AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
949 const MemoryLocation &LocB, AAQueryInfo &AAQI,
950 const Instruction *CtxI) {
951 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
952 "BasicAliasAnalysis doesn't support interprocedural queries.");
953 return aliasCheck(V1: LocA.Ptr, V1Size: LocA.Size, V2: LocB.Ptr, V2Size: LocB.Size, AAQI, CtxI);
954}
955
956/// Checks to see if the specified callsite can clobber the specified memory
957/// object.
958///
959/// Since we only look at local properties of this function, we really can't
960/// say much about this query. We do, however, use simple "address taken"
961/// analysis on local objects.
962ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,
963 const MemoryLocation &Loc,
964 AAQueryInfo &AAQI) {
965 assert(notDifferentParent(Call, Loc.Ptr) &&
966 "AliasAnalysis query involving multiple functions!");
967
968 const Value *Object = getUnderlyingObject(V: Loc.Ptr);
969
970 // Calls marked 'tail' cannot read or write allocas from the current frame
971 // because the current frame might be destroyed by the time they run. However,
972 // a tail call may use an alloca with byval. Calling with byval copies the
973 // contents of the alloca into argument registers or stack slots, so there is
974 // no lifetime issue.
975 if (isa<AllocaInst>(Val: Object))
976 if (const CallInst *CI = dyn_cast<CallInst>(Val: Call))
977 if (CI->isTailCall() &&
978 !CI->getAttributes().hasAttrSomewhere(Kind: Attribute::ByVal))
979 return ModRefInfo::NoModRef;
980
981 // Stack restore is able to modify unescaped dynamic allocas. Assume it may
982 // modify them even though the alloca is not escaped.
983 if (auto *AI = dyn_cast<AllocaInst>(Val: Object))
984 if (!AI->isStaticAlloca() && isIntrinsicCall(Call, IID: Intrinsic::stackrestore))
985 return ModRefInfo::Mod;
986
987 // We can completely ignore inaccessible memory here, because MemoryLocations
988 // can only reference accessible memory.
989 auto ME = AAQI.AAR.getMemoryEffects(Call, AAQI)
990 .getWithoutLoc(Loc: IRMemLocation::InaccessibleMem);
991 if (ME.doesNotAccessMemory())
992 return ModRefInfo::NoModRef;
993
994 ModRefInfo ArgMR = ME.getModRef(Loc: IRMemLocation::ArgMem);
995 ModRefInfo ErrnoMR = ME.getModRef(Loc: IRMemLocation::ErrnoMem);
996 ModRefInfo OtherMR = ME.getModRef(Loc: IRMemLocation::Other);
997
998 // Take into account potential synchronization effects of the call.
999 // We assume synchronization can not occur if the call does not read/write
1000 // other memory (this in particular ensures that readonly/argmemonly continue
1001 // to work as expected for frontends that do not emit nosync).
1002 // FIXME: This should apply to all calls, but is limited to inline asm to
1003 // limit impact. This ensures that inline asm memory barriers work correctly.
1004 ModRefInfo SyncMR = ModRefInfo::NoModRef;
1005 if (isModAndRefSet(MRI: OtherMR) && Call->maySynchronize() &&
1006 Call->isInlineAsm()) {
1007 SyncMR = getSyncEffects(AA: &AAQI.AAR, Loc, AAQI);
1008 if (isModAndRefSet(MRI: SyncMR))
1009 return SyncMR;
1010 }
1011
1012 // An identified function-local object that does not escape can only be
1013 // accessed via call arguments. Reduce OtherMR (which includes accesses to
1014 // escaped memory) based on that.
1015 //
1016 // We model calls that can return twice (setjmp) as clobbering non-escaping
1017 // objects, to model any accesses that may occur prior to the second return.
1018 // As an exception, ignore allocas, as setjmp is not required to preserve
1019 // non-volatile stores for them.
1020 if (isModOrRefSet(MRI: OtherMR) && !isa<Constant>(Val: Object) && Call != Object &&
1021 (isa<AllocaInst>(Val: Object) || !Call->hasFnAttr(Kind: Attribute::ReturnsTwice))) {
1022 CaptureComponents CC = AAQI.CA->getCapturesBefore(
1023 Object, I: Call, /*OrAt=*/false, /*ReturnCaptures=*/false);
1024 if (capturesNothing(CC))
1025 OtherMR = ModRefInfo::NoModRef;
1026 else if (capturesReadProvenanceOnly(CC))
1027 OtherMR = ModRefInfo::Ref;
1028 }
1029
1030 // Refine the modref info for argument memory. We only bother to do this
1031 // if ArgMR is not a subset of OtherMR, otherwise this won't have an impact
1032 // on the final result.
1033 if ((ArgMR | OtherMR) != OtherMR) {
1034 ModRefInfo NewArgMR = ModRefInfo::NoModRef;
1035 for (const Use &U : Call->data_ops()) {
1036 const Value *Arg = U;
1037 if (!Arg->getType()->isPointerTy())
1038 continue;
1039 unsigned ArgIdx = Call->getDataOperandNo(U: &U);
1040 MemoryLocation ArgLoc =
1041 Call->isArgOperand(U: &U)
1042 ? MemoryLocation::getForArgument(Call, ArgIdx, TLI)
1043 : MemoryLocation::getBeforeOrAfter(Ptr: Arg);
1044 AliasResult ArgAlias = AAQI.AAR.alias(LocA: ArgLoc, LocB: Loc, AAQI, CtxI: Call);
1045 if (ArgAlias != AliasResult::NoAlias)
1046 NewArgMR |= ArgMR & AAQI.AAR.getArgModRefInfo(Call, ArgIdx);
1047
1048 // Exit early if we cannot improve over the original ArgMR.
1049 if (NewArgMR == ArgMR)
1050 break;
1051 }
1052 ArgMR = NewArgMR;
1053 }
1054
1055 ModRefInfo Result = ArgMR | OtherMR | SyncMR;
1056
1057 // Refine accesses to errno memory.
1058 if ((ErrnoMR | Result) != Result) {
1059 if (AAQI.AAR.aliasErrno(Loc, CtxI: Call) != AliasResult::NoAlias) {
1060 // Exclusion conditions do not hold, this memory location may alias errno.
1061 Result |= ErrnoMR;
1062 }
1063 }
1064
1065 if (!isModAndRefSet(MRI: Result))
1066 return Result;
1067
1068 // Like assumes, invariant.start intrinsics were also marked as arbitrarily
1069 // writing so that proper control dependencies are maintained but they never
1070 // mod any particular memory location visible to the IR.
1071 // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
1072 // intrinsic is now modeled as reading memory. This prevents hoisting the
1073 // invariant.start intrinsic over stores. Consider:
1074 // *ptr = 40;
1075 // *ptr = 50;
1076 // invariant_start(ptr)
1077 // int val = *ptr;
1078 // print(val);
1079 //
1080 // This cannot be transformed to:
1081 //
1082 // *ptr = 40;
1083 // invariant_start(ptr)
1084 // *ptr = 50;
1085 // int val = *ptr;
1086 // print(val);
1087 //
1088 // The transformation will cause the second store to be ignored (based on
1089 // rules of invariant.start) and print 40, while the first program always
1090 // prints 50.
1091 if (isIntrinsicCall(Call, IID: Intrinsic::invariant_start))
1092 return ModRefInfo::Ref;
1093
1094 // Be conservative.
1095 return ModRefInfo::ModRef;
1096}
1097
1098ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,
1099 const CallBase *Call2,
1100 AAQueryInfo &AAQI) {
1101 // Guard intrinsics are marked as arbitrarily writing so that proper control
1102 // dependencies are maintained but they never mods any particular memory
1103 // location.
1104 //
1105 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
1106 // heap state at the point the guard is issued needs to be consistent in case
1107 // the guard invokes the "deopt" continuation.
1108
1109 // NB! This function is *not* commutative, so we special case two
1110 // possibilities for guard intrinsics.
1111
1112 if (isIntrinsicCall(Call: Call1, IID: Intrinsic::experimental_guard))
1113 return isModSet(MRI: getMemoryEffects(Call: Call2, AAQI).getModRef())
1114 ? ModRefInfo::Ref
1115 : ModRefInfo::NoModRef;
1116
1117 if (isIntrinsicCall(Call: Call2, IID: Intrinsic::experimental_guard))
1118 return isModSet(MRI: getMemoryEffects(Call: Call1, AAQI).getModRef())
1119 ? ModRefInfo::Mod
1120 : ModRefInfo::NoModRef;
1121
1122 // Be conservative.
1123 return ModRefInfo::ModRef;
1124}
1125
1126/// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
1127/// another pointer.
1128///
1129/// We know that V1 is a GEP, but we don't know anything about V2.
1130/// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for
1131/// V2.
1132AliasResult BasicAAResult::aliasGEP(
1133 const GEPOperator *GEP1, LocationSize V1Size,
1134 const Value *V2, LocationSize V2Size,
1135 const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
1136 auto BaseObjectsAlias = [&]() {
1137 AliasResult BaseAlias =
1138 AAQI.AAR.alias(LocA: MemoryLocation::getBeforeOrAfter(Ptr: UnderlyingV1),
1139 LocB: MemoryLocation::getBeforeOrAfter(Ptr: UnderlyingV2), AAQI);
1140 return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias
1141 : AliasResult::MayAlias;
1142 };
1143
1144 if (!V1Size.hasValue() && !V2Size.hasValue()) {
1145 // Skip if V2 is itself a phi or select, leave the recursive walk to
1146 // aliasPHI/aliasSelect.
1147 if (isa<PHINode, SelectInst>(Val: V2))
1148 return AliasResult::MayAlias;
1149
1150 // Otherwise check whether the base objects don't alias. Only do so if V2
1151 // is a GEP or an underlying object is a GEP/phi/select, which can be
1152 // analyzed further.
1153 if (isa<GEPOperator>(Val: V2) ||
1154 isa<GEPOperator, PHINode, SelectInst>(Val: UnderlyingV1) ||
1155 isa<GEPOperator, PHINode, SelectInst>(Val: UnderlyingV2))
1156 return BaseObjectsAlias();
1157
1158 return AliasResult::MayAlias;
1159 }
1160
1161 DominatorTree *DT = getDT(AAQI);
1162 DecomposedGEP DecompGEP1 = DecomposeGEPExpression(V: GEP1, DL, AC: &AC, DT);
1163 DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V: V2, DL, AC: &AC, DT);
1164
1165 // Bail if we were not able to decompose anything.
1166 if (DecompGEP1.Base == GEP1 && DecompGEP2.Base == V2)
1167 return AliasResult::MayAlias;
1168
1169 // Fall back to base objects if pointers have different index widths.
1170 if (DecompGEP1.Offset.getBitWidth() != DecompGEP2.Offset.getBitWidth())
1171 return BaseObjectsAlias();
1172
1173 // Swap GEP1 and GEP2 if GEP2 has more variable indices.
1174 if (DecompGEP1.VarIndices.size() < DecompGEP2.VarIndices.size()) {
1175 std::swap(a&: DecompGEP1, b&: DecompGEP2);
1176 std::swap(a&: V1Size, b&: V2Size);
1177 std::swap(a&: UnderlyingV1, b&: UnderlyingV2);
1178 }
1179
1180 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1181 // symbolic difference.
1182 subtractDecomposedGEPs(DestGEP&: DecompGEP1, SrcGEP: DecompGEP2, AAQI);
1183
1184 // If an inbounds GEP would have to start from an out of bounds address
1185 // for the two to alias, then we can assume noalias.
1186 // TODO: Remove !isScalable() once BasicAA fully support scalable location
1187 // size.
1188 if (DecompGEP1.NWFlags.isInBounds() && DecompGEP1.VarIndices.empty() &&
1189 V2Size.hasValue() && !V2Size.isScalable() &&
1190 DecompGEP1.Offset.sge(RHS: V2Size.getValue()) &&
1191 isBaseOfObject(V: DecompGEP2.Base))
1192 return AliasResult::NoAlias;
1193
1194 // Symmetric case to above.
1195 if (DecompGEP2.NWFlags.isInBounds() && DecompGEP1.VarIndices.empty() &&
1196 V1Size.hasValue() && !V1Size.isScalable() &&
1197 DecompGEP1.Offset.sle(RHS: -V1Size.getValue()) &&
1198 isBaseOfObject(V: DecompGEP1.Base))
1199 return AliasResult::NoAlias;
1200
1201 // For GEPs with identical offsets, we can preserve the size and AAInfo
1202 // when performing the alias check on the underlying objects.
1203 if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty())
1204 return AAQI.AAR.alias(LocA: MemoryLocation(DecompGEP1.Base, V1Size),
1205 LocB: MemoryLocation(DecompGEP2.Base, V2Size), AAQI);
1206
1207 // Do the base pointers alias?
1208 AliasResult BaseAlias =
1209 AAQI.AAR.alias(LocA: MemoryLocation::getBeforeOrAfter(Ptr: DecompGEP1.Base),
1210 LocB: MemoryLocation::getBeforeOrAfter(Ptr: DecompGEP2.Base), AAQI);
1211
1212 // If we get a No or May, then return it immediately, no amount of analysis
1213 // will improve this situation.
1214 if (BaseAlias != AliasResult::MustAlias) {
1215 assert(BaseAlias == AliasResult::NoAlias ||
1216 BaseAlias == AliasResult::MayAlias);
1217 return BaseAlias;
1218 }
1219
1220 // If there is a constant difference between the pointers, but the difference
1221 // is less than the size of the associated memory object, then we know
1222 // that the objects are partially overlapping. If the difference is
1223 // greater, we know they do not overlap.
1224 if (DecompGEP1.VarIndices.empty()) {
1225 APInt &Off = DecompGEP1.Offset;
1226
1227 // Initialize for Off >= 0 (V2 <= GEP1) case.
1228 LocationSize VLeftSize = V2Size;
1229 LocationSize VRightSize = V1Size;
1230 const bool Swapped = Off.isNegative();
1231
1232 if (Swapped) {
1233 // Swap if we have the situation where:
1234 // + +
1235 // | BaseOffset |
1236 // ---------------->|
1237 // |-->V1Size |-------> V2Size
1238 // GEP1 V2
1239 std::swap(a&: VLeftSize, b&: VRightSize);
1240 Off = -Off;
1241 }
1242
1243 if (!VLeftSize.hasValue())
1244 return AliasResult::MayAlias;
1245
1246 const TypeSize LSize = VLeftSize.getValue();
1247 if (!LSize.isScalable()) {
1248 if (Off.ult(RHS: LSize)) {
1249 // Conservatively drop processing if a phi was visited and/or offset is
1250 // too big.
1251 AliasResult AR = AliasResult::PartialAlias;
1252 if (VRightSize.hasValue() && !VRightSize.isScalable() &&
1253 Off.ule(INT32_MAX) && (Off + VRightSize.getValue()).ule(RHS: LSize)) {
1254 // Memory referenced by right pointer is nested. Save the offset in
1255 // cache. Note that originally offset estimated as GEP1-V2, but
1256 // AliasResult contains the shift that represents GEP1+Offset=V2.
1257 AR.setOffset(-Off.getSExtValue());
1258 AR.swap(DoSwap: Swapped);
1259 }
1260 return AR;
1261 }
1262 return AliasResult::NoAlias;
1263 }
1264
1265 // We can use the getVScaleRange to prove that Off >= (CR.upper * LSize).
1266 ConstantRange CR = getVScaleRange(F: &F, BitWidth: Off.getBitWidth());
1267 bool Overflow;
1268 APInt UpperRange = CR.getUnsignedMax().umul_ov(
1269 RHS: APInt(Off.getBitWidth(), LSize.getKnownMinValue()), Overflow);
1270 if (!Overflow && Off.uge(RHS: UpperRange))
1271 return AliasResult::NoAlias;
1272 }
1273
1274 // VScale Alias Analysis - Given one scalable offset between accesses and a
1275 // scalable typesize, we can divide each side by vscale, treating both values
1276 // as a constant. We prove that Offset/vscale >= TypeSize/vscale.
1277 if (DecompGEP1.VarIndices.size() == 1 &&
1278 DecompGEP1.VarIndices[0].Val.TruncBits == 0 &&
1279 DecompGEP1.Offset.isZero() &&
1280 PatternMatch::match(V: DecompGEP1.VarIndices[0].Val.V,
1281 P: PatternMatch::m_VScale())) {
1282 const VariableGEPIndex &ScalableVar = DecompGEP1.VarIndices[0];
1283 APInt Scale =
1284 ScalableVar.IsNegated ? -ScalableVar.Scale : ScalableVar.Scale;
1285 LocationSize VLeftSize = Scale.isNegative() ? V1Size : V2Size;
1286
1287 // Check if the offset is known to not overflow, if it does then attempt to
1288 // prove it with the known values of vscale_range.
1289 bool Overflows = !DecompGEP1.VarIndices[0].IsNSW;
1290 if (Overflows) {
1291 ConstantRange CR = getVScaleRange(F: &F, BitWidth: Scale.getBitWidth());
1292 (void)CR.getSignedMax().smul_ov(RHS: Scale, Overflow&: Overflows);
1293 }
1294
1295 if (!Overflows) {
1296 // Note that we do not check that the typesize is scalable, as vscale >= 1
1297 // so noalias still holds so long as the dependency distance is at least
1298 // as big as the typesize.
1299 if (VLeftSize.hasValue() &&
1300 Scale.abs().uge(RHS: VLeftSize.getValue().getKnownMinValue()))
1301 return AliasResult::NoAlias;
1302 }
1303 }
1304
1305 // If the difference between pointers is Offset +<nuw> Indices then we know
1306 // that the addition does not wrap the pointer index type (add nuw) and the
1307 // constant Offset is a lower bound on the distance between the pointers. We
1308 // can then prove NoAlias via Offset u>= VLeftSize.
1309 // + + +
1310 // | BaseOffset | +<nuw> Indices |
1311 // ---------------->|-------------------->|
1312 // |-->V2Size | |-------> V1Size
1313 // LHS RHS
1314 if (!DecompGEP1.VarIndices.empty() &&
1315 DecompGEP1.NWFlags.hasNoUnsignedWrap() && V2Size.hasValue() &&
1316 !V2Size.isScalable() && DecompGEP1.Offset.uge(RHS: V2Size.getValue()))
1317 return AliasResult::NoAlias;
1318
1319 // Bail on analyzing scalable LocationSize.
1320 if (V1Size.isScalable() || V2Size.isScalable())
1321 return AliasResult::MayAlias;
1322
1323 // We need to know both access sizes for all the following heuristics. Don't
1324 // try to reason about sizes larger than the index space.
1325 unsigned BW = DecompGEP1.Offset.getBitWidth();
1326 if (!V1Size.hasValue() || !V2Size.hasValue() ||
1327 !isUIntN(N: BW, x: V1Size.getValue()) || !isUIntN(N: BW, x: V2Size.getValue()))
1328 return AliasResult::MayAlias;
1329
1330 // Analyze the variable indices, and compute the GCD that the total
1331 // variable offset is guaranteed to be a multiple of, and its approximate
1332 // range.
1333 auto [GCD, OffsetRange, VIKnownBits] = analyzeVariableOffsets(GEP: DecompGEP1, DT);
1334
1335 // We now have accesses at two offsets from the same base:
1336 // 1. (...)*GCD + DecompGEP1.Offset with size V1Size
1337 // 2. 0 with size V2Size
1338 // Using arithmetic modulo GCD, the accesses are at
1339 // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits
1340 // into the range [V2Size..GCD), then we know they cannot overlap.
1341 APInt ModOffset = DecompGEP1.Offset.srem(RHS: GCD);
1342 if (ModOffset.isNegative())
1343 ModOffset += GCD; // We want mod, not rem.
1344 if (ModOffset.uge(RHS: V2Size.getValue()) &&
1345 (GCD - ModOffset).uge(RHS: V1Size.getValue()))
1346 return AliasResult::NoAlias;
1347
1348 // If the ranges of potentially accessed bytes are disjoint, there cannot be
1349 // any overlap.
1350 ConstantRange Range1 = OffsetRange.add(
1351 Other: ConstantRange(APInt(BW, 0), APInt(BW, V1Size.getValue())));
1352 ConstantRange Range2 =
1353 ConstantRange(APInt(BW, 0), APInt(BW, V2Size.getValue()));
1354 if (Range1.intersectWith(CR: Range2).isEmptySet())
1355 return AliasResult::NoAlias;
1356
1357 // If a minimum absolute variable offset can be established, employ it to
1358 // prove that the two accesses are far enough apart.
1359 if (auto MinAbsVarIndex =
1360 computeMinAbsVarOffset(GEP: DecompGEP1, VIKnownBits, DT, AAQI)) {
1361 // The constant offset will have added at least +/-MinAbsVarIndex to it.
1362 APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex;
1363 APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex;
1364 // We know that Offset <= OffsetLo || Offset >= OffsetHi
1365 if (OffsetLo.isNegative() && (-OffsetLo).uge(RHS: V1Size.getValue()) &&
1366 OffsetHi.isNonNegative() && OffsetHi.uge(RHS: V2Size.getValue()))
1367 return AliasResult::NoAlias;
1368 }
1369
1370 // As a last attempt, search for a constant offset between the variable
1371 // indices that GetLinearExpression could not extract through casts.
1372 if (computeConstantOffsetHeuristic(GEP: DecompGEP1, V1Size, V2Size, AC: &AC, DT, AAQI))
1373 return AliasResult::NoAlias;
1374
1375 // Statically, we can see that the base objects are the same, but the
1376 // pointers have dynamic offsets which we can't resolve. And none of our
1377 // little tricks above worked.
1378 return AliasResult::MayAlias;
1379}
1380
1381static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
1382 // If the results agree, take it.
1383 if (A == B)
1384 return A;
1385 // A mix of PartialAlias and MustAlias is PartialAlias.
1386 if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) ||
1387 (B == AliasResult::PartialAlias && A == AliasResult::MustAlias))
1388 return AliasResult::PartialAlias;
1389 // Otherwise, we don't know anything.
1390 return AliasResult::MayAlias;
1391}
1392
1393/// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
1394/// against another.
1395AliasResult
1396BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
1397 const Value *V2, LocationSize V2Size,
1398 AAQueryInfo &AAQI) {
1399 // If the values are Selects with the same condition, we can do a more precise
1400 // check: just check for aliases between the values on corresponding arms.
1401 if (const SelectInst *SI2 = dyn_cast<SelectInst>(Val: V2))
1402 if (isValueEqualInPotentialCycles(V1: SI->getCondition(), V2: SI2->getCondition(),
1403 AAQI)) {
1404 AliasResult Alias =
1405 AAQI.AAR.alias(LocA: MemoryLocation(SI->getTrueValue(), SISize),
1406 LocB: MemoryLocation(SI2->getTrueValue(), V2Size), AAQI);
1407 if (Alias == AliasResult::MayAlias)
1408 return AliasResult::MayAlias;
1409 AliasResult ThisAlias =
1410 AAQI.AAR.alias(LocA: MemoryLocation(SI->getFalseValue(), SISize),
1411 LocB: MemoryLocation(SI2->getFalseValue(), V2Size), AAQI);
1412 return MergeAliasResults(A: ThisAlias, B: Alias);
1413 }
1414
1415 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1416 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1417 AliasResult Alias = AAQI.AAR.alias(LocA: MemoryLocation(SI->getTrueValue(), SISize),
1418 LocB: MemoryLocation(V2, V2Size), AAQI);
1419 if (Alias == AliasResult::MayAlias)
1420 return AliasResult::MayAlias;
1421
1422 AliasResult ThisAlias =
1423 AAQI.AAR.alias(LocA: MemoryLocation(SI->getFalseValue(), SISize),
1424 LocB: MemoryLocation(V2, V2Size), AAQI);
1425 return MergeAliasResults(A: ThisAlias, B: Alias);
1426}
1427
1428/// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
1429/// another.
1430AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
1431 const Value *V2, LocationSize V2Size,
1432 AAQueryInfo &AAQI) {
1433 if (!PN->getNumIncomingValues())
1434 return AliasResult::NoAlias;
1435 // If the values are PHIs in the same block, we can do a more precise
1436 // as well as efficient check: just check for aliases between the values
1437 // on corresponding edges. Don't do this if we are analyzing across
1438 // iterations, as we may pick a different phi entry in different iterations.
1439 if (const PHINode *PN2 = dyn_cast<PHINode>(Val: V2))
1440 if (PN2->getParent() == PN->getParent() && !AAQI.MayBeCrossIteration) {
1441 std::optional<AliasResult> Alias;
1442 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1443 AliasResult ThisAlias = AAQI.AAR.alias(
1444 LocA: MemoryLocation(PN->getIncomingValue(i), PNSize),
1445 LocB: MemoryLocation(
1446 PN2->getIncomingValueForBlock(BB: PN->getIncomingBlock(i)), V2Size),
1447 AAQI);
1448 if (Alias)
1449 *Alias = MergeAliasResults(A: *Alias, B: ThisAlias);
1450 else
1451 Alias = ThisAlias;
1452 if (*Alias == AliasResult::MayAlias)
1453 break;
1454 }
1455 return *Alias;
1456 }
1457
1458 SmallVector<Value *, 4> V1Srcs;
1459 // If a phi operand recurses back to the phi, we can still determine NoAlias
1460 // if we don't alias the underlying objects of the other phi operands, as we
1461 // know that the recursive phi needs to be based on them in some way.
1462 bool isRecursive = false;
1463 auto CheckForRecPhi = [&](Value *PV) {
1464 if (!EnableRecPhiAnalysis)
1465 return false;
1466 if (getUnderlyingObject(V: PV) == PN) {
1467 isRecursive = true;
1468 return true;
1469 }
1470 return false;
1471 };
1472
1473 SmallPtrSet<Value *, 4> UniqueSrc;
1474 Value *OnePhi = nullptr;
1475 for (Value *PV1 : PN->incoming_values()) {
1476 // Skip the phi itself being the incoming value.
1477 if (PV1 == PN)
1478 continue;
1479
1480 if (isa<PHINode>(Val: PV1)) {
1481 if (OnePhi && OnePhi != PV1) {
1482 // To control potential compile time explosion, we choose to be
1483 // conserviate when we have more than one Phi input. It is important
1484 // that we handle the single phi case as that lets us handle LCSSA
1485 // phi nodes and (combined with the recursive phi handling) simple
1486 // pointer induction variable patterns.
1487 return AliasResult::MayAlias;
1488 }
1489 OnePhi = PV1;
1490 }
1491
1492 if (CheckForRecPhi(PV1))
1493 continue;
1494
1495 if (UniqueSrc.insert(Ptr: PV1).second)
1496 V1Srcs.push_back(Elt: PV1);
1497 }
1498
1499 if (OnePhi && UniqueSrc.size() > 1)
1500 // Out of an abundance of caution, allow only the trivial lcssa and
1501 // recursive phi cases.
1502 return AliasResult::MayAlias;
1503
1504 // If V1Srcs is empty then that means that the phi has no underlying non-phi
1505 // value. This should only be possible in blocks unreachable from the entry
1506 // block, but return MayAlias just in case.
1507 if (V1Srcs.empty())
1508 return AliasResult::MayAlias;
1509
1510 // If this PHI node is recursive, indicate that the pointer may be moved
1511 // across iterations. We can only prove NoAlias if different underlying
1512 // objects are involved.
1513 if (isRecursive)
1514 PNSize = LocationSize::beforeOrAfterPointer();
1515
1516 // In the recursive alias queries below, we may compare values from two
1517 // different loop iterations.
1518 SaveAndRestore SavedMayBeCrossIteration(AAQI.MayBeCrossIteration, true);
1519
1520 AliasResult Alias = AAQI.AAR.alias(LocA: MemoryLocation(V1Srcs[0], PNSize),
1521 LocB: MemoryLocation(V2, V2Size), AAQI);
1522
1523 // Early exit if the check of the first PHI source against V2 is MayAlias.
1524 // Other results are not possible.
1525 if (Alias == AliasResult::MayAlias)
1526 return AliasResult::MayAlias;
1527 // With recursive phis we cannot guarantee that MustAlias/PartialAlias will
1528 // remain valid to all elements and needs to conservatively return MayAlias.
1529 if (isRecursive && Alias != AliasResult::NoAlias)
1530 return AliasResult::MayAlias;
1531
1532 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1533 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1534 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1535 Value *V = V1Srcs[i];
1536
1537 AliasResult ThisAlias = AAQI.AAR.alias(
1538 LocA: MemoryLocation(V, PNSize), LocB: MemoryLocation(V2, V2Size), AAQI);
1539 Alias = MergeAliasResults(A: ThisAlias, B: Alias);
1540 if (Alias == AliasResult::MayAlias)
1541 break;
1542 }
1543
1544 return Alias;
1545}
1546
1547// Return true for an Argument or extractvalue(Argument). These are all known
1548// to not alias with FunctionLocal objects and can come up from coerced function
1549// arguments.
1550static bool isArgumentOrArgumentLike(const Value *V) {
1551 if (isa<Argument>(Val: V))
1552 return true;
1553 auto *E = dyn_cast<ExtractValueInst>(Val: V);
1554 return E && isa<Argument>(Val: E->getOperand(i_nocapture: 0));
1555}
1556
1557/// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
1558/// array references.
1559AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
1560 const Value *V2, LocationSize V2Size,
1561 AAQueryInfo &AAQI,
1562 const Instruction *CtxI) {
1563 // If either of the memory references is empty, it doesn't matter what the
1564 // pointer values are.
1565 if (V1Size.isZero() || V2Size.isZero())
1566 return AliasResult::NoAlias;
1567
1568 // Strip off any casts if they exist.
1569 V1 = V1->stripPointerCastsForAliasAnalysis();
1570 V2 = V2->stripPointerCastsForAliasAnalysis();
1571
1572 // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1573 // value for undef that aliases nothing in the program.
1574 if (isa<UndefValue>(Val: V1) || isa<UndefValue>(Val: V2))
1575 return AliasResult::NoAlias;
1576
1577 // Are we checking for alias of the same value?
1578 // Because we look 'through' phi nodes, we could look at "Value" pointers from
1579 // different iterations. We must therefore make sure that this is not the
1580 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1581 // happen by looking at the visited phi nodes and making sure they cannot
1582 // reach the value.
1583 if (isValueEqualInPotentialCycles(V1, V2, AAQI))
1584 return AliasResult::MustAlias;
1585
1586 // Figure out what objects these things are pointing to if we can.
1587 const Value *O1 = getUnderlyingObject(V: V1, MaxLookup: MaxLookupSearchDepth);
1588 const Value *O2 = getUnderlyingObject(V: V2, MaxLookup: MaxLookupSearchDepth);
1589
1590 // Null values in the default address space don't point to any object, so they
1591 // don't alias any other pointer.
1592 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(Val: O1))
1593 if (!NullPointerIsDefined(F: &F, AS: CPN->getPointerType()->getAddressSpace()))
1594 return AliasResult::NoAlias;
1595 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(Val: O2))
1596 if (!NullPointerIsDefined(F: &F, AS: CPN->getPointerType()->getAddressSpace()))
1597 return AliasResult::NoAlias;
1598
1599 if (O1 != O2) {
1600 // If V1/V2 point to two different objects, we know that we have no alias.
1601 if (isIdentifiedObject(V: O1) && isIdentifiedObject(V: O2))
1602 return AliasResult::NoAlias;
1603
1604 // Function arguments can't alias with things that are known to be
1605 // unambigously identified at the function level.
1606 if ((isArgumentOrArgumentLike(V: O1) && isIdentifiedFunctionLocal(V: O2)) ||
1607 (isArgumentOrArgumentLike(V: O2) && isIdentifiedFunctionLocal(V: O1)))
1608 return AliasResult::NoAlias;
1609
1610 // If one pointer is the result of a call/invoke or load and the other is a
1611 // non-escaping local object within the same function, then we know the
1612 // object couldn't escape to a point where the call could return it.
1613 //
1614 // Note that if the pointers are in different functions, there are a
1615 // variety of complications. A call with a nocapture argument may still
1616 // temporary store the nocapture argument's value in a temporary memory
1617 // location if that memory location doesn't escape. Or it may pass a
1618 // nocapture value to other functions as long as they don't capture it.
1619 if (isEscapeSource(V: O1) && capturesNothing(CC: AAQI.CA->getCapturesBefore(
1620 Object: O2, I: dyn_cast<Instruction>(Val: O1), /*OrAt=*/true,
1621 /*ReturnCaptures=*/false)))
1622 return AliasResult::NoAlias;
1623 if (isEscapeSource(V: O2) && capturesNothing(CC: AAQI.CA->getCapturesBefore(
1624 Object: O1, I: dyn_cast<Instruction>(Val: O2), /*OrAt=*/true,
1625 /*ReturnCaptures=*/false)))
1626 return AliasResult::NoAlias;
1627 }
1628
1629 // If the size of one access is larger than the entire object on the other
1630 // side, then we know such behavior is undefined and can assume no alias.
1631 bool NullIsValidLocation = NullPointerIsDefined(F: &F);
1632 if (isObjectSmallerThan(V: O2, OtherV: *V1, OtherSize: V1Size, DL, TLI, NullIsValidLoc: NullIsValidLocation) ||
1633 isObjectSmallerThan(V: O1, OtherV: *V2, OtherSize: V2Size, DL, TLI, NullIsValidLoc: NullIsValidLocation))
1634 return AliasResult::NoAlias;
1635
1636 if (EnableSeparateStorageAnalysis) {
1637 for (AssumptionCache::ResultElem &Elem : AC.assumptionsFor(V: O1)) {
1638 if (!Elem || Elem.Index == AssumptionCache::ExprResultIdx)
1639 continue;
1640
1641 AssumeInst *Assume = cast<AssumeInst>(Val&: Elem);
1642 OperandBundleUse OBU = Assume->getOperandBundleAt(Index: Elem.Index);
1643 if (OBU.getTagName() == "separate_storage") {
1644 assert(OBU.Inputs.size() == 2);
1645 const Value *Hint1 = OBU.Inputs[0].get();
1646 const Value *Hint2 = OBU.Inputs[1].get();
1647 // This is often a no-op; instcombine rewrites this for us. No-op
1648 // getUnderlyingObject calls are fast, though.
1649 const Value *HintO1 = getUnderlyingObject(V: Hint1);
1650 const Value *HintO2 = getUnderlyingObject(V: Hint2);
1651
1652 DominatorTree *DT = getDT(AAQI);
1653 auto ValidAssumeForPtrContext = [&](const Value *Ptr) {
1654 if (const Instruction *PtrI = dyn_cast<Instruction>(Val: Ptr)) {
1655 return isValidAssumeForContext(I: Assume, CtxI: PtrI, DT,
1656 /* AllowEphemerals */ true);
1657 }
1658 if (const Argument *PtrA = dyn_cast<Argument>(Val: Ptr)) {
1659 const Instruction *FirstI =
1660 &*PtrA->getParent()->getEntryBlock().begin();
1661 return isValidAssumeForContext(I: Assume, CtxI: FirstI, DT,
1662 /* AllowEphemerals */ true);
1663 }
1664 return false;
1665 };
1666
1667 if ((O1 == HintO1 && O2 == HintO2) || (O1 == HintO2 && O2 == HintO1)) {
1668 // Note that we go back to V1 and V2 for the
1669 // ValidAssumeForPtrContext checks; they're dominated by O1 and O2,
1670 // so strictly more assumptions are valid for them.
1671 if ((CtxI && isValidAssumeForContext(I: Assume, CtxI, DT,
1672 /* AllowEphemerals */ true)) ||
1673 ValidAssumeForPtrContext(V1) || ValidAssumeForPtrContext(V2)) {
1674 return AliasResult::NoAlias;
1675 }
1676 }
1677 }
1678 }
1679 }
1680
1681 // If one the accesses may be before the accessed pointer, canonicalize this
1682 // by using unknown after-pointer sizes for both accesses. This is
1683 // equivalent, because regardless of which pointer is lower, one of them
1684 // will always came after the other, as long as the underlying objects aren't
1685 // disjoint. We do this so that the rest of BasicAA does not have to deal
1686 // with accesses before the base pointer, and to improve cache utilization by
1687 // merging equivalent states.
1688 if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) {
1689 V1Size = LocationSize::afterPointer();
1690 V2Size = LocationSize::afterPointer();
1691 }
1692
1693 // FIXME: If this depth limit is hit, then we may cache sub-optimal results
1694 // for recursive queries. For this reason, this limit is chosen to be large
1695 // enough to be very rarely hit, while still being small enough to avoid
1696 // stack overflows.
1697 if (AAQI.Depth >= 512)
1698 return AliasResult::MayAlias;
1699
1700 // Check the cache before climbing up use-def chains. This also terminates
1701 // otherwise infinitely recursive queries. Include MayBeCrossIteration in the
1702 // cache key, because some cases where MayBeCrossIteration==false returns
1703 // MustAlias or NoAlias may become MayAlias under MayBeCrossIteration==true.
1704 AAQueryInfo::LocPair Locs({V1, V1Size, AAQI.MayBeCrossIteration},
1705 {V2, V2Size, AAQI.MayBeCrossIteration});
1706 const bool Swapped = V1 > V2;
1707 if (Swapped)
1708 std::swap(a&: Locs.first, b&: Locs.second);
1709 const auto &Pair = AAQI.AliasCache.try_emplace(
1710 Key: Locs, Args: AAQueryInfo::CacheEntry{.Result: AliasResult::NoAlias, .NumAssumptionUses: 0});
1711 if (!Pair.second) {
1712 auto &Entry = Pair.first->second;
1713 if (!Entry.isDefinitive()) {
1714 // Remember that we used an assumption. This may either be a direct use
1715 // of an assumption, or a use of an entry that may itself be based on an
1716 // assumption.
1717 ++AAQI.NumAssumptionUses;
1718 if (Entry.isAssumption())
1719 ++Entry.NumAssumptionUses;
1720 }
1721 // Cache contains sorted {V1,V2} pairs but we should return original order.
1722 auto Result = Entry.Result;
1723 Result.swap(DoSwap: Swapped);
1724 return Result;
1725 }
1726
1727 int OrigNumAssumptionUses = AAQI.NumAssumptionUses;
1728 unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size();
1729 AliasResult Result =
1730 aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2);
1731
1732 auto It = AAQI.AliasCache.find(Val: Locs);
1733 assert(It != AAQI.AliasCache.end() && "Must be in cache");
1734 auto &Entry = It->second;
1735
1736 // Check whether a NoAlias assumption has been used, but disproven.
1737 bool AssumptionDisproven =
1738 Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias;
1739 if (AssumptionDisproven)
1740 Result = AliasResult::MayAlias;
1741
1742 // This is a definitive result now, when considered as a root query.
1743 AAQI.NumAssumptionUses -= Entry.NumAssumptionUses;
1744 Entry.Result = Result;
1745 // Cache contains sorted {V1,V2} pairs.
1746 Entry.Result.swap(DoSwap: Swapped);
1747
1748 // If the assumption has been disproven, remove any results that may have
1749 // been based on this assumption. Do this after the Entry updates above to
1750 // avoid iterator invalidation.
1751 if (AssumptionDisproven)
1752 while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults)
1753 AAQI.AliasCache.erase(Val: AAQI.AssumptionBasedResults.pop_back_val());
1754
1755 // The result may still be based on assumptions higher up in the chain.
1756 // Remember it, so it can be purged from the cache later.
1757 if (OrigNumAssumptionUses != AAQI.NumAssumptionUses &&
1758 Result != AliasResult::MayAlias) {
1759 AAQI.AssumptionBasedResults.push_back(Elt: Locs);
1760 Entry.NumAssumptionUses = AAQueryInfo::CacheEntry::AssumptionBased;
1761 } else {
1762 Entry.NumAssumptionUses = AAQueryInfo::CacheEntry::Definitive;
1763 }
1764
1765 // Depth is incremented before this function is called, so Depth==1 indicates
1766 // a root query.
1767 if (AAQI.Depth == 1) {
1768 // Any remaining assumption based results must be based on proven
1769 // assumptions, so convert them to definitive results.
1770 for (const auto &Loc : AAQI.AssumptionBasedResults) {
1771 auto It = AAQI.AliasCache.find(Val: Loc);
1772 if (It != AAQI.AliasCache.end())
1773 It->second.NumAssumptionUses = AAQueryInfo::CacheEntry::Definitive;
1774 }
1775 AAQI.AssumptionBasedResults.clear();
1776 AAQI.NumAssumptionUses = 0;
1777 }
1778 return Result;
1779}
1780
1781AliasResult BasicAAResult::aliasCheckRecursive(
1782 const Value *V1, LocationSize V1Size,
1783 const Value *V2, LocationSize V2Size,
1784 AAQueryInfo &AAQI, const Value *O1, const Value *O2) {
1785 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(Val: V1)) {
1786 AliasResult Result = aliasGEP(GEP1: GV1, V1Size, V2, V2Size, UnderlyingV1: O1, UnderlyingV2: O2, AAQI);
1787 if (Result != AliasResult::MayAlias)
1788 return Result;
1789 } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(Val: V2)) {
1790 AliasResult Result = aliasGEP(GEP1: GV2, V1Size: V2Size, V2: V1, V2Size: V1Size, UnderlyingV1: O2, UnderlyingV2: O1, AAQI);
1791 Result.swap();
1792 if (Result != AliasResult::MayAlias)
1793 return Result;
1794 }
1795
1796 if (const PHINode *PN = dyn_cast<PHINode>(Val: V1)) {
1797 AliasResult Result = aliasPHI(PN, PNSize: V1Size, V2, V2Size, AAQI);
1798 if (Result != AliasResult::MayAlias)
1799 return Result;
1800 } else if (const PHINode *PN = dyn_cast<PHINode>(Val: V2)) {
1801 AliasResult Result = aliasPHI(PN, PNSize: V2Size, V2: V1, V2Size: V1Size, AAQI);
1802 Result.swap();
1803 if (Result != AliasResult::MayAlias)
1804 return Result;
1805 }
1806
1807 if (const SelectInst *S1 = dyn_cast<SelectInst>(Val: V1)) {
1808 AliasResult Result = aliasSelect(SI: S1, SISize: V1Size, V2, V2Size, AAQI);
1809 if (Result != AliasResult::MayAlias)
1810 return Result;
1811 } else if (const SelectInst *S2 = dyn_cast<SelectInst>(Val: V2)) {
1812 AliasResult Result = aliasSelect(SI: S2, SISize: V2Size, V2: V1, V2Size: V1Size, AAQI);
1813 Result.swap();
1814 if (Result != AliasResult::MayAlias)
1815 return Result;
1816 }
1817
1818 // If both pointers are pointing into the same object and one of them
1819 // accesses the entire object, then the accesses must overlap in some way.
1820 if (O1 == O2) {
1821 bool NullIsValidLocation = NullPointerIsDefined(F: &F);
1822 if (V1Size.isPrecise() && V2Size.isPrecise() &&
1823 (isObjectSize(V: O1, Size: V1Size.getValue(), DL, TLI, NullIsValidLoc: NullIsValidLocation) ||
1824 isObjectSize(V: O2, Size: V2Size.getValue(), DL, TLI, NullIsValidLoc: NullIsValidLocation)))
1825 return AliasResult::PartialAlias;
1826 }
1827
1828 return AliasResult::MayAlias;
1829}
1830
1831AliasResult BasicAAResult::aliasErrno(const MemoryLocation &Loc,
1832 const Instruction *CtxI) {
1833 // Do not make any assumptions when targeting freestanding environments (e.g.,
1834 // in the context of baremetal LTO, errno may have been internalized or
1835 // otherwise promoted to a local variable).
1836 bool IsFreestanding = CtxI->getFunction()->hasFnAttribute(Kind: "no-builtins");
1837 if (IsFreestanding)
1838 return AliasResult::MayAlias;
1839
1840 // There cannot be any alias with errno if the given memory location is an
1841 // identified function-local object, or the size of the memory access is
1842 // larger than the integer size.
1843 if (Loc.Size.hasValue() &&
1844 Loc.Size.getValue().getKnownMinValue() * 8 > TLI.getIntSize())
1845 return AliasResult::NoAlias;
1846
1847 const Value *Object = getUnderlyingObject(V: Loc.Ptr);
1848 if (isIdentifiedFunctionLocal(V: Object))
1849 return AliasResult::NoAlias;
1850
1851 if (auto *GV = dyn_cast<GlobalVariable>(Val: Object)) {
1852 // Errno cannot alias internal/private globals.
1853 if (GV->hasLocalLinkage())
1854 return AliasResult::NoAlias;
1855
1856 // Neither can errno alias globals where environments define it as a
1857 // function call.
1858 if (TLI.isErrnoFunctionCall())
1859 return AliasResult::NoAlias;
1860 }
1861
1862 return AliasResult::MayAlias;
1863}
1864
1865/// Check whether two Values can be considered equivalent.
1866///
1867/// If the values may come from different cycle iterations, this will also
1868/// check that the values are not part of cycle. We have to do this because we
1869/// are looking through phi nodes, that is we say
1870/// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
1871bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
1872 const Value *V2,
1873 const AAQueryInfo &AAQI) {
1874 if (V != V2)
1875 return false;
1876
1877 if (!AAQI.MayBeCrossIteration)
1878 return true;
1879
1880 // Non-instructions and instructions in the entry block cannot be part of
1881 // a loop.
1882 const Instruction *Inst = dyn_cast<Instruction>(Val: V);
1883 if (!Inst || Inst->getParent()->isEntryBlock())
1884 return true;
1885
1886 return isNotInCycle(I: Inst, DT: getDT(AAQI), /*LI=*/nullptr, /*CI=*/nullptr);
1887}
1888
1889/// Computes the symbolic difference between two de-composed GEPs.
1890void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP,
1891 const DecomposedGEP &SrcGEP,
1892 const AAQueryInfo &AAQI) {
1893 // Drop nuw flag from GEP if subtraction of constant offsets overflows in an
1894 // unsigned sense.
1895 if (DestGEP.Offset.ult(RHS: SrcGEP.Offset))
1896 DestGEP.NWFlags = DestGEP.NWFlags.withoutNoUnsignedWrap();
1897
1898 DestGEP.Offset -= SrcGEP.Offset;
1899 for (const VariableGEPIndex &Src : SrcGEP.VarIndices) {
1900 // Find V in Dest. This is N^2, but pointer indices almost never have more
1901 // than a few variable indexes.
1902 bool Found = false;
1903 for (auto I : enumerate(First&: DestGEP.VarIndices)) {
1904 VariableGEPIndex &Dest = I.value();
1905 if ((!isValueEqualInPotentialCycles(V: Dest.Val.V, V2: Src.Val.V, AAQI) &&
1906 !areBothVScale(V1: Dest.Val.V, V2: Src.Val.V)) ||
1907 !Dest.Val.hasSameCastsAs(Other: Src.Val))
1908 continue;
1909
1910 // Normalize IsNegated if we're going to lose the NSW flag anyway.
1911 if (Dest.IsNegated) {
1912 Dest.Scale = -Dest.Scale;
1913 Dest.IsNegated = false;
1914 Dest.IsNSW = false;
1915 }
1916
1917 // If we found it, subtract off Scale V's from the entry in Dest. If it
1918 // goes to zero, remove the entry.
1919 if (Dest.Scale != Src.Scale) {
1920 // Drop nuw flag from GEP if subtraction of V's Scale overflows in an
1921 // unsigned sense.
1922 if (Dest.Scale.ult(RHS: Src.Scale))
1923 DestGEP.NWFlags = DestGEP.NWFlags.withoutNoUnsignedWrap();
1924
1925 Dest.Scale -= Src.Scale;
1926 Dest.IsNSW = false;
1927 } else {
1928 DestGEP.VarIndices.erase(CI: DestGEP.VarIndices.begin() + I.index());
1929 }
1930 Found = true;
1931 break;
1932 }
1933
1934 // If we didn't consume this entry, add it to the end of the Dest list.
1935 if (!Found) {
1936 VariableGEPIndex Entry = {.Val: Src.Val, .Scale: Src.Scale, .CtxI: Src.CtxI, .IsNSW: Src.IsNSW,
1937 /* IsNegated */ true};
1938 DestGEP.VarIndices.push_back(Elt: Entry);
1939
1940 // Drop nuw flag when we have unconsumed variable indices from SrcGEP.
1941 DestGEP.NWFlags = DestGEP.NWFlags.withoutNoUnsignedWrap();
1942 }
1943 }
1944}
1945
1946BasicAAResult::VariableGEPOffsetInfo
1947BasicAAResult::analyzeVariableOffsets(const DecomposedGEP &GEP,
1948 DominatorTree *DT) {
1949 APInt GCD;
1950 ConstantRange OffsetRange(GEP.Offset);
1951 SmallVector<KnownBits, 4> VarIndexKnownBits;
1952 VarIndexKnownBits.reserve(N: GEP.VarIndices.size());
1953
1954 for (unsigned I = 0, E = GEP.VarIndices.size(); I != E; ++I) {
1955 const VariableGEPIndex &Index = GEP.VarIndices[I];
1956 const APInt &Scale = Index.Scale;
1957
1958 SimplifyQuery SQ(DL, DT, &AC, Index.CtxI, /*UseInstrInfo=*/true);
1959 KnownBits Known = computeKnownBits(V: Index.Val.V, Q: SQ);
1960 VarIndexKnownBits.emplace_back(Args&: Known);
1961
1962 APInt ScaleForGCD = Scale;
1963 if (!Index.IsNSW)
1964 ScaleForGCD =
1965 APInt::getOneBitSet(numBits: Scale.getBitWidth(), BitNo: Scale.countr_zero());
1966
1967 // If V has known trailing zeros, V is a multiple of 2^VarTZ, so
1968 // V*Scale is a multiple of ScaleForGCD * 2^VarTZ. Shift ScaleForGCD
1969 // left to account for this (trailing zeros compose additively through
1970 // multiplication, even in Z/2^n).
1971 unsigned VarTZ = Known.countMinTrailingZeros();
1972 if (VarTZ > 0) {
1973 unsigned MaxShift =
1974 Scale.getBitWidth() - ScaleForGCD.getSignificantBits();
1975 ScaleForGCD <<= std::min(a: VarTZ, b: MaxShift);
1976 }
1977
1978 if (I == 0)
1979 GCD = ScaleForGCD.abs();
1980 else
1981 GCD = APIntOps::GreatestCommonDivisor(A: GCD, B: ScaleForGCD.abs());
1982
1983 ConstantRange CR =
1984 computeConstantRange(V: Index.Val.V, /*ForSigned=*/false, SQ);
1985 CR =
1986 CR.intersectWith(CR: ConstantRange::fromKnownBits(Known, /*IsSigned=*/true),
1987 Type: ConstantRange::Signed);
1988 CR = Index.Val.evaluateWith(N: CR).sextOrTrunc(BitWidth: OffsetRange.getBitWidth());
1989
1990 assert(OffsetRange.getBitWidth() == Scale.getBitWidth() &&
1991 "Bit widths are normalized to MaxIndexSize");
1992 if (Index.IsNSW)
1993 CR = CR.smul_sat(Other: ConstantRange(Scale));
1994 else
1995 CR = CR.smul_fast(Other: ConstantRange(Scale));
1996
1997 if (Index.IsNegated)
1998 OffsetRange = OffsetRange.sub(Other: CR);
1999 else
2000 OffsetRange = OffsetRange.add(Other: CR);
2001 }
2002
2003 return {.GCD: GCD, .OffsetRange: OffsetRange, .VarIndexKnownBits: std::move(VarIndexKnownBits)};
2004}
2005
2006std::optional<APInt> BasicAAResult::computeMinAbsVarOffset(
2007 const DecomposedGEP &GEP, ArrayRef<KnownBits> VIKnownBits,
2008 DominatorTree *DT, const AAQueryInfo &AAQI) {
2009 // Check if abs(V*Scale) >= abs(Scale) holds in the presence of
2010 // potentially wrapping math.
2011 auto MultiplyByScaleNoWrap = [](const VariableGEPIndex &Var) {
2012 if (Var.IsNSW)
2013 return true;
2014
2015 int ValOrigBW = Var.Val.V->getType()->getPrimitiveSizeInBits();
2016 // If Scale is small enough so that abs(V*Scale) >= abs(Scale) holds.
2017 // The max value of abs(V) is 2^ValOrigBW - 1. Multiplying with a
2018 // constant smaller than 2^(bitwidth(Val) - ValOrigBW) won't wrap.
2019 int MaxScaleValueBW = Var.Val.getBitWidth() - ValOrigBW;
2020 if (MaxScaleValueBW <= 0)
2021 return false;
2022 return Var.Scale.ule(
2023 RHS: APInt::getMaxValue(numBits: MaxScaleValueBW).zext(width: Var.Scale.getBitWidth()));
2024 };
2025
2026 const auto &VarIndices = GEP.VarIndices;
2027 if (VarIndices.size() == 1) {
2028 // VarIndex = Scale*V.
2029 const VariableGEPIndex &Var = VarIndices[0];
2030 if (Var.Val.TruncBits == 0 &&
2031 isKnownNonZero(V: Var.Val.V, Q: SimplifyQuery(DL, DT, &AC, Var.CtxI))) {
2032 // Refine MinAbsVarIndex, if abs(Scale*V) >= abs(Scale) holds in the
2033 // presence of potentially wrapping math.
2034 if (MultiplyByScaleNoWrap(Var)) {
2035 // If V != 0 then abs(VarIndex) >= abs(Scale).
2036 return Var.Scale.abs();
2037 }
2038 }
2039 return std::nullopt;
2040 }
2041
2042 if (VarIndices.size() == 2) {
2043 // VarIndex = Scale*V0 + (-Scale)*V1.
2044 // If V0 != V1 then abs(VarIndex) >= abs(Scale).
2045 // Check that MayBeCrossIteration is false, to avoid reasoning about
2046 // inequality of values across loop iterations.
2047 const VariableGEPIndex &Var0 = VarIndices[0];
2048 const VariableGEPIndex &Var1 = VarIndices[1];
2049 bool Preconditions =
2050 Var0.Val.TruncBits == 0 && Var0.Val.hasSameCastsAs(Other: Var1.Val) &&
2051 !AAQI.MayBeCrossIteration && MultiplyByScaleNoWrap(Var0) &&
2052 MultiplyByScaleNoWrap(Var1);
2053
2054 if (!Preconditions)
2055 return std::nullopt;
2056
2057 if (Var0.hasNegatedScaleOf(Other: Var1)) {
2058 if (isKnownNonEqual(V1: Var0.Val.V, V2: Var1.Val.V,
2059 SQ: SimplifyQuery(DL, DT, &AC, /*CtxI=*/Var0.CtxI
2060 ? Var0.CtxI
2061 : Var1.CtxI)))
2062 return Var0.Scale.abs();
2063 // Equal scales would imply the GCD equals the scale itself, leading
2064 // the generalized path below not to do better than isKnownNonEqual.
2065 return std::nullopt;
2066 }
2067
2068 // On the chance we have not found a min abs, fallback to the generalization
2069 // of the two variables case being handled to different scales:
2070 // VarIndex = Scale0*V0 + (-Scale1)*V1 = ScaleGCD*(C0*V0 - C1*V1)
2071 // where C0 = abs(Scale0)/ScaleGCD, C1 = abs(Scale1)/ScaleGCD.
2072 // If C0*V0 != C1*V1, then abs(VarIndex) >= ScaleGCD, leading to the min
2073 // absolute value being ScaleGCD.
2074 //
2075 // Ensure scales, after subtraction, have opposite signs.
2076 bool EffectiveNeg0 = Var0.IsNegated ^ Var0.Scale.isNegative();
2077 bool EffectiveNeg1 = Var1.IsNegated ^ Var1.Scale.isNegative();
2078 if (EffectiveNeg0 != EffectiveNeg1) {
2079 APInt AbsScale0 = Var0.Scale.abs();
2080 APInt AbsScale1 = Var1.Scale.abs();
2081 APInt ScaleGCD = APIntOps::GreatestCommonDivisor(A: AbsScale0, B: AbsScale1);
2082 APInt C0 = AbsScale0.udiv(RHS: ScaleGCD);
2083 APInt C1 = AbsScale1.udiv(RHS: ScaleGCD);
2084
2085 // Try to check whether C0*V0 and C1*V1 are provably distinct (i.e., one
2086 // is guaranteed even while the other is guaranteed odd).
2087 auto Known0 = KnownBits::mul(LHS: Var0.Val.evaluateWith(K: VIKnownBits[0]),
2088 RHS: KnownBits::makeConstant(C: C0));
2089
2090 auto Known1 = KnownBits::mul(LHS: Var1.Val.evaluateWith(K: VIKnownBits[1]),
2091 RHS: KnownBits::makeConstant(C: C1));
2092
2093 if (auto Res = KnownBits::ne(LHS: Known0, RHS: Known1); Res && *Res)
2094 return ScaleGCD;
2095 }
2096 }
2097
2098 return std::nullopt;
2099}
2100
2101bool BasicAAResult::computeConstantOffsetHeuristic(const DecomposedGEP &GEP,
2102 LocationSize MaybeV1Size,
2103 LocationSize MaybeV2Size,
2104 AssumptionCache *AC,
2105 DominatorTree *DT,
2106 const AAQueryInfo &AAQI) {
2107 if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() ||
2108 !MaybeV2Size.hasValue())
2109 return false;
2110
2111 const uint64_t V1Size = MaybeV1Size.getValue();
2112 const uint64_t V2Size = MaybeV2Size.getValue();
2113
2114 const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1];
2115
2116 if (Var0.Val.TruncBits != 0 || !Var0.Val.hasSameCastsAs(Other: Var1.Val) ||
2117 !Var0.hasNegatedScaleOf(Other: Var1) ||
2118 Var0.Val.V->getType() != Var1.Val.V->getType())
2119 return false;
2120
2121 // We'll strip off the Extensions of Var0 and Var1 and do another round
2122 // of GetLinearExpression decomposition. In the example above, if Var0
2123 // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
2124
2125 LinearExpression E0 =
2126 GetLinearExpression(Val: CastedValue(Var0.Val.V), DL, Depth: 0, AC, DT);
2127 LinearExpression E1 =
2128 GetLinearExpression(Val: CastedValue(Var1.Val.V), DL, Depth: 0, AC, DT);
2129 if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(Other: E1.Val) ||
2130 !isValueEqualInPotentialCycles(V: E0.Val.V, V2: E1.Val.V, AAQI))
2131 return false;
2132
2133 // We have a hit - Var0 and Var1 only differ by a constant offset!
2134
2135 // If we've been sext'ed then zext'd the maximum difference between Var0 and
2136 // Var1 is possible to calculate, but we're just interested in the absolute
2137 // minimum difference between the two. The minimum distance may occur due to
2138 // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
2139 // the minimum distance between %i and %i + 5 is 3.
2140 APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff;
2141 MinDiff = APIntOps::umin(A: MinDiff, B: Wrapped);
2142 APInt MinDiffBytes =
2143 MinDiff.zextOrTrunc(width: Var0.Scale.getBitWidth()) * Var0.Scale.abs();
2144
2145 // We can't definitely say whether GEP1 is before or after V2 due to wrapping
2146 // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
2147 // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
2148 // V2Size can fit in the MinDiffBytes gap.
2149 return MinDiffBytes.uge(RHS: V1Size + GEP.Offset.abs()) &&
2150 MinDiffBytes.uge(RHS: V2Size + GEP.Offset.abs());
2151}
2152
2153//===----------------------------------------------------------------------===//
2154// BasicAliasAnalysis Pass
2155//===----------------------------------------------------------------------===//
2156
2157AnalysisKey BasicAA::Key;
2158
2159BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
2160 auto &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F);
2161 auto &AC = AM.getResult<AssumptionAnalysis>(IR&: F);
2162 auto *DT = &AM.getResult<DominatorTreeAnalysis>(IR&: F);
2163 return BasicAAResult(F.getDataLayout(), F, TLI, AC, DT);
2164}
2165
2166BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {}
2167
2168char BasicAAWrapperPass::ID = 0;
2169
2170void BasicAAWrapperPass::anchor() {}
2171
2172INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa",
2173 "Basic Alias Analysis (stateless AA impl)", true, true)
2174INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2175INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2176INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2177INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa",
2178 "Basic Alias Analysis (stateless AA impl)", true, true)
2179
2180FunctionPass *llvm::createBasicAAWrapperPass() {
2181 return new BasicAAWrapperPass();
2182}
2183
2184bool BasicAAWrapperPass::runOnFunction(Function &F) {
2185 auto &ACT = getAnalysis<AssumptionCacheTracker>();
2186 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
2187 auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
2188
2189 Result.reset(p: new BasicAAResult(F.getDataLayout(), F,
2190 TLIWP.getTLI(F), ACT.getAssumptionCache(F),
2191 &DTWP.getDomTree()));
2192
2193 return false;
2194}
2195
2196void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
2197 AU.setPreservesAll();
2198 AU.addRequiredTransitive<AssumptionCacheTracker>();
2199 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2200 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
2201}
2202