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/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AssumptionCache.h"
22 #include "llvm/Analysis/CFG.h"
23 #include "llvm/Analysis/CaptureTracking.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/LoopInfo.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/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GetElementPtrTypeIterator.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/InstrTypes.h"
43 #include "llvm/IR/Instruction.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/IR/Operator.h"
49 #include "llvm/IR/Type.h"
50 #include "llvm/IR/User.h"
51 #include "llvm/IR/Value.h"
52 #include "llvm/InitializePasses.h"
53 #include "llvm/Pass.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/Support/KnownBits.h"
58 #include <cassert>
59 #include <cstdint>
60 #include <cstdlib>
61 #include <utility>
62 
63 #define DEBUG_TYPE "basicaa"
64 
65 using namespace llvm;
66 
67 /// Enable analysis of recursive PHI nodes.
68 static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden,
69                                           cl::init(true));
70 
71 /// By default, even on 32-bit architectures we use 64-bit integers for
72 /// calculations. This will allow us to more-aggressively decompose indexing
73 /// expressions calculated using i64 values (e.g., long long in C) which is
74 /// common enough to worry about.
75 static cl::opt<bool> ForceAtLeast64Bits("basic-aa-force-at-least-64b",
76                                         cl::Hidden, cl::init(true));
77 static cl::opt<bool> DoubleCalcBits("basic-aa-double-calc-bits",
78                                     cl::Hidden, cl::init(false));
79 
80 /// SearchLimitReached / SearchTimes shows how often the limit of
81 /// to decompose GEPs is reached. It will affect the precision
82 /// of basic alias analysis.
83 STATISTIC(SearchLimitReached, "Number of times the limit to "
84                               "decompose GEPs is reached");
85 STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
86 
87 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
88 /// in a cycle. Because we are analysing 'through' phi nodes, we need to be
89 /// careful with value equivalence. We use reachability to make sure a value
90 /// cannot be involved in a cycle.
91 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
92 
93 // The max limit of the search depth in DecomposeGEPExpression() and
94 // getUnderlyingObject(), both functions need to use the same search
95 // depth otherwise the algorithm in aliasGEP will assert.
96 static const unsigned MaxLookupSearchDepth = 6;
97 
98 bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
99                                FunctionAnalysisManager::Invalidator &Inv) {
100   // We don't care if this analysis itself is preserved, it has no state. But
101   // we need to check that the analyses it depends on have been. Note that we
102   // may be created without handles to some analyses and in that case don't
103   // depend on them.
104   if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
105       (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
106       (LI && Inv.invalidate<LoopAnalysis>(Fn, PA)) ||
107       (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA)))
108     return true;
109 
110   // Otherwise this analysis result remains valid.
111   return false;
112 }
113 
114 //===----------------------------------------------------------------------===//
115 // Useful predicates
116 //===----------------------------------------------------------------------===//
117 
118 /// Returns true if the pointer is one which would have been considered an
119 /// escape by isNonEscapingLocalObject.
120 static bool isEscapeSource(const Value *V) {
121   if (isa<CallBase>(V))
122     return true;
123 
124   if (isa<Argument>(V))
125     return true;
126 
127   // The load case works because isNonEscapingLocalObject considers all
128   // stores to be escapes (it passes true for the StoreCaptures argument
129   // to PointerMayBeCaptured).
130   if (isa<LoadInst>(V))
131     return true;
132 
133   return false;
134 }
135 
136 /// Returns the size of the object specified by V or UnknownSize if unknown.
137 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
138                               const TargetLibraryInfo &TLI,
139                               bool NullIsValidLoc,
140                               bool RoundToAlign = false) {
141   uint64_t Size;
142   ObjectSizeOpts Opts;
143   Opts.RoundToAlign = RoundToAlign;
144   Opts.NullIsUnknownSize = NullIsValidLoc;
145   if (getObjectSize(V, Size, DL, &TLI, Opts))
146     return Size;
147   return MemoryLocation::UnknownSize;
148 }
149 
150 /// Returns true if we can prove that the object specified by V is smaller than
151 /// Size.
152 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
153                                 const DataLayout &DL,
154                                 const TargetLibraryInfo &TLI,
155                                 bool NullIsValidLoc) {
156   // Note that the meanings of the "object" are slightly different in the
157   // following contexts:
158   //    c1: llvm::getObjectSize()
159   //    c2: llvm.objectsize() intrinsic
160   //    c3: isObjectSmallerThan()
161   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
162   // refers to the "entire object".
163   //
164   //  Consider this example:
165   //     char *p = (char*)malloc(100)
166   //     char *q = p+80;
167   //
168   //  In the context of c1 and c2, the "object" pointed by q refers to the
169   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
170   //
171   //  However, in the context of c3, the "object" refers to the chunk of memory
172   // being allocated. So, the "object" has 100 bytes, and q points to the middle
173   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
174   // parameter, before the llvm::getObjectSize() is called to get the size of
175   // entire object, we should:
176   //    - either rewind the pointer q to the base-address of the object in
177   //      question (in this case rewind to p), or
178   //    - just give up. It is up to caller to make sure the pointer is pointing
179   //      to the base address the object.
180   //
181   // We go for 2nd option for simplicity.
182   if (!isIdentifiedObject(V))
183     return false;
184 
185   // This function needs to use the aligned object size because we allow
186   // reads a bit past the end given sufficient alignment.
187   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
188                                       /*RoundToAlign*/ true);
189 
190   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
191 }
192 
193 /// Return the minimal extent from \p V to the end of the underlying object,
194 /// assuming the result is used in an aliasing query. E.g., we do use the query
195 /// location size and the fact that null pointers cannot alias here.
196 static uint64_t getMinimalExtentFrom(const Value &V,
197                                      const LocationSize &LocSize,
198                                      const DataLayout &DL,
199                                      bool NullIsValidLoc) {
200   // If we have dereferenceability information we know a lower bound for the
201   // extent as accesses for a lower offset would be valid. We need to exclude
202   // the "or null" part if null is a valid pointer.
203   bool CanBeNull;
204   uint64_t DerefBytes = V.getPointerDereferenceableBytes(DL, CanBeNull);
205   DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
206   // If queried with a precise location size, we assume that location size to be
207   // accessed, thus valid.
208   if (LocSize.isPrecise())
209     DerefBytes = std::max(DerefBytes, LocSize.getValue());
210   return DerefBytes;
211 }
212 
213 /// Returns true if we can prove that the object specified by V has size Size.
214 static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
215                          const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
216   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc);
217   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
218 }
219 
220 //===----------------------------------------------------------------------===//
221 // GetElementPtr Instruction Decomposition and Analysis
222 //===----------------------------------------------------------------------===//
223 
224 /// Analyzes the specified value as a linear expression: "A*V + B", where A and
225 /// B are constant integers.
226 ///
227 /// Returns the scale and offset values as APInts and return V as a Value*, and
228 /// return whether we looked through any sign or zero extends.  The incoming
229 /// Value is known to have IntegerType, and it may already be sign or zero
230 /// extended.
231 ///
232 /// Note that this looks through extends, so the high bits may not be
233 /// represented in the result.
234 /*static*/ const Value *BasicAAResult::GetLinearExpression(
235     const Value *V, APInt &Scale, APInt &Offset, unsigned &ZExtBits,
236     unsigned &SExtBits, const DataLayout &DL, unsigned Depth,
237     AssumptionCache *AC, DominatorTree *DT, bool &NSW, bool &NUW) {
238   assert(V->getType()->isIntegerTy() && "Not an integer value");
239 
240   // Limit our recursion depth.
241   if (Depth == 6) {
242     Scale = 1;
243     Offset = 0;
244     return V;
245   }
246 
247   if (const ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
248     // If it's a constant, just convert it to an offset and remove the variable.
249     // If we've been called recursively, the Offset bit width will be greater
250     // than the constant's (the Offset's always as wide as the outermost call),
251     // so we'll zext here and process any extension in the isa<SExtInst> &
252     // isa<ZExtInst> cases below.
253     Offset += Const->getValue().zextOrSelf(Offset.getBitWidth());
254     assert(Scale == 0 && "Constant values don't have a scale");
255     return V;
256   }
257 
258   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
259     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
260       // If we've been called recursively, then Offset and Scale will be wider
261       // than the BOp operands. We'll always zext it here as we'll process sign
262       // extensions below (see the isa<SExtInst> / isa<ZExtInst> cases).
263       APInt RHS = RHSC->getValue().zextOrSelf(Offset.getBitWidth());
264 
265       switch (BOp->getOpcode()) {
266       default:
267         // We don't understand this instruction, so we can't decompose it any
268         // further.
269         Scale = 1;
270         Offset = 0;
271         return V;
272       case Instruction::Or:
273         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
274         // analyze it.
275         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
276                                BOp, DT)) {
277           Scale = 1;
278           Offset = 0;
279           return V;
280         }
281         LLVM_FALLTHROUGH;
282       case Instruction::Add:
283         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
284                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
285         Offset += RHS;
286         break;
287       case Instruction::Sub:
288         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
289                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
290         Offset -= RHS;
291         break;
292       case Instruction::Mul:
293         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
294                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
295         Offset *= RHS;
296         Scale *= RHS;
297         break;
298       case Instruction::Shl:
299         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
300                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
301 
302         // We're trying to linearize an expression of the kind:
303         //   shl i8 -128, 36
304         // where the shift count exceeds the bitwidth of the type.
305         // We can't decompose this further (the expression would return
306         // a poison value).
307         if (Offset.getBitWidth() < RHS.getLimitedValue() ||
308             Scale.getBitWidth() < RHS.getLimitedValue()) {
309           Scale = 1;
310           Offset = 0;
311           return V;
312         }
313 
314         Offset <<= RHS.getLimitedValue();
315         Scale <<= RHS.getLimitedValue();
316         // the semantics of nsw and nuw for left shifts don't match those of
317         // multiplications, so we won't propagate them.
318         NSW = NUW = false;
319         return V;
320       }
321 
322       if (isa<OverflowingBinaryOperator>(BOp)) {
323         NUW &= BOp->hasNoUnsignedWrap();
324         NSW &= BOp->hasNoSignedWrap();
325       }
326       return V;
327     }
328   }
329 
330   // Since GEP indices are sign extended anyway, we don't care about the high
331   // bits of a sign or zero extended value - just scales and offsets.  The
332   // extensions have to be consistent though.
333   if (isa<SExtInst>(V) || isa<ZExtInst>(V)) {
334     Value *CastOp = cast<CastInst>(V)->getOperand(0);
335     unsigned NewWidth = V->getType()->getPrimitiveSizeInBits();
336     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
337     unsigned OldZExtBits = ZExtBits, OldSExtBits = SExtBits;
338     const Value *Result =
339         GetLinearExpression(CastOp, Scale, Offset, ZExtBits, SExtBits, DL,
340                             Depth + 1, AC, DT, NSW, NUW);
341 
342     // zext(zext(%x)) == zext(%x), and similarly for sext; we'll handle this
343     // by just incrementing the number of bits we've extended by.
344     unsigned ExtendedBy = NewWidth - SmallWidth;
345 
346     if (isa<SExtInst>(V) && ZExtBits == 0) {
347       // sext(sext(%x, a), b) == sext(%x, a + b)
348 
349       if (NSW) {
350         // We haven't sign-wrapped, so it's valid to decompose sext(%x + c)
351         // into sext(%x) + sext(c). We'll sext the Offset ourselves:
352         unsigned OldWidth = Offset.getBitWidth();
353         Offset = Offset.trunc(SmallWidth).sext(NewWidth).zextOrSelf(OldWidth);
354       } else {
355         // We may have signed-wrapped, so don't decompose sext(%x + c) into
356         // sext(%x) + sext(c)
357         Scale = 1;
358         Offset = 0;
359         Result = CastOp;
360         ZExtBits = OldZExtBits;
361         SExtBits = OldSExtBits;
362       }
363       SExtBits += ExtendedBy;
364     } else {
365       // sext(zext(%x, a), b) = zext(zext(%x, a), b) = zext(%x, a + b)
366 
367       if (!NUW) {
368         // We may have unsigned-wrapped, so don't decompose zext(%x + c) into
369         // zext(%x) + zext(c)
370         Scale = 1;
371         Offset = 0;
372         Result = CastOp;
373         ZExtBits = OldZExtBits;
374         SExtBits = OldSExtBits;
375       }
376       ZExtBits += ExtendedBy;
377     }
378 
379     return Result;
380   }
381 
382   Scale = 1;
383   Offset = 0;
384   return V;
385 }
386 
387 /// To ensure a pointer offset fits in an integer of size PointerSize
388 /// (in bits) when that size is smaller than the maximum pointer size. This is
389 /// an issue, for example, in particular for 32b pointers with negative indices
390 /// that rely on two's complement wrap-arounds for precise alias information
391 /// where the maximum pointer size is 64b.
392 static APInt adjustToPointerSize(const APInt &Offset, unsigned PointerSize) {
393   assert(PointerSize <= Offset.getBitWidth() && "Invalid PointerSize!");
394   unsigned ShiftBits = Offset.getBitWidth() - PointerSize;
395   return (Offset << ShiftBits).ashr(ShiftBits);
396 }
397 
398 static unsigned getMaxPointerSize(const DataLayout &DL) {
399   unsigned MaxPointerSize = DL.getMaxPointerSizeInBits();
400   if (MaxPointerSize < 64 && ForceAtLeast64Bits) MaxPointerSize = 64;
401   if (DoubleCalcBits) MaxPointerSize *= 2;
402 
403   return MaxPointerSize;
404 }
405 
406 /// If V is a symbolic pointer expression, decompose it into a base pointer
407 /// with a constant offset and a number of scaled symbolic offsets.
408 ///
409 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale
410 /// in the VarIndices vector) are Value*'s that are known to be scaled by the
411 /// specified amount, but which may have other unrepresented high bits. As
412 /// such, the gep cannot necessarily be reconstructed from its decomposed form.
413 ///
414 /// When DataLayout is around, this function is capable of analyzing everything
415 /// that getUnderlyingObject can look through. To be able to do that
416 /// getUnderlyingObject and DecomposeGEPExpression must use the same search
417 /// depth (MaxLookupSearchDepth). When DataLayout not is around, it just looks
418 /// through pointer casts.
419 bool BasicAAResult::DecomposeGEPExpression(const Value *V,
420        DecomposedGEP &Decomposed, const DataLayout &DL, AssumptionCache *AC,
421        DominatorTree *DT) {
422   // Limit recursion depth to limit compile time in crazy cases.
423   unsigned MaxLookup = MaxLookupSearchDepth;
424   SearchTimes++;
425 
426   unsigned MaxPointerSize = getMaxPointerSize(DL);
427   Decomposed.VarIndices.clear();
428   do {
429     // See if this is a bitcast or GEP.
430     const Operator *Op = dyn_cast<Operator>(V);
431     if (!Op) {
432       // The only non-operator case we can handle are GlobalAliases.
433       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
434         if (!GA->isInterposable()) {
435           V = GA->getAliasee();
436           continue;
437         }
438       }
439       Decomposed.Base = V;
440       return false;
441     }
442 
443     if (Op->getOpcode() == Instruction::BitCast ||
444         Op->getOpcode() == Instruction::AddrSpaceCast) {
445       V = Op->getOperand(0);
446       continue;
447     }
448 
449     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
450     if (!GEPOp) {
451       if (const auto *PHI = dyn_cast<PHINode>(V)) {
452         // Look through single-arg phi nodes created by LCSSA.
453         if (PHI->getNumIncomingValues() == 1) {
454           V = PHI->getIncomingValue(0);
455           continue;
456         }
457       } else if (const auto *Call = dyn_cast<CallBase>(V)) {
458         // CaptureTracking can know about special capturing properties of some
459         // intrinsics like launder.invariant.group, that can't be expressed with
460         // the attributes, but have properties like returning aliasing pointer.
461         // Because some analysis may assume that nocaptured pointer is not
462         // returned from some special intrinsic (because function would have to
463         // be marked with returns attribute), it is crucial to use this function
464         // because it should be in sync with CaptureTracking. Not using it may
465         // cause weird miscompilations where 2 aliasing pointers are assumed to
466         // noalias.
467         if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
468           V = RP;
469           continue;
470         }
471       }
472 
473       Decomposed.Base = V;
474       return false;
475     }
476 
477     // Don't attempt to analyze GEPs over unsized objects.
478     if (!GEPOp->getSourceElementType()->isSized()) {
479       Decomposed.Base = V;
480       return false;
481     }
482 
483     // Don't attempt to analyze GEPs if index scale is not a compile-time
484     // constant.
485     if (isa<ScalableVectorType>(GEPOp->getSourceElementType())) {
486       Decomposed.Base = V;
487       Decomposed.HasCompileTimeConstantScale = false;
488       return false;
489     }
490 
491     unsigned AS = GEPOp->getPointerAddressSpace();
492     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
493     gep_type_iterator GTI = gep_type_begin(GEPOp);
494     unsigned PointerSize = DL.getPointerSizeInBits(AS);
495     // Assume all GEP operands are constants until proven otherwise.
496     bool GepHasConstantOffset = true;
497     for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
498          I != E; ++I, ++GTI) {
499       const Value *Index = *I;
500       // Compute the (potentially symbolic) offset in bytes for this index.
501       if (StructType *STy = GTI.getStructTypeOrNull()) {
502         // For a struct, add the member offset.
503         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
504         if (FieldNo == 0)
505           continue;
506 
507         Decomposed.StructOffset +=
508           DL.getStructLayout(STy)->getElementOffset(FieldNo);
509         continue;
510       }
511 
512       // For an array/pointer, add the element offset, explicitly scaled.
513       if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
514         if (CIdx->isZero())
515           continue;
516         Decomposed.OtherOffset +=
517             (DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize() *
518              CIdx->getValue().sextOrSelf(MaxPointerSize))
519                 .sextOrTrunc(MaxPointerSize);
520         continue;
521       }
522 
523       GepHasConstantOffset = false;
524 
525       APInt Scale(MaxPointerSize,
526                   DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize());
527       unsigned ZExtBits = 0, SExtBits = 0;
528 
529       // If the integer type is smaller than the pointer size, it is implicitly
530       // sign extended to pointer size.
531       unsigned Width = Index->getType()->getIntegerBitWidth();
532       if (PointerSize > Width)
533         SExtBits += PointerSize - Width;
534 
535       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
536       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
537       bool NSW = true, NUW = true;
538       const Value *OrigIndex = Index;
539       Index = GetLinearExpression(Index, IndexScale, IndexOffset, ZExtBits,
540                                   SExtBits, DL, 0, AC, DT, NSW, NUW);
541 
542       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
543       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
544 
545       // It can be the case that, even through C1*V+C2 does not overflow for
546       // relevant values of V, (C2*Scale) can overflow. In that case, we cannot
547       // decompose the expression in this way.
548       //
549       // FIXME: C1*Scale and the other operations in the decomposed
550       // (C1*Scale)*V+C2*Scale can also overflow. We should check for this
551       // possibility.
552       APInt WideScaledOffset = IndexOffset.sextOrTrunc(MaxPointerSize*2) *
553                                  Scale.sext(MaxPointerSize*2);
554       if (WideScaledOffset.getMinSignedBits() > MaxPointerSize) {
555         Index = OrigIndex;
556         IndexScale = 1;
557         IndexOffset = 0;
558 
559         ZExtBits = SExtBits = 0;
560         if (PointerSize > Width)
561           SExtBits += PointerSize - Width;
562       } else {
563         Decomposed.OtherOffset += IndexOffset.sextOrTrunc(MaxPointerSize) * Scale;
564         Scale *= IndexScale.sextOrTrunc(MaxPointerSize);
565       }
566 
567       // If we already had an occurrence of this index variable, merge this
568       // scale into it.  For example, we want to handle:
569       //   A[x][x] -> x*16 + x*4 -> x*20
570       // This also ensures that 'x' only appears in the index list once.
571       for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
572         if (Decomposed.VarIndices[i].V == Index &&
573             Decomposed.VarIndices[i].ZExtBits == ZExtBits &&
574             Decomposed.VarIndices[i].SExtBits == SExtBits) {
575           Scale += Decomposed.VarIndices[i].Scale;
576           Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
577           break;
578         }
579       }
580 
581       // Make sure that we have a scale that makes sense for this target's
582       // pointer size.
583       Scale = adjustToPointerSize(Scale, PointerSize);
584 
585       if (!!Scale) {
586         VariableGEPIndex Entry = {Index, ZExtBits, SExtBits, Scale};
587         Decomposed.VarIndices.push_back(Entry);
588       }
589     }
590 
591     // Take care of wrap-arounds
592     if (GepHasConstantOffset) {
593       Decomposed.StructOffset =
594           adjustToPointerSize(Decomposed.StructOffset, PointerSize);
595       Decomposed.OtherOffset =
596           adjustToPointerSize(Decomposed.OtherOffset, PointerSize);
597     }
598 
599     // Analyze the base pointer next.
600     V = GEPOp->getOperand(0);
601   } while (--MaxLookup);
602 
603   // If the chain of expressions is too deep, just return early.
604   Decomposed.Base = V;
605   SearchLimitReached++;
606   return true;
607 }
608 
609 /// Returns whether the given pointer value points to memory that is local to
610 /// the function, with global constants being considered local to all
611 /// functions.
612 bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
613                                            AAQueryInfo &AAQI, bool OrLocal) {
614   assert(Visited.empty() && "Visited must be cleared after use!");
615 
616   unsigned MaxLookup = 8;
617   SmallVector<const Value *, 16> Worklist;
618   Worklist.push_back(Loc.Ptr);
619   do {
620     const Value *V = getUnderlyingObject(Worklist.pop_back_val());
621     if (!Visited.insert(V).second) {
622       Visited.clear();
623       return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
624     }
625 
626     // An alloca instruction defines local memory.
627     if (OrLocal && isa<AllocaInst>(V))
628       continue;
629 
630     // A global constant counts as local memory for our purposes.
631     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
632       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
633       // global to be marked constant in some modules and non-constant in
634       // others.  GV may even be a declaration, not a definition.
635       if (!GV->isConstant()) {
636         Visited.clear();
637         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
638       }
639       continue;
640     }
641 
642     // If both select values point to local memory, then so does the select.
643     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
644       Worklist.push_back(SI->getTrueValue());
645       Worklist.push_back(SI->getFalseValue());
646       continue;
647     }
648 
649     // If all values incoming to a phi node point to local memory, then so does
650     // the phi.
651     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
652       // Don't bother inspecting phi nodes with many operands.
653       if (PN->getNumIncomingValues() > MaxLookup) {
654         Visited.clear();
655         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
656       }
657       for (Value *IncValue : PN->incoming_values())
658         Worklist.push_back(IncValue);
659       continue;
660     }
661 
662     // Otherwise be conservative.
663     Visited.clear();
664     return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
665   } while (!Worklist.empty() && --MaxLookup);
666 
667   Visited.clear();
668   return Worklist.empty();
669 }
670 
671 /// Returns the behavior when calling the given call site.
672 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) {
673   if (Call->doesNotAccessMemory())
674     // Can't do better than this.
675     return FMRB_DoesNotAccessMemory;
676 
677   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
678 
679   // If the callsite knows it only reads memory, don't return worse
680   // than that.
681   if (Call->onlyReadsMemory())
682     Min = FMRB_OnlyReadsMemory;
683   else if (Call->doesNotReadMemory())
684     Min = FMRB_OnlyWritesMemory;
685 
686   if (Call->onlyAccessesArgMemory())
687     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
688   else if (Call->onlyAccessesInaccessibleMemory())
689     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
690   else if (Call->onlyAccessesInaccessibleMemOrArgMem())
691     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
692 
693   // If the call has operand bundles then aliasing attributes from the function
694   // it calls do not directly apply to the call.  This can be made more precise
695   // in the future.
696   if (!Call->hasOperandBundles())
697     if (const Function *F = Call->getCalledFunction())
698       Min =
699           FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F));
700 
701   return Min;
702 }
703 
704 /// Returns the behavior when calling the given function. For use when the call
705 /// site is not known.
706 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
707   // If the function declares it doesn't access memory, we can't do better.
708   if (F->doesNotAccessMemory())
709     return FMRB_DoesNotAccessMemory;
710 
711   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
712 
713   // If the function declares it only reads memory, go with that.
714   if (F->onlyReadsMemory())
715     Min = FMRB_OnlyReadsMemory;
716   else if (F->doesNotReadMemory())
717     Min = FMRB_OnlyWritesMemory;
718 
719   if (F->onlyAccessesArgMemory())
720     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
721   else if (F->onlyAccessesInaccessibleMemory())
722     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
723   else if (F->onlyAccessesInaccessibleMemOrArgMem())
724     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
725 
726   return Min;
727 }
728 
729 /// Returns true if this is a writeonly (i.e Mod only) parameter.
730 static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx,
731                              const TargetLibraryInfo &TLI) {
732   if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly))
733     return true;
734 
735   // We can bound the aliasing properties of memset_pattern16 just as we can
736   // for memcpy/memset.  This is particularly important because the
737   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
738   // whenever possible.
739   // FIXME Consider handling this in InferFunctionAttr.cpp together with other
740   // attributes.
741   LibFunc F;
742   if (Call->getCalledFunction() &&
743       TLI.getLibFunc(*Call->getCalledFunction(), F) &&
744       F == LibFunc_memset_pattern16 && TLI.has(F))
745     if (ArgIdx == 0)
746       return true;
747 
748   // TODO: memset_pattern4, memset_pattern8
749   // TODO: _chk variants
750   // TODO: strcmp, strcpy
751 
752   return false;
753 }
754 
755 ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,
756                                            unsigned ArgIdx) {
757   // Checking for known builtin intrinsics and target library functions.
758   if (isWriteOnlyParam(Call, ArgIdx, TLI))
759     return ModRefInfo::Mod;
760 
761   if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly))
762     return ModRefInfo::Ref;
763 
764   if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone))
765     return ModRefInfo::NoModRef;
766 
767   return AAResultBase::getArgModRefInfo(Call, ArgIdx);
768 }
769 
770 static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
771   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call);
772   return II && II->getIntrinsicID() == IID;
773 }
774 
775 #ifndef NDEBUG
776 static const Function *getParent(const Value *V) {
777   if (const Instruction *inst = dyn_cast<Instruction>(V)) {
778     if (!inst->getParent())
779       return nullptr;
780     return inst->getParent()->getParent();
781   }
782 
783   if (const Argument *arg = dyn_cast<Argument>(V))
784     return arg->getParent();
785 
786   return nullptr;
787 }
788 
789 static bool notDifferentParent(const Value *O1, const Value *O2) {
790 
791   const Function *F1 = getParent(O1);
792   const Function *F2 = getParent(O2);
793 
794   return !F1 || !F2 || F1 == F2;
795 }
796 #endif
797 
798 AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
799                                  const MemoryLocation &LocB,
800                                  AAQueryInfo &AAQI) {
801   assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
802          "BasicAliasAnalysis doesn't support interprocedural queries.");
803 
804   // If we have a directly cached entry for these locations, we have recursed
805   // through this once, so just return the cached results. Notably, when this
806   // happens, we don't clear the cache.
807   auto CacheIt = AAQI.AliasCache.find(AAQueryInfo::LocPair(LocA, LocB));
808   if (CacheIt != AAQI.AliasCache.end())
809     return CacheIt->second;
810 
811   CacheIt = AAQI.AliasCache.find(AAQueryInfo::LocPair(LocB, LocA));
812   if (CacheIt != AAQI.AliasCache.end())
813     return CacheIt->second;
814 
815   AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr,
816                                  LocB.Size, LocB.AATags, AAQI);
817 
818   VisitedPhiBBs.clear();
819   return Alias;
820 }
821 
822 /// Checks to see if the specified callsite can clobber the specified memory
823 /// object.
824 ///
825 /// Since we only look at local properties of this function, we really can't
826 /// say much about this query.  We do, however, use simple "address taken"
827 /// analysis on local objects.
828 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,
829                                         const MemoryLocation &Loc,
830                                         AAQueryInfo &AAQI) {
831   assert(notDifferentParent(Call, Loc.Ptr) &&
832          "AliasAnalysis query involving multiple functions!");
833 
834   const Value *Object = getUnderlyingObject(Loc.Ptr);
835 
836   // Calls marked 'tail' cannot read or write allocas from the current frame
837   // because the current frame might be destroyed by the time they run. However,
838   // a tail call may use an alloca with byval. Calling with byval copies the
839   // contents of the alloca into argument registers or stack slots, so there is
840   // no lifetime issue.
841   if (isa<AllocaInst>(Object))
842     if (const CallInst *CI = dyn_cast<CallInst>(Call))
843       if (CI->isTailCall() &&
844           !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
845         return ModRefInfo::NoModRef;
846 
847   // Stack restore is able to modify unescaped dynamic allocas. Assume it may
848   // modify them even though the alloca is not escaped.
849   if (auto *AI = dyn_cast<AllocaInst>(Object))
850     if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))
851       return ModRefInfo::Mod;
852 
853   // If the pointer is to a locally allocated object that does not escape,
854   // then the call can not mod/ref the pointer unless the call takes the pointer
855   // as an argument, and itself doesn't capture it.
856   if (!isa<Constant>(Object) && Call != Object &&
857       isNonEscapingLocalObject(Object, &AAQI.IsCapturedCache)) {
858 
859     // Optimistically assume that call doesn't touch Object and check this
860     // assumption in the following loop.
861     ModRefInfo Result = ModRefInfo::NoModRef;
862     bool IsMustAlias = true;
863 
864     unsigned OperandNo = 0;
865     for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
866          CI != CE; ++CI, ++OperandNo) {
867       // Only look at the no-capture or byval pointer arguments.  If this
868       // pointer were passed to arguments that were neither of these, then it
869       // couldn't be no-capture.
870       if (!(*CI)->getType()->isPointerTy() ||
871           (!Call->doesNotCapture(OperandNo) &&
872            OperandNo < Call->getNumArgOperands() &&
873            !Call->isByValArgument(OperandNo)))
874         continue;
875 
876       // Call doesn't access memory through this operand, so we don't care
877       // if it aliases with Object.
878       if (Call->doesNotAccessMemory(OperandNo))
879         continue;
880 
881       // If this is a no-capture pointer argument, see if we can tell that it
882       // is impossible to alias the pointer we're checking.
883       AliasResult AR = getBestAAResults().alias(MemoryLocation(*CI),
884                                                 MemoryLocation(Object), AAQI);
885       if (AR != MustAlias)
886         IsMustAlias = false;
887       // Operand doesn't alias 'Object', continue looking for other aliases
888       if (AR == NoAlias)
889         continue;
890       // Operand aliases 'Object', but call doesn't modify it. Strengthen
891       // initial assumption and keep looking in case if there are more aliases.
892       if (Call->onlyReadsMemory(OperandNo)) {
893         Result = setRef(Result);
894         continue;
895       }
896       // Operand aliases 'Object' but call only writes into it.
897       if (Call->doesNotReadMemory(OperandNo)) {
898         Result = setMod(Result);
899         continue;
900       }
901       // This operand aliases 'Object' and call reads and writes into it.
902       // Setting ModRef will not yield an early return below, MustAlias is not
903       // used further.
904       Result = ModRefInfo::ModRef;
905       break;
906     }
907 
908     // No operand aliases, reset Must bit. Add below if at least one aliases
909     // and all aliases found are MustAlias.
910     if (isNoModRef(Result))
911       IsMustAlias = false;
912 
913     // Early return if we improved mod ref information
914     if (!isModAndRefSet(Result)) {
915       if (isNoModRef(Result))
916         return ModRefInfo::NoModRef;
917       return IsMustAlias ? setMust(Result) : clearMust(Result);
918     }
919   }
920 
921   // If the call is malloc/calloc like, we can assume that it doesn't
922   // modify any IR visible value.  This is only valid because we assume these
923   // routines do not read values visible in the IR.  TODO: Consider special
924   // casing realloc and strdup routines which access only their arguments as
925   // well.  Or alternatively, replace all of this with inaccessiblememonly once
926   // that's implemented fully.
927   if (isMallocOrCallocLikeFn(Call, &TLI)) {
928     // Be conservative if the accessed pointer may alias the allocation -
929     // fallback to the generic handling below.
930     if (getBestAAResults().alias(MemoryLocation(Call), Loc, AAQI) == NoAlias)
931       return ModRefInfo::NoModRef;
932   }
933 
934   // The semantics of memcpy intrinsics either exactly overlap or do not
935   // overlap, i.e., source and destination of any given memcpy are either
936   // no-alias or must-alias.
937   if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) {
938     AliasResult SrcAA =
939         getBestAAResults().alias(MemoryLocation::getForSource(Inst), Loc, AAQI);
940     AliasResult DestAA =
941         getBestAAResults().alias(MemoryLocation::getForDest(Inst), Loc, AAQI);
942     // It's also possible for Loc to alias both src and dest, or neither.
943     ModRefInfo rv = ModRefInfo::NoModRef;
944     if (SrcAA != NoAlias)
945       rv = setRef(rv);
946     if (DestAA != NoAlias)
947       rv = setMod(rv);
948     return rv;
949   }
950 
951   // While the assume intrinsic is marked as arbitrarily writing so that
952   // proper control dependencies will be maintained, it never aliases any
953   // particular memory location.
954   if (isIntrinsicCall(Call, Intrinsic::assume))
955     return ModRefInfo::NoModRef;
956 
957   // Like assumes, guard intrinsics are also marked as arbitrarily writing so
958   // that proper control dependencies are maintained but they never mods any
959   // particular memory location.
960   //
961   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
962   // heap state at the point the guard is issued needs to be consistent in case
963   // the guard invokes the "deopt" continuation.
964   if (isIntrinsicCall(Call, Intrinsic::experimental_guard))
965     return ModRefInfo::Ref;
966 
967   // Like assumes, invariant.start intrinsics were also marked as arbitrarily
968   // writing so that proper control dependencies are maintained but they never
969   // mod any particular memory location visible to the IR.
970   // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
971   // intrinsic is now modeled as reading memory. This prevents hoisting the
972   // invariant.start intrinsic over stores. Consider:
973   // *ptr = 40;
974   // *ptr = 50;
975   // invariant_start(ptr)
976   // int val = *ptr;
977   // print(val);
978   //
979   // This cannot be transformed to:
980   //
981   // *ptr = 40;
982   // invariant_start(ptr)
983   // *ptr = 50;
984   // int val = *ptr;
985   // print(val);
986   //
987   // The transformation will cause the second store to be ignored (based on
988   // rules of invariant.start)  and print 40, while the first program always
989   // prints 50.
990   if (isIntrinsicCall(Call, Intrinsic::invariant_start))
991     return ModRefInfo::Ref;
992 
993   // The AAResultBase base class has some smarts, lets use them.
994   return AAResultBase::getModRefInfo(Call, Loc, AAQI);
995 }
996 
997 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,
998                                         const CallBase *Call2,
999                                         AAQueryInfo &AAQI) {
1000   // While the assume intrinsic is marked as arbitrarily writing so that
1001   // proper control dependencies will be maintained, it never aliases any
1002   // particular memory location.
1003   if (isIntrinsicCall(Call1, Intrinsic::assume) ||
1004       isIntrinsicCall(Call2, Intrinsic::assume))
1005     return ModRefInfo::NoModRef;
1006 
1007   // Like assumes, guard intrinsics are also marked as arbitrarily writing so
1008   // that proper control dependencies are maintained but they never mod any
1009   // particular memory location.
1010   //
1011   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
1012   // heap state at the point the guard is issued needs to be consistent in case
1013   // the guard invokes the "deopt" continuation.
1014 
1015   // NB! This function is *not* commutative, so we special case two
1016   // possibilities for guard intrinsics.
1017 
1018   if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))
1019     return isModSet(createModRefInfo(getModRefBehavior(Call2)))
1020                ? ModRefInfo::Ref
1021                : ModRefInfo::NoModRef;
1022 
1023   if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
1024     return isModSet(createModRefInfo(getModRefBehavior(Call1)))
1025                ? ModRefInfo::Mod
1026                : ModRefInfo::NoModRef;
1027 
1028   // The AAResultBase base class has some smarts, lets use them.
1029   return AAResultBase::getModRefInfo(Call1, Call2, AAQI);
1030 }
1031 
1032 /// Provide ad-hoc rules to disambiguate accesses through two GEP operators,
1033 /// both having the exact same pointer operand.
1034 static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
1035                                             LocationSize MaybeV1Size,
1036                                             const GEPOperator *GEP2,
1037                                             LocationSize MaybeV2Size,
1038                                             const DataLayout &DL) {
1039   assert(GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() ==
1040              GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() &&
1041          GEP1->getPointerOperandType() == GEP2->getPointerOperandType() &&
1042          "Expected GEPs with the same pointer operand");
1043 
1044   // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
1045   // such that the struct field accesses provably cannot alias.
1046   // We also need at least two indices (the pointer, and the struct field).
1047   if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
1048       GEP1->getNumIndices() < 2)
1049     return MayAlias;
1050 
1051   // If we don't know the size of the accesses through both GEPs, we can't
1052   // determine whether the struct fields accessed can't alias.
1053   if (MaybeV1Size == LocationSize::unknown() ||
1054       MaybeV2Size == LocationSize::unknown())
1055     return MayAlias;
1056 
1057   const uint64_t V1Size = MaybeV1Size.getValue();
1058   const uint64_t V2Size = MaybeV2Size.getValue();
1059 
1060   ConstantInt *C1 =
1061       dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
1062   ConstantInt *C2 =
1063       dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
1064 
1065   // If the last (struct) indices are constants and are equal, the other indices
1066   // might be also be dynamically equal, so the GEPs can alias.
1067   if (C1 && C2) {
1068     unsigned BitWidth = std::max(C1->getBitWidth(), C2->getBitWidth());
1069     if (C1->getValue().sextOrSelf(BitWidth) ==
1070         C2->getValue().sextOrSelf(BitWidth))
1071       return MayAlias;
1072   }
1073 
1074   // Find the last-indexed type of the GEP, i.e., the type you'd get if
1075   // you stripped the last index.
1076   // On the way, look at each indexed type.  If there's something other
1077   // than an array, different indices can lead to different final types.
1078   SmallVector<Value *, 8> IntermediateIndices;
1079 
1080   // Insert the first index; we don't need to check the type indexed
1081   // through it as it only drops the pointer indirection.
1082   assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
1083   IntermediateIndices.push_back(GEP1->getOperand(1));
1084 
1085   // Insert all the remaining indices but the last one.
1086   // Also, check that they all index through arrays.
1087   for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
1088     if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
1089             GEP1->getSourceElementType(), IntermediateIndices)))
1090       return MayAlias;
1091     IntermediateIndices.push_back(GEP1->getOperand(i + 1));
1092   }
1093 
1094   auto *Ty = GetElementPtrInst::getIndexedType(
1095     GEP1->getSourceElementType(), IntermediateIndices);
1096   StructType *LastIndexedStruct = dyn_cast<StructType>(Ty);
1097 
1098   if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
1099     // We know that:
1100     // - both GEPs begin indexing from the exact same pointer;
1101     // - the last indices in both GEPs are constants, indexing into a sequential
1102     //   type (array or vector);
1103     // - both GEPs only index through arrays prior to that.
1104     //
1105     // Because array indices greater than the number of elements are valid in
1106     // GEPs, unless we know the intermediate indices are identical between
1107     // GEP1 and GEP2 we cannot guarantee that the last indexed arrays don't
1108     // partially overlap. We also need to check that the loaded size matches
1109     // the element size, otherwise we could still have overlap.
1110     Type *LastElementTy = GetElementPtrInst::getTypeAtIndex(Ty, (uint64_t)0);
1111     const uint64_t ElementSize =
1112         DL.getTypeStoreSize(LastElementTy).getFixedSize();
1113     if (V1Size != ElementSize || V2Size != ElementSize)
1114       return MayAlias;
1115 
1116     for (unsigned i = 0, e = GEP1->getNumIndices() - 1; i != e; ++i)
1117       if (GEP1->getOperand(i + 1) != GEP2->getOperand(i + 1))
1118         return MayAlias;
1119 
1120     // Now we know that the array/pointer that GEP1 indexes into and that
1121     // that GEP2 indexes into must either precisely overlap or be disjoint.
1122     // Because they cannot partially overlap and because fields in an array
1123     // cannot overlap, if we can prove the final indices are different between
1124     // GEP1 and GEP2, we can conclude GEP1 and GEP2 don't alias.
1125 
1126     // If the last indices are constants, we've already checked they don't
1127     // equal each other so we can exit early.
1128     if (C1 && C2)
1129       return NoAlias;
1130     {
1131       Value *GEP1LastIdx = GEP1->getOperand(GEP1->getNumOperands() - 1);
1132       Value *GEP2LastIdx = GEP2->getOperand(GEP2->getNumOperands() - 1);
1133       if (isa<PHINode>(GEP1LastIdx) || isa<PHINode>(GEP2LastIdx)) {
1134         // If one of the indices is a PHI node, be safe and only use
1135         // computeKnownBits so we don't make any assumptions about the
1136         // relationships between the two indices. This is important if we're
1137         // asking about values from different loop iterations. See PR32314.
1138         // TODO: We may be able to change the check so we only do this when
1139         // we definitely looked through a PHINode.
1140         if (GEP1LastIdx != GEP2LastIdx &&
1141             GEP1LastIdx->getType() == GEP2LastIdx->getType()) {
1142           KnownBits Known1 = computeKnownBits(GEP1LastIdx, DL);
1143           KnownBits Known2 = computeKnownBits(GEP2LastIdx, DL);
1144           if (Known1.Zero.intersects(Known2.One) ||
1145               Known1.One.intersects(Known2.Zero))
1146             return NoAlias;
1147         }
1148       } else if (isKnownNonEqual(GEP1LastIdx, GEP2LastIdx, DL))
1149         return NoAlias;
1150     }
1151     return MayAlias;
1152   } else if (!LastIndexedStruct || !C1 || !C2) {
1153     return MayAlias;
1154   }
1155 
1156   if (C1->getValue().getActiveBits() > 64 ||
1157       C2->getValue().getActiveBits() > 64)
1158     return MayAlias;
1159 
1160   // We know that:
1161   // - both GEPs begin indexing from the exact same pointer;
1162   // - the last indices in both GEPs are constants, indexing into a struct;
1163   // - said indices are different, hence, the pointed-to fields are different;
1164   // - both GEPs only index through arrays prior to that.
1165   //
1166   // This lets us determine that the struct that GEP1 indexes into and the
1167   // struct that GEP2 indexes into must either precisely overlap or be
1168   // completely disjoint.  Because they cannot partially overlap, indexing into
1169   // different non-overlapping fields of the struct will never alias.
1170 
1171   // Therefore, the only remaining thing needed to show that both GEPs can't
1172   // alias is that the fields are not overlapping.
1173   const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
1174   const uint64_t StructSize = SL->getSizeInBytes();
1175   const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
1176   const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
1177 
1178   auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
1179                                       uint64_t V2Off, uint64_t V2Size) {
1180     return V1Off < V2Off && V1Off + V1Size <= V2Off &&
1181            ((V2Off + V2Size <= StructSize) ||
1182             (V2Off + V2Size - StructSize <= V1Off));
1183   };
1184 
1185   if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
1186       EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
1187     return NoAlias;
1188 
1189   return MayAlias;
1190 }
1191 
1192 // If a we have (a) a GEP and (b) a pointer based on an alloca, and the
1193 // beginning of the object the GEP points would have a negative offset with
1194 // repsect to the alloca, that means the GEP can not alias pointer (b).
1195 // Note that the pointer based on the alloca may not be a GEP. For
1196 // example, it may be the alloca itself.
1197 // The same applies if (b) is based on a GlobalVariable. Note that just being
1198 // based on isIdentifiedObject() is not enough - we need an identified object
1199 // that does not permit access to negative offsets. For example, a negative
1200 // offset from a noalias argument or call can be inbounds w.r.t the actual
1201 // underlying object.
1202 //
1203 // For example, consider:
1204 //
1205 //   struct { int f0, int f1, ...} foo;
1206 //   foo alloca;
1207 //   foo* random = bar(alloca);
1208 //   int *f0 = &alloca.f0
1209 //   int *f1 = &random->f1;
1210 //
1211 // Which is lowered, approximately, to:
1212 //
1213 //  %alloca = alloca %struct.foo
1214 //  %random = call %struct.foo* @random(%struct.foo* %alloca)
1215 //  %f0 = getelementptr inbounds %struct, %struct.foo* %alloca, i32 0, i32 0
1216 //  %f1 = getelementptr inbounds %struct, %struct.foo* %random, i32 0, i32 1
1217 //
1218 // Assume %f1 and %f0 alias. Then %f1 would point into the object allocated
1219 // by %alloca. Since the %f1 GEP is inbounds, that means %random must also
1220 // point into the same object. But since %f0 points to the beginning of %alloca,
1221 // the highest %f1 can be is (%alloca + 3). This means %random can not be higher
1222 // than (%alloca - 1), and so is not inbounds, a contradiction.
1223 bool BasicAAResult::isGEPBaseAtNegativeOffset(const GEPOperator *GEPOp,
1224       const DecomposedGEP &DecompGEP, const DecomposedGEP &DecompObject,
1225       LocationSize MaybeObjectAccessSize) {
1226   // If the object access size is unknown, or the GEP isn't inbounds, bail.
1227   if (MaybeObjectAccessSize == LocationSize::unknown() || !GEPOp->isInBounds())
1228     return false;
1229 
1230   const uint64_t ObjectAccessSize = MaybeObjectAccessSize.getValue();
1231 
1232   // We need the object to be an alloca or a globalvariable, and want to know
1233   // the offset of the pointer from the object precisely, so no variable
1234   // indices are allowed.
1235   if (!(isa<AllocaInst>(DecompObject.Base) ||
1236         isa<GlobalVariable>(DecompObject.Base)) ||
1237       !DecompObject.VarIndices.empty())
1238     return false;
1239 
1240   APInt ObjectBaseOffset = DecompObject.StructOffset +
1241                            DecompObject.OtherOffset;
1242 
1243   // If the GEP has no variable indices, we know the precise offset
1244   // from the base, then use it. If the GEP has variable indices,
1245   // we can't get exact GEP offset to identify pointer alias. So return
1246   // false in that case.
1247   if (!DecompGEP.VarIndices.empty())
1248     return false;
1249 
1250   APInt GEPBaseOffset = DecompGEP.StructOffset;
1251   GEPBaseOffset += DecompGEP.OtherOffset;
1252 
1253   return GEPBaseOffset.sge(ObjectBaseOffset + (int64_t)ObjectAccessSize);
1254 }
1255 
1256 /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
1257 /// another pointer.
1258 ///
1259 /// We know that V1 is a GEP, but we don't know anything about V2.
1260 /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for
1261 /// V2.
1262 AliasResult BasicAAResult::aliasGEP(
1263     const GEPOperator *GEP1, LocationSize V1Size, const AAMDNodes &V1AAInfo,
1264     const Value *V2, LocationSize V2Size, const AAMDNodes &V2AAInfo,
1265     const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
1266   DecomposedGEP DecompGEP1, DecompGEP2;
1267   unsigned MaxPointerSize = getMaxPointerSize(DL);
1268   DecompGEP1.StructOffset = DecompGEP1.OtherOffset = APInt(MaxPointerSize, 0);
1269   DecompGEP2.StructOffset = DecompGEP2.OtherOffset = APInt(MaxPointerSize, 0);
1270   DecompGEP1.HasCompileTimeConstantScale =
1271       DecompGEP2.HasCompileTimeConstantScale = true;
1272 
1273   bool GEP1MaxLookupReached =
1274     DecomposeGEPExpression(GEP1, DecompGEP1, DL, &AC, DT);
1275   bool GEP2MaxLookupReached =
1276     DecomposeGEPExpression(V2, DecompGEP2, DL, &AC, DT);
1277 
1278   // Don't attempt to analyze the decomposed GEP if index scale is not a
1279   // compile-time constant.
1280   if (!DecompGEP1.HasCompileTimeConstantScale ||
1281       !DecompGEP2.HasCompileTimeConstantScale)
1282     return MayAlias;
1283 
1284   APInt GEP1BaseOffset = DecompGEP1.StructOffset + DecompGEP1.OtherOffset;
1285   APInt GEP2BaseOffset = DecompGEP2.StructOffset + DecompGEP2.OtherOffset;
1286 
1287   assert(DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 &&
1288          "DecomposeGEPExpression returned a result different from "
1289          "getUnderlyingObject");
1290 
1291   // If the GEP's offset relative to its base is such that the base would
1292   // fall below the start of the object underlying V2, then the GEP and V2
1293   // cannot alias.
1294   if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
1295       isGEPBaseAtNegativeOffset(GEP1, DecompGEP1, DecompGEP2, V2Size))
1296     return NoAlias;
1297   // If we have two gep instructions with must-alias or not-alias'ing base
1298   // pointers, figure out if the indexes to the GEP tell us anything about the
1299   // derived pointer.
1300   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
1301     // Check for the GEP base being at a negative offset, this time in the other
1302     // direction.
1303     if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
1304         isGEPBaseAtNegativeOffset(GEP2, DecompGEP2, DecompGEP1, V1Size))
1305       return NoAlias;
1306     // Do the base pointers alias?
1307     AliasResult BaseAlias =
1308         aliasCheck(UnderlyingV1, LocationSize::unknown(), AAMDNodes(),
1309                    UnderlyingV2, LocationSize::unknown(), AAMDNodes(), AAQI);
1310 
1311     // Check for geps of non-aliasing underlying pointers where the offsets are
1312     // identical.
1313     if ((BaseAlias == MayAlias) && V1Size == V2Size) {
1314       // Do the base pointers alias assuming type and size.
1315       AliasResult PreciseBaseAlias = aliasCheck(
1316           UnderlyingV1, V1Size, V1AAInfo, UnderlyingV2, V2Size, V2AAInfo, AAQI);
1317       if (PreciseBaseAlias == NoAlias) {
1318         // See if the computed offset from the common pointer tells us about the
1319         // relation of the resulting pointer.
1320         // If the max search depth is reached the result is undefined
1321         if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1322           return MayAlias;
1323 
1324         // Same offsets.
1325         if (GEP1BaseOffset == GEP2BaseOffset &&
1326             DecompGEP1.VarIndices == DecompGEP2.VarIndices)
1327           return NoAlias;
1328       }
1329     }
1330 
1331     // If we get a No or May, then return it immediately, no amount of analysis
1332     // will improve this situation.
1333     if (BaseAlias != MustAlias) {
1334       assert(BaseAlias == NoAlias || BaseAlias == MayAlias);
1335       return BaseAlias;
1336     }
1337 
1338     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
1339     // exactly, see if the computed offset from the common pointer tells us
1340     // about the relation of the resulting pointer.
1341     // If we know the two GEPs are based off of the exact same pointer (and not
1342     // just the same underlying object), see if that tells us anything about
1343     // the resulting pointers.
1344     if (GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() ==
1345             GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() &&
1346         GEP1->getPointerOperandType() == GEP2->getPointerOperandType()) {
1347       AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, DL);
1348       // If we couldn't find anything interesting, don't abandon just yet.
1349       if (R != MayAlias)
1350         return R;
1351     }
1352 
1353     // If the max search depth is reached, the result is undefined
1354     if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1355       return MayAlias;
1356 
1357     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1358     // symbolic difference.
1359     GEP1BaseOffset -= GEP2BaseOffset;
1360     GetIndexDifference(DecompGEP1.VarIndices, DecompGEP2.VarIndices);
1361 
1362   } else {
1363     // Check to see if these two pointers are related by the getelementptr
1364     // instruction.  If one pointer is a GEP with a non-zero index of the other
1365     // pointer, we know they cannot alias.
1366 
1367     // If both accesses are unknown size, we can't do anything useful here.
1368     if (V1Size == LocationSize::unknown() && V2Size == LocationSize::unknown())
1369       return MayAlias;
1370 
1371     AliasResult R = aliasCheck(UnderlyingV1, LocationSize::unknown(),
1372                                AAMDNodes(), V2, LocationSize::unknown(),
1373                                V2AAInfo, AAQI, nullptr, UnderlyingV2);
1374     if (R != MustAlias) {
1375       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
1376       // If V2 is known not to alias GEP base pointer, then the two values
1377       // cannot alias per GEP semantics: "Any memory access must be done through
1378       // a pointer value associated with an address range of the memory access,
1379       // otherwise the behavior is undefined.".
1380       assert(R == NoAlias || R == MayAlias);
1381       return R;
1382     }
1383 
1384     // If the max search depth is reached the result is undefined
1385     if (GEP1MaxLookupReached)
1386       return MayAlias;
1387   }
1388 
1389   // In the two GEP Case, if there is no difference in the offsets of the
1390   // computed pointers, the resultant pointers are a must alias.  This
1391   // happens when we have two lexically identical GEP's (for example).
1392   //
1393   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1394   // must aliases the GEP, the end result is a must alias also.
1395   if (GEP1BaseOffset == 0 && DecompGEP1.VarIndices.empty())
1396     return MustAlias;
1397 
1398   // If there is a constant difference between the pointers, but the difference
1399   // is less than the size of the associated memory object, then we know
1400   // that the objects are partially overlapping.  If the difference is
1401   // greater, we know they do not overlap.
1402   if (GEP1BaseOffset != 0 && DecompGEP1.VarIndices.empty()) {
1403     if (GEP1BaseOffset.sge(0)) {
1404       if (V2Size != LocationSize::unknown()) {
1405         if (GEP1BaseOffset.ult(V2Size.getValue()))
1406           return PartialAlias;
1407         return NoAlias;
1408       }
1409     } else {
1410       // We have the situation where:
1411       // +                +
1412       // | BaseOffset     |
1413       // ---------------->|
1414       // |-->V1Size       |-------> V2Size
1415       // GEP1             V2
1416       // We need to know that V2Size is not unknown, otherwise we might have
1417       // stripped a gep with negative index ('gep <ptr>, -1, ...).
1418       if (V1Size != LocationSize::unknown() &&
1419           V2Size != LocationSize::unknown()) {
1420         if ((-GEP1BaseOffset).ult(V1Size.getValue()))
1421           return PartialAlias;
1422         return NoAlias;
1423       }
1424     }
1425   }
1426 
1427   if (!DecompGEP1.VarIndices.empty()) {
1428     APInt Modulo(MaxPointerSize, 0);
1429     bool AllPositive = true;
1430     for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
1431 
1432       // Try to distinguish something like &A[i][1] against &A[42][0].
1433       // Grab the least significant bit set in any of the scales. We
1434       // don't need std::abs here (even if the scale's negative) as we'll
1435       // be ^'ing Modulo with itself later.
1436       Modulo |= DecompGEP1.VarIndices[i].Scale;
1437 
1438       if (AllPositive) {
1439         // If the Value could change between cycles, then any reasoning about
1440         // the Value this cycle may not hold in the next cycle. We'll just
1441         // give up if we can't determine conditions that hold for every cycle:
1442         const Value *V = DecompGEP1.VarIndices[i].V;
1443 
1444         KnownBits Known =
1445             computeKnownBits(V, DL, 0, &AC, dyn_cast<Instruction>(GEP1), DT);
1446         bool SignKnownZero = Known.isNonNegative();
1447         bool SignKnownOne = Known.isNegative();
1448 
1449         // Zero-extension widens the variable, and so forces the sign
1450         // bit to zero.
1451         bool IsZExt = DecompGEP1.VarIndices[i].ZExtBits > 0 || isa<ZExtInst>(V);
1452         SignKnownZero |= IsZExt;
1453         SignKnownOne &= !IsZExt;
1454 
1455         // If the variable begins with a zero then we know it's
1456         // positive, regardless of whether the value is signed or
1457         // unsigned.
1458         APInt Scale = DecompGEP1.VarIndices[i].Scale;
1459         AllPositive =
1460             (SignKnownZero && Scale.sge(0)) || (SignKnownOne && Scale.slt(0));
1461       }
1462     }
1463 
1464     Modulo = Modulo ^ (Modulo & (Modulo - 1));
1465 
1466     // We can compute the difference between the two addresses
1467     // mod Modulo. Check whether that difference guarantees that the
1468     // two locations do not alias.
1469     APInt ModOffset = GEP1BaseOffset & (Modulo - 1);
1470     if (V1Size != LocationSize::unknown() &&
1471         V2Size != LocationSize::unknown() && ModOffset.uge(V2Size.getValue()) &&
1472         (Modulo - ModOffset).uge(V1Size.getValue()))
1473       return NoAlias;
1474 
1475     // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1476     // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1477     // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1478     if (AllPositive && GEP1BaseOffset.sgt(0) &&
1479         V2Size != LocationSize::unknown() &&
1480         GEP1BaseOffset.uge(V2Size.getValue()))
1481       return NoAlias;
1482 
1483     if (constantOffsetHeuristic(DecompGEP1.VarIndices, V1Size, V2Size,
1484                                 GEP1BaseOffset, &AC, DT))
1485       return NoAlias;
1486   }
1487 
1488   // Statically, we can see that the base objects are the same, but the
1489   // pointers have dynamic offsets which we can't resolve. And none of our
1490   // little tricks above worked.
1491   return MayAlias;
1492 }
1493 
1494 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
1495   // If the results agree, take it.
1496   if (A == B)
1497     return A;
1498   // A mix of PartialAlias and MustAlias is PartialAlias.
1499   if ((A == PartialAlias && B == MustAlias) ||
1500       (B == PartialAlias && A == MustAlias))
1501     return PartialAlias;
1502   // Otherwise, we don't know anything.
1503   return MayAlias;
1504 }
1505 
1506 /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
1507 /// against another.
1508 AliasResult
1509 BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
1510                            const AAMDNodes &SIAAInfo, const Value *V2,
1511                            LocationSize V2Size, const AAMDNodes &V2AAInfo,
1512                            const Value *UnderV2, AAQueryInfo &AAQI) {
1513   // If the values are Selects with the same condition, we can do a more precise
1514   // check: just check for aliases between the values on corresponding arms.
1515   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1516     if (SI->getCondition() == SI2->getCondition()) {
1517       AliasResult Alias =
1518           aliasCheck(SI->getTrueValue(), SISize, SIAAInfo, SI2->getTrueValue(),
1519                      V2Size, V2AAInfo, AAQI);
1520       if (Alias == MayAlias)
1521         return MayAlias;
1522       AliasResult ThisAlias =
1523           aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1524                      SI2->getFalseValue(), V2Size, V2AAInfo, AAQI);
1525       return MergeAliasResults(ThisAlias, Alias);
1526     }
1527 
1528   // If both arms of the Select node NoAlias or MustAlias V2, then returns
1529   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1530   AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(),
1531                                  SISize, SIAAInfo, AAQI, UnderV2);
1532   if (Alias == MayAlias)
1533     return MayAlias;
1534 
1535   AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(),
1536                                      SISize, SIAAInfo, AAQI, UnderV2);
1537   return MergeAliasResults(ThisAlias, Alias);
1538 }
1539 
1540 /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
1541 /// another.
1542 AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
1543                                     const AAMDNodes &PNAAInfo, const Value *V2,
1544                                     LocationSize V2Size,
1545                                     const AAMDNodes &V2AAInfo,
1546                                     const Value *UnderV2, AAQueryInfo &AAQI) {
1547   // Track phi nodes we have visited. We use this information when we determine
1548   // value equivalence.
1549   VisitedPhiBBs.insert(PN->getParent());
1550 
1551   // If the values are PHIs in the same block, we can do a more precise
1552   // as well as efficient check: just check for aliases between the values
1553   // on corresponding edges.
1554   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1555     if (PN2->getParent() == PN->getParent()) {
1556       AAQueryInfo::LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
1557                                 MemoryLocation(V2, V2Size, V2AAInfo));
1558       if (PN > V2)
1559         std::swap(Locs.first, Locs.second);
1560       // Analyse the PHIs' inputs under the assumption that the PHIs are
1561       // NoAlias.
1562       // If the PHIs are May/MustAlias there must be (recursively) an input
1563       // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1564       // there must be an operation on the PHIs within the PHIs' value cycle
1565       // that causes a MayAlias.
1566       // Pretend the phis do not alias.
1567       AliasResult Alias = NoAlias;
1568       AliasResult OrigAliasResult;
1569       {
1570         // Limited lifetime iterator invalidated by the aliasCheck call below.
1571         auto CacheIt = AAQI.AliasCache.find(Locs);
1572         assert((CacheIt != AAQI.AliasCache.end()) &&
1573                "There must exist an entry for the phi node");
1574         OrigAliasResult = CacheIt->second;
1575         CacheIt->second = NoAlias;
1576       }
1577 
1578       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1579         AliasResult ThisAlias =
1580             aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
1581                        PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1582                        V2Size, V2AAInfo, AAQI);
1583         Alias = MergeAliasResults(ThisAlias, Alias);
1584         if (Alias == MayAlias)
1585           break;
1586       }
1587 
1588       // Reset if speculation failed.
1589       if (Alias != NoAlias) {
1590         auto Pair =
1591             AAQI.AliasCache.insert(std::make_pair(Locs, OrigAliasResult));
1592         assert(!Pair.second && "Entry must have existed");
1593         Pair.first->second = OrigAliasResult;
1594       }
1595       return Alias;
1596     }
1597 
1598   SmallVector<Value *, 4> V1Srcs;
1599   // For a recursive phi, that recurses through a contant gep, we can perform
1600   // aliasing calculations using the other phi operands with an unknown size to
1601   // specify that an unknown number of elements after the initial value are
1602   // potentially accessed.
1603   bool isRecursive = false;
1604   auto CheckForRecPhi = [&](Value *PV) {
1605     if (!EnableRecPhiAnalysis)
1606       return false;
1607     if (GEPOperator *PVGEP = dyn_cast<GEPOperator>(PV)) {
1608       // Check whether the incoming value is a GEP that advances the pointer
1609       // result of this PHI node (e.g. in a loop). If this is the case, we
1610       // would recurse and always get a MayAlias. Handle this case specially
1611       // below. We need to ensure that the phi is inbounds and has a constant
1612       // positive operand so that we can check for alias with the initial value
1613       // and an unknown but positive size.
1614       if (PVGEP->getPointerOperand() == PN && PVGEP->isInBounds() &&
1615           PVGEP->getNumIndices() == 1 && isa<ConstantInt>(PVGEP->idx_begin()) &&
1616           !cast<ConstantInt>(PVGEP->idx_begin())->isNegative()) {
1617         isRecursive = true;
1618         return true;
1619       }
1620     }
1621     return false;
1622   };
1623 
1624   if (PV) {
1625     // If we have PhiValues then use it to get the underlying phi values.
1626     const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN);
1627     // If we have more phi values than the search depth then return MayAlias
1628     // conservatively to avoid compile time explosion. The worst possible case
1629     // is if both sides are PHI nodes. In which case, this is O(m x n) time
1630     // where 'm' and 'n' are the number of PHI sources.
1631     if (PhiValueSet.size() > MaxLookupSearchDepth)
1632       return MayAlias;
1633     // Add the values to V1Srcs
1634     for (Value *PV1 : PhiValueSet) {
1635       if (CheckForRecPhi(PV1))
1636         continue;
1637       V1Srcs.push_back(PV1);
1638     }
1639   } else {
1640     // If we don't have PhiInfo then just look at the operands of the phi itself
1641     // FIXME: Remove this once we can guarantee that we have PhiInfo always
1642     SmallPtrSet<Value *, 4> UniqueSrc;
1643     for (Value *PV1 : PN->incoming_values()) {
1644       if (isa<PHINode>(PV1))
1645         // If any of the source itself is a PHI, return MayAlias conservatively
1646         // to avoid compile time explosion. The worst possible case is if both
1647         // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1648         // and 'n' are the number of PHI sources.
1649         return MayAlias;
1650 
1651       if (CheckForRecPhi(PV1))
1652         continue;
1653 
1654       if (UniqueSrc.insert(PV1).second)
1655         V1Srcs.push_back(PV1);
1656     }
1657   }
1658 
1659   // If V1Srcs is empty then that means that the phi has no underlying non-phi
1660   // value. This should only be possible in blocks unreachable from the entry
1661   // block, but return MayAlias just in case.
1662   if (V1Srcs.empty())
1663     return MayAlias;
1664 
1665   // If this PHI node is recursive, set the size of the accessed memory to
1666   // unknown to represent all the possible values the GEP could advance the
1667   // pointer to.
1668   if (isRecursive)
1669     PNSize = LocationSize::unknown();
1670 
1671   AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo, V1Srcs[0], PNSize,
1672                                  PNAAInfo, AAQI, UnderV2);
1673 
1674   // Early exit if the check of the first PHI source against V2 is MayAlias.
1675   // Other results are not possible.
1676   if (Alias == MayAlias)
1677     return MayAlias;
1678   // With recursive phis we cannot guarantee that MustAlias/PartialAlias will
1679   // remain valid to all elements and needs to conservatively return MayAlias.
1680   if (isRecursive && Alias != NoAlias)
1681     return MayAlias;
1682 
1683   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1684   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1685   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1686     Value *V = V1Srcs[i];
1687 
1688     AliasResult ThisAlias =
1689         aliasCheck(V2, V2Size, V2AAInfo, V, PNSize, PNAAInfo, AAQI, UnderV2);
1690     Alias = MergeAliasResults(ThisAlias, Alias);
1691     if (Alias == MayAlias)
1692       break;
1693   }
1694 
1695   return Alias;
1696 }
1697 
1698 /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
1699 /// array references.
1700 AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
1701                                       AAMDNodes V1AAInfo, const Value *V2,
1702                                       LocationSize V2Size, AAMDNodes V2AAInfo,
1703                                       AAQueryInfo &AAQI, const Value *O1,
1704                                       const Value *O2) {
1705   // If either of the memory references is empty, it doesn't matter what the
1706   // pointer values are.
1707   if (V1Size.isZero() || V2Size.isZero())
1708     return NoAlias;
1709 
1710   // Strip off any casts if they exist.
1711   V1 = V1->stripPointerCastsAndInvariantGroups();
1712   V2 = V2->stripPointerCastsAndInvariantGroups();
1713 
1714   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1715   // value for undef that aliases nothing in the program.
1716   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1717     return NoAlias;
1718 
1719   // Are we checking for alias of the same value?
1720   // Because we look 'through' phi nodes, we could look at "Value" pointers from
1721   // different iterations. We must therefore make sure that this is not the
1722   // case. The function isValueEqualInPotentialCycles ensures that this cannot
1723   // happen by looking at the visited phi nodes and making sure they cannot
1724   // reach the value.
1725   if (isValueEqualInPotentialCycles(V1, V2))
1726     return MustAlias;
1727 
1728   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1729     return NoAlias; // Scalars cannot alias each other
1730 
1731   // Figure out what objects these things are pointing to if we can.
1732   if (O1 == nullptr)
1733     O1 = getUnderlyingObject(V1, MaxLookupSearchDepth);
1734 
1735   if (O2 == nullptr)
1736     O2 = getUnderlyingObject(V2, MaxLookupSearchDepth);
1737 
1738   // Null values in the default address space don't point to any object, so they
1739   // don't alias any other pointer.
1740   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1741     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1742       return NoAlias;
1743   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1744     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1745       return NoAlias;
1746 
1747   if (O1 != O2) {
1748     // If V1/V2 point to two different objects, we know that we have no alias.
1749     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1750       return NoAlias;
1751 
1752     // Constant pointers can't alias with non-const isIdentifiedObject objects.
1753     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1754         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1755       return NoAlias;
1756 
1757     // Function arguments can't alias with things that are known to be
1758     // unambigously identified at the function level.
1759     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1760         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1761       return NoAlias;
1762 
1763     // If one pointer is the result of a call/invoke or load and the other is a
1764     // non-escaping local object within the same function, then we know the
1765     // object couldn't escape to a point where the call could return it.
1766     //
1767     // Note that if the pointers are in different functions, there are a
1768     // variety of complications. A call with a nocapture argument may still
1769     // temporary store the nocapture argument's value in a temporary memory
1770     // location if that memory location doesn't escape. Or it may pass a
1771     // nocapture value to other functions as long as they don't capture it.
1772     if (isEscapeSource(O1) &&
1773         isNonEscapingLocalObject(O2, &AAQI.IsCapturedCache))
1774       return NoAlias;
1775     if (isEscapeSource(O2) &&
1776         isNonEscapingLocalObject(O1, &AAQI.IsCapturedCache))
1777       return NoAlias;
1778   }
1779 
1780   // If the size of one access is larger than the entire object on the other
1781   // side, then we know such behavior is undefined and can assume no alias.
1782   bool NullIsValidLocation = NullPointerIsDefined(&F);
1783   if ((isObjectSmallerThan(
1784           O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL,
1785           TLI, NullIsValidLocation)) ||
1786       (isObjectSmallerThan(
1787           O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL,
1788           TLI, NullIsValidLocation)))
1789     return NoAlias;
1790 
1791   // Check the cache before climbing up use-def chains. This also terminates
1792   // otherwise infinitely recursive queries.
1793   AAQueryInfo::LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
1794                             MemoryLocation(V2, V2Size, V2AAInfo));
1795   if (V1 > V2)
1796     std::swap(Locs.first, Locs.second);
1797   std::pair<AAQueryInfo::AliasCacheT::iterator, bool> Pair =
1798       AAQI.AliasCache.try_emplace(Locs, MayAlias);
1799   if (!Pair.second)
1800     return Pair.first->second;
1801 
1802   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1803   // GEP can't simplify, we don't even look at the PHI cases.
1804   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1805     std::swap(V1, V2);
1806     std::swap(V1Size, V2Size);
1807     std::swap(O1, O2);
1808     std::swap(V1AAInfo, V2AAInfo);
1809   }
1810   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1811     AliasResult Result =
1812         aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2, AAQI);
1813     if (Result != MayAlias) {
1814       auto ItInsPair = AAQI.AliasCache.insert(std::make_pair(Locs, Result));
1815       assert(!ItInsPair.second && "Entry must have existed");
1816       ItInsPair.first->second = Result;
1817       return Result;
1818     }
1819   }
1820 
1821   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1822     std::swap(V1, V2);
1823     std::swap(O1, O2);
1824     std::swap(V1Size, V2Size);
1825     std::swap(V1AAInfo, V2AAInfo);
1826   }
1827   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1828     AliasResult Result =
1829         aliasPHI(PN, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O2, AAQI);
1830     if (Result != MayAlias) {
1831       Pair = AAQI.AliasCache.try_emplace(Locs, Result);
1832       assert(!Pair.second && "Entry must have existed");
1833       return Pair.first->second = Result;
1834     }
1835   }
1836 
1837   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1838     std::swap(V1, V2);
1839     std::swap(O1, O2);
1840     std::swap(V1Size, V2Size);
1841     std::swap(V1AAInfo, V2AAInfo);
1842   }
1843   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1844     AliasResult Result =
1845         aliasSelect(S1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O2, AAQI);
1846     if (Result != MayAlias) {
1847       Pair = AAQI.AliasCache.try_emplace(Locs, Result);
1848       assert(!Pair.second && "Entry must have existed");
1849       return Pair.first->second = Result;
1850     }
1851   }
1852 
1853   // If both pointers are pointing into the same object and one of them
1854   // accesses the entire object, then the accesses must overlap in some way.
1855   if (O1 == O2)
1856     if (V1Size.isPrecise() && V2Size.isPrecise() &&
1857         (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
1858          isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation))) {
1859       Pair = AAQI.AliasCache.try_emplace(Locs, PartialAlias);
1860       assert(!Pair.second && "Entry must have existed");
1861       return Pair.first->second = PartialAlias;
1862     }
1863 
1864   // Recurse back into the best AA results we have, potentially with refined
1865   // memory locations. We have already ensured that BasicAA has a MayAlias
1866   // cache result for these, so any recursion back into BasicAA won't loop.
1867   AliasResult Result = getBestAAResults().alias(Locs.first, Locs.second, AAQI);
1868   Pair = AAQI.AliasCache.try_emplace(Locs, Result);
1869   assert(!Pair.second && "Entry must have existed");
1870   return Pair.first->second = Result;
1871 }
1872 
1873 /// Check whether two Values can be considered equivalent.
1874 ///
1875 /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
1876 /// they can not be part of a cycle in the value graph by looking at all
1877 /// visited phi nodes an making sure that the phis cannot reach the value. We
1878 /// have to do this because we are looking through phi nodes (That is we say
1879 /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
1880 bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
1881                                                   const Value *V2) {
1882   if (V != V2)
1883     return false;
1884 
1885   const Instruction *Inst = dyn_cast<Instruction>(V);
1886   if (!Inst)
1887     return true;
1888 
1889   if (VisitedPhiBBs.empty())
1890     return true;
1891 
1892   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1893     return false;
1894 
1895   // Make sure that the visited phis cannot reach the Value. This ensures that
1896   // the Values cannot come from different iterations of a potential cycle the
1897   // phi nodes could be involved in.
1898   for (auto *P : VisitedPhiBBs)
1899     if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT, LI))
1900       return false;
1901 
1902   return true;
1903 }
1904 
1905 /// Computes the symbolic difference between two de-composed GEPs.
1906 ///
1907 /// Dest and Src are the variable indices from two decomposed GetElementPtr
1908 /// instructions GEP1 and GEP2 which have common base pointers.
1909 void BasicAAResult::GetIndexDifference(
1910     SmallVectorImpl<VariableGEPIndex> &Dest,
1911     const SmallVectorImpl<VariableGEPIndex> &Src) {
1912   if (Src.empty())
1913     return;
1914 
1915   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1916     const Value *V = Src[i].V;
1917     unsigned ZExtBits = Src[i].ZExtBits, SExtBits = Src[i].SExtBits;
1918     APInt Scale = Src[i].Scale;
1919 
1920     // Find V in Dest.  This is N^2, but pointer indices almost never have more
1921     // than a few variable indexes.
1922     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1923       if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1924           Dest[j].ZExtBits != ZExtBits || Dest[j].SExtBits != SExtBits)
1925         continue;
1926 
1927       // If we found it, subtract off Scale V's from the entry in Dest.  If it
1928       // goes to zero, remove the entry.
1929       if (Dest[j].Scale != Scale)
1930         Dest[j].Scale -= Scale;
1931       else
1932         Dest.erase(Dest.begin() + j);
1933       Scale = 0;
1934       break;
1935     }
1936 
1937     // If we didn't consume this entry, add it to the end of the Dest list.
1938     if (!!Scale) {
1939       VariableGEPIndex Entry = {V, ZExtBits, SExtBits, -Scale};
1940       Dest.push_back(Entry);
1941     }
1942   }
1943 }
1944 
1945 bool BasicAAResult::constantOffsetHeuristic(
1946     const SmallVectorImpl<VariableGEPIndex> &VarIndices,
1947     LocationSize MaybeV1Size, LocationSize MaybeV2Size, const APInt &BaseOffset,
1948     AssumptionCache *AC, DominatorTree *DT) {
1949   if (VarIndices.size() != 2 || MaybeV1Size == LocationSize::unknown() ||
1950       MaybeV2Size == LocationSize::unknown())
1951     return false;
1952 
1953   const uint64_t V1Size = MaybeV1Size.getValue();
1954   const uint64_t V2Size = MaybeV2Size.getValue();
1955 
1956   const VariableGEPIndex &Var0 = VarIndices[0], &Var1 = VarIndices[1];
1957 
1958   if (Var0.ZExtBits != Var1.ZExtBits || Var0.SExtBits != Var1.SExtBits ||
1959       Var0.Scale != -Var1.Scale)
1960     return false;
1961 
1962   unsigned Width = Var1.V->getType()->getIntegerBitWidth();
1963 
1964   // We'll strip off the Extensions of Var0 and Var1 and do another round
1965   // of GetLinearExpression decomposition. In the example above, if Var0
1966   // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
1967 
1968   APInt V0Scale(Width, 0), V0Offset(Width, 0), V1Scale(Width, 0),
1969       V1Offset(Width, 0);
1970   bool NSW = true, NUW = true;
1971   unsigned V0ZExtBits = 0, V0SExtBits = 0, V1ZExtBits = 0, V1SExtBits = 0;
1972   const Value *V0 = GetLinearExpression(Var0.V, V0Scale, V0Offset, V0ZExtBits,
1973                                         V0SExtBits, DL, 0, AC, DT, NSW, NUW);
1974   NSW = true;
1975   NUW = true;
1976   const Value *V1 = GetLinearExpression(Var1.V, V1Scale, V1Offset, V1ZExtBits,
1977                                         V1SExtBits, DL, 0, AC, DT, NSW, NUW);
1978 
1979   if (V0Scale != V1Scale || V0ZExtBits != V1ZExtBits ||
1980       V0SExtBits != V1SExtBits || !isValueEqualInPotentialCycles(V0, V1))
1981     return false;
1982 
1983   // We have a hit - Var0 and Var1 only differ by a constant offset!
1984 
1985   // If we've been sext'ed then zext'd the maximum difference between Var0 and
1986   // Var1 is possible to calculate, but we're just interested in the absolute
1987   // minimum difference between the two. The minimum distance may occur due to
1988   // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
1989   // the minimum distance between %i and %i + 5 is 3.
1990   APInt MinDiff = V0Offset - V1Offset, Wrapped = -MinDiff;
1991   MinDiff = APIntOps::umin(MinDiff, Wrapped);
1992   APInt MinDiffBytes =
1993     MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();
1994 
1995   // We can't definitely say whether GEP1 is before or after V2 due to wrapping
1996   // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
1997   // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
1998   // V2Size can fit in the MinDiffBytes gap.
1999   return MinDiffBytes.uge(V1Size + BaseOffset.abs()) &&
2000          MinDiffBytes.uge(V2Size + BaseOffset.abs());
2001 }
2002 
2003 //===----------------------------------------------------------------------===//
2004 // BasicAliasAnalysis Pass
2005 //===----------------------------------------------------------------------===//
2006 
2007 AnalysisKey BasicAA::Key;
2008 
2009 BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
2010   return BasicAAResult(F.getParent()->getDataLayout(),
2011                        F,
2012                        AM.getResult<TargetLibraryAnalysis>(F),
2013                        AM.getResult<AssumptionAnalysis>(F),
2014                        &AM.getResult<DominatorTreeAnalysis>(F),
2015                        AM.getCachedResult<LoopAnalysis>(F),
2016                        AM.getCachedResult<PhiValuesAnalysis>(F));
2017 }
2018 
2019 BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
2020   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
2021 }
2022 
2023 char BasicAAWrapperPass::ID = 0;
2024 
2025 void BasicAAWrapperPass::anchor() {}
2026 
2027 INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa",
2028                       "Basic Alias Analysis (stateless AA impl)", true, true)
2029 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2030 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2031 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2032 INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass)
2033 INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa",
2034                     "Basic Alias Analysis (stateless AA impl)", true, true)
2035 
2036 FunctionPass *llvm::createBasicAAWrapperPass() {
2037   return new BasicAAWrapperPass();
2038 }
2039 
2040 bool BasicAAWrapperPass::runOnFunction(Function &F) {
2041   auto &ACT = getAnalysis<AssumptionCacheTracker>();
2042   auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
2043   auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
2044   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
2045   auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>();
2046 
2047   Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F,
2048                                  TLIWP.getTLI(F), ACT.getAssumptionCache(F),
2049                                  &DTWP.getDomTree(),
2050                                  LIWP ? &LIWP->getLoopInfo() : nullptr,
2051                                  PVWP ? &PVWP->getResult() : nullptr));
2052 
2053   return false;
2054 }
2055 
2056 void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
2057   AU.setPreservesAll();
2058   AU.addRequired<AssumptionCacheTracker>();
2059   AU.addRequired<DominatorTreeWrapperPass>();
2060   AU.addRequired<TargetLibraryInfoWrapperPass>();
2061   AU.addUsedIfAvailable<PhiValuesWrapperPass>();
2062 }
2063 
2064 BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) {
2065   return BasicAAResult(
2066       F.getParent()->getDataLayout(), F,
2067       P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
2068       P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
2069 }
2070