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