LLVM 24.0.0git
BasicAliasAnalysis.cpp
Go to the documentation of this file.
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
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ScopeExit.h"
20#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/CFG.h"
29#include "llvm/IR/Argument.h"
30#include "llvm/IR/Attributes.h"
31#include "llvm/IR/Constant.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/CycleInfo.h"
35#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/Dominators.h"
38#include "llvm/IR/Function.h"
40#include "llvm/IR/GlobalAlias.h"
42#include "llvm/IR/InstrTypes.h"
43#include "llvm/IR/Instruction.h"
46#include "llvm/IR/Intrinsics.h"
47#include "llvm/IR/Operator.h"
49#include "llvm/IR/Type.h"
50#include "llvm/IR/User.h"
51#include "llvm/IR/Value.h"
53#include "llvm/Pass.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.
71 cl::init(true));
72
73static cl::opt<bool> EnableSeparateStorageAnalysis("basic-aa-separate-storage",
74 cl::Hidden, cl::init(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
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>(Fn, PA) ||
90 (DT_ && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
91 Inv.invalidate<TargetLibraryAnalysis>(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(V, DL, &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.
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(DerefBytes, LocSize.getValue().getKnownMinValue());
139 return TypeSize::getFixed(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(OtherV, OtherSize, DL, NullIsValidLoc);
180 return TypeSize::isKnownLT(*ObjectSize, 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) {
195}
196
197//===----------------------------------------------------------------------===//
198// CaptureAnalysis implementations
199//===----------------------------------------------------------------------===//
200
202
204 const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) {
205 if (!isIdentifiedFunctionLocal(Object))
207
208 auto [CacheIt, Inserted] = IsCapturedCache.try_emplace(Object);
209 if (Inserted)
210 CacheIt->second = PointerMayBeCaptured(
212 [](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(I->getParent());
221
222 BasicBlock *BB = const_cast<BasicBlock *>(I->getParent());
224 return Succs.empty() ||
225 !isPotentiallyReachableFromMany(Succs, BB, nullptr, DT, LI);
226}
227
229 const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) {
230 if (!isIdentifiedFunctionLocal(Object))
232
233 auto Iter = EarliestEscapes.try_emplace(Object);
234 if (Iter.second) {
235 auto [EarliestInst, Res] = FindEarliestCapture(
236 Object, *DT.getRoot()->getParent(), DT, CaptureComponents::Provenance);
237 if (EarliestInst)
238 Inst2Obj[EarliestInst].push_back(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, LI, CI);
265 }
266
267 return !isPotentiallyReachable(CaptureInst, I, nullptr, &DT, LI, CI);
268 };
269 if (IsNotCapturedBefore())
271 return Iter.first->second.second.WithoutRet;
272}
273
274bool EarliestEscapeAnalysis::callsReturnsTwiceFn() {
275 if (!CallsReturnsTwiceFn)
276 CallsReturnsTwiceFn =
278 return *CallsReturnsTwiceFn;
279}
280
282 auto Iter = Inst2Obj.find(I);
283 if (Iter != Inst2Obj.end()) {
284 for (const Value *Obj : Iter->second)
285 EarliestEscapes.erase(Obj);
286 Inst2Obj.erase(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() -
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() -
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(N.getBitWidth() - TruncBits);
361 if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits);
362 if (ZExtBits) N = N.zext(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(N.getBitWidth() - TruncBits);
370 if (IsNonNegative && !N.isAllNonNegative())
371 N = N.intersectWith(
372 ConstantRange(APInt::getZero(N.getBitWidth()),
373 APInt::getSignedMinValue(N.getBitWidth())));
374 if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits);
375 if (ZExtBits) N = N.zeroExtend(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(K.getBitWidth() - TruncBits);
384 if (SExtBits)
385 K = K.sext(K.getBitWidth() + SExtBits);
386 if (ZExtBits)
387 K = K.zext(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.
449 const CastedValue &Val, const DataLayout &DL, unsigned Depth,
451 // Limit our recursion depth.
452 if (Depth == 6)
453 return Val;
454
455 if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V))
456 return LinearExpression(Val, APInt(Val.getBitWidth(), 0),
457 Val.evaluateWith(Const->getValue()), true, true);
458
459 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) {
460 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
461 APInt RHS = Val.evaluateWith(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;
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>(BOp)->isDisjoint())
486 return Val;
487
488 [[fallthrough]];
489 case Instruction::Add: {
490 E = GetLinearExpression(Val.withValue(BOp->getOperand(0), false), DL,
491 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.withValue(BOp->getOperand(0), false), DL,
499 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.withValue(BOp->getOperand(0), false), DL,
507 Depth + 1, AC, DT)
508 .mul(RHS, NUW, 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.withValue(BOp->getOperand(0), NSW), DL,
520 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.V))
532 return GetLinearExpression(
533 Val.withZExtOfValue(ZExt->getOperand(0), ZExt->hasNonNeg()), DL,
534 Depth + 1, AC, DT);
535
536 if (isa<SExtInst>(Val.V))
537 return GetLinearExpression(
538 Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)),
539 DL, 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(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.
587 // Base pointer of the GEP
588 const Value *Base;
589 // Total constant offset from base.
591 // Scaled variable (non-constant) indices.
593 // Nowrap flags common to all GEP operations involved in expression.
595
596 void dump() const {
597 print(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.
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.
629BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL,
631 // Limit recursion depth to limit compile time in crazy cases.
632 unsigned MaxLookup = MaxLookupSearchDepth;
633 SearchTimes++;
634 const Instruction *CtxI = dyn_cast<Instruction>(V);
635
636 unsigned IndexSize = DL.getIndexTypeSizeInBits(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>(V);
642 if (!Op) {
643 // The only non-operator case we can handle are GlobalAliases.
644 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(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(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>(NewVTy) ||
661 DL.getIndexTypeSizeInBits(NewVTy) != IndexSize) {
662 Decomposed.Base = V;
663 return Decomposed;
664 }
665 V = NewV;
666 continue;
667 }
668
669 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
670 if (!GEPOp) {
671 if (const auto *PHI = dyn_cast<PHINode>(V)) {
672 // Look through single-arg phi nodes created by LCSSA.
673 if (PHI->getNumIncomingValues() == 1) {
674 V = PHI->getIncomingValue(0);
675 continue;
676 }
677 } else if (const auto *Call = dyn_cast<CallBase>(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`.
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.
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>(Index)->getZExtValue();
715 if (FieldNo == 0)
716 continue;
717
718 Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo);
719 continue;
720 }
721
722 // For an array/pointer, add the element offset, explicitly scaled.
723 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(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(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;
754 CastedValue(Index, 0, SExtBits, TruncBits, NonNeg), DL, 0, AC, DT);
755
756 // Scale by the type size.
757 unsigned TypeSize = AllocTypeSize.getFixedValue();
758 LE = LE.mul(APInt(IndexSize, TypeSize), NUW, 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(Decomposed.VarIndices[i].Val.V, LE.Val.V)) &&
771 Decomposed.VarIndices[i].Val.hasSameCastsAs(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(Decomposed.VarIndices.begin() + i);
776 break;
777 }
778 }
779
780 if (!!Scale) {
781 VariableGEPIndex Entry = {LE.Val, Scale, CtxI, LE.IsNSW,
782 /* IsNegated */ false};
783 Decomposed.VarIndices.push_back(Entry);
784 }
785 }
786
787 // Analyze the base pointer next.
788 V = GEPOp->getOperand(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
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;
805 Worklist.push_back(Loc.Ptr);
807
808 do {
809 const Value *V = getUnderlyingObject(Worklist.pop_back_val());
810 if (!Visited.insert(V).second)
811 continue;
812
813 // Ignore allocas if we were instructed to do so.
814 if (IgnoreLocals && isa<AllocaInst>(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>(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>(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>(V)) {
842 Worklist.push_back(SI->getTrueValue());
843 Worklist.push_back(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>(V)) {
850 // Don't bother inspecting phi nodes with many operands.
851 if (PN->getNumIncomingValues() > MaxLookup)
852 return ModRefInfo::ModRef;
853 append_range(Worklist, 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) {
870 return II && II->getIntrinsicID() == IID;
871}
872
873/// Returns the behavior when calling the given call site.
875 AAQueryInfo &AAQI) {
876 MemoryEffects Min = Call->getAttributes().getMemoryEffects();
877
878 if (const Function *F = dyn_cast<Function>(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.
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.
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() |
906 }
907
908 return F->getMemoryEffects();
909}
910
912 unsigned ArgIdx) {
913 if (Call->doesNotAccessMemory(ArgIdx))
915
916 if (Call->onlyWritesMemory(ArgIdx))
917 return ModRefInfo::Mod;
918
919 if (Call->onlyReadsMemory(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
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(LocA.Ptr, LocA.Size, LocB.Ptr, 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.
963 const MemoryLocation &Loc,
964 AAQueryInfo &AAQI) {
966 "AliasAnalysis query involving multiple functions!");
967
968 const Value *Object = getUnderlyingObject(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>(Object))
976 if (const CallInst *CI = dyn_cast<CallInst>(Call))
977 if (CI->isTailCall() &&
978 !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
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>(Object))
984 if (!AI->isStaticAlloca() && isIntrinsicCall(Call, 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)
991 if (ME.doesNotAccessMemory())
993
994 ModRefInfo ArgMR = ME.getModRef(IRMemLocation::ArgMem);
995 ModRefInfo ErrnoMR = ME.getModRef(IRMemLocation::ErrnoMem);
996 ModRefInfo OtherMR = ME.getModRef(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.
1005 if (isModAndRefSet(OtherMR) && Call->maySynchronize() &&
1006 Call->isInlineAsm()) {
1007 SyncMR = getSyncEffects(&AAQI.AAR, Loc, AAQI);
1008 if (isModAndRefSet(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(OtherMR) && !isa<Constant>(Object) && Call != Object &&
1021 (isa<AllocaInst>(Object) || !Call->hasFnAttr(Attribute::ReturnsTwice))) {
1023 Object, 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) {
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);
1040 MemoryLocation ArgLoc =
1041 Call->isArgOperand(&U)
1042 ? MemoryLocation::getForArgument(Call, ArgIdx, TLI)
1044 AliasResult ArgAlias = AAQI.AAR.alias(ArgLoc, Loc, AAQI, 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, Call) != AliasResult::NoAlias) {
1060 // Exclusion conditions do not hold, this memory location may alias errno.
1061 Result |= ErrnoMR;
1062 }
1063 }
1064
1065 if (!isModAndRefSet(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, Intrinsic::invariant_start))
1092 return ModRefInfo::Ref;
1093
1094 // Be conservative.
1095 return ModRefInfo::ModRef;
1096}
1097
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(Call1, Intrinsic::experimental_guard))
1113 return isModSet(getMemoryEffects(Call2, AAQI).getModRef())
1116
1117 if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
1118 return isModSet(getMemoryEffects(Call1, AAQI).getModRef())
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(MemoryLocation::getBeforeOrAfter(UnderlyingV1),
1139 MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI);
1140 return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias
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.
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>(V2) ||
1156 return BaseObjectsAlias();
1157
1158 return AliasResult::MayAlias;
1159 }
1160
1161 DominatorTree *DT = getDT(AAQI);
1162 DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT);
1163 DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &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(DecompGEP1, DecompGEP2);
1176 std::swap(V1Size, V2Size);
1177 std::swap(UnderlyingV1, UnderlyingV2);
1178 }
1179
1180 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1181 // symbolic difference.
1182 subtractDecomposedGEPs(DecompGEP1, 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(V2Size.getValue()) &&
1191 isBaseOfObject(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(-V1Size.getValue()) &&
1198 isBaseOfObject(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(MemoryLocation(DecompGEP1.Base, V1Size),
1205 MemoryLocation(DecompGEP2.Base, V2Size), AAQI);
1206
1207 // Do the base pointers alias?
1208 AliasResult BaseAlias =
1209 AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(DecompGEP1.Base),
1210 MemoryLocation::getBeforeOrAfter(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(VLeftSize, 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(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(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(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, Off.getBitWidth());
1267 bool Overflow;
1268 APInt UpperRange = CR.getUnsignedMax().umul_ov(
1269 APInt(Off.getBitWidth(), LSize.getKnownMinValue()), Overflow);
1270 if (!Overflow && Off.uge(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(DecompGEP1.VarIndices[0].Val.V,
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, Scale.getBitWidth());
1292 (void)CR.getSignedMax().smul_ov(Scale, 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(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(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(BW, V1Size.getValue()) || !isUIntN(BW, 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(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(GCD);
1342 if (ModOffset.isNegative())
1343 ModOffset += GCD; // We want mod, not rem.
1344 if (ModOffset.uge(V2Size.getValue()) &&
1345 (GCD - ModOffset).uge(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 ConstantRange(APInt(BW, 0), APInt(BW, V1Size.getValue())));
1352 ConstantRange Range2 =
1353 ConstantRange(APInt(BW, 0), APInt(BW, V2Size.getValue()));
1354 if (Range1.intersectWith(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(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(V1Size.getValue()) &&
1366 OffsetHi.isNonNegative() && OffsetHi.uge(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(DecompGEP1, V1Size, V2Size, &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
1382 // If the results agree, take it.
1383 if (A == B)
1384 return A;
1385 // A mix of PartialAlias and MustAlias is 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.
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>(V2))
1402 if (isValueEqualInPotentialCycles(SI->getCondition(), SI2->getCondition(),
1403 AAQI)) {
1404 AliasResult Alias =
1405 AAQI.AAR.alias(MemoryLocation(SI->getTrueValue(), SISize),
1406 MemoryLocation(SI2->getTrueValue(), V2Size), AAQI);
1407 if (Alias == AliasResult::MayAlias)
1408 return AliasResult::MayAlias;
1409 AliasResult ThisAlias =
1410 AAQI.AAR.alias(MemoryLocation(SI->getFalseValue(), SISize),
1411 MemoryLocation(SI2->getFalseValue(), V2Size), AAQI);
1412 return MergeAliasResults(ThisAlias, 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(MemoryLocation(SI->getTrueValue(), SISize),
1418 MemoryLocation(V2, V2Size), AAQI);
1419 if (Alias == AliasResult::MayAlias)
1420 return AliasResult::MayAlias;
1421
1422 AliasResult ThisAlias =
1423 AAQI.AAR.alias(MemoryLocation(SI->getFalseValue(), SISize),
1424 MemoryLocation(V2, V2Size), AAQI);
1425 return MergeAliasResults(ThisAlias, 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>(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 MemoryLocation(PN->getIncomingValue(i), PNSize),
1445 MemoryLocation(
1446 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size),
1447 AAQI);
1448 if (Alias)
1449 *Alias = MergeAliasResults(*Alias, 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) {
1465 return false;
1466 if (getUnderlyingObject(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>(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(PV1).second)
1496 V1Srcs.push_back(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)
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(MemoryLocation(V1Srcs[0], PNSize),
1521 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 MemoryLocation(V, PNSize), MemoryLocation(V2, V2Size), AAQI);
1539 Alias = MergeAliasResults(ThisAlias, 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>(V))
1552 return true;
1553 auto *E = dyn_cast<ExtractValueInst>(V);
1554 return E && isa<Argument>(E->getOperand(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();
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.
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))
1585
1586 // Figure out what objects these things are pointing to if we can.
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>(O1))
1593 if (!NullPointerIsDefined(&F, CPN->getPointerType()->getAddressSpace()))
1594 return AliasResult::NoAlias;
1595 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1596 if (!NullPointerIsDefined(&F, 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.
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.
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.
1620 O2, dyn_cast<Instruction>(O1), /*OrAt=*/true,
1621 /*ReturnCaptures=*/false)))
1622 return AliasResult::NoAlias;
1624 O1, dyn_cast<Instruction>(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);
1632 if (isObjectSmallerThan(O2, *V1, V1Size, DL, TLI, NullIsValidLocation) ||
1633 isObjectSmallerThan(O1, *V2, V2Size, DL, TLI, NullIsValidLocation))
1634 return AliasResult::NoAlias;
1635
1637 for (AssumptionCache::ResultElem &Elem : AC.assumptionsFor(O1)) {
1638 if (!Elem || Elem.Index == AssumptionCache::ExprResultIdx)
1639 continue;
1640
1641 AssumeInst *Assume = cast<AssumeInst>(Elem);
1642 OperandBundleUse OBU = Assume->getOperandBundleAt(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(Hint1);
1650 const Value *HintO2 = getUnderlyingObject(Hint2);
1651
1652 DominatorTree *DT = getDT(AAQI);
1653 auto ValidAssumeForPtrContext = [&](const Value *Ptr) {
1654 if (const Instruction *PtrI = dyn_cast<Instruction>(Ptr)) {
1655 return isValidAssumeForContext(Assume, PtrI, DT,
1656 /* AllowEphemerals */ true);
1657 }
1658 if (const Argument *PtrA = dyn_cast<Argument>(Ptr)) {
1659 const Instruction *FirstI =
1660 &*PtrA->getParent()->getEntryBlock().begin();
1661 return isValidAssumeForContext(Assume, 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(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(Locs.first, Locs.second);
1709 const auto &Pair = AAQI.AliasCache.try_emplace(
1710 Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 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(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(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)
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(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)
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) {
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(Loc);
1772 if (It != AAQI.AliasCache.end())
1773 It->second.NumAssumptionUses = AAQueryInfo::CacheEntry::Definitive;
1774 }
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>(V1)) {
1786 AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI);
1787 if (Result != AliasResult::MayAlias)
1788 return Result;
1789 } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) {
1790 AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI);
1791 Result.swap();
1792 if (Result != AliasResult::MayAlias)
1793 return Result;
1794 }
1795
1796 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1797 AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI);
1798 if (Result != AliasResult::MayAlias)
1799 return Result;
1800 } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) {
1801 AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI);
1802 Result.swap();
1803 if (Result != AliasResult::MayAlias)
1804 return Result;
1805 }
1806
1807 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1808 AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI);
1809 if (Result != AliasResult::MayAlias)
1810 return Result;
1811 } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) {
1812 AliasResult Result = aliasSelect(S2, V2Size, V1, 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);
1822 if (V1Size.isPrecise() && V2Size.isPrecise() &&
1823 (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
1824 isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation)))
1826 }
1827
1828 return AliasResult::MayAlias;
1829}
1830
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("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(Loc.Ptr);
1848 if (isIdentifiedFunctionLocal(Object))
1849 return AliasResult::NoAlias;
1850
1851 if (auto *GV = dyn_cast<GlobalVariable>(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>(V);
1883 if (!Inst || Inst->getParent()->isEntryBlock())
1884 return true;
1885
1886 return isNotInCycle(Inst, 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(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(DestGEP.VarIndices)) {
1904 VariableGEPIndex &Dest = I.value();
1905 if ((!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V, AAQI) &&
1906 !areBothVScale(Dest.Val.V, Src.Val.V)) ||
1907 !Dest.Val.hasSameCastsAs(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(Src.Scale))
1923 DestGEP.NWFlags = DestGEP.NWFlags.withoutNoUnsignedWrap();
1924
1925 Dest.Scale -= Src.Scale;
1926 Dest.IsNSW = false;
1927 } else {
1928 DestGEP.VarIndices.erase(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 = {Src.Val, Src.Scale, Src.CtxI, Src.IsNSW,
1937 /* IsNegated */ true};
1938 DestGEP.VarIndices.push_back(Entry);
1939
1940 // Drop nuw flag when we have unconsumed variable indices from SrcGEP.
1941 DestGEP.NWFlags = DestGEP.NWFlags.withoutNoUnsignedWrap();
1942 }
1943 }
1944}
1945
1947BasicAAResult::analyzeVariableOffsets(const DecomposedGEP &GEP,
1948 DominatorTree *DT) {
1949 APInt GCD;
1950 ConstantRange OffsetRange(GEP.Offset);
1951 SmallVector<KnownBits, 4> VarIndexKnownBits;
1952 VarIndexKnownBits.reserve(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(Index.Val.V, SQ);
1960 VarIndexKnownBits.emplace_back(Known);
1961
1962 APInt ScaleForGCD = Scale;
1963 if (!Index.IsNSW)
1964 ScaleForGCD =
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(VarTZ, MaxShift);
1976 }
1977
1978 if (I == 0)
1979 GCD = ScaleForGCD.abs();
1980 else
1981 GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs());
1982
1983 ConstantRange CR =
1984 computeConstantRange(Index.Val.V, /*ForSigned=*/false, SQ);
1985 CR =
1986 CR.intersectWith(ConstantRange::fromKnownBits(Known, /*IsSigned=*/true),
1988 CR = Index.Val.evaluateWith(CR).sextOrTrunc(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(ConstantRange(Scale));
1994 else
1995 CR = CR.smul_fast(ConstantRange(Scale));
1996
1997 if (Index.IsNegated)
1998 OffsetRange = OffsetRange.sub(CR);
1999 else
2000 OffsetRange = OffsetRange.add(CR);
2001 }
2002
2003 return {GCD, OffsetRange, 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 APInt::getMaxValue(MaxScaleValueBW).zext(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(Var.Val.V, 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(Var1.Val) &&
2051 !AAQI.MayBeCrossIteration && MultiplyByScaleNoWrap(Var0) &&
2052 MultiplyByScaleNoWrap(Var1);
2053
2054 if (!Preconditions)
2055 return std::nullopt;
2056
2057 if (Var0.hasNegatedScaleOf(Var1)) {
2058 if (isKnownNonEqual(Var0.Val.V, Var1.Val.V,
2059 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(AbsScale0, AbsScale1);
2082 APInt C0 = AbsScale0.udiv(ScaleGCD);
2083 APInt C1 = AbsScale1.udiv(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(Var0.Val.evaluateWith(VIKnownBits[0]),
2089
2090 auto Known1 = KnownBits::mul(Var1.Val.evaluateWith(VIKnownBits[1]),
2092
2093 if (auto Res = KnownBits::ne(Known0, 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(Var1.Val) ||
2117 !Var0.hasNegatedScaleOf(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(CastedValue(Var0.Val.V), DL, 0, AC, DT);
2127 LinearExpression E1 =
2128 GetLinearExpression(CastedValue(Var1.Val.V), DL, 0, AC, DT);
2129 if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(E1.Val) ||
2130 !isValueEqualInPotentialCycles(E0.Val.V, 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(MinDiff, Wrapped);
2142 APInt MinDiffBytes =
2143 MinDiff.zextOrTrunc(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(V1Size + GEP.Offset.abs()) &&
2150 MinDiffBytes.uge(V2Size + GEP.Offset.abs());
2151}
2152
2153//===----------------------------------------------------------------------===//
2154// BasicAliasAnalysis Pass
2155//===----------------------------------------------------------------------===//
2156
2157AnalysisKey BasicAA::Key;
2158
2160 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
2161 auto &AC = AM.getResult<AssumptionAnalysis>(F);
2162 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
2163 return BasicAAResult(F.getDataLayout(), F, TLI, AC, DT);
2164}
2165
2167
2168char BasicAAWrapperPass::ID = 0;
2169
2170void BasicAAWrapperPass::anchor() {}
2171
2173 "Basic Alias Analysis (stateless AA impl)", true, true)
2178 "Basic Alias Analysis (stateless AA impl)", true, true)
2179
2183
2188
2189 Result.reset(new BasicAAResult(F.getDataLayout(), F,
2190 TLIWP.getTLI(F), ACT.getAssumptionCache(F),
2191 &DTWP.getDomTree()));
2192
2193 return false;
2194}
2195
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
constexpr LLT S1
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
static cl::opt< bool > EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden, cl::init(true))
Enable analysis of recursive PHI nodes.
static const Function * getParent(const Value *V)
static bool isObjectSize(const Value *V, TypeSize Size, const DataLayout &DL, const TargetLibraryInfo &TLI, bool NullIsValidLoc)
Returns true if we can prove that the object specified by V has size Size.
static cl::opt< bool > EnableSeparateStorageAnalysis("basic-aa-separate-storage", cl::Hidden, cl::init(true))
static bool isArgumentOrArgumentLike(const Value *V)
static bool notDifferentParent(const Value *O1, const Value *O2)
static LinearExpression GetLinearExpression(const CastedValue &Val, const DataLayout &DL, unsigned Depth, AssumptionCache *AC, DominatorTree *DT)
Analyzes the specified value as a linear expression: "A*V + B", where A and B are constant integers.
static bool isNotInCycle(const Instruction *I, const DominatorTree *DT, const LoopInfo *LI, const CycleInfo *CI)
static bool areBothVScale(const Value *V1, const Value *V2)
Return true if both V1 and V2 are VScale.
basic Basic Alias true
static TypeSize getMinimalExtentFrom(const Value &V, const LocationSize &LocSize, const DataLayout &DL, bool NullIsValidLoc)
Return the minimal extent from V to the end of the underlying object, assuming the result is used in ...
static AliasResult MergeAliasResults(AliasResult A, AliasResult B)
static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID)
static bool isObjectSmallerThan(const Value *V, const Value &OtherV, LocationSize OtherSize, const DataLayout &DL, const TargetLibraryInfo &TLI, bool NullIsValidLoc)
Returns true if we can prove that the object specified by V is smaller than the minimal extent access...
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
Hexagon Common GEP
#define _
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file provides utility classes that use RAII to save and restore values.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
This class stores info we want to provide to or retain within an alias query.
SmallVector< AAQueryInfo::LocPair, 4 > AssumptionBasedResults
Location pairs for which an assumption based result is currently stored.
unsigned Depth
Query depth used to distinguish recursive queries.
int NumAssumptionUses
How many active NoAlias assumption uses there are.
std::pair< AACacheLoc, AACacheLoc > LocPair
AliasCacheT AliasCache
bool MayBeCrossIteration
Tracks whether the accesses may be on different cycle iterations.
CaptureAnalysis * CA
LLVM_ABI AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
LLVM_ABI AliasResult aliasErrno(const MemoryLocation &Loc, const Instruction *CtxI)
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call)
Return the behavior of the given call site.
LLVM_ABI ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx)
Get the ModRef info associated with a pointer argument of a call.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1998
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
The possible results of an alias query.
void swap(bool DoSwap=true)
Helper for processing AliasResult for swapped memory location pairs.
@ MayAlias
The two locations may or may not alias.
@ NoAlias
The two locations do not alias at all.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
void setOffset(int32_t NewOffset)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
This is the AA result object for the basic, local, and stateless alias analysis.
LLVM_ABI ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, AAQueryInfo &AAQI)
Checks to see if the specified callsite can clobber the specified memory object.
LLVM_ABI ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx)
Get the location associated with a pointer argument of a callsite.
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI)
Returns the behavior when calling the given call site.
LLVM_ABI AliasResult aliasErrno(const MemoryLocation &Loc, const Instruction *CtxI)
LLVM_ABI ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
LLVM_ABI bool invalidate(Function &Fn, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
LLVM_ABI AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, AAQueryInfo &AAQI, const Instruction *CtxI)
Legacy wrapper pass to provide the BasicAAResult object.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
LLVM_ABI BasicAAResult run(Function &F, FunctionAnalysisManager &AM)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a function call, abstracting a target machine's calling convention.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI ConstantRange smul_fast(const ConstantRange &Other) const
Return range of possible values for a signed multiplication of this and Other.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange smul_sat(const ConstantRange &Other) const
Perform a signed saturating multiplication of two constant ranges.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
iterator end()
Definition DenseMap.h:687
bool erase(const KeyT &Val)
Definition DenseMap.h:931
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:857
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
void removeInstruction(Instruction *I)
CaptureComponents getCapturesBefore(const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) override
Return how Object may be captured before instruction I, considering only provenance captures.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
FunctionPass(char &pid)
Definition Pass.h:316
bool callsFunctionThatReturnsTwice() const
callsFunctionThatReturnsTwice - Return true if the function has a call to setjmp or other function th...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:734
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags all()
GEPNoWrapFlags withoutNoUnsignedWrap() const
bool hasNoUnsignedSignedWrap() const
Definition Operator.h:392
bool hasNoUnsignedWrap() const
Definition Operator.h:396
LLVM_ABI Type * getSourceElementType() const
Definition Operator.cpp:86
GEPNoWrapFlags getNoWrapFlags() const
Definition Operator.h:385
CycleRef getCycle(const BlockT *Block) const
Find the innermost cycle containing Block.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
bool hasValue() const
bool mayBeBeforePointer() const
Whether accesses before the base pointer are possible.
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
bool isScalable() const
TypeSize getValue() const
bool isPrecise() const
static constexpr LocationSize afterPointer()
Any location after the base pointer (but still within the underlying object).
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
MemoryEffectsBase getWithoutLoc(Location Loc) const
Get new MemoryEffectsBase with NoModRef on the given Loc.
Definition ModRef.h:231
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
Representation for a specific memory location.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
const Value * Ptr
The address of the start of the location.
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
This class represents the LLVM 'select' instruction.
CaptureComponents getCapturesBefore(const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures) override
Return how Object may be captured before instruction I, considering only provenance captures.
size_type size() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_iterator op_begin()
Definition User.h:259
const Use * const_op_iterator
Definition User.h:255
Value * getOperand(unsigned i) const
Definition User.h:207
op_iterator op_end()
Definition User.h:261
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI const Value * stripPointerCastsForAliasAnalysis() const
Strip off pointer casts, all-zero GEPs, single-argument phi nodes and invariant group info.
Definition Value.cpp:728
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:216
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
@ Entry
Definition COFF.h:862
bool match(Val *V, const Pattern &P)
auto m_VScale()
Matches a call to llvm.vscale().
initializer< Ty > init(const Ty &Val)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
bool capturesReadProvenanceOnly(CaptureComponents CC)
Definition ModRef.h:391
SaveAndRestore(T &) -> SaveAndRestore< T >
@ Known
Known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool isBaseOfObject(const Value *V)
Return true if we know V to the base address of the corresponding memory object.
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
This function returns call pointer argument that is considered the same by aliasing rules.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI std::optional< TypeSize > getBaseObjectSize(const Value *Ptr, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Like getObjectSize(), but only returns the size of base objects (like allocas, global variables and a...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
LLVM_ABI bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts={})
Compute the size of the object pointed by Ptr.
bool capturesFullProvenance(CaptureComponents CC)
Definition ModRef.h:396
LLVM_ABI ModRefInfo getSyncEffects(AAResults *AA, const MemoryLocation &Loc, AAQueryInfo &AAQI)
Get ModRefInfo for a synchronizing operation, such as a fence or stronger than monotonic atomic load/...
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
generic_gep_type_iterator<> gep_type_iterator
bool isModOrRefSet(const ModRefInfo MRI)
Definition ModRef.h:43
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI FunctionPass * createBasicAAWrapperPass()
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ ErrnoMem
Errno memory.
Definition ModRef.h:66
@ ArgMem
Access to memory via argument pointers.
Definition ModRef.h:62
@ Other
Any other memory.
Definition ModRef.h:68
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
Definition ModRef.h:64
LLVM_ABI bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
Definition CFG.cpp:335
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
LLVM_ABI bool isPotentiallyReachableFromMany(SmallVectorImpl< BasicBlock * > &Worklist, const BasicBlock *StopBB, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether there is at least one path from a block in 'Worklist' to 'StopBB' without passing t...
Definition CFG.cpp:293
LLVM_ABI std::pair< Instruction *, CaptureResult > FindEarliestCapture(const Value *V, Function &F, const DominatorTree &DT, CaptureComponents Mask, unsigned MaxUsesToExplore=0)
bool isModAndRefSet(const ModRefInfo MRI)
Definition ModRef.h:46
LLVM_ABI bool isIdentifiedFunctionLocal(const Value *V)
Return true if V is umabigously identified at the function-level.
constexpr unsigned BitWidth
LLVM_ABI bool isEscapeSource(const Value *V)
Returns true if the pointer is one which would have been considered an escape by isNotCapturedBefore.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
SmallVector< VariableGEPIndex, 4 > VarIndices
static constexpr int Definitive
Cache entry is neither an assumption nor does it use a (non-definitive) assumption.
static constexpr int AssumptionBased
Cache entry is not an assumption itself, but may be using an assumption from higher up the stack.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
virtual CaptureComponents getCapturesBefore(const Value *Object, const Instruction *I, bool OrAt, bool ReturnCaptures)=0
Return how Object may be captured before instruction I, considering only provenance captures.
virtual ~CaptureAnalysis()=0
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI std::optional< bool > ne(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_NE result.
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:224
LinearExpression(Value *BasePtr, unsigned BitWidth)
Definition Loads.h:231
Various options to control the behavior of getObjectSize.
bool NullIsUnknownSize
If this is true, null pointers in address space 0 will be treated as though they can't be evaluated.
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables.
StringRef getTagName() const
Return the tag of this operand bundle as a string.
ArrayRef< Use > Inputs