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