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