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