xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/BasicAliasAnalysis.cpp (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the primary stateless implementation of the
10 // Alias Analysis interface that implements identities (two different
11 // globals cannot alias, etc), but does no stateful analysis.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/BasicAliasAnalysis.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ScopeExit.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/CFG.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/PhiValues.h"
29 #include "llvm/Analysis/TargetLibraryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/Argument.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/ConstantRange.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GetElementPtrTypeIterator.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/InstrTypes.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Intrinsics.h"
48 #include "llvm/IR/Metadata.h"
49 #include "llvm/IR/Operator.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/IR/User.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/InitializePasses.h"
54 #include "llvm/Pass.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/KnownBits.h"
59 #include <cassert>
60 #include <cstdint>
61 #include <cstdlib>
62 #include <utility>
63 
64 #define DEBUG_TYPE "basicaa"
65 
66 using namespace llvm;
67 
68 /// Enable analysis of recursive PHI nodes.
69 static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden,
70                                           cl::init(true));
71 
72 /// SearchLimitReached / SearchTimes shows how often the limit of
73 /// to decompose GEPs is reached. It will affect the precision
74 /// of basic alias analysis.
75 STATISTIC(SearchLimitReached, "Number of times the limit to "
76                               "decompose GEPs is reached");
77 STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
78 
79 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
80 /// in a cycle. Because we are analysing 'through' phi nodes, we need to be
81 /// careful with value equivalence. We use reachability to make sure a value
82 /// cannot be involved in a cycle.
83 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
84 
85 // The max limit of the search depth in DecomposeGEPExpression() and
86 // getUnderlyingObject().
87 static const unsigned MaxLookupSearchDepth = 6;
88 
89 bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
90                                FunctionAnalysisManager::Invalidator &Inv) {
91   // We don't care if this analysis itself is preserved, it has no state. But
92   // we need to check that the analyses it depends on have been. Note that we
93   // may be created without handles to some analyses and in that case don't
94   // depend on them.
95   if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
96       (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
97       (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA)))
98     return true;
99 
100   // Otherwise this analysis result remains valid.
101   return false;
102 }
103 
104 //===----------------------------------------------------------------------===//
105 // Useful predicates
106 //===----------------------------------------------------------------------===//
107 
108 /// Returns true if the pointer is one which would have been considered an
109 /// escape by isNonEscapingLocalObject.
110 static bool isEscapeSource(const Value *V) {
111   if (isa<CallBase>(V))
112     return true;
113 
114   // The load case works because isNonEscapingLocalObject considers all
115   // stores to be escapes (it passes true for the StoreCaptures argument
116   // to PointerMayBeCaptured).
117   if (isa<LoadInst>(V))
118     return true;
119 
120   // The inttoptr case works because isNonEscapingLocalObject considers all
121   // means of converting or equating a pointer to an int (ptrtoint, ptr store
122   // which could be followed by an integer load, ptr<->int compare) as
123   // escaping, and objects located at well-known addresses via platform-specific
124   // means cannot be considered non-escaping local objects.
125   if (isa<IntToPtrInst>(V))
126     return true;
127 
128   return false;
129 }
130 
131 /// Returns the size of the object specified by V or UnknownSize if unknown.
132 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
133                               const TargetLibraryInfo &TLI,
134                               bool NullIsValidLoc,
135                               bool RoundToAlign = false) {
136   uint64_t Size;
137   ObjectSizeOpts Opts;
138   Opts.RoundToAlign = RoundToAlign;
139   Opts.NullIsUnknownSize = NullIsValidLoc;
140   if (getObjectSize(V, Size, DL, &TLI, Opts))
141     return Size;
142   return MemoryLocation::UnknownSize;
143 }
144 
145 /// Returns true if we can prove that the object specified by V is smaller than
146 /// Size.
147 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
148                                 const DataLayout &DL,
149                                 const TargetLibraryInfo &TLI,
150                                 bool NullIsValidLoc) {
151   // Note that the meanings of the "object" are slightly different in the
152   // following contexts:
153   //    c1: llvm::getObjectSize()
154   //    c2: llvm.objectsize() intrinsic
155   //    c3: isObjectSmallerThan()
156   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
157   // refers to the "entire object".
158   //
159   //  Consider this example:
160   //     char *p = (char*)malloc(100)
161   //     char *q = p+80;
162   //
163   //  In the context of c1 and c2, the "object" pointed by q refers to the
164   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
165   //
166   //  However, in the context of c3, the "object" refers to the chunk of memory
167   // being allocated. So, the "object" has 100 bytes, and q points to the middle
168   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
169   // parameter, before the llvm::getObjectSize() is called to get the size of
170   // entire object, we should:
171   //    - either rewind the pointer q to the base-address of the object in
172   //      question (in this case rewind to p), or
173   //    - just give up. It is up to caller to make sure the pointer is pointing
174   //      to the base address the object.
175   //
176   // We go for 2nd option for simplicity.
177   if (!isIdentifiedObject(V))
178     return false;
179 
180   // This function needs to use the aligned object size because we allow
181   // reads a bit past the end given sufficient alignment.
182   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
183                                       /*RoundToAlign*/ true);
184 
185   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
186 }
187 
188 /// Return the minimal extent from \p V to the end of the underlying object,
189 /// assuming the result is used in an aliasing query. E.g., we do use the query
190 /// location size and the fact that null pointers cannot alias here.
191 static uint64_t getMinimalExtentFrom(const Value &V,
192                                      const LocationSize &LocSize,
193                                      const DataLayout &DL,
194                                      bool NullIsValidLoc) {
195   // If we have dereferenceability information we know a lower bound for the
196   // extent as accesses for a lower offset would be valid. We need to exclude
197   // the "or null" part if null is a valid pointer. We can ignore frees, as an
198   // access after free would be undefined behavior.
199   bool CanBeNull, CanBeFreed;
200   uint64_t DerefBytes =
201     V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
202   DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
203   // If queried with a precise location size, we assume that location size to be
204   // accessed, thus valid.
205   if (LocSize.isPrecise())
206     DerefBytes = std::max(DerefBytes, LocSize.getValue());
207   return DerefBytes;
208 }
209 
210 /// Returns true if we can prove that the object specified by V has size Size.
211 static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
212                          const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
213   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc);
214   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
215 }
216 
217 //===----------------------------------------------------------------------===//
218 // CaptureInfo implementations
219 //===----------------------------------------------------------------------===//
220 
221 CaptureInfo::~CaptureInfo() = default;
222 
223 bool SimpleCaptureInfo::isNotCapturedBeforeOrAt(const Value *Object,
224                                                 const Instruction *I) {
225   return isNonEscapingLocalObject(Object, &IsCapturedCache);
226 }
227 
228 bool EarliestEscapeInfo::isNotCapturedBeforeOrAt(const Value *Object,
229                                                  const Instruction *I) {
230   if (!isIdentifiedFunctionLocal(Object))
231     return false;
232 
233   auto Iter = EarliestEscapes.insert({Object, nullptr});
234   if (Iter.second) {
235     Instruction *EarliestCapture = FindEarliestCapture(
236         Object, *const_cast<Function *>(I->getFunction()),
237         /*ReturnCaptures=*/false, /*StoreCaptures=*/true, DT);
238     if (EarliestCapture) {
239       auto Ins = Inst2Obj.insert({EarliestCapture, {}});
240       Ins.first->second.push_back(Object);
241     }
242     Iter.first->second = EarliestCapture;
243   }
244 
245   // No capturing instruction.
246   if (!Iter.first->second)
247     return true;
248 
249   return I != Iter.first->second &&
250          !isPotentiallyReachable(Iter.first->second, I, nullptr, &DT, &LI);
251 }
252 
253 void EarliestEscapeInfo::removeInstruction(Instruction *I) {
254   auto Iter = Inst2Obj.find(I);
255   if (Iter != Inst2Obj.end()) {
256     for (const Value *Obj : Iter->second)
257       EarliestEscapes.erase(Obj);
258     Inst2Obj.erase(I);
259   }
260 }
261 
262 //===----------------------------------------------------------------------===//
263 // GetElementPtr Instruction Decomposition and Analysis
264 //===----------------------------------------------------------------------===//
265 
266 namespace {
267 /// Represents zext(sext(trunc(V))).
268 struct CastedValue {
269   const Value *V;
270   unsigned ZExtBits = 0;
271   unsigned SExtBits = 0;
272   unsigned TruncBits = 0;
273 
274   explicit CastedValue(const Value *V) : V(V) {}
275   explicit CastedValue(const Value *V, unsigned ZExtBits, unsigned SExtBits,
276                        unsigned TruncBits)
277       : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits), TruncBits(TruncBits) {}
278 
279   unsigned getBitWidth() const {
280     return V->getType()->getPrimitiveSizeInBits() - TruncBits + ZExtBits +
281            SExtBits;
282   }
283 
284   CastedValue withValue(const Value *NewV) const {
285     return CastedValue(NewV, ZExtBits, SExtBits, TruncBits);
286   }
287 
288   /// Replace V with zext(NewV)
289   CastedValue withZExtOfValue(const Value *NewV) const {
290     unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
291                         NewV->getType()->getPrimitiveSizeInBits();
292     if (ExtendBy <= TruncBits)
293       return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy);
294 
295     // zext(sext(zext(NewV))) == zext(zext(zext(NewV)))
296     ExtendBy -= TruncBits;
297     return CastedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0, 0);
298   }
299 
300   /// Replace V with sext(NewV)
301   CastedValue withSExtOfValue(const Value *NewV) const {
302     unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
303                         NewV->getType()->getPrimitiveSizeInBits();
304     if (ExtendBy <= TruncBits)
305       return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy);
306 
307     // zext(sext(sext(NewV)))
308     ExtendBy -= TruncBits;
309     return CastedValue(NewV, ZExtBits, SExtBits + ExtendBy, 0);
310   }
311 
312   APInt evaluateWith(APInt N) const {
313     assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
314            "Incompatible bit width");
315     if (TruncBits) N = N.trunc(N.getBitWidth() - TruncBits);
316     if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits);
317     if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits);
318     return N;
319   }
320 
321   ConstantRange evaluateWith(ConstantRange N) const {
322     assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
323            "Incompatible bit width");
324     if (TruncBits) N = N.truncate(N.getBitWidth() - TruncBits);
325     if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits);
326     if (ZExtBits) N = N.zeroExtend(N.getBitWidth() + ZExtBits);
327     return N;
328   }
329 
330   bool canDistributeOver(bool NUW, bool NSW) const {
331     // zext(x op<nuw> y) == zext(x) op<nuw> zext(y)
332     // sext(x op<nsw> y) == sext(x) op<nsw> sext(y)
333     // trunc(x op y) == trunc(x) op trunc(y)
334     return (!ZExtBits || NUW) && (!SExtBits || NSW);
335   }
336 
337   bool hasSameCastsAs(const CastedValue &Other) const {
338     return ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits &&
339            TruncBits == Other.TruncBits;
340   }
341 };
342 
343 /// Represents zext(sext(trunc(V))) * Scale + Offset.
344 struct LinearExpression {
345   CastedValue Val;
346   APInt Scale;
347   APInt Offset;
348 
349   /// True if all operations in this expression are NSW.
350   bool IsNSW;
351 
352   LinearExpression(const CastedValue &Val, const APInt &Scale,
353                    const APInt &Offset, bool IsNSW)
354       : Val(Val), Scale(Scale), Offset(Offset), IsNSW(IsNSW) {}
355 
356   LinearExpression(const CastedValue &Val) : Val(Val), IsNSW(true) {
357     unsigned BitWidth = Val.getBitWidth();
358     Scale = APInt(BitWidth, 1);
359     Offset = APInt(BitWidth, 0);
360   }
361 
362   LinearExpression mul(const APInt &Other, bool MulIsNSW) const {
363     // The check for zero offset is necessary, because generally
364     // (X +nsw Y) *nsw Z does not imply (X *nsw Z) +nsw (Y *nsw Z).
365     bool NSW = IsNSW && (Other.isOne() || (MulIsNSW && Offset.isZero()));
366     return LinearExpression(Val, Scale * Other, Offset * Other, NSW);
367   }
368 };
369 }
370 
371 /// Analyzes the specified value as a linear expression: "A*V + B", where A and
372 /// B are constant integers.
373 static LinearExpression GetLinearExpression(
374     const CastedValue &Val,  const DataLayout &DL, unsigned Depth,
375     AssumptionCache *AC, DominatorTree *DT) {
376   // Limit our recursion depth.
377   if (Depth == 6)
378     return Val;
379 
380   if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V))
381     return LinearExpression(Val, APInt(Val.getBitWidth(), 0),
382                             Val.evaluateWith(Const->getValue()), true);
383 
384   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) {
385     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
386       APInt RHS = Val.evaluateWith(RHSC->getValue());
387       // The only non-OBO case we deal with is or, and only limited to the
388       // case where it is both nuw and nsw.
389       bool NUW = true, NSW = true;
390       if (isa<OverflowingBinaryOperator>(BOp)) {
391         NUW &= BOp->hasNoUnsignedWrap();
392         NSW &= BOp->hasNoSignedWrap();
393       }
394       if (!Val.canDistributeOver(NUW, NSW))
395         return Val;
396 
397       // While we can distribute over trunc, we cannot preserve nowrap flags
398       // in that case.
399       if (Val.TruncBits)
400         NUW = NSW = false;
401 
402       LinearExpression E(Val);
403       switch (BOp->getOpcode()) {
404       default:
405         // We don't understand this instruction, so we can't decompose it any
406         // further.
407         return Val;
408       case Instruction::Or:
409         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
410         // analyze it.
411         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
412                                BOp, DT))
413           return Val;
414 
415         LLVM_FALLTHROUGH;
416       case Instruction::Add: {
417         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
418                                 Depth + 1, AC, DT);
419         E.Offset += RHS;
420         E.IsNSW &= NSW;
421         break;
422       }
423       case Instruction::Sub: {
424         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
425                                 Depth + 1, AC, DT);
426         E.Offset -= RHS;
427         E.IsNSW &= NSW;
428         break;
429       }
430       case Instruction::Mul:
431         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
432                                 Depth + 1, AC, DT)
433                 .mul(RHS, NSW);
434         break;
435       case Instruction::Shl:
436         // We're trying to linearize an expression of the kind:
437         //   shl i8 -128, 36
438         // where the shift count exceeds the bitwidth of the type.
439         // We can't decompose this further (the expression would return
440         // a poison value).
441         if (RHS.getLimitedValue() > Val.getBitWidth())
442           return Val;
443 
444         E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL,
445                                 Depth + 1, AC, DT);
446         E.Offset <<= RHS.getLimitedValue();
447         E.Scale <<= RHS.getLimitedValue();
448         E.IsNSW &= NSW;
449         break;
450       }
451       return E;
452     }
453   }
454 
455   if (isa<ZExtInst>(Val.V))
456     return GetLinearExpression(
457         Val.withZExtOfValue(cast<CastInst>(Val.V)->getOperand(0)),
458         DL, Depth + 1, AC, DT);
459 
460   if (isa<SExtInst>(Val.V))
461     return GetLinearExpression(
462         Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)),
463         DL, Depth + 1, AC, DT);
464 
465   return Val;
466 }
467 
468 /// To ensure a pointer offset fits in an integer of size IndexSize
469 /// (in bits) when that size is smaller than the maximum index size. This is
470 /// an issue, for example, in particular for 32b pointers with negative indices
471 /// that rely on two's complement wrap-arounds for precise alias information
472 /// where the maximum index size is 64b.
473 static APInt adjustToIndexSize(const APInt &Offset, unsigned IndexSize) {
474   assert(IndexSize <= Offset.getBitWidth() && "Invalid IndexSize!");
475   unsigned ShiftBits = Offset.getBitWidth() - IndexSize;
476   return (Offset << ShiftBits).ashr(ShiftBits);
477 }
478 
479 namespace {
480 // A linear transformation of a Value; this class represents
481 // ZExt(SExt(Trunc(V, TruncBits), SExtBits), ZExtBits) * Scale.
482 struct VariableGEPIndex {
483   CastedValue Val;
484   APInt Scale;
485 
486   // Context instruction to use when querying information about this index.
487   const Instruction *CxtI;
488 
489   /// True if all operations in this expression are NSW.
490   bool IsNSW;
491 
492   void dump() const {
493     print(dbgs());
494     dbgs() << "\n";
495   }
496   void print(raw_ostream &OS) const {
497     OS << "(V=" << Val.V->getName()
498        << ", zextbits=" << Val.ZExtBits
499        << ", sextbits=" << Val.SExtBits
500        << ", truncbits=" << Val.TruncBits
501        << ", scale=" << Scale << ")";
502   }
503 };
504 }
505 
506 // Represents the internal structure of a GEP, decomposed into a base pointer,
507 // constant offsets, and variable scaled indices.
508 struct BasicAAResult::DecomposedGEP {
509   // Base pointer of the GEP
510   const Value *Base;
511   // Total constant offset from base.
512   APInt Offset;
513   // Scaled variable (non-constant) indices.
514   SmallVector<VariableGEPIndex, 4> VarIndices;
515   // Are all operations inbounds GEPs or non-indexing operations?
516   // (None iff expression doesn't involve any geps)
517   Optional<bool> InBounds;
518 
519   void dump() const {
520     print(dbgs());
521     dbgs() << "\n";
522   }
523   void print(raw_ostream &OS) const {
524     OS << "(DecomposedGEP Base=" << Base->getName()
525        << ", Offset=" << Offset
526        << ", VarIndices=[";
527     for (size_t i = 0; i < VarIndices.size(); i++) {
528       if (i != 0)
529         OS << ", ";
530       VarIndices[i].print(OS);
531     }
532     OS << "])";
533   }
534 };
535 
536 
537 /// If V is a symbolic pointer expression, decompose it into a base pointer
538 /// with a constant offset and a number of scaled symbolic offsets.
539 ///
540 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale
541 /// in the VarIndices vector) are Value*'s that are known to be scaled by the
542 /// specified amount, but which may have other unrepresented high bits. As
543 /// such, the gep cannot necessarily be reconstructed from its decomposed form.
544 BasicAAResult::DecomposedGEP
545 BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL,
546                                       AssumptionCache *AC, DominatorTree *DT) {
547   // Limit recursion depth to limit compile time in crazy cases.
548   unsigned MaxLookup = MaxLookupSearchDepth;
549   SearchTimes++;
550   const Instruction *CxtI = dyn_cast<Instruction>(V);
551 
552   unsigned MaxIndexSize = DL.getMaxIndexSizeInBits();
553   DecomposedGEP Decomposed;
554   Decomposed.Offset = APInt(MaxIndexSize, 0);
555   do {
556     // See if this is a bitcast or GEP.
557     const Operator *Op = dyn_cast<Operator>(V);
558     if (!Op) {
559       // The only non-operator case we can handle are GlobalAliases.
560       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
561         if (!GA->isInterposable()) {
562           V = GA->getAliasee();
563           continue;
564         }
565       }
566       Decomposed.Base = V;
567       return Decomposed;
568     }
569 
570     if (Op->getOpcode() == Instruction::BitCast ||
571         Op->getOpcode() == Instruction::AddrSpaceCast) {
572       V = Op->getOperand(0);
573       continue;
574     }
575 
576     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
577     if (!GEPOp) {
578       if (const auto *PHI = dyn_cast<PHINode>(V)) {
579         // Look through single-arg phi nodes created by LCSSA.
580         if (PHI->getNumIncomingValues() == 1) {
581           V = PHI->getIncomingValue(0);
582           continue;
583         }
584       } else if (const auto *Call = dyn_cast<CallBase>(V)) {
585         // CaptureTracking can know about special capturing properties of some
586         // intrinsics like launder.invariant.group, that can't be expressed with
587         // the attributes, but have properties like returning aliasing pointer.
588         // Because some analysis may assume that nocaptured pointer is not
589         // returned from some special intrinsic (because function would have to
590         // be marked with returns attribute), it is crucial to use this function
591         // because it should be in sync with CaptureTracking. Not using it may
592         // cause weird miscompilations where 2 aliasing pointers are assumed to
593         // noalias.
594         if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
595           V = RP;
596           continue;
597         }
598       }
599 
600       Decomposed.Base = V;
601       return Decomposed;
602     }
603 
604     // Track whether we've seen at least one in bounds gep, and if so, whether
605     // all geps parsed were in bounds.
606     if (Decomposed.InBounds == None)
607       Decomposed.InBounds = GEPOp->isInBounds();
608     else if (!GEPOp->isInBounds())
609       Decomposed.InBounds = false;
610 
611     assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized");
612 
613     // Don't attempt to analyze GEPs if index scale is not a compile-time
614     // constant.
615     if (isa<ScalableVectorType>(GEPOp->getSourceElementType())) {
616       Decomposed.Base = V;
617       return Decomposed;
618     }
619 
620     unsigned AS = GEPOp->getPointerAddressSpace();
621     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
622     gep_type_iterator GTI = gep_type_begin(GEPOp);
623     unsigned IndexSize = DL.getIndexSizeInBits(AS);
624     // Assume all GEP operands are constants until proven otherwise.
625     bool GepHasConstantOffset = true;
626     for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
627          I != E; ++I, ++GTI) {
628       const Value *Index = *I;
629       // Compute the (potentially symbolic) offset in bytes for this index.
630       if (StructType *STy = GTI.getStructTypeOrNull()) {
631         // For a struct, add the member offset.
632         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
633         if (FieldNo == 0)
634           continue;
635 
636         Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo);
637         continue;
638       }
639 
640       // For an array/pointer, add the element offset, explicitly scaled.
641       if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
642         if (CIdx->isZero())
643           continue;
644         Decomposed.Offset +=
645             DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize() *
646             CIdx->getValue().sextOrTrunc(MaxIndexSize);
647         continue;
648       }
649 
650       GepHasConstantOffset = false;
651 
652       // If the integer type is smaller than the index size, it is implicitly
653       // sign extended or truncated to index size.
654       unsigned Width = Index->getType()->getIntegerBitWidth();
655       unsigned SExtBits = IndexSize > Width ? IndexSize - Width : 0;
656       unsigned TruncBits = IndexSize < Width ? Width - IndexSize : 0;
657       LinearExpression LE = GetLinearExpression(
658           CastedValue(Index, 0, SExtBits, TruncBits), DL, 0, AC, DT);
659 
660       // Scale by the type size.
661       unsigned TypeSize =
662           DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize();
663       LE = LE.mul(APInt(IndexSize, TypeSize), GEPOp->isInBounds());
664       Decomposed.Offset += LE.Offset.sextOrSelf(MaxIndexSize);
665       APInt Scale = LE.Scale.sextOrSelf(MaxIndexSize);
666 
667       // If we already had an occurrence of this index variable, merge this
668       // scale into it.  For example, we want to handle:
669       //   A[x][x] -> x*16 + x*4 -> x*20
670       // This also ensures that 'x' only appears in the index list once.
671       for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
672         if (Decomposed.VarIndices[i].Val.V == LE.Val.V &&
673             Decomposed.VarIndices[i].Val.hasSameCastsAs(LE.Val)) {
674           Scale += Decomposed.VarIndices[i].Scale;
675           Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
676           break;
677         }
678       }
679 
680       // Make sure that we have a scale that makes sense for this target's
681       // index size.
682       Scale = adjustToIndexSize(Scale, IndexSize);
683 
684       if (!!Scale) {
685         VariableGEPIndex Entry = {LE.Val, Scale, CxtI, LE.IsNSW};
686         Decomposed.VarIndices.push_back(Entry);
687       }
688     }
689 
690     // Take care of wrap-arounds
691     if (GepHasConstantOffset)
692       Decomposed.Offset = adjustToIndexSize(Decomposed.Offset, IndexSize);
693 
694     // Analyze the base pointer next.
695     V = GEPOp->getOperand(0);
696   } while (--MaxLookup);
697 
698   // If the chain of expressions is too deep, just return early.
699   Decomposed.Base = V;
700   SearchLimitReached++;
701   return Decomposed;
702 }
703 
704 /// Returns whether the given pointer value points to memory that is local to
705 /// the function, with global constants being considered local to all
706 /// functions.
707 bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
708                                            AAQueryInfo &AAQI, bool OrLocal) {
709   assert(Visited.empty() && "Visited must be cleared after use!");
710 
711   unsigned MaxLookup = 8;
712   SmallVector<const Value *, 16> Worklist;
713   Worklist.push_back(Loc.Ptr);
714   do {
715     const Value *V = getUnderlyingObject(Worklist.pop_back_val());
716     if (!Visited.insert(V).second) {
717       Visited.clear();
718       return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
719     }
720 
721     // An alloca instruction defines local memory.
722     if (OrLocal && isa<AllocaInst>(V))
723       continue;
724 
725     // A global constant counts as local memory for our purposes.
726     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
727       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
728       // global to be marked constant in some modules and non-constant in
729       // others.  GV may even be a declaration, not a definition.
730       if (!GV->isConstant()) {
731         Visited.clear();
732         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
733       }
734       continue;
735     }
736 
737     // If both select values point to local memory, then so does the select.
738     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
739       Worklist.push_back(SI->getTrueValue());
740       Worklist.push_back(SI->getFalseValue());
741       continue;
742     }
743 
744     // If all values incoming to a phi node point to local memory, then so does
745     // the phi.
746     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
747       // Don't bother inspecting phi nodes with many operands.
748       if (PN->getNumIncomingValues() > MaxLookup) {
749         Visited.clear();
750         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
751       }
752       append_range(Worklist, PN->incoming_values());
753       continue;
754     }
755 
756     // Otherwise be conservative.
757     Visited.clear();
758     return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
759   } while (!Worklist.empty() && --MaxLookup);
760 
761   Visited.clear();
762   return Worklist.empty();
763 }
764 
765 static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
766   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call);
767   return II && II->getIntrinsicID() == IID;
768 }
769 
770 /// Returns the behavior when calling the given call site.
771 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) {
772   if (Call->doesNotAccessMemory())
773     // Can't do better than this.
774     return FMRB_DoesNotAccessMemory;
775 
776   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
777 
778   // If the callsite knows it only reads memory, don't return worse
779   // than that.
780   if (Call->onlyReadsMemory())
781     Min = FMRB_OnlyReadsMemory;
782   else if (Call->onlyWritesMemory())
783     Min = FMRB_OnlyWritesMemory;
784 
785   if (Call->onlyAccessesArgMemory())
786     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
787   else if (Call->onlyAccessesInaccessibleMemory())
788     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
789   else if (Call->onlyAccessesInaccessibleMemOrArgMem())
790     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
791 
792   // If the call has operand bundles then aliasing attributes from the function
793   // it calls do not directly apply to the call.  This can be made more precise
794   // in the future.
795   if (!Call->hasOperandBundles())
796     if (const Function *F = Call->getCalledFunction())
797       Min =
798           FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F));
799 
800   return Min;
801 }
802 
803 /// Returns the behavior when calling the given function. For use when the call
804 /// site is not known.
805 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
806   // If the function declares it doesn't access memory, we can't do better.
807   if (F->doesNotAccessMemory())
808     return FMRB_DoesNotAccessMemory;
809 
810   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
811 
812   // If the function declares it only reads memory, go with that.
813   if (F->onlyReadsMemory())
814     Min = FMRB_OnlyReadsMemory;
815   else if (F->onlyWritesMemory())
816     Min = FMRB_OnlyWritesMemory;
817 
818   if (F->onlyAccessesArgMemory())
819     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
820   else if (F->onlyAccessesInaccessibleMemory())
821     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
822   else if (F->onlyAccessesInaccessibleMemOrArgMem())
823     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
824 
825   return Min;
826 }
827 
828 /// Returns true if this is a writeonly (i.e Mod only) parameter.
829 static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx,
830                              const TargetLibraryInfo &TLI) {
831   if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly))
832     return true;
833 
834   // We can bound the aliasing properties of memset_pattern16 just as we can
835   // for memcpy/memset.  This is particularly important because the
836   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
837   // whenever possible.
838   // FIXME Consider handling this in InferFunctionAttr.cpp together with other
839   // attributes.
840   LibFunc F;
841   if (Call->getCalledFunction() &&
842       TLI.getLibFunc(*Call->getCalledFunction(), F) &&
843       F == LibFunc_memset_pattern16 && TLI.has(F))
844     if (ArgIdx == 0)
845       return true;
846 
847   // TODO: memset_pattern4, memset_pattern8
848   // TODO: _chk variants
849   // TODO: strcmp, strcpy
850 
851   return false;
852 }
853 
854 ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,
855                                            unsigned ArgIdx) {
856   // Checking for known builtin intrinsics and target library functions.
857   if (isWriteOnlyParam(Call, ArgIdx, TLI))
858     return ModRefInfo::Mod;
859 
860   if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly))
861     return ModRefInfo::Ref;
862 
863   if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone))
864     return ModRefInfo::NoModRef;
865 
866   return AAResultBase::getArgModRefInfo(Call, ArgIdx);
867 }
868 
869 #ifndef NDEBUG
870 static const Function *getParent(const Value *V) {
871   if (const Instruction *inst = dyn_cast<Instruction>(V)) {
872     if (!inst->getParent())
873       return nullptr;
874     return inst->getParent()->getParent();
875   }
876 
877   if (const Argument *arg = dyn_cast<Argument>(V))
878     return arg->getParent();
879 
880   return nullptr;
881 }
882 
883 static bool notDifferentParent(const Value *O1, const Value *O2) {
884 
885   const Function *F1 = getParent(O1);
886   const Function *F2 = getParent(O2);
887 
888   return !F1 || !F2 || F1 == F2;
889 }
890 #endif
891 
892 AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
893                                  const MemoryLocation &LocB,
894                                  AAQueryInfo &AAQI) {
895   assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
896          "BasicAliasAnalysis doesn't support interprocedural queries.");
897   return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI);
898 }
899 
900 /// Checks to see if the specified callsite can clobber the specified memory
901 /// object.
902 ///
903 /// Since we only look at local properties of this function, we really can't
904 /// say much about this query.  We do, however, use simple "address taken"
905 /// analysis on local objects.
906 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,
907                                         const MemoryLocation &Loc,
908                                         AAQueryInfo &AAQI) {
909   assert(notDifferentParent(Call, Loc.Ptr) &&
910          "AliasAnalysis query involving multiple functions!");
911 
912   const Value *Object = getUnderlyingObject(Loc.Ptr);
913 
914   // Calls marked 'tail' cannot read or write allocas from the current frame
915   // because the current frame might be destroyed by the time they run. However,
916   // a tail call may use an alloca with byval. Calling with byval copies the
917   // contents of the alloca into argument registers or stack slots, so there is
918   // no lifetime issue.
919   if (isa<AllocaInst>(Object))
920     if (const CallInst *CI = dyn_cast<CallInst>(Call))
921       if (CI->isTailCall() &&
922           !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
923         return ModRefInfo::NoModRef;
924 
925   // Stack restore is able to modify unescaped dynamic allocas. Assume it may
926   // modify them even though the alloca is not escaped.
927   if (auto *AI = dyn_cast<AllocaInst>(Object))
928     if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))
929       return ModRefInfo::Mod;
930 
931   // If the pointer is to a locally allocated object that does not escape,
932   // then the call can not mod/ref the pointer unless the call takes the pointer
933   // as an argument, and itself doesn't capture it.
934   if (!isa<Constant>(Object) && Call != Object &&
935       AAQI.CI->isNotCapturedBeforeOrAt(Object, Call)) {
936 
937     // Optimistically assume that call doesn't touch Object and check this
938     // assumption in the following loop.
939     ModRefInfo Result = ModRefInfo::NoModRef;
940     bool IsMustAlias = true;
941 
942     unsigned OperandNo = 0;
943     for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
944          CI != CE; ++CI, ++OperandNo) {
945       // Only look at the no-capture or byval pointer arguments.  If this
946       // pointer were passed to arguments that were neither of these, then it
947       // couldn't be no-capture.
948       if (!(*CI)->getType()->isPointerTy() ||
949           (!Call->doesNotCapture(OperandNo) && OperandNo < Call->arg_size() &&
950            !Call->isByValArgument(OperandNo)))
951         continue;
952 
953       // Call doesn't access memory through this operand, so we don't care
954       // if it aliases with Object.
955       if (Call->doesNotAccessMemory(OperandNo))
956         continue;
957 
958       // If this is a no-capture pointer argument, see if we can tell that it
959       // is impossible to alias the pointer we're checking.
960       AliasResult AR = getBestAAResults().alias(
961           MemoryLocation::getBeforeOrAfter(*CI),
962           MemoryLocation::getBeforeOrAfter(Object), AAQI);
963       if (AR != AliasResult::MustAlias)
964         IsMustAlias = false;
965       // Operand doesn't alias 'Object', continue looking for other aliases
966       if (AR == AliasResult::NoAlias)
967         continue;
968       // Operand aliases 'Object', but call doesn't modify it. Strengthen
969       // initial assumption and keep looking in case if there are more aliases.
970       if (Call->onlyReadsMemory(OperandNo)) {
971         Result = setRef(Result);
972         continue;
973       }
974       // Operand aliases 'Object' but call only writes into it.
975       if (Call->onlyWritesMemory(OperandNo)) {
976         Result = setMod(Result);
977         continue;
978       }
979       // This operand aliases 'Object' and call reads and writes into it.
980       // Setting ModRef will not yield an early return below, MustAlias is not
981       // used further.
982       Result = ModRefInfo::ModRef;
983       break;
984     }
985 
986     // No operand aliases, reset Must bit. Add below if at least one aliases
987     // and all aliases found are MustAlias.
988     if (isNoModRef(Result))
989       IsMustAlias = false;
990 
991     // Early return if we improved mod ref information
992     if (!isModAndRefSet(Result)) {
993       if (isNoModRef(Result))
994         return ModRefInfo::NoModRef;
995       return IsMustAlias ? setMust(Result) : clearMust(Result);
996     }
997   }
998 
999   // If the call is malloc/calloc like, we can assume that it doesn't
1000   // modify any IR visible value.  This is only valid because we assume these
1001   // routines do not read values visible in the IR.  TODO: Consider special
1002   // casing realloc and strdup routines which access only their arguments as
1003   // well.  Or alternatively, replace all of this with inaccessiblememonly once
1004   // that's implemented fully.
1005   if (isMallocOrCallocLikeFn(Call, &TLI)) {
1006     // Be conservative if the accessed pointer may alias the allocation -
1007     // fallback to the generic handling below.
1008     if (getBestAAResults().alias(MemoryLocation::getBeforeOrAfter(Call), Loc,
1009                                  AAQI) == AliasResult::NoAlias)
1010       return ModRefInfo::NoModRef;
1011   }
1012 
1013   // Ideally, there should be no need to special case for memcpy/memove
1014   // intrinsics here since general machinery (based on memory attributes) should
1015   // already handle it just fine. Unfortunately, it doesn't due to deficiency in
1016   // operand bundles support. At the moment it's not clear if complexity behind
1017   // enhancing general mechanism worths it.
1018   // TODO: Consider improving operand bundles support in general mechanism.
1019   if (auto *Inst = dyn_cast<AnyMemTransferInst>(Call)) {
1020     AliasResult SrcAA =
1021         getBestAAResults().alias(MemoryLocation::getForSource(Inst), Loc, AAQI);
1022     AliasResult DestAA =
1023         getBestAAResults().alias(MemoryLocation::getForDest(Inst), Loc, AAQI);
1024     // It's also possible for Loc to alias both src and dest, or neither.
1025     ModRefInfo rv = ModRefInfo::NoModRef;
1026     if (SrcAA != AliasResult::NoAlias || Call->hasReadingOperandBundles())
1027       rv = setRef(rv);
1028     if (DestAA != AliasResult::NoAlias || Call->hasClobberingOperandBundles())
1029       rv = setMod(rv);
1030     return rv;
1031   }
1032 
1033   // Guard intrinsics are marked as arbitrarily writing so that proper control
1034   // dependencies are maintained but they never mods any particular memory
1035   // location.
1036   //
1037   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
1038   // heap state at the point the guard is issued needs to be consistent in case
1039   // the guard invokes the "deopt" continuation.
1040   if (isIntrinsicCall(Call, Intrinsic::experimental_guard))
1041     return ModRefInfo::Ref;
1042   // The same applies to deoptimize which is essentially a guard(false).
1043   if (isIntrinsicCall(Call, Intrinsic::experimental_deoptimize))
1044     return ModRefInfo::Ref;
1045 
1046   // Like assumes, invariant.start intrinsics were also marked as arbitrarily
1047   // writing so that proper control dependencies are maintained but they never
1048   // mod any particular memory location visible to the IR.
1049   // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
1050   // intrinsic is now modeled as reading memory. This prevents hoisting the
1051   // invariant.start intrinsic over stores. Consider:
1052   // *ptr = 40;
1053   // *ptr = 50;
1054   // invariant_start(ptr)
1055   // int val = *ptr;
1056   // print(val);
1057   //
1058   // This cannot be transformed to:
1059   //
1060   // *ptr = 40;
1061   // invariant_start(ptr)
1062   // *ptr = 50;
1063   // int val = *ptr;
1064   // print(val);
1065   //
1066   // The transformation will cause the second store to be ignored (based on
1067   // rules of invariant.start)  and print 40, while the first program always
1068   // prints 50.
1069   if (isIntrinsicCall(Call, Intrinsic::invariant_start))
1070     return ModRefInfo::Ref;
1071 
1072   // The AAResultBase base class has some smarts, lets use them.
1073   return AAResultBase::getModRefInfo(Call, Loc, AAQI);
1074 }
1075 
1076 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,
1077                                         const CallBase *Call2,
1078                                         AAQueryInfo &AAQI) {
1079   // Guard intrinsics are marked as arbitrarily writing so that proper control
1080   // dependencies are maintained but they never mods any particular memory
1081   // location.
1082   //
1083   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
1084   // heap state at the point the guard is issued needs to be consistent in case
1085   // the guard invokes the "deopt" continuation.
1086 
1087   // NB! This function is *not* commutative, so we special case two
1088   // possibilities for guard intrinsics.
1089 
1090   if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))
1091     return isModSet(createModRefInfo(getModRefBehavior(Call2)))
1092                ? ModRefInfo::Ref
1093                : ModRefInfo::NoModRef;
1094 
1095   if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
1096     return isModSet(createModRefInfo(getModRefBehavior(Call1)))
1097                ? ModRefInfo::Mod
1098                : ModRefInfo::NoModRef;
1099 
1100   // The AAResultBase base class has some smarts, lets use them.
1101   return AAResultBase::getModRefInfo(Call1, Call2, AAQI);
1102 }
1103 
1104 /// Return true if we know V to the base address of the corresponding memory
1105 /// object.  This implies that any address less than V must be out of bounds
1106 /// for the underlying object.  Note that just being isIdentifiedObject() is
1107 /// not enough - For example, a negative offset from a noalias argument or call
1108 /// can be inbounds w.r.t the actual underlying object.
1109 static bool isBaseOfObject(const Value *V) {
1110   // TODO: We can handle other cases here
1111   // 1) For GC languages, arguments to functions are often required to be
1112   //    base pointers.
1113   // 2) Result of allocation routines are often base pointers.  Leverage TLI.
1114   return (isa<AllocaInst>(V) || isa<GlobalVariable>(V));
1115 }
1116 
1117 /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
1118 /// another pointer.
1119 ///
1120 /// We know that V1 is a GEP, but we don't know anything about V2.
1121 /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for
1122 /// V2.
1123 AliasResult BasicAAResult::aliasGEP(
1124     const GEPOperator *GEP1, LocationSize V1Size,
1125     const Value *V2, LocationSize V2Size,
1126     const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
1127   if (!V1Size.hasValue() && !V2Size.hasValue()) {
1128     // TODO: This limitation exists for compile-time reasons. Relax it if we
1129     // can avoid exponential pathological cases.
1130     if (!isa<GEPOperator>(V2))
1131       return AliasResult::MayAlias;
1132 
1133     // If both accesses have unknown size, we can only check whether the base
1134     // objects don't alias.
1135     AliasResult BaseAlias = getBestAAResults().alias(
1136         MemoryLocation::getBeforeOrAfter(UnderlyingV1),
1137         MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI);
1138     return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias
1139                                              : AliasResult::MayAlias;
1140   }
1141 
1142   DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT);
1143   DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT);
1144 
1145   // Bail if we were not able to decompose anything.
1146   if (DecompGEP1.Base == GEP1 && DecompGEP2.Base == V2)
1147     return AliasResult::MayAlias;
1148 
1149   // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1150   // symbolic difference.
1151   subtractDecomposedGEPs(DecompGEP1, DecompGEP2);
1152 
1153   // If an inbounds GEP would have to start from an out of bounds address
1154   // for the two to alias, then we can assume noalias.
1155   if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() &&
1156       V2Size.hasValue() && DecompGEP1.Offset.sge(V2Size.getValue()) &&
1157       isBaseOfObject(DecompGEP2.Base))
1158     return AliasResult::NoAlias;
1159 
1160   if (isa<GEPOperator>(V2)) {
1161     // Symmetric case to above.
1162     if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() &&
1163         V1Size.hasValue() && DecompGEP1.Offset.sle(-V1Size.getValue()) &&
1164         isBaseOfObject(DecompGEP1.Base))
1165       return AliasResult::NoAlias;
1166   }
1167 
1168   // For GEPs with identical offsets, we can preserve the size and AAInfo
1169   // when performing the alias check on the underlying objects.
1170   if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty())
1171     return getBestAAResults().alias(MemoryLocation(DecompGEP1.Base, V1Size),
1172                                     MemoryLocation(DecompGEP2.Base, V2Size),
1173                                     AAQI);
1174 
1175   // Do the base pointers alias?
1176   AliasResult BaseAlias = getBestAAResults().alias(
1177       MemoryLocation::getBeforeOrAfter(DecompGEP1.Base),
1178       MemoryLocation::getBeforeOrAfter(DecompGEP2.Base), AAQI);
1179 
1180   // If we get a No or May, then return it immediately, no amount of analysis
1181   // will improve this situation.
1182   if (BaseAlias != AliasResult::MustAlias) {
1183     assert(BaseAlias == AliasResult::NoAlias ||
1184            BaseAlias == AliasResult::MayAlias);
1185     return BaseAlias;
1186   }
1187 
1188   // If there is a constant difference between the pointers, but the difference
1189   // is less than the size of the associated memory object, then we know
1190   // that the objects are partially overlapping.  If the difference is
1191   // greater, we know they do not overlap.
1192   if (DecompGEP1.VarIndices.empty()) {
1193     APInt &Off = DecompGEP1.Offset;
1194 
1195     // Initialize for Off >= 0 (V2 <= GEP1) case.
1196     const Value *LeftPtr = V2;
1197     const Value *RightPtr = GEP1;
1198     LocationSize VLeftSize = V2Size;
1199     LocationSize VRightSize = V1Size;
1200     const bool Swapped = Off.isNegative();
1201 
1202     if (Swapped) {
1203       // Swap if we have the situation where:
1204       // +                +
1205       // | BaseOffset     |
1206       // ---------------->|
1207       // |-->V1Size       |-------> V2Size
1208       // GEP1             V2
1209       std::swap(LeftPtr, RightPtr);
1210       std::swap(VLeftSize, VRightSize);
1211       Off = -Off;
1212     }
1213 
1214     if (!VLeftSize.hasValue())
1215       return AliasResult::MayAlias;
1216 
1217     const uint64_t LSize = VLeftSize.getValue();
1218     if (Off.ult(LSize)) {
1219       // Conservatively drop processing if a phi was visited and/or offset is
1220       // too big.
1221       AliasResult AR = AliasResult::PartialAlias;
1222       if (VRightSize.hasValue() && Off.ule(INT32_MAX) &&
1223           (Off + VRightSize.getValue()).ule(LSize)) {
1224         // Memory referenced by right pointer is nested. Save the offset in
1225         // cache. Note that originally offset estimated as GEP1-V2, but
1226         // AliasResult contains the shift that represents GEP1+Offset=V2.
1227         AR.setOffset(-Off.getSExtValue());
1228         AR.swap(Swapped);
1229       }
1230       return AR;
1231     }
1232     return AliasResult::NoAlias;
1233   }
1234 
1235   // We need to know both acess sizes for all the following heuristics.
1236   if (!V1Size.hasValue() || !V2Size.hasValue())
1237     return AliasResult::MayAlias;
1238 
1239   APInt GCD;
1240   ConstantRange OffsetRange = ConstantRange(DecompGEP1.Offset);
1241   for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
1242     const VariableGEPIndex &Index = DecompGEP1.VarIndices[i];
1243     const APInt &Scale = Index.Scale;
1244     APInt ScaleForGCD = Scale;
1245     if (!Index.IsNSW)
1246       ScaleForGCD = APInt::getOneBitSet(Scale.getBitWidth(),
1247                                         Scale.countTrailingZeros());
1248 
1249     if (i == 0)
1250       GCD = ScaleForGCD.abs();
1251     else
1252       GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs());
1253 
1254     ConstantRange CR = computeConstantRange(Index.Val.V, /* ForSigned */ false,
1255                                             true, &AC, Index.CxtI);
1256     KnownBits Known =
1257         computeKnownBits(Index.Val.V, DL, 0, &AC, Index.CxtI, DT);
1258     CR = CR.intersectWith(
1259         ConstantRange::fromKnownBits(Known, /* Signed */ true),
1260         ConstantRange::Signed);
1261     CR = Index.Val.evaluateWith(CR).sextOrTrunc(OffsetRange.getBitWidth());
1262 
1263     assert(OffsetRange.getBitWidth() == Scale.getBitWidth() &&
1264            "Bit widths are normalized to MaxIndexSize");
1265     if (Index.IsNSW)
1266       OffsetRange = OffsetRange.add(CR.smul_sat(ConstantRange(Scale)));
1267     else
1268       OffsetRange = OffsetRange.add(CR.smul_fast(ConstantRange(Scale)));
1269   }
1270 
1271   // We now have accesses at two offsets from the same base:
1272   //  1. (...)*GCD + DecompGEP1.Offset with size V1Size
1273   //  2. 0 with size V2Size
1274   // Using arithmetic modulo GCD, the accesses are at
1275   // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits
1276   // into the range [V2Size..GCD), then we know they cannot overlap.
1277   APInt ModOffset = DecompGEP1.Offset.srem(GCD);
1278   if (ModOffset.isNegative())
1279     ModOffset += GCD; // We want mod, not rem.
1280   if (ModOffset.uge(V2Size.getValue()) &&
1281       (GCD - ModOffset).uge(V1Size.getValue()))
1282     return AliasResult::NoAlias;
1283 
1284   // Compute ranges of potentially accessed bytes for both accesses. If the
1285   // interseciton is empty, there can be no overlap.
1286   unsigned BW = OffsetRange.getBitWidth();
1287   ConstantRange Range1 = OffsetRange.add(
1288       ConstantRange(APInt(BW, 0), APInt(BW, V1Size.getValue())));
1289   ConstantRange Range2 =
1290       ConstantRange(APInt(BW, 0), APInt(BW, V2Size.getValue()));
1291   if (Range1.intersectWith(Range2).isEmptySet())
1292     return AliasResult::NoAlias;
1293 
1294   // Try to determine the range of values for VarIndex such that
1295   // VarIndex <= -MinAbsVarIndex || MinAbsVarIndex <= VarIndex.
1296   Optional<APInt> MinAbsVarIndex;
1297   if (DecompGEP1.VarIndices.size() == 1) {
1298     // VarIndex = Scale*V.
1299     const VariableGEPIndex &Var = DecompGEP1.VarIndices[0];
1300     if (Var.Val.TruncBits == 0 &&
1301         isKnownNonZero(Var.Val.V, DL, 0, &AC, Var.CxtI, DT)) {
1302       // If V != 0 then abs(VarIndex) >= abs(Scale).
1303       MinAbsVarIndex = Var.Scale.abs();
1304     }
1305   } else if (DecompGEP1.VarIndices.size() == 2) {
1306     // VarIndex = Scale*V0 + (-Scale)*V1.
1307     // If V0 != V1 then abs(VarIndex) >= abs(Scale).
1308     // Check that VisitedPhiBBs is empty, to avoid reasoning about
1309     // inequality of values across loop iterations.
1310     const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0];
1311     const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1];
1312     if (Var0.Scale == -Var1.Scale && Var0.Val.TruncBits == 0 &&
1313         Var0.Val.hasSameCastsAs(Var1.Val) && VisitedPhiBBs.empty() &&
1314         isKnownNonEqual(Var0.Val.V, Var1.Val.V, DL, &AC, /* CxtI */ nullptr,
1315                         DT))
1316       MinAbsVarIndex = Var0.Scale.abs();
1317   }
1318 
1319   if (MinAbsVarIndex) {
1320     // The constant offset will have added at least +/-MinAbsVarIndex to it.
1321     APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex;
1322     APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex;
1323     // We know that Offset <= OffsetLo || Offset >= OffsetHi
1324     if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) &&
1325         OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue()))
1326       return AliasResult::NoAlias;
1327   }
1328 
1329   if (constantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT))
1330     return AliasResult::NoAlias;
1331 
1332   // Statically, we can see that the base objects are the same, but the
1333   // pointers have dynamic offsets which we can't resolve. And none of our
1334   // little tricks above worked.
1335   return AliasResult::MayAlias;
1336 }
1337 
1338 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
1339   // If the results agree, take it.
1340   if (A == B)
1341     return A;
1342   // A mix of PartialAlias and MustAlias is PartialAlias.
1343   if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) ||
1344       (B == AliasResult::PartialAlias && A == AliasResult::MustAlias))
1345     return AliasResult::PartialAlias;
1346   // Otherwise, we don't know anything.
1347   return AliasResult::MayAlias;
1348 }
1349 
1350 /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
1351 /// against another.
1352 AliasResult
1353 BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
1354                            const Value *V2, LocationSize V2Size,
1355                            AAQueryInfo &AAQI) {
1356   // If the values are Selects with the same condition, we can do a more precise
1357   // check: just check for aliases between the values on corresponding arms.
1358   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1359     if (SI->getCondition() == SI2->getCondition()) {
1360       AliasResult Alias = getBestAAResults().alias(
1361           MemoryLocation(SI->getTrueValue(), SISize),
1362           MemoryLocation(SI2->getTrueValue(), V2Size), AAQI);
1363       if (Alias == AliasResult::MayAlias)
1364         return AliasResult::MayAlias;
1365       AliasResult ThisAlias = getBestAAResults().alias(
1366           MemoryLocation(SI->getFalseValue(), SISize),
1367           MemoryLocation(SI2->getFalseValue(), V2Size), AAQI);
1368       return MergeAliasResults(ThisAlias, Alias);
1369     }
1370 
1371   // If both arms of the Select node NoAlias or MustAlias V2, then returns
1372   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1373   AliasResult Alias = getBestAAResults().alias(
1374       MemoryLocation(V2, V2Size),
1375       MemoryLocation(SI->getTrueValue(), SISize), AAQI);
1376   if (Alias == AliasResult::MayAlias)
1377     return AliasResult::MayAlias;
1378 
1379   AliasResult ThisAlias = getBestAAResults().alias(
1380       MemoryLocation(V2, V2Size),
1381       MemoryLocation(SI->getFalseValue(), SISize), AAQI);
1382   return MergeAliasResults(ThisAlias, Alias);
1383 }
1384 
1385 /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
1386 /// another.
1387 AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
1388                                     const Value *V2, LocationSize V2Size,
1389                                     AAQueryInfo &AAQI) {
1390   if (!PN->getNumIncomingValues())
1391     return AliasResult::NoAlias;
1392   // If the values are PHIs in the same block, we can do a more precise
1393   // as well as efficient check: just check for aliases between the values
1394   // on corresponding edges.
1395   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1396     if (PN2->getParent() == PN->getParent()) {
1397       Optional<AliasResult> Alias;
1398       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1399         AliasResult ThisAlias = getBestAAResults().alias(
1400             MemoryLocation(PN->getIncomingValue(i), PNSize),
1401             MemoryLocation(
1402                 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size),
1403             AAQI);
1404         if (Alias)
1405           *Alias = MergeAliasResults(*Alias, ThisAlias);
1406         else
1407           Alias = ThisAlias;
1408         if (*Alias == AliasResult::MayAlias)
1409           break;
1410       }
1411       return *Alias;
1412     }
1413 
1414   SmallVector<Value *, 4> V1Srcs;
1415   // If a phi operand recurses back to the phi, we can still determine NoAlias
1416   // if we don't alias the underlying objects of the other phi operands, as we
1417   // know that the recursive phi needs to be based on them in some way.
1418   bool isRecursive = false;
1419   auto CheckForRecPhi = [&](Value *PV) {
1420     if (!EnableRecPhiAnalysis)
1421       return false;
1422     if (getUnderlyingObject(PV) == PN) {
1423       isRecursive = true;
1424       return true;
1425     }
1426     return false;
1427   };
1428 
1429   if (PV) {
1430     // If we have PhiValues then use it to get the underlying phi values.
1431     const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN);
1432     // If we have more phi values than the search depth then return MayAlias
1433     // conservatively to avoid compile time explosion. The worst possible case
1434     // is if both sides are PHI nodes. In which case, this is O(m x n) time
1435     // where 'm' and 'n' are the number of PHI sources.
1436     if (PhiValueSet.size() > MaxLookupSearchDepth)
1437       return AliasResult::MayAlias;
1438     // Add the values to V1Srcs
1439     for (Value *PV1 : PhiValueSet) {
1440       if (CheckForRecPhi(PV1))
1441         continue;
1442       V1Srcs.push_back(PV1);
1443     }
1444   } else {
1445     // If we don't have PhiInfo then just look at the operands of the phi itself
1446     // FIXME: Remove this once we can guarantee that we have PhiInfo always
1447     SmallPtrSet<Value *, 4> UniqueSrc;
1448     Value *OnePhi = nullptr;
1449     for (Value *PV1 : PN->incoming_values()) {
1450       if (isa<PHINode>(PV1)) {
1451         if (OnePhi && OnePhi != PV1) {
1452           // To control potential compile time explosion, we choose to be
1453           // conserviate when we have more than one Phi input.  It is important
1454           // that we handle the single phi case as that lets us handle LCSSA
1455           // phi nodes and (combined with the recursive phi handling) simple
1456           // pointer induction variable patterns.
1457           return AliasResult::MayAlias;
1458         }
1459         OnePhi = PV1;
1460       }
1461 
1462       if (CheckForRecPhi(PV1))
1463         continue;
1464 
1465       if (UniqueSrc.insert(PV1).second)
1466         V1Srcs.push_back(PV1);
1467     }
1468 
1469     if (OnePhi && UniqueSrc.size() > 1)
1470       // Out of an abundance of caution, allow only the trivial lcssa and
1471       // recursive phi cases.
1472       return AliasResult::MayAlias;
1473   }
1474 
1475   // If V1Srcs is empty then that means that the phi has no underlying non-phi
1476   // value. This should only be possible in blocks unreachable from the entry
1477   // block, but return MayAlias just in case.
1478   if (V1Srcs.empty())
1479     return AliasResult::MayAlias;
1480 
1481   // If this PHI node is recursive, indicate that the pointer may be moved
1482   // across iterations. We can only prove NoAlias if different underlying
1483   // objects are involved.
1484   if (isRecursive)
1485     PNSize = LocationSize::beforeOrAfterPointer();
1486 
1487   // In the recursive alias queries below, we may compare values from two
1488   // different loop iterations. Keep track of visited phi blocks, which will
1489   // be used when determining value equivalence.
1490   bool BlockInserted = VisitedPhiBBs.insert(PN->getParent()).second;
1491   auto _ = make_scope_exit([&]() {
1492     if (BlockInserted)
1493       VisitedPhiBBs.erase(PN->getParent());
1494   });
1495 
1496   // If we inserted a block into VisitedPhiBBs, alias analysis results that
1497   // have been cached earlier may no longer be valid. Perform recursive queries
1498   // with a new AAQueryInfo.
1499   AAQueryInfo NewAAQI = AAQI.withEmptyCache();
1500   AAQueryInfo *UseAAQI = BlockInserted ? &NewAAQI : &AAQI;
1501 
1502   AliasResult Alias = getBestAAResults().alias(
1503       MemoryLocation(V2, V2Size),
1504       MemoryLocation(V1Srcs[0], PNSize), *UseAAQI);
1505 
1506   // Early exit if the check of the first PHI source against V2 is MayAlias.
1507   // Other results are not possible.
1508   if (Alias == AliasResult::MayAlias)
1509     return AliasResult::MayAlias;
1510   // With recursive phis we cannot guarantee that MustAlias/PartialAlias will
1511   // remain valid to all elements and needs to conservatively return MayAlias.
1512   if (isRecursive && Alias != AliasResult::NoAlias)
1513     return AliasResult::MayAlias;
1514 
1515   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1516   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1517   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1518     Value *V = V1Srcs[i];
1519 
1520     AliasResult ThisAlias = getBestAAResults().alias(
1521         MemoryLocation(V2, V2Size), MemoryLocation(V, PNSize), *UseAAQI);
1522     Alias = MergeAliasResults(ThisAlias, Alias);
1523     if (Alias == AliasResult::MayAlias)
1524       break;
1525   }
1526 
1527   return Alias;
1528 }
1529 
1530 /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
1531 /// array references.
1532 AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
1533                                       const Value *V2, LocationSize V2Size,
1534                                       AAQueryInfo &AAQI) {
1535   // If either of the memory references is empty, it doesn't matter what the
1536   // pointer values are.
1537   if (V1Size.isZero() || V2Size.isZero())
1538     return AliasResult::NoAlias;
1539 
1540   // Strip off any casts if they exist.
1541   V1 = V1->stripPointerCastsForAliasAnalysis();
1542   V2 = V2->stripPointerCastsForAliasAnalysis();
1543 
1544   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1545   // value for undef that aliases nothing in the program.
1546   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1547     return AliasResult::NoAlias;
1548 
1549   // Are we checking for alias of the same value?
1550   // Because we look 'through' phi nodes, we could look at "Value" pointers from
1551   // different iterations. We must therefore make sure that this is not the
1552   // case. The function isValueEqualInPotentialCycles ensures that this cannot
1553   // happen by looking at the visited phi nodes and making sure they cannot
1554   // reach the value.
1555   if (isValueEqualInPotentialCycles(V1, V2))
1556     return AliasResult::MustAlias;
1557 
1558   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1559     return AliasResult::NoAlias; // Scalars cannot alias each other
1560 
1561   // Figure out what objects these things are pointing to if we can.
1562   const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth);
1563   const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth);
1564 
1565   // Null values in the default address space don't point to any object, so they
1566   // don't alias any other pointer.
1567   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1568     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1569       return AliasResult::NoAlias;
1570   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1571     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1572       return AliasResult::NoAlias;
1573 
1574   if (O1 != O2) {
1575     // If V1/V2 point to two different objects, we know that we have no alias.
1576     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1577       return AliasResult::NoAlias;
1578 
1579     // Constant pointers can't alias with non-const isIdentifiedObject objects.
1580     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1581         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1582       return AliasResult::NoAlias;
1583 
1584     // Function arguments can't alias with things that are known to be
1585     // unambigously identified at the function level.
1586     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1587         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1588       return AliasResult::NoAlias;
1589 
1590     // If one pointer is the result of a call/invoke or load and the other is a
1591     // non-escaping local object within the same function, then we know the
1592     // object couldn't escape to a point where the call could return it.
1593     //
1594     // Note that if the pointers are in different functions, there are a
1595     // variety of complications. A call with a nocapture argument may still
1596     // temporary store the nocapture argument's value in a temporary memory
1597     // location if that memory location doesn't escape. Or it may pass a
1598     // nocapture value to other functions as long as they don't capture it.
1599     if (isEscapeSource(O1) &&
1600         AAQI.CI->isNotCapturedBeforeOrAt(O2, cast<Instruction>(O1)))
1601       return AliasResult::NoAlias;
1602     if (isEscapeSource(O2) &&
1603         AAQI.CI->isNotCapturedBeforeOrAt(O1, cast<Instruction>(O2)))
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(
1611           O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL,
1612           TLI, NullIsValidLocation)) ||
1613       (isObjectSmallerThan(
1614           O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL,
1615           TLI, NullIsValidLocation)))
1616     return AliasResult::NoAlias;
1617 
1618   // If one the accesses may be before the accessed pointer, canonicalize this
1619   // by using unknown after-pointer sizes for both accesses. This is
1620   // equivalent, because regardless of which pointer is lower, one of them
1621   // will always came after the other, as long as the underlying objects aren't
1622   // disjoint. We do this so that the rest of BasicAA does not have to deal
1623   // with accesses before the base pointer, and to improve cache utilization by
1624   // merging equivalent states.
1625   if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) {
1626     V1Size = LocationSize::afterPointer();
1627     V2Size = LocationSize::afterPointer();
1628   }
1629 
1630   // FIXME: If this depth limit is hit, then we may cache sub-optimal results
1631   // for recursive queries. For this reason, this limit is chosen to be large
1632   // enough to be very rarely hit, while still being small enough to avoid
1633   // stack overflows.
1634   if (AAQI.Depth >= 512)
1635     return AliasResult::MayAlias;
1636 
1637   // Check the cache before climbing up use-def chains. This also terminates
1638   // otherwise infinitely recursive queries.
1639   AAQueryInfo::LocPair Locs({V1, V1Size}, {V2, V2Size});
1640   const bool Swapped = V1 > V2;
1641   if (Swapped)
1642     std::swap(Locs.first, Locs.second);
1643   const auto &Pair = AAQI.AliasCache.try_emplace(
1644       Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0});
1645   if (!Pair.second) {
1646     auto &Entry = Pair.first->second;
1647     if (!Entry.isDefinitive()) {
1648       // Remember that we used an assumption.
1649       ++Entry.NumAssumptionUses;
1650       ++AAQI.NumAssumptionUses;
1651     }
1652     // Cache contains sorted {V1,V2} pairs but we should return original order.
1653     auto Result = Entry.Result;
1654     Result.swap(Swapped);
1655     return Result;
1656   }
1657 
1658   int OrigNumAssumptionUses = AAQI.NumAssumptionUses;
1659   unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size();
1660   AliasResult Result =
1661       aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2);
1662 
1663   auto It = AAQI.AliasCache.find(Locs);
1664   assert(It != AAQI.AliasCache.end() && "Must be in cache");
1665   auto &Entry = It->second;
1666 
1667   // Check whether a NoAlias assumption has been used, but disproven.
1668   bool AssumptionDisproven =
1669       Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias;
1670   if (AssumptionDisproven)
1671     Result = AliasResult::MayAlias;
1672 
1673   // This is a definitive result now, when considered as a root query.
1674   AAQI.NumAssumptionUses -= Entry.NumAssumptionUses;
1675   Entry.Result = Result;
1676   // Cache contains sorted {V1,V2} pairs.
1677   Entry.Result.swap(Swapped);
1678   Entry.NumAssumptionUses = -1;
1679 
1680   // If the assumption has been disproven, remove any results that may have
1681   // been based on this assumption. Do this after the Entry updates above to
1682   // avoid iterator invalidation.
1683   if (AssumptionDisproven)
1684     while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults)
1685       AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val());
1686 
1687   // The result may still be based on assumptions higher up in the chain.
1688   // Remember it, so it can be purged from the cache later.
1689   if (OrigNumAssumptionUses != AAQI.NumAssumptionUses &&
1690       Result != AliasResult::MayAlias)
1691     AAQI.AssumptionBasedResults.push_back(Locs);
1692   return Result;
1693 }
1694 
1695 AliasResult BasicAAResult::aliasCheckRecursive(
1696     const Value *V1, LocationSize V1Size,
1697     const Value *V2, LocationSize V2Size,
1698     AAQueryInfo &AAQI, const Value *O1, const Value *O2) {
1699   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1700     AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI);
1701     if (Result != AliasResult::MayAlias)
1702       return Result;
1703   } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) {
1704     AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI);
1705     Result.swap();
1706     if (Result != AliasResult::MayAlias)
1707       return Result;
1708   }
1709 
1710   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1711     AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI);
1712     if (Result != AliasResult::MayAlias)
1713       return Result;
1714   } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) {
1715     AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI);
1716     Result.swap();
1717     if (Result != AliasResult::MayAlias)
1718       return Result;
1719   }
1720 
1721   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1722     AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI);
1723     if (Result != AliasResult::MayAlias)
1724       return Result;
1725   } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) {
1726     AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI);
1727     Result.swap();
1728     if (Result != AliasResult::MayAlias)
1729       return Result;
1730   }
1731 
1732   // If both pointers are pointing into the same object and one of them
1733   // accesses the entire object, then the accesses must overlap in some way.
1734   if (O1 == O2) {
1735     bool NullIsValidLocation = NullPointerIsDefined(&F);
1736     if (V1Size.isPrecise() && V2Size.isPrecise() &&
1737         (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
1738          isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation)))
1739       return AliasResult::PartialAlias;
1740   }
1741 
1742   return AliasResult::MayAlias;
1743 }
1744 
1745 /// Check whether two Values can be considered equivalent.
1746 ///
1747 /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
1748 /// they can not be part of a cycle in the value graph by looking at all
1749 /// visited phi nodes an making sure that the phis cannot reach the value. We
1750 /// have to do this because we are looking through phi nodes (That is we say
1751 /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
1752 bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
1753                                                   const Value *V2) {
1754   if (V != V2)
1755     return false;
1756 
1757   const Instruction *Inst = dyn_cast<Instruction>(V);
1758   if (!Inst)
1759     return true;
1760 
1761   if (VisitedPhiBBs.empty())
1762     return true;
1763 
1764   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1765     return false;
1766 
1767   // Make sure that the visited phis cannot reach the Value. This ensures that
1768   // the Values cannot come from different iterations of a potential cycle the
1769   // phi nodes could be involved in.
1770   for (auto *P : VisitedPhiBBs)
1771     if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT))
1772       return false;
1773 
1774   return true;
1775 }
1776 
1777 /// Computes the symbolic difference between two de-composed GEPs.
1778 void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP,
1779                                            const DecomposedGEP &SrcGEP) {
1780   DestGEP.Offset -= SrcGEP.Offset;
1781   for (const VariableGEPIndex &Src : SrcGEP.VarIndices) {
1782     // Find V in Dest.  This is N^2, but pointer indices almost never have more
1783     // than a few variable indexes.
1784     bool Found = false;
1785     for (auto I : enumerate(DestGEP.VarIndices)) {
1786       VariableGEPIndex &Dest = I.value();
1787       if (!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V) ||
1788           !Dest.Val.hasSameCastsAs(Src.Val))
1789         continue;
1790 
1791       // If we found it, subtract off Scale V's from the entry in Dest.  If it
1792       // goes to zero, remove the entry.
1793       if (Dest.Scale != Src.Scale) {
1794         Dest.Scale -= Src.Scale;
1795         Dest.IsNSW = false;
1796       } else {
1797         DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index());
1798       }
1799       Found = true;
1800       break;
1801     }
1802 
1803     // If we didn't consume this entry, add it to the end of the Dest list.
1804     if (!Found) {
1805       VariableGEPIndex Entry = {Src.Val, -Src.Scale, Src.CxtI, Src.IsNSW};
1806       DestGEP.VarIndices.push_back(Entry);
1807     }
1808   }
1809 }
1810 
1811 bool BasicAAResult::constantOffsetHeuristic(
1812     const DecomposedGEP &GEP, LocationSize MaybeV1Size,
1813     LocationSize MaybeV2Size, AssumptionCache *AC, DominatorTree *DT) {
1814   if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() ||
1815       !MaybeV2Size.hasValue())
1816     return false;
1817 
1818   const uint64_t V1Size = MaybeV1Size.getValue();
1819   const uint64_t V2Size = MaybeV2Size.getValue();
1820 
1821   const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1];
1822 
1823   if (Var0.Val.TruncBits != 0 || !Var0.Val.hasSameCastsAs(Var1.Val) ||
1824       Var0.Scale != -Var1.Scale ||
1825       Var0.Val.V->getType() != Var1.Val.V->getType())
1826     return false;
1827 
1828   // We'll strip off the Extensions of Var0 and Var1 and do another round
1829   // of GetLinearExpression decomposition. In the example above, if Var0
1830   // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
1831 
1832   LinearExpression E0 =
1833       GetLinearExpression(CastedValue(Var0.Val.V), DL, 0, AC, DT);
1834   LinearExpression E1 =
1835       GetLinearExpression(CastedValue(Var1.Val.V), DL, 0, AC, DT);
1836   if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(E1.Val) ||
1837       !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V))
1838     return false;
1839 
1840   // We have a hit - Var0 and Var1 only differ by a constant offset!
1841 
1842   // If we've been sext'ed then zext'd the maximum difference between Var0 and
1843   // Var1 is possible to calculate, but we're just interested in the absolute
1844   // minimum difference between the two. The minimum distance may occur due to
1845   // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
1846   // the minimum distance between %i and %i + 5 is 3.
1847   APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff;
1848   MinDiff = APIntOps::umin(MinDiff, Wrapped);
1849   APInt MinDiffBytes =
1850     MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();
1851 
1852   // We can't definitely say whether GEP1 is before or after V2 due to wrapping
1853   // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
1854   // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
1855   // V2Size can fit in the MinDiffBytes gap.
1856   return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) &&
1857          MinDiffBytes.uge(V2Size + GEP.Offset.abs());
1858 }
1859 
1860 //===----------------------------------------------------------------------===//
1861 // BasicAliasAnalysis Pass
1862 //===----------------------------------------------------------------------===//
1863 
1864 AnalysisKey BasicAA::Key;
1865 
1866 BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
1867   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1868   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1869   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1870   auto *PV = AM.getCachedResult<PhiValuesAnalysis>(F);
1871   return BasicAAResult(F.getParent()->getDataLayout(), F, TLI, AC, DT, PV);
1872 }
1873 
1874 BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
1875   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
1876 }
1877 
1878 char BasicAAWrapperPass::ID = 0;
1879 
1880 void BasicAAWrapperPass::anchor() {}
1881 
1882 INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa",
1883                       "Basic Alias Analysis (stateless AA impl)", true, true)
1884 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1885 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1886 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1887 INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass)
1888 INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa",
1889                     "Basic Alias Analysis (stateless AA impl)", true, true)
1890 
1891 FunctionPass *llvm::createBasicAAWrapperPass() {
1892   return new BasicAAWrapperPass();
1893 }
1894 
1895 bool BasicAAWrapperPass::runOnFunction(Function &F) {
1896   auto &ACT = getAnalysis<AssumptionCacheTracker>();
1897   auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
1898   auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
1899   auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>();
1900 
1901   Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F,
1902                                  TLIWP.getTLI(F), ACT.getAssumptionCache(F),
1903                                  &DTWP.getDomTree(),
1904                                  PVWP ? &PVWP->getResult() : nullptr));
1905 
1906   return false;
1907 }
1908 
1909 void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1910   AU.setPreservesAll();
1911   AU.addRequiredTransitive<AssumptionCacheTracker>();
1912   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1913   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
1914   AU.addUsedIfAvailable<PhiValuesWrapperPass>();
1915 }
1916 
1917 BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) {
1918   return BasicAAResult(
1919       F.getParent()->getDataLayout(), F,
1920       P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
1921       P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
1922 }
1923