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