10b57cec5SDimitry Andric //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines the primary stateless implementation of the
100b57cec5SDimitry Andric // Alias Analysis interface that implements identities (two different
110b57cec5SDimitry Andric // globals cannot alias, etc), but does no stateful analysis.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
160b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
28480093f4SDimitry Andric #include "llvm/Analysis/PhiValues.h"
290b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
300b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
310b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
320b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
330b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
340b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
350b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
360b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
370b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
380b57cec5SDimitry Andric #include "llvm/IR/Function.h"
390b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
400b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
410b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
420b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
430b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
440b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
450b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
460b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
470b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
480b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
490b57cec5SDimitry Andric #include "llvm/IR/Type.h"
500b57cec5SDimitry Andric #include "llvm/IR/User.h"
510b57cec5SDimitry Andric #include "llvm/IR/Value.h"
52480093f4SDimitry Andric #include "llvm/InitializePasses.h"
530b57cec5SDimitry Andric #include "llvm/Pass.h"
540b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
550b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
560b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
570b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h"
580b57cec5SDimitry Andric #include <cassert>
590b57cec5SDimitry Andric #include <cstdint>
600b57cec5SDimitry Andric #include <cstdlib>
610b57cec5SDimitry Andric #include <utility>
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric #define DEBUG_TYPE "basicaa"
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric using namespace llvm;
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric /// Enable analysis of recursive PHI nodes.
685ffd83dbSDimitry Andric static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden,
690b57cec5SDimitry Andric                                           cl::init(false));
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric /// By default, even on 32-bit architectures we use 64-bit integers for
720b57cec5SDimitry Andric /// calculations. This will allow us to more-aggressively decompose indexing
730b57cec5SDimitry Andric /// expressions calculated using i64 values (e.g., long long in C) which is
740b57cec5SDimitry Andric /// common enough to worry about.
755ffd83dbSDimitry Andric static cl::opt<bool> ForceAtLeast64Bits("basic-aa-force-at-least-64b",
760b57cec5SDimitry Andric                                         cl::Hidden, cl::init(true));
775ffd83dbSDimitry Andric static cl::opt<bool> DoubleCalcBits("basic-aa-double-calc-bits",
780b57cec5SDimitry Andric                                     cl::Hidden, cl::init(false));
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric /// SearchLimitReached / SearchTimes shows how often the limit of
810b57cec5SDimitry Andric /// to decompose GEPs is reached. It will affect the precision
820b57cec5SDimitry Andric /// of basic alias analysis.
830b57cec5SDimitry Andric STATISTIC(SearchLimitReached, "Number of times the limit to "
840b57cec5SDimitry Andric                               "decompose GEPs is reached");
850b57cec5SDimitry Andric STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric /// Cutoff after which to stop analysing a set of phi nodes potentially involved
880b57cec5SDimitry Andric /// in a cycle. Because we are analysing 'through' phi nodes, we need to be
890b57cec5SDimitry Andric /// careful with value equivalence. We use reachability to make sure a value
900b57cec5SDimitry Andric /// cannot be involved in a cycle.
910b57cec5SDimitry Andric const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric // The max limit of the search depth in DecomposeGEPExpression() and
940b57cec5SDimitry Andric // GetUnderlyingObject(), both functions need to use the same search
950b57cec5SDimitry Andric // depth otherwise the algorithm in aliasGEP will assert.
960b57cec5SDimitry Andric static const unsigned MaxLookupSearchDepth = 6;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
990b57cec5SDimitry Andric                                FunctionAnalysisManager::Invalidator &Inv) {
1000b57cec5SDimitry Andric   // We don't care if this analysis itself is preserved, it has no state. But
1010b57cec5SDimitry Andric   // we need to check that the analyses it depends on have been. Note that we
1020b57cec5SDimitry Andric   // may be created without handles to some analyses and in that case don't
1030b57cec5SDimitry Andric   // depend on them.
1040b57cec5SDimitry Andric   if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
1050b57cec5SDimitry Andric       (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
1060b57cec5SDimitry Andric       (LI && Inv.invalidate<LoopAnalysis>(Fn, PA)) ||
1070b57cec5SDimitry Andric       (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA)))
1080b57cec5SDimitry Andric     return true;
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   // Otherwise this analysis result remains valid.
1110b57cec5SDimitry Andric   return false;
1120b57cec5SDimitry Andric }
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1150b57cec5SDimitry Andric // Useful predicates
1160b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric /// Returns true if the pointer is to a function-local object that never
1190b57cec5SDimitry Andric /// escapes from the function.
1200b57cec5SDimitry Andric static bool isNonEscapingLocalObject(
1210b57cec5SDimitry Andric     const Value *V,
1220b57cec5SDimitry Andric     SmallDenseMap<const Value *, bool, 8> *IsCapturedCache = nullptr) {
1230b57cec5SDimitry Andric   SmallDenseMap<const Value *, bool, 8>::iterator CacheIt;
1240b57cec5SDimitry Andric   if (IsCapturedCache) {
1250b57cec5SDimitry Andric     bool Inserted;
1260b57cec5SDimitry Andric     std::tie(CacheIt, Inserted) = IsCapturedCache->insert({V, false});
1270b57cec5SDimitry Andric     if (!Inserted)
1280b57cec5SDimitry Andric       // Found cached result, return it!
1290b57cec5SDimitry Andric       return CacheIt->second;
1300b57cec5SDimitry Andric   }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric   // If this is a local allocation, check to see if it escapes.
1330b57cec5SDimitry Andric   if (isa<AllocaInst>(V) || isNoAliasCall(V)) {
1340b57cec5SDimitry Andric     // Set StoreCaptures to True so that we can assume in our callers that the
1350b57cec5SDimitry Andric     // pointer is not the result of a load instruction. Currently
1360b57cec5SDimitry Andric     // PointerMayBeCaptured doesn't have any special analysis for the
1370b57cec5SDimitry Andric     // StoreCaptures=false case; if it did, our callers could be refined to be
1380b57cec5SDimitry Andric     // more precise.
1390b57cec5SDimitry Andric     auto Ret = !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
1400b57cec5SDimitry Andric     if (IsCapturedCache)
1410b57cec5SDimitry Andric       CacheIt->second = Ret;
1420b57cec5SDimitry Andric     return Ret;
1430b57cec5SDimitry Andric   }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric   // If this is an argument that corresponds to a byval or noalias argument,
1460b57cec5SDimitry Andric   // then it has not escaped before entering the function.  Check if it escapes
1470b57cec5SDimitry Andric   // inside the function.
1480b57cec5SDimitry Andric   if (const Argument *A = dyn_cast<Argument>(V))
1490b57cec5SDimitry Andric     if (A->hasByValAttr() || A->hasNoAliasAttr()) {
1500b57cec5SDimitry Andric       // Note even if the argument is marked nocapture, we still need to check
1510b57cec5SDimitry Andric       // for copies made inside the function. The nocapture attribute only
1520b57cec5SDimitry Andric       // specifies that there are no copies made that outlive the function.
1530b57cec5SDimitry Andric       auto Ret = !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
1540b57cec5SDimitry Andric       if (IsCapturedCache)
1550b57cec5SDimitry Andric         CacheIt->second = Ret;
1560b57cec5SDimitry Andric       return Ret;
1570b57cec5SDimitry Andric     }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   return false;
1600b57cec5SDimitry Andric }
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric /// Returns true if the pointer is one which would have been considered an
1630b57cec5SDimitry Andric /// escape by isNonEscapingLocalObject.
1640b57cec5SDimitry Andric static bool isEscapeSource(const Value *V) {
1650b57cec5SDimitry Andric   if (isa<CallBase>(V))
1660b57cec5SDimitry Andric     return true;
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   if (isa<Argument>(V))
1690b57cec5SDimitry Andric     return true;
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   // The load case works because isNonEscapingLocalObject considers all
1720b57cec5SDimitry Andric   // stores to be escapes (it passes true for the StoreCaptures argument
1730b57cec5SDimitry Andric   // to PointerMayBeCaptured).
1740b57cec5SDimitry Andric   if (isa<LoadInst>(V))
1750b57cec5SDimitry Andric     return true;
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   return false;
1780b57cec5SDimitry Andric }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric /// Returns the size of the object specified by V or UnknownSize if unknown.
1810b57cec5SDimitry Andric static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
1820b57cec5SDimitry Andric                               const TargetLibraryInfo &TLI,
1830b57cec5SDimitry Andric                               bool NullIsValidLoc,
1840b57cec5SDimitry Andric                               bool RoundToAlign = false) {
1850b57cec5SDimitry Andric   uint64_t Size;
1860b57cec5SDimitry Andric   ObjectSizeOpts Opts;
1870b57cec5SDimitry Andric   Opts.RoundToAlign = RoundToAlign;
1880b57cec5SDimitry Andric   Opts.NullIsUnknownSize = NullIsValidLoc;
1890b57cec5SDimitry Andric   if (getObjectSize(V, Size, DL, &TLI, Opts))
1900b57cec5SDimitry Andric     return Size;
1910b57cec5SDimitry Andric   return MemoryLocation::UnknownSize;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V is smaller than
1950b57cec5SDimitry Andric /// Size.
1960b57cec5SDimitry Andric static bool isObjectSmallerThan(const Value *V, uint64_t Size,
1970b57cec5SDimitry Andric                                 const DataLayout &DL,
1980b57cec5SDimitry Andric                                 const TargetLibraryInfo &TLI,
1990b57cec5SDimitry Andric                                 bool NullIsValidLoc) {
2000b57cec5SDimitry Andric   // Note that the meanings of the "object" are slightly different in the
2010b57cec5SDimitry Andric   // following contexts:
2020b57cec5SDimitry Andric   //    c1: llvm::getObjectSize()
2030b57cec5SDimitry Andric   //    c2: llvm.objectsize() intrinsic
2040b57cec5SDimitry Andric   //    c3: isObjectSmallerThan()
2050b57cec5SDimitry Andric   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
2060b57cec5SDimitry Andric   // refers to the "entire object".
2070b57cec5SDimitry Andric   //
2080b57cec5SDimitry Andric   //  Consider this example:
2090b57cec5SDimitry Andric   //     char *p = (char*)malloc(100)
2100b57cec5SDimitry Andric   //     char *q = p+80;
2110b57cec5SDimitry Andric   //
2120b57cec5SDimitry Andric   //  In the context of c1 and c2, the "object" pointed by q refers to the
2130b57cec5SDimitry Andric   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
2140b57cec5SDimitry Andric   //
2150b57cec5SDimitry Andric   //  However, in the context of c3, the "object" refers to the chunk of memory
2160b57cec5SDimitry Andric   // being allocated. So, the "object" has 100 bytes, and q points to the middle
2170b57cec5SDimitry Andric   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
2180b57cec5SDimitry Andric   // parameter, before the llvm::getObjectSize() is called to get the size of
2190b57cec5SDimitry Andric   // entire object, we should:
2200b57cec5SDimitry Andric   //    - either rewind the pointer q to the base-address of the object in
2210b57cec5SDimitry Andric   //      question (in this case rewind to p), or
2220b57cec5SDimitry Andric   //    - just give up. It is up to caller to make sure the pointer is pointing
2230b57cec5SDimitry Andric   //      to the base address the object.
2240b57cec5SDimitry Andric   //
2250b57cec5SDimitry Andric   // We go for 2nd option for simplicity.
2260b57cec5SDimitry Andric   if (!isIdentifiedObject(V))
2270b57cec5SDimitry Andric     return false;
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   // This function needs to use the aligned object size because we allow
2300b57cec5SDimitry Andric   // reads a bit past the end given sufficient alignment.
2310b57cec5SDimitry Andric   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
2320b57cec5SDimitry Andric                                       /*RoundToAlign*/ true);
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric 
2378bcb0991SDimitry Andric /// Return the minimal extent from \p V to the end of the underlying object,
2388bcb0991SDimitry Andric /// assuming the result is used in an aliasing query. E.g., we do use the query
2398bcb0991SDimitry Andric /// location size and the fact that null pointers cannot alias here.
2408bcb0991SDimitry Andric static uint64_t getMinimalExtentFrom(const Value &V,
2418bcb0991SDimitry Andric                                      const LocationSize &LocSize,
2428bcb0991SDimitry Andric                                      const DataLayout &DL,
2438bcb0991SDimitry Andric                                      bool NullIsValidLoc) {
2448bcb0991SDimitry Andric   // If we have dereferenceability information we know a lower bound for the
2458bcb0991SDimitry Andric   // extent as accesses for a lower offset would be valid. We need to exclude
2468bcb0991SDimitry Andric   // the "or null" part if null is a valid pointer.
2478bcb0991SDimitry Andric   bool CanBeNull;
2488bcb0991SDimitry Andric   uint64_t DerefBytes = V.getPointerDereferenceableBytes(DL, CanBeNull);
2498bcb0991SDimitry Andric   DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
2508bcb0991SDimitry Andric   // If queried with a precise location size, we assume that location size to be
2518bcb0991SDimitry Andric   // accessed, thus valid.
2528bcb0991SDimitry Andric   if (LocSize.isPrecise())
2538bcb0991SDimitry Andric     DerefBytes = std::max(DerefBytes, LocSize.getValue());
2548bcb0991SDimitry Andric   return DerefBytes;
2558bcb0991SDimitry Andric }
2568bcb0991SDimitry Andric 
2570b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V has size Size.
2580b57cec5SDimitry Andric static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
2590b57cec5SDimitry Andric                          const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
2600b57cec5SDimitry Andric   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc);
2610b57cec5SDimitry Andric   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
2620b57cec5SDimitry Andric }
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2650b57cec5SDimitry Andric // GetElementPtr Instruction Decomposition and Analysis
2660b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric /// Analyzes the specified value as a linear expression: "A*V + B", where A and
2690b57cec5SDimitry Andric /// B are constant integers.
2700b57cec5SDimitry Andric ///
2710b57cec5SDimitry Andric /// Returns the scale and offset values as APInts and return V as a Value*, and
2720b57cec5SDimitry Andric /// return whether we looked through any sign or zero extends.  The incoming
2730b57cec5SDimitry Andric /// Value is known to have IntegerType, and it may already be sign or zero
2740b57cec5SDimitry Andric /// extended.
2750b57cec5SDimitry Andric ///
2760b57cec5SDimitry Andric /// Note that this looks through extends, so the high bits may not be
2770b57cec5SDimitry Andric /// represented in the result.
2780b57cec5SDimitry Andric /*static*/ const Value *BasicAAResult::GetLinearExpression(
2790b57cec5SDimitry Andric     const Value *V, APInt &Scale, APInt &Offset, unsigned &ZExtBits,
2800b57cec5SDimitry Andric     unsigned &SExtBits, const DataLayout &DL, unsigned Depth,
2810b57cec5SDimitry Andric     AssumptionCache *AC, DominatorTree *DT, bool &NSW, bool &NUW) {
2820b57cec5SDimitry Andric   assert(V->getType()->isIntegerTy() && "Not an integer value");
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric   // Limit our recursion depth.
2850b57cec5SDimitry Andric   if (Depth == 6) {
2860b57cec5SDimitry Andric     Scale = 1;
2870b57cec5SDimitry Andric     Offset = 0;
2880b57cec5SDimitry Andric     return V;
2890b57cec5SDimitry Andric   }
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   if (const ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
2920b57cec5SDimitry Andric     // If it's a constant, just convert it to an offset and remove the variable.
2930b57cec5SDimitry Andric     // If we've been called recursively, the Offset bit width will be greater
2940b57cec5SDimitry Andric     // than the constant's (the Offset's always as wide as the outermost call),
2950b57cec5SDimitry Andric     // so we'll zext here and process any extension in the isa<SExtInst> &
2960b57cec5SDimitry Andric     // isa<ZExtInst> cases below.
2970b57cec5SDimitry Andric     Offset += Const->getValue().zextOrSelf(Offset.getBitWidth());
2980b57cec5SDimitry Andric     assert(Scale == 0 && "Constant values don't have a scale");
2990b57cec5SDimitry Andric     return V;
3000b57cec5SDimitry Andric   }
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
3030b57cec5SDimitry Andric     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
3040b57cec5SDimitry Andric       // If we've been called recursively, then Offset and Scale will be wider
3050b57cec5SDimitry Andric       // than the BOp operands. We'll always zext it here as we'll process sign
3060b57cec5SDimitry Andric       // extensions below (see the isa<SExtInst> / isa<ZExtInst> cases).
3070b57cec5SDimitry Andric       APInt RHS = RHSC->getValue().zextOrSelf(Offset.getBitWidth());
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric       switch (BOp->getOpcode()) {
3100b57cec5SDimitry Andric       default:
3110b57cec5SDimitry Andric         // We don't understand this instruction, so we can't decompose it any
3120b57cec5SDimitry Andric         // further.
3130b57cec5SDimitry Andric         Scale = 1;
3140b57cec5SDimitry Andric         Offset = 0;
3150b57cec5SDimitry Andric         return V;
3160b57cec5SDimitry Andric       case Instruction::Or:
3170b57cec5SDimitry Andric         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
3180b57cec5SDimitry Andric         // analyze it.
3190b57cec5SDimitry Andric         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
3200b57cec5SDimitry Andric                                BOp, DT)) {
3210b57cec5SDimitry Andric           Scale = 1;
3220b57cec5SDimitry Andric           Offset = 0;
3230b57cec5SDimitry Andric           return V;
3240b57cec5SDimitry Andric         }
3250b57cec5SDimitry Andric         LLVM_FALLTHROUGH;
3260b57cec5SDimitry Andric       case Instruction::Add:
3270b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
3280b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
3290b57cec5SDimitry Andric         Offset += RHS;
3300b57cec5SDimitry Andric         break;
3310b57cec5SDimitry Andric       case Instruction::Sub:
3320b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
3330b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
3340b57cec5SDimitry Andric         Offset -= RHS;
3350b57cec5SDimitry Andric         break;
3360b57cec5SDimitry Andric       case Instruction::Mul:
3370b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
3380b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
3390b57cec5SDimitry Andric         Offset *= RHS;
3400b57cec5SDimitry Andric         Scale *= RHS;
3410b57cec5SDimitry Andric         break;
3420b57cec5SDimitry Andric       case Instruction::Shl:
3430b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
3440b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric         // We're trying to linearize an expression of the kind:
3470b57cec5SDimitry Andric         //   shl i8 -128, 36
3480b57cec5SDimitry Andric         // where the shift count exceeds the bitwidth of the type.
3490b57cec5SDimitry Andric         // We can't decompose this further (the expression would return
3500b57cec5SDimitry Andric         // a poison value).
3510b57cec5SDimitry Andric         if (Offset.getBitWidth() < RHS.getLimitedValue() ||
3520b57cec5SDimitry Andric             Scale.getBitWidth() < RHS.getLimitedValue()) {
3530b57cec5SDimitry Andric           Scale = 1;
3540b57cec5SDimitry Andric           Offset = 0;
3550b57cec5SDimitry Andric           return V;
3560b57cec5SDimitry Andric         }
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric         Offset <<= RHS.getLimitedValue();
3590b57cec5SDimitry Andric         Scale <<= RHS.getLimitedValue();
3600b57cec5SDimitry Andric         // the semantics of nsw and nuw for left shifts don't match those of
3610b57cec5SDimitry Andric         // multiplications, so we won't propagate them.
3620b57cec5SDimitry Andric         NSW = NUW = false;
3630b57cec5SDimitry Andric         return V;
3640b57cec5SDimitry Andric       }
3650b57cec5SDimitry Andric 
3660b57cec5SDimitry Andric       if (isa<OverflowingBinaryOperator>(BOp)) {
3670b57cec5SDimitry Andric         NUW &= BOp->hasNoUnsignedWrap();
3680b57cec5SDimitry Andric         NSW &= BOp->hasNoSignedWrap();
3690b57cec5SDimitry Andric       }
3700b57cec5SDimitry Andric       return V;
3710b57cec5SDimitry Andric     }
3720b57cec5SDimitry Andric   }
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   // Since GEP indices are sign extended anyway, we don't care about the high
3750b57cec5SDimitry Andric   // bits of a sign or zero extended value - just scales and offsets.  The
3760b57cec5SDimitry Andric   // extensions have to be consistent though.
3770b57cec5SDimitry Andric   if (isa<SExtInst>(V) || isa<ZExtInst>(V)) {
3780b57cec5SDimitry Andric     Value *CastOp = cast<CastInst>(V)->getOperand(0);
3790b57cec5SDimitry Andric     unsigned NewWidth = V->getType()->getPrimitiveSizeInBits();
3800b57cec5SDimitry Andric     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
3810b57cec5SDimitry Andric     unsigned OldZExtBits = ZExtBits, OldSExtBits = SExtBits;
3820b57cec5SDimitry Andric     const Value *Result =
3830b57cec5SDimitry Andric         GetLinearExpression(CastOp, Scale, Offset, ZExtBits, SExtBits, DL,
3840b57cec5SDimitry Andric                             Depth + 1, AC, DT, NSW, NUW);
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric     // zext(zext(%x)) == zext(%x), and similarly for sext; we'll handle this
3870b57cec5SDimitry Andric     // by just incrementing the number of bits we've extended by.
3880b57cec5SDimitry Andric     unsigned ExtendedBy = NewWidth - SmallWidth;
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric     if (isa<SExtInst>(V) && ZExtBits == 0) {
3910b57cec5SDimitry Andric       // sext(sext(%x, a), b) == sext(%x, a + b)
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric       if (NSW) {
3940b57cec5SDimitry Andric         // We haven't sign-wrapped, so it's valid to decompose sext(%x + c)
3950b57cec5SDimitry Andric         // into sext(%x) + sext(c). We'll sext the Offset ourselves:
3960b57cec5SDimitry Andric         unsigned OldWidth = Offset.getBitWidth();
3970b57cec5SDimitry Andric         Offset = Offset.trunc(SmallWidth).sext(NewWidth).zextOrSelf(OldWidth);
3980b57cec5SDimitry Andric       } else {
3990b57cec5SDimitry Andric         // We may have signed-wrapped, so don't decompose sext(%x + c) into
4000b57cec5SDimitry Andric         // sext(%x) + sext(c)
4010b57cec5SDimitry Andric         Scale = 1;
4020b57cec5SDimitry Andric         Offset = 0;
4030b57cec5SDimitry Andric         Result = CastOp;
4040b57cec5SDimitry Andric         ZExtBits = OldZExtBits;
4050b57cec5SDimitry Andric         SExtBits = OldSExtBits;
4060b57cec5SDimitry Andric       }
4070b57cec5SDimitry Andric       SExtBits += ExtendedBy;
4080b57cec5SDimitry Andric     } else {
4090b57cec5SDimitry Andric       // sext(zext(%x, a), b) = zext(zext(%x, a), b) = zext(%x, a + b)
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric       if (!NUW) {
4120b57cec5SDimitry Andric         // We may have unsigned-wrapped, so don't decompose zext(%x + c) into
4130b57cec5SDimitry Andric         // zext(%x) + zext(c)
4140b57cec5SDimitry Andric         Scale = 1;
4150b57cec5SDimitry Andric         Offset = 0;
4160b57cec5SDimitry Andric         Result = CastOp;
4170b57cec5SDimitry Andric         ZExtBits = OldZExtBits;
4180b57cec5SDimitry Andric         SExtBits = OldSExtBits;
4190b57cec5SDimitry Andric       }
4200b57cec5SDimitry Andric       ZExtBits += ExtendedBy;
4210b57cec5SDimitry Andric     }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric     return Result;
4240b57cec5SDimitry Andric   }
4250b57cec5SDimitry Andric 
4260b57cec5SDimitry Andric   Scale = 1;
4270b57cec5SDimitry Andric   Offset = 0;
4280b57cec5SDimitry Andric   return V;
4290b57cec5SDimitry Andric }
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric /// To ensure a pointer offset fits in an integer of size PointerSize
4320b57cec5SDimitry Andric /// (in bits) when that size is smaller than the maximum pointer size. This is
4330b57cec5SDimitry Andric /// an issue, for example, in particular for 32b pointers with negative indices
4340b57cec5SDimitry Andric /// that rely on two's complement wrap-arounds for precise alias information
4350b57cec5SDimitry Andric /// where the maximum pointer size is 64b.
4365ffd83dbSDimitry Andric static APInt adjustToPointerSize(const APInt &Offset, unsigned PointerSize) {
4370b57cec5SDimitry Andric   assert(PointerSize <= Offset.getBitWidth() && "Invalid PointerSize!");
4380b57cec5SDimitry Andric   unsigned ShiftBits = Offset.getBitWidth() - PointerSize;
4390b57cec5SDimitry Andric   return (Offset << ShiftBits).ashr(ShiftBits);
4400b57cec5SDimitry Andric }
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric static unsigned getMaxPointerSize(const DataLayout &DL) {
4430b57cec5SDimitry Andric   unsigned MaxPointerSize = DL.getMaxPointerSizeInBits();
4440b57cec5SDimitry Andric   if (MaxPointerSize < 64 && ForceAtLeast64Bits) MaxPointerSize = 64;
4450b57cec5SDimitry Andric   if (DoubleCalcBits) MaxPointerSize *= 2;
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   return MaxPointerSize;
4480b57cec5SDimitry Andric }
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric /// If V is a symbolic pointer expression, decompose it into a base pointer
4510b57cec5SDimitry Andric /// with a constant offset and a number of scaled symbolic offsets.
4520b57cec5SDimitry Andric ///
4530b57cec5SDimitry Andric /// The scaled symbolic offsets (represented by pairs of a Value* and a scale
4540b57cec5SDimitry Andric /// in the VarIndices vector) are Value*'s that are known to be scaled by the
4550b57cec5SDimitry Andric /// specified amount, but which may have other unrepresented high bits. As
4560b57cec5SDimitry Andric /// such, the gep cannot necessarily be reconstructed from its decomposed form.
4570b57cec5SDimitry Andric ///
4580b57cec5SDimitry Andric /// When DataLayout is around, this function is capable of analyzing everything
4590b57cec5SDimitry Andric /// that GetUnderlyingObject can look through. To be able to do that
4600b57cec5SDimitry Andric /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
4610b57cec5SDimitry Andric /// depth (MaxLookupSearchDepth). When DataLayout not is around, it just looks
4620b57cec5SDimitry Andric /// through pointer casts.
4630b57cec5SDimitry Andric bool BasicAAResult::DecomposeGEPExpression(const Value *V,
4640b57cec5SDimitry Andric        DecomposedGEP &Decomposed, const DataLayout &DL, AssumptionCache *AC,
4650b57cec5SDimitry Andric        DominatorTree *DT) {
4660b57cec5SDimitry Andric   // Limit recursion depth to limit compile time in crazy cases.
4670b57cec5SDimitry Andric   unsigned MaxLookup = MaxLookupSearchDepth;
4680b57cec5SDimitry Andric   SearchTimes++;
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   unsigned MaxPointerSize = getMaxPointerSize(DL);
4710b57cec5SDimitry Andric   Decomposed.VarIndices.clear();
4720b57cec5SDimitry Andric   do {
4730b57cec5SDimitry Andric     // See if this is a bitcast or GEP.
4740b57cec5SDimitry Andric     const Operator *Op = dyn_cast<Operator>(V);
4750b57cec5SDimitry Andric     if (!Op) {
4760b57cec5SDimitry Andric       // The only non-operator case we can handle are GlobalAliases.
4770b57cec5SDimitry Andric       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
4780b57cec5SDimitry Andric         if (!GA->isInterposable()) {
4790b57cec5SDimitry Andric           V = GA->getAliasee();
4800b57cec5SDimitry Andric           continue;
4810b57cec5SDimitry Andric         }
4820b57cec5SDimitry Andric       }
4830b57cec5SDimitry Andric       Decomposed.Base = V;
4840b57cec5SDimitry Andric       return false;
4850b57cec5SDimitry Andric     }
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric     if (Op->getOpcode() == Instruction::BitCast ||
4880b57cec5SDimitry Andric         Op->getOpcode() == Instruction::AddrSpaceCast) {
4890b57cec5SDimitry Andric       V = Op->getOperand(0);
4900b57cec5SDimitry Andric       continue;
4910b57cec5SDimitry Andric     }
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
4940b57cec5SDimitry Andric     if (!GEPOp) {
4955ffd83dbSDimitry Andric       if (const auto *PHI = dyn_cast<PHINode>(V)) {
4965ffd83dbSDimitry Andric         // Look through single-arg phi nodes created by LCSSA.
4975ffd83dbSDimitry Andric         if (PHI->getNumIncomingValues() == 1) {
4985ffd83dbSDimitry Andric           V = PHI->getIncomingValue(0);
4995ffd83dbSDimitry Andric           continue;
5005ffd83dbSDimitry Andric         }
5015ffd83dbSDimitry Andric       } else if (const auto *Call = dyn_cast<CallBase>(V)) {
5020b57cec5SDimitry Andric         // CaptureTracking can know about special capturing properties of some
5030b57cec5SDimitry Andric         // intrinsics like launder.invariant.group, that can't be expressed with
5040b57cec5SDimitry Andric         // the attributes, but have properties like returning aliasing pointer.
5050b57cec5SDimitry Andric         // Because some analysis may assume that nocaptured pointer is not
5060b57cec5SDimitry Andric         // returned from some special intrinsic (because function would have to
5070b57cec5SDimitry Andric         // be marked with returns attribute), it is crucial to use this function
5080b57cec5SDimitry Andric         // because it should be in sync with CaptureTracking. Not using it may
5090b57cec5SDimitry Andric         // cause weird miscompilations where 2 aliasing pointers are assumed to
5100b57cec5SDimitry Andric         // noalias.
5118bcb0991SDimitry Andric         if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
5120b57cec5SDimitry Andric           V = RP;
5130b57cec5SDimitry Andric           continue;
5140b57cec5SDimitry Andric         }
5150b57cec5SDimitry Andric       }
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric       Decomposed.Base = V;
5180b57cec5SDimitry Andric       return false;
5190b57cec5SDimitry Andric     }
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric     // Don't attempt to analyze GEPs over unsized objects.
5220b57cec5SDimitry Andric     if (!GEPOp->getSourceElementType()->isSized()) {
5230b57cec5SDimitry Andric       Decomposed.Base = V;
5240b57cec5SDimitry Andric       return false;
5250b57cec5SDimitry Andric     }
5260b57cec5SDimitry Andric 
5275ffd83dbSDimitry Andric     // Don't attempt to analyze GEPs if index scale is not a compile-time
5285ffd83dbSDimitry Andric     // constant.
5295ffd83dbSDimitry Andric     if (isa<ScalableVectorType>(GEPOp->getSourceElementType())) {
5305ffd83dbSDimitry Andric       Decomposed.Base = V;
5315ffd83dbSDimitry Andric       Decomposed.HasCompileTimeConstantScale = false;
5325ffd83dbSDimitry Andric       return false;
5335ffd83dbSDimitry Andric     }
5345ffd83dbSDimitry Andric 
5350b57cec5SDimitry Andric     unsigned AS = GEPOp->getPointerAddressSpace();
5360b57cec5SDimitry Andric     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
5370b57cec5SDimitry Andric     gep_type_iterator GTI = gep_type_begin(GEPOp);
5380b57cec5SDimitry Andric     unsigned PointerSize = DL.getPointerSizeInBits(AS);
5390b57cec5SDimitry Andric     // Assume all GEP operands are constants until proven otherwise.
5400b57cec5SDimitry Andric     bool GepHasConstantOffset = true;
5410b57cec5SDimitry Andric     for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
5420b57cec5SDimitry Andric          I != E; ++I, ++GTI) {
5430b57cec5SDimitry Andric       const Value *Index = *I;
5440b57cec5SDimitry Andric       // Compute the (potentially symbolic) offset in bytes for this index.
5450b57cec5SDimitry Andric       if (StructType *STy = GTI.getStructTypeOrNull()) {
5460b57cec5SDimitry Andric         // For a struct, add the member offset.
5470b57cec5SDimitry Andric         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
5480b57cec5SDimitry Andric         if (FieldNo == 0)
5490b57cec5SDimitry Andric           continue;
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric         Decomposed.StructOffset +=
5520b57cec5SDimitry Andric           DL.getStructLayout(STy)->getElementOffset(FieldNo);
5530b57cec5SDimitry Andric         continue;
5540b57cec5SDimitry Andric       }
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric       // For an array/pointer, add the element offset, explicitly scaled.
5570b57cec5SDimitry Andric       if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
5580b57cec5SDimitry Andric         if (CIdx->isZero())
5590b57cec5SDimitry Andric           continue;
5600b57cec5SDimitry Andric         Decomposed.OtherOffset +=
5615ffd83dbSDimitry Andric             (DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize() *
5620b57cec5SDimitry Andric              CIdx->getValue().sextOrSelf(MaxPointerSize))
5630b57cec5SDimitry Andric                 .sextOrTrunc(MaxPointerSize);
5640b57cec5SDimitry Andric         continue;
5650b57cec5SDimitry Andric       }
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric       GepHasConstantOffset = false;
5680b57cec5SDimitry Andric 
5695ffd83dbSDimitry Andric       APInt Scale(MaxPointerSize,
5705ffd83dbSDimitry Andric                   DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize());
5710b57cec5SDimitry Andric       unsigned ZExtBits = 0, SExtBits = 0;
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric       // If the integer type is smaller than the pointer size, it is implicitly
5740b57cec5SDimitry Andric       // sign extended to pointer size.
5750b57cec5SDimitry Andric       unsigned Width = Index->getType()->getIntegerBitWidth();
5760b57cec5SDimitry Andric       if (PointerSize > Width)
5770b57cec5SDimitry Andric         SExtBits += PointerSize - Width;
5780b57cec5SDimitry Andric 
5790b57cec5SDimitry Andric       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
5800b57cec5SDimitry Andric       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
5810b57cec5SDimitry Andric       bool NSW = true, NUW = true;
5820b57cec5SDimitry Andric       const Value *OrigIndex = Index;
5830b57cec5SDimitry Andric       Index = GetLinearExpression(Index, IndexScale, IndexOffset, ZExtBits,
5840b57cec5SDimitry Andric                                   SExtBits, DL, 0, AC, DT, NSW, NUW);
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
5870b57cec5SDimitry Andric       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric       // It can be the case that, even through C1*V+C2 does not overflow for
5900b57cec5SDimitry Andric       // relevant values of V, (C2*Scale) can overflow. In that case, we cannot
5910b57cec5SDimitry Andric       // decompose the expression in this way.
5920b57cec5SDimitry Andric       //
5930b57cec5SDimitry Andric       // FIXME: C1*Scale and the other operations in the decomposed
5940b57cec5SDimitry Andric       // (C1*Scale)*V+C2*Scale can also overflow. We should check for this
5950b57cec5SDimitry Andric       // possibility.
5960b57cec5SDimitry Andric       APInt WideScaledOffset = IndexOffset.sextOrTrunc(MaxPointerSize*2) *
5970b57cec5SDimitry Andric                                  Scale.sext(MaxPointerSize*2);
5980b57cec5SDimitry Andric       if (WideScaledOffset.getMinSignedBits() > MaxPointerSize) {
5990b57cec5SDimitry Andric         Index = OrigIndex;
6000b57cec5SDimitry Andric         IndexScale = 1;
6010b57cec5SDimitry Andric         IndexOffset = 0;
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric         ZExtBits = SExtBits = 0;
6040b57cec5SDimitry Andric         if (PointerSize > Width)
6050b57cec5SDimitry Andric           SExtBits += PointerSize - Width;
6060b57cec5SDimitry Andric       } else {
6070b57cec5SDimitry Andric         Decomposed.OtherOffset += IndexOffset.sextOrTrunc(MaxPointerSize) * Scale;
6080b57cec5SDimitry Andric         Scale *= IndexScale.sextOrTrunc(MaxPointerSize);
6090b57cec5SDimitry Andric       }
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric       // If we already had an occurrence of this index variable, merge this
6120b57cec5SDimitry Andric       // scale into it.  For example, we want to handle:
6130b57cec5SDimitry Andric       //   A[x][x] -> x*16 + x*4 -> x*20
6140b57cec5SDimitry Andric       // This also ensures that 'x' only appears in the index list once.
6150b57cec5SDimitry Andric       for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
6160b57cec5SDimitry Andric         if (Decomposed.VarIndices[i].V == Index &&
6170b57cec5SDimitry Andric             Decomposed.VarIndices[i].ZExtBits == ZExtBits &&
6180b57cec5SDimitry Andric             Decomposed.VarIndices[i].SExtBits == SExtBits) {
6190b57cec5SDimitry Andric           Scale += Decomposed.VarIndices[i].Scale;
6200b57cec5SDimitry Andric           Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
6210b57cec5SDimitry Andric           break;
6220b57cec5SDimitry Andric         }
6230b57cec5SDimitry Andric       }
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric       // Make sure that we have a scale that makes sense for this target's
6260b57cec5SDimitry Andric       // pointer size.
6270b57cec5SDimitry Andric       Scale = adjustToPointerSize(Scale, PointerSize);
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric       if (!!Scale) {
6300b57cec5SDimitry Andric         VariableGEPIndex Entry = {Index, ZExtBits, SExtBits, Scale};
6310b57cec5SDimitry Andric         Decomposed.VarIndices.push_back(Entry);
6320b57cec5SDimitry Andric       }
6330b57cec5SDimitry Andric     }
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric     // Take care of wrap-arounds
6360b57cec5SDimitry Andric     if (GepHasConstantOffset) {
6370b57cec5SDimitry Andric       Decomposed.StructOffset =
6380b57cec5SDimitry Andric           adjustToPointerSize(Decomposed.StructOffset, PointerSize);
6390b57cec5SDimitry Andric       Decomposed.OtherOffset =
6400b57cec5SDimitry Andric           adjustToPointerSize(Decomposed.OtherOffset, PointerSize);
6410b57cec5SDimitry Andric     }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric     // Analyze the base pointer next.
6440b57cec5SDimitry Andric     V = GEPOp->getOperand(0);
6450b57cec5SDimitry Andric   } while (--MaxLookup);
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric   // If the chain of expressions is too deep, just return early.
6480b57cec5SDimitry Andric   Decomposed.Base = V;
6490b57cec5SDimitry Andric   SearchLimitReached++;
6500b57cec5SDimitry Andric   return true;
6510b57cec5SDimitry Andric }
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric /// Returns whether the given pointer value points to memory that is local to
6540b57cec5SDimitry Andric /// the function, with global constants being considered local to all
6550b57cec5SDimitry Andric /// functions.
6560b57cec5SDimitry Andric bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
6570b57cec5SDimitry Andric                                            AAQueryInfo &AAQI, bool OrLocal) {
6580b57cec5SDimitry Andric   assert(Visited.empty() && "Visited must be cleared after use!");
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric   unsigned MaxLookup = 8;
6610b57cec5SDimitry Andric   SmallVector<const Value *, 16> Worklist;
6620b57cec5SDimitry Andric   Worklist.push_back(Loc.Ptr);
6630b57cec5SDimitry Andric   do {
6640b57cec5SDimitry Andric     const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
6650b57cec5SDimitry Andric     if (!Visited.insert(V).second) {
6660b57cec5SDimitry Andric       Visited.clear();
6670b57cec5SDimitry Andric       return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
6680b57cec5SDimitry Andric     }
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric     // An alloca instruction defines local memory.
6710b57cec5SDimitry Andric     if (OrLocal && isa<AllocaInst>(V))
6720b57cec5SDimitry Andric       continue;
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric     // A global constant counts as local memory for our purposes.
6750b57cec5SDimitry Andric     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6760b57cec5SDimitry Andric       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
6770b57cec5SDimitry Andric       // global to be marked constant in some modules and non-constant in
6780b57cec5SDimitry Andric       // others.  GV may even be a declaration, not a definition.
6790b57cec5SDimitry Andric       if (!GV->isConstant()) {
6800b57cec5SDimitry Andric         Visited.clear();
6810b57cec5SDimitry Andric         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
6820b57cec5SDimitry Andric       }
6830b57cec5SDimitry Andric       continue;
6840b57cec5SDimitry Andric     }
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric     // If both select values point to local memory, then so does the select.
6870b57cec5SDimitry Andric     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
6880b57cec5SDimitry Andric       Worklist.push_back(SI->getTrueValue());
6890b57cec5SDimitry Andric       Worklist.push_back(SI->getFalseValue());
6900b57cec5SDimitry Andric       continue;
6910b57cec5SDimitry Andric     }
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric     // If all values incoming to a phi node point to local memory, then so does
6940b57cec5SDimitry Andric     // the phi.
6950b57cec5SDimitry Andric     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
6960b57cec5SDimitry Andric       // Don't bother inspecting phi nodes with many operands.
6970b57cec5SDimitry Andric       if (PN->getNumIncomingValues() > MaxLookup) {
6980b57cec5SDimitry Andric         Visited.clear();
6990b57cec5SDimitry Andric         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
7000b57cec5SDimitry Andric       }
7010b57cec5SDimitry Andric       for (Value *IncValue : PN->incoming_values())
7020b57cec5SDimitry Andric         Worklist.push_back(IncValue);
7030b57cec5SDimitry Andric       continue;
7040b57cec5SDimitry Andric     }
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric     // Otherwise be conservative.
7070b57cec5SDimitry Andric     Visited.clear();
7080b57cec5SDimitry Andric     return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
7090b57cec5SDimitry Andric   } while (!Worklist.empty() && --MaxLookup);
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric   Visited.clear();
7120b57cec5SDimitry Andric   return Worklist.empty();
7130b57cec5SDimitry Andric }
7140b57cec5SDimitry Andric 
7150b57cec5SDimitry Andric /// Returns the behavior when calling the given call site.
7160b57cec5SDimitry Andric FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) {
7170b57cec5SDimitry Andric   if (Call->doesNotAccessMemory())
7180b57cec5SDimitry Andric     // Can't do better than this.
7190b57cec5SDimitry Andric     return FMRB_DoesNotAccessMemory;
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   // If the callsite knows it only reads memory, don't return worse
7240b57cec5SDimitry Andric   // than that.
7250b57cec5SDimitry Andric   if (Call->onlyReadsMemory())
7260b57cec5SDimitry Andric     Min = FMRB_OnlyReadsMemory;
7270b57cec5SDimitry Andric   else if (Call->doesNotReadMemory())
7285ffd83dbSDimitry Andric     Min = FMRB_OnlyWritesMemory;
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   if (Call->onlyAccessesArgMemory())
7310b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
7320b57cec5SDimitry Andric   else if (Call->onlyAccessesInaccessibleMemory())
7330b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
7340b57cec5SDimitry Andric   else if (Call->onlyAccessesInaccessibleMemOrArgMem())
7350b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric   // If the call has operand bundles then aliasing attributes from the function
7380b57cec5SDimitry Andric   // it calls do not directly apply to the call.  This can be made more precise
7390b57cec5SDimitry Andric   // in the future.
7400b57cec5SDimitry Andric   if (!Call->hasOperandBundles())
7410b57cec5SDimitry Andric     if (const Function *F = Call->getCalledFunction())
7420b57cec5SDimitry Andric       Min =
7430b57cec5SDimitry Andric           FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F));
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   return Min;
7460b57cec5SDimitry Andric }
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric /// Returns the behavior when calling the given function. For use when the call
7490b57cec5SDimitry Andric /// site is not known.
7500b57cec5SDimitry Andric FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
7510b57cec5SDimitry Andric   // If the function declares it doesn't access memory, we can't do better.
7520b57cec5SDimitry Andric   if (F->doesNotAccessMemory())
7530b57cec5SDimitry Andric     return FMRB_DoesNotAccessMemory;
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric   // If the function declares it only reads memory, go with that.
7580b57cec5SDimitry Andric   if (F->onlyReadsMemory())
7590b57cec5SDimitry Andric     Min = FMRB_OnlyReadsMemory;
7600b57cec5SDimitry Andric   else if (F->doesNotReadMemory())
7615ffd83dbSDimitry Andric     Min = FMRB_OnlyWritesMemory;
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric   if (F->onlyAccessesArgMemory())
7640b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
7650b57cec5SDimitry Andric   else if (F->onlyAccessesInaccessibleMemory())
7660b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
7670b57cec5SDimitry Andric   else if (F->onlyAccessesInaccessibleMemOrArgMem())
7680b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric   return Min;
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric /// Returns true if this is a writeonly (i.e Mod only) parameter.
7740b57cec5SDimitry Andric static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx,
7750b57cec5SDimitry Andric                              const TargetLibraryInfo &TLI) {
7760b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly))
7770b57cec5SDimitry Andric     return true;
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   // We can bound the aliasing properties of memset_pattern16 just as we can
7800b57cec5SDimitry Andric   // for memcpy/memset.  This is particularly important because the
7810b57cec5SDimitry Andric   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
7820b57cec5SDimitry Andric   // whenever possible.
7830b57cec5SDimitry Andric   // FIXME Consider handling this in InferFunctionAttr.cpp together with other
7840b57cec5SDimitry Andric   // attributes.
7850b57cec5SDimitry Andric   LibFunc F;
7860b57cec5SDimitry Andric   if (Call->getCalledFunction() &&
7870b57cec5SDimitry Andric       TLI.getLibFunc(*Call->getCalledFunction(), F) &&
7880b57cec5SDimitry Andric       F == LibFunc_memset_pattern16 && TLI.has(F))
7890b57cec5SDimitry Andric     if (ArgIdx == 0)
7900b57cec5SDimitry Andric       return true;
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   // TODO: memset_pattern4, memset_pattern8
7930b57cec5SDimitry Andric   // TODO: _chk variants
7940b57cec5SDimitry Andric   // TODO: strcmp, strcpy
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric   return false;
7970b57cec5SDimitry Andric }
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,
8000b57cec5SDimitry Andric                                            unsigned ArgIdx) {
8010b57cec5SDimitry Andric   // Checking for known builtin intrinsics and target library functions.
8020b57cec5SDimitry Andric   if (isWriteOnlyParam(Call, ArgIdx, TLI))
8030b57cec5SDimitry Andric     return ModRefInfo::Mod;
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly))
8060b57cec5SDimitry Andric     return ModRefInfo::Ref;
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone))
8090b57cec5SDimitry Andric     return ModRefInfo::NoModRef;
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric   return AAResultBase::getArgModRefInfo(Call, ArgIdx);
8120b57cec5SDimitry Andric }
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
8150b57cec5SDimitry Andric   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call);
8160b57cec5SDimitry Andric   return II && II->getIntrinsicID() == IID;
8170b57cec5SDimitry Andric }
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric #ifndef NDEBUG
8200b57cec5SDimitry Andric static const Function *getParent(const Value *V) {
8210b57cec5SDimitry Andric   if (const Instruction *inst = dyn_cast<Instruction>(V)) {
8220b57cec5SDimitry Andric     if (!inst->getParent())
8230b57cec5SDimitry Andric       return nullptr;
8240b57cec5SDimitry Andric     return inst->getParent()->getParent();
8250b57cec5SDimitry Andric   }
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   if (const Argument *arg = dyn_cast<Argument>(V))
8280b57cec5SDimitry Andric     return arg->getParent();
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric   return nullptr;
8310b57cec5SDimitry Andric }
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric static bool notDifferentParent(const Value *O1, const Value *O2) {
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric   const Function *F1 = getParent(O1);
8360b57cec5SDimitry Andric   const Function *F2 = getParent(O2);
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric   return !F1 || !F2 || F1 == F2;
8390b57cec5SDimitry Andric }
8400b57cec5SDimitry Andric #endif
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
8430b57cec5SDimitry Andric                                  const MemoryLocation &LocB,
8440b57cec5SDimitry Andric                                  AAQueryInfo &AAQI) {
8450b57cec5SDimitry Andric   assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
8460b57cec5SDimitry Andric          "BasicAliasAnalysis doesn't support interprocedural queries.");
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   // If we have a directly cached entry for these locations, we have recursed
8490b57cec5SDimitry Andric   // through this once, so just return the cached results. Notably, when this
8500b57cec5SDimitry Andric   // happens, we don't clear the cache.
8510b57cec5SDimitry Andric   auto CacheIt = AAQI.AliasCache.find(AAQueryInfo::LocPair(LocA, LocB));
8520b57cec5SDimitry Andric   if (CacheIt != AAQI.AliasCache.end())
8530b57cec5SDimitry Andric     return CacheIt->second;
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric   CacheIt = AAQI.AliasCache.find(AAQueryInfo::LocPair(LocB, LocA));
8560b57cec5SDimitry Andric   if (CacheIt != AAQI.AliasCache.end())
8570b57cec5SDimitry Andric     return CacheIt->second;
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric   AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr,
8600b57cec5SDimitry Andric                                  LocB.Size, LocB.AATags, AAQI);
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   VisitedPhiBBs.clear();
8630b57cec5SDimitry Andric   return Alias;
8640b57cec5SDimitry Andric }
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric /// Checks to see if the specified callsite can clobber the specified memory
8670b57cec5SDimitry Andric /// object.
8680b57cec5SDimitry Andric ///
8690b57cec5SDimitry Andric /// Since we only look at local properties of this function, we really can't
8700b57cec5SDimitry Andric /// say much about this query.  We do, however, use simple "address taken"
8710b57cec5SDimitry Andric /// analysis on local objects.
8720b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,
8730b57cec5SDimitry Andric                                         const MemoryLocation &Loc,
8740b57cec5SDimitry Andric                                         AAQueryInfo &AAQI) {
8750b57cec5SDimitry Andric   assert(notDifferentParent(Call, Loc.Ptr) &&
8760b57cec5SDimitry Andric          "AliasAnalysis query involving multiple functions!");
8770b57cec5SDimitry Andric 
8780b57cec5SDimitry Andric   const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric   // Calls marked 'tail' cannot read or write allocas from the current frame
8810b57cec5SDimitry Andric   // because the current frame might be destroyed by the time they run. However,
8820b57cec5SDimitry Andric   // a tail call may use an alloca with byval. Calling with byval copies the
8830b57cec5SDimitry Andric   // contents of the alloca into argument registers or stack slots, so there is
8840b57cec5SDimitry Andric   // no lifetime issue.
8850b57cec5SDimitry Andric   if (isa<AllocaInst>(Object))
8860b57cec5SDimitry Andric     if (const CallInst *CI = dyn_cast<CallInst>(Call))
8870b57cec5SDimitry Andric       if (CI->isTailCall() &&
8880b57cec5SDimitry Andric           !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
8890b57cec5SDimitry Andric         return ModRefInfo::NoModRef;
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric   // Stack restore is able to modify unescaped dynamic allocas. Assume it may
8920b57cec5SDimitry Andric   // modify them even though the alloca is not escaped.
8930b57cec5SDimitry Andric   if (auto *AI = dyn_cast<AllocaInst>(Object))
8940b57cec5SDimitry Andric     if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))
8950b57cec5SDimitry Andric       return ModRefInfo::Mod;
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric   // If the pointer is to a locally allocated object that does not escape,
8980b57cec5SDimitry Andric   // then the call can not mod/ref the pointer unless the call takes the pointer
8990b57cec5SDimitry Andric   // as an argument, and itself doesn't capture it.
9000b57cec5SDimitry Andric   if (!isa<Constant>(Object) && Call != Object &&
9010b57cec5SDimitry Andric       isNonEscapingLocalObject(Object, &AAQI.IsCapturedCache)) {
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric     // Optimistically assume that call doesn't touch Object and check this
9040b57cec5SDimitry Andric     // assumption in the following loop.
9050b57cec5SDimitry Andric     ModRefInfo Result = ModRefInfo::NoModRef;
9060b57cec5SDimitry Andric     bool IsMustAlias = true;
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric     unsigned OperandNo = 0;
9090b57cec5SDimitry Andric     for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
9100b57cec5SDimitry Andric          CI != CE; ++CI, ++OperandNo) {
9110b57cec5SDimitry Andric       // Only look at the no-capture or byval pointer arguments.  If this
9120b57cec5SDimitry Andric       // pointer were passed to arguments that were neither of these, then it
9130b57cec5SDimitry Andric       // couldn't be no-capture.
9140b57cec5SDimitry Andric       if (!(*CI)->getType()->isPointerTy() ||
9150b57cec5SDimitry Andric           (!Call->doesNotCapture(OperandNo) &&
9160b57cec5SDimitry Andric            OperandNo < Call->getNumArgOperands() &&
9170b57cec5SDimitry Andric            !Call->isByValArgument(OperandNo)))
9180b57cec5SDimitry Andric         continue;
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric       // Call doesn't access memory through this operand, so we don't care
9210b57cec5SDimitry Andric       // if it aliases with Object.
9220b57cec5SDimitry Andric       if (Call->doesNotAccessMemory(OperandNo))
9230b57cec5SDimitry Andric         continue;
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric       // If this is a no-capture pointer argument, see if we can tell that it
9260b57cec5SDimitry Andric       // is impossible to alias the pointer we're checking.
9270b57cec5SDimitry Andric       AliasResult AR = getBestAAResults().alias(MemoryLocation(*CI),
9280b57cec5SDimitry Andric                                                 MemoryLocation(Object), AAQI);
9290b57cec5SDimitry Andric       if (AR != MustAlias)
9300b57cec5SDimitry Andric         IsMustAlias = false;
9310b57cec5SDimitry Andric       // Operand doesn't alias 'Object', continue looking for other aliases
9320b57cec5SDimitry Andric       if (AR == NoAlias)
9330b57cec5SDimitry Andric         continue;
9340b57cec5SDimitry Andric       // Operand aliases 'Object', but call doesn't modify it. Strengthen
9350b57cec5SDimitry Andric       // initial assumption and keep looking in case if there are more aliases.
9360b57cec5SDimitry Andric       if (Call->onlyReadsMemory(OperandNo)) {
9370b57cec5SDimitry Andric         Result = setRef(Result);
9380b57cec5SDimitry Andric         continue;
9390b57cec5SDimitry Andric       }
9400b57cec5SDimitry Andric       // Operand aliases 'Object' but call only writes into it.
9410b57cec5SDimitry Andric       if (Call->doesNotReadMemory(OperandNo)) {
9420b57cec5SDimitry Andric         Result = setMod(Result);
9430b57cec5SDimitry Andric         continue;
9440b57cec5SDimitry Andric       }
9450b57cec5SDimitry Andric       // This operand aliases 'Object' and call reads and writes into it.
9460b57cec5SDimitry Andric       // Setting ModRef will not yield an early return below, MustAlias is not
9470b57cec5SDimitry Andric       // used further.
9480b57cec5SDimitry Andric       Result = ModRefInfo::ModRef;
9490b57cec5SDimitry Andric       break;
9500b57cec5SDimitry Andric     }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric     // No operand aliases, reset Must bit. Add below if at least one aliases
9530b57cec5SDimitry Andric     // and all aliases found are MustAlias.
9540b57cec5SDimitry Andric     if (isNoModRef(Result))
9550b57cec5SDimitry Andric       IsMustAlias = false;
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric     // Early return if we improved mod ref information
9580b57cec5SDimitry Andric     if (!isModAndRefSet(Result)) {
9590b57cec5SDimitry Andric       if (isNoModRef(Result))
9600b57cec5SDimitry Andric         return ModRefInfo::NoModRef;
9610b57cec5SDimitry Andric       return IsMustAlias ? setMust(Result) : clearMust(Result);
9620b57cec5SDimitry Andric     }
9630b57cec5SDimitry Andric   }
9640b57cec5SDimitry Andric 
9655ffd83dbSDimitry Andric   // If the call is malloc/calloc like, we can assume that it doesn't
9660b57cec5SDimitry Andric   // modify any IR visible value.  This is only valid because we assume these
9670b57cec5SDimitry Andric   // routines do not read values visible in the IR.  TODO: Consider special
9680b57cec5SDimitry Andric   // casing realloc and strdup routines which access only their arguments as
9690b57cec5SDimitry Andric   // well.  Or alternatively, replace all of this with inaccessiblememonly once
9700b57cec5SDimitry Andric   // that's implemented fully.
9710b57cec5SDimitry Andric   if (isMallocOrCallocLikeFn(Call, &TLI)) {
9720b57cec5SDimitry Andric     // Be conservative if the accessed pointer may alias the allocation -
9730b57cec5SDimitry Andric     // fallback to the generic handling below.
9740b57cec5SDimitry Andric     if (getBestAAResults().alias(MemoryLocation(Call), Loc, AAQI) == NoAlias)
9750b57cec5SDimitry Andric       return ModRefInfo::NoModRef;
9760b57cec5SDimitry Andric   }
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric   // The semantics of memcpy intrinsics forbid overlap between their respective
9790b57cec5SDimitry Andric   // operands, i.e., source and destination of any given memcpy must no-alias.
9800b57cec5SDimitry Andric   // If Loc must-aliases either one of these two locations, then it necessarily
9810b57cec5SDimitry Andric   // no-aliases the other.
9820b57cec5SDimitry Andric   if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) {
9830b57cec5SDimitry Andric     AliasResult SrcAA, DestAA;
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric     if ((SrcAA = getBestAAResults().alias(MemoryLocation::getForSource(Inst),
9860b57cec5SDimitry Andric                                           Loc, AAQI)) == MustAlias)
9870b57cec5SDimitry Andric       // Loc is exactly the memcpy source thus disjoint from memcpy dest.
9880b57cec5SDimitry Andric       return ModRefInfo::Ref;
9890b57cec5SDimitry Andric     if ((DestAA = getBestAAResults().alias(MemoryLocation::getForDest(Inst),
9900b57cec5SDimitry Andric                                            Loc, AAQI)) == MustAlias)
9910b57cec5SDimitry Andric       // The converse case.
9920b57cec5SDimitry Andric       return ModRefInfo::Mod;
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric     // It's also possible for Loc to alias both src and dest, or neither.
9950b57cec5SDimitry Andric     ModRefInfo rv = ModRefInfo::NoModRef;
9960b57cec5SDimitry Andric     if (SrcAA != NoAlias)
9970b57cec5SDimitry Andric       rv = setRef(rv);
9980b57cec5SDimitry Andric     if (DestAA != NoAlias)
9990b57cec5SDimitry Andric       rv = setMod(rv);
10000b57cec5SDimitry Andric     return rv;
10010b57cec5SDimitry Andric   }
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric   // While the assume intrinsic is marked as arbitrarily writing so that
10040b57cec5SDimitry Andric   // proper control dependencies will be maintained, it never aliases any
10050b57cec5SDimitry Andric   // particular memory location.
10060b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::assume))
10070b57cec5SDimitry Andric     return ModRefInfo::NoModRef;
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   // Like assumes, guard intrinsics are also marked as arbitrarily writing so
10100b57cec5SDimitry Andric   // that proper control dependencies are maintained but they never mods any
10110b57cec5SDimitry Andric   // particular memory location.
10120b57cec5SDimitry Andric   //
10130b57cec5SDimitry Andric   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
10140b57cec5SDimitry Andric   // heap state at the point the guard is issued needs to be consistent in case
10150b57cec5SDimitry Andric   // the guard invokes the "deopt" continuation.
10160b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::experimental_guard))
10170b57cec5SDimitry Andric     return ModRefInfo::Ref;
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric   // Like assumes, invariant.start intrinsics were also marked as arbitrarily
10200b57cec5SDimitry Andric   // writing so that proper control dependencies are maintained but they never
10210b57cec5SDimitry Andric   // mod any particular memory location visible to the IR.
10220b57cec5SDimitry Andric   // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
10230b57cec5SDimitry Andric   // intrinsic is now modeled as reading memory. This prevents hoisting the
10240b57cec5SDimitry Andric   // invariant.start intrinsic over stores. Consider:
10250b57cec5SDimitry Andric   // *ptr = 40;
10260b57cec5SDimitry Andric   // *ptr = 50;
10270b57cec5SDimitry Andric   // invariant_start(ptr)
10280b57cec5SDimitry Andric   // int val = *ptr;
10290b57cec5SDimitry Andric   // print(val);
10300b57cec5SDimitry Andric   //
10310b57cec5SDimitry Andric   // This cannot be transformed to:
10320b57cec5SDimitry Andric   //
10330b57cec5SDimitry Andric   // *ptr = 40;
10340b57cec5SDimitry Andric   // invariant_start(ptr)
10350b57cec5SDimitry Andric   // *ptr = 50;
10360b57cec5SDimitry Andric   // int val = *ptr;
10370b57cec5SDimitry Andric   // print(val);
10380b57cec5SDimitry Andric   //
10390b57cec5SDimitry Andric   // The transformation will cause the second store to be ignored (based on
10400b57cec5SDimitry Andric   // rules of invariant.start)  and print 40, while the first program always
10410b57cec5SDimitry Andric   // prints 50.
10420b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::invariant_start))
10430b57cec5SDimitry Andric     return ModRefInfo::Ref;
10440b57cec5SDimitry Andric 
10450b57cec5SDimitry Andric   // The AAResultBase base class has some smarts, lets use them.
10460b57cec5SDimitry Andric   return AAResultBase::getModRefInfo(Call, Loc, AAQI);
10470b57cec5SDimitry Andric }
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,
10500b57cec5SDimitry Andric                                         const CallBase *Call2,
10510b57cec5SDimitry Andric                                         AAQueryInfo &AAQI) {
10520b57cec5SDimitry Andric   // While the assume intrinsic is marked as arbitrarily writing so that
10530b57cec5SDimitry Andric   // proper control dependencies will be maintained, it never aliases any
10540b57cec5SDimitry Andric   // particular memory location.
10550b57cec5SDimitry Andric   if (isIntrinsicCall(Call1, Intrinsic::assume) ||
10560b57cec5SDimitry Andric       isIntrinsicCall(Call2, Intrinsic::assume))
10570b57cec5SDimitry Andric     return ModRefInfo::NoModRef;
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric   // Like assumes, guard intrinsics are also marked as arbitrarily writing so
10600b57cec5SDimitry Andric   // that proper control dependencies are maintained but they never mod any
10610b57cec5SDimitry Andric   // particular memory location.
10620b57cec5SDimitry Andric   //
10630b57cec5SDimitry Andric   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
10640b57cec5SDimitry Andric   // heap state at the point the guard is issued needs to be consistent in case
10650b57cec5SDimitry Andric   // the guard invokes the "deopt" continuation.
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric   // NB! This function is *not* commutative, so we special case two
10680b57cec5SDimitry Andric   // possibilities for guard intrinsics.
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric   if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))
10710b57cec5SDimitry Andric     return isModSet(createModRefInfo(getModRefBehavior(Call2)))
10720b57cec5SDimitry Andric                ? ModRefInfo::Ref
10730b57cec5SDimitry Andric                : ModRefInfo::NoModRef;
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric   if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
10760b57cec5SDimitry Andric     return isModSet(createModRefInfo(getModRefBehavior(Call1)))
10770b57cec5SDimitry Andric                ? ModRefInfo::Mod
10780b57cec5SDimitry Andric                : ModRefInfo::NoModRef;
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   // The AAResultBase base class has some smarts, lets use them.
10810b57cec5SDimitry Andric   return AAResultBase::getModRefInfo(Call1, Call2, AAQI);
10820b57cec5SDimitry Andric }
10830b57cec5SDimitry Andric 
10840b57cec5SDimitry Andric /// Provide ad-hoc rules to disambiguate accesses through two GEP operators,
10850b57cec5SDimitry Andric /// both having the exact same pointer operand.
10860b57cec5SDimitry Andric static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
10870b57cec5SDimitry Andric                                             LocationSize MaybeV1Size,
10880b57cec5SDimitry Andric                                             const GEPOperator *GEP2,
10890b57cec5SDimitry Andric                                             LocationSize MaybeV2Size,
10900b57cec5SDimitry Andric                                             const DataLayout &DL) {
10910b57cec5SDimitry Andric   assert(GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() ==
10920b57cec5SDimitry Andric              GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() &&
10930b57cec5SDimitry Andric          GEP1->getPointerOperandType() == GEP2->getPointerOperandType() &&
10940b57cec5SDimitry Andric          "Expected GEPs with the same pointer operand");
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric   // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
10970b57cec5SDimitry Andric   // such that the struct field accesses provably cannot alias.
10980b57cec5SDimitry Andric   // We also need at least two indices (the pointer, and the struct field).
10990b57cec5SDimitry Andric   if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
11000b57cec5SDimitry Andric       GEP1->getNumIndices() < 2)
11010b57cec5SDimitry Andric     return MayAlias;
11020b57cec5SDimitry Andric 
11030b57cec5SDimitry Andric   // If we don't know the size of the accesses through both GEPs, we can't
11040b57cec5SDimitry Andric   // determine whether the struct fields accessed can't alias.
11050b57cec5SDimitry Andric   if (MaybeV1Size == LocationSize::unknown() ||
11060b57cec5SDimitry Andric       MaybeV2Size == LocationSize::unknown())
11070b57cec5SDimitry Andric     return MayAlias;
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric   const uint64_t V1Size = MaybeV1Size.getValue();
11100b57cec5SDimitry Andric   const uint64_t V2Size = MaybeV2Size.getValue();
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric   ConstantInt *C1 =
11130b57cec5SDimitry Andric       dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
11140b57cec5SDimitry Andric   ConstantInt *C2 =
11150b57cec5SDimitry Andric       dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
11160b57cec5SDimitry Andric 
11170b57cec5SDimitry Andric   // If the last (struct) indices are constants and are equal, the other indices
11180b57cec5SDimitry Andric   // might be also be dynamically equal, so the GEPs can alias.
11190b57cec5SDimitry Andric   if (C1 && C2) {
11200b57cec5SDimitry Andric     unsigned BitWidth = std::max(C1->getBitWidth(), C2->getBitWidth());
11210b57cec5SDimitry Andric     if (C1->getValue().sextOrSelf(BitWidth) ==
11220b57cec5SDimitry Andric         C2->getValue().sextOrSelf(BitWidth))
11230b57cec5SDimitry Andric       return MayAlias;
11240b57cec5SDimitry Andric   }
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric   // Find the last-indexed type of the GEP, i.e., the type you'd get if
11270b57cec5SDimitry Andric   // you stripped the last index.
11280b57cec5SDimitry Andric   // On the way, look at each indexed type.  If there's something other
11290b57cec5SDimitry Andric   // than an array, different indices can lead to different final types.
11300b57cec5SDimitry Andric   SmallVector<Value *, 8> IntermediateIndices;
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric   // Insert the first index; we don't need to check the type indexed
11330b57cec5SDimitry Andric   // through it as it only drops the pointer indirection.
11340b57cec5SDimitry Andric   assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
11350b57cec5SDimitry Andric   IntermediateIndices.push_back(GEP1->getOperand(1));
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric   // Insert all the remaining indices but the last one.
11380b57cec5SDimitry Andric   // Also, check that they all index through arrays.
11390b57cec5SDimitry Andric   for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
11400b57cec5SDimitry Andric     if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
11410b57cec5SDimitry Andric             GEP1->getSourceElementType(), IntermediateIndices)))
11420b57cec5SDimitry Andric       return MayAlias;
11430b57cec5SDimitry Andric     IntermediateIndices.push_back(GEP1->getOperand(i + 1));
11440b57cec5SDimitry Andric   }
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric   auto *Ty = GetElementPtrInst::getIndexedType(
11470b57cec5SDimitry Andric     GEP1->getSourceElementType(), IntermediateIndices);
11480b57cec5SDimitry Andric   StructType *LastIndexedStruct = dyn_cast<StructType>(Ty);
11490b57cec5SDimitry Andric 
11505ffd83dbSDimitry Andric   if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
11510b57cec5SDimitry Andric     // We know that:
11520b57cec5SDimitry Andric     // - both GEPs begin indexing from the exact same pointer;
11530b57cec5SDimitry Andric     // - the last indices in both GEPs are constants, indexing into a sequential
11545ffd83dbSDimitry Andric     //   type (array or vector);
11550b57cec5SDimitry Andric     // - both GEPs only index through arrays prior to that.
11560b57cec5SDimitry Andric     //
11570b57cec5SDimitry Andric     // Because array indices greater than the number of elements are valid in
11580b57cec5SDimitry Andric     // GEPs, unless we know the intermediate indices are identical between
11590b57cec5SDimitry Andric     // GEP1 and GEP2 we cannot guarantee that the last indexed arrays don't
11600b57cec5SDimitry Andric     // partially overlap. We also need to check that the loaded size matches
11610b57cec5SDimitry Andric     // the element size, otherwise we could still have overlap.
11625ffd83dbSDimitry Andric     Type *LastElementTy = GetElementPtrInst::getTypeAtIndex(Ty, (uint64_t)0);
11630b57cec5SDimitry Andric     const uint64_t ElementSize =
11645ffd83dbSDimitry Andric         DL.getTypeStoreSize(LastElementTy).getFixedSize();
11650b57cec5SDimitry Andric     if (V1Size != ElementSize || V2Size != ElementSize)
11660b57cec5SDimitry Andric       return MayAlias;
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric     for (unsigned i = 0, e = GEP1->getNumIndices() - 1; i != e; ++i)
11690b57cec5SDimitry Andric       if (GEP1->getOperand(i + 1) != GEP2->getOperand(i + 1))
11700b57cec5SDimitry Andric         return MayAlias;
11710b57cec5SDimitry Andric 
11720b57cec5SDimitry Andric     // Now we know that the array/pointer that GEP1 indexes into and that
11730b57cec5SDimitry Andric     // that GEP2 indexes into must either precisely overlap or be disjoint.
11740b57cec5SDimitry Andric     // Because they cannot partially overlap and because fields in an array
11750b57cec5SDimitry Andric     // cannot overlap, if we can prove the final indices are different between
11760b57cec5SDimitry Andric     // GEP1 and GEP2, we can conclude GEP1 and GEP2 don't alias.
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric     // If the last indices are constants, we've already checked they don't
11790b57cec5SDimitry Andric     // equal each other so we can exit early.
11800b57cec5SDimitry Andric     if (C1 && C2)
11810b57cec5SDimitry Andric       return NoAlias;
11820b57cec5SDimitry Andric     {
11830b57cec5SDimitry Andric       Value *GEP1LastIdx = GEP1->getOperand(GEP1->getNumOperands() - 1);
11840b57cec5SDimitry Andric       Value *GEP2LastIdx = GEP2->getOperand(GEP2->getNumOperands() - 1);
11850b57cec5SDimitry Andric       if (isa<PHINode>(GEP1LastIdx) || isa<PHINode>(GEP2LastIdx)) {
11860b57cec5SDimitry Andric         // If one of the indices is a PHI node, be safe and only use
11870b57cec5SDimitry Andric         // computeKnownBits so we don't make any assumptions about the
11880b57cec5SDimitry Andric         // relationships between the two indices. This is important if we're
11890b57cec5SDimitry Andric         // asking about values from different loop iterations. See PR32314.
11900b57cec5SDimitry Andric         // TODO: We may be able to change the check so we only do this when
11910b57cec5SDimitry Andric         // we definitely looked through a PHINode.
11920b57cec5SDimitry Andric         if (GEP1LastIdx != GEP2LastIdx &&
11930b57cec5SDimitry Andric             GEP1LastIdx->getType() == GEP2LastIdx->getType()) {
11940b57cec5SDimitry Andric           KnownBits Known1 = computeKnownBits(GEP1LastIdx, DL);
11950b57cec5SDimitry Andric           KnownBits Known2 = computeKnownBits(GEP2LastIdx, DL);
11960b57cec5SDimitry Andric           if (Known1.Zero.intersects(Known2.One) ||
11970b57cec5SDimitry Andric               Known1.One.intersects(Known2.Zero))
11980b57cec5SDimitry Andric             return NoAlias;
11990b57cec5SDimitry Andric         }
12000b57cec5SDimitry Andric       } else if (isKnownNonEqual(GEP1LastIdx, GEP2LastIdx, DL))
12010b57cec5SDimitry Andric         return NoAlias;
12020b57cec5SDimitry Andric     }
12030b57cec5SDimitry Andric     return MayAlias;
12040b57cec5SDimitry Andric   } else if (!LastIndexedStruct || !C1 || !C2) {
12050b57cec5SDimitry Andric     return MayAlias;
12060b57cec5SDimitry Andric   }
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   if (C1->getValue().getActiveBits() > 64 ||
12090b57cec5SDimitry Andric       C2->getValue().getActiveBits() > 64)
12100b57cec5SDimitry Andric     return MayAlias;
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric   // We know that:
12130b57cec5SDimitry Andric   // - both GEPs begin indexing from the exact same pointer;
12140b57cec5SDimitry Andric   // - the last indices in both GEPs are constants, indexing into a struct;
12150b57cec5SDimitry Andric   // - said indices are different, hence, the pointed-to fields are different;
12160b57cec5SDimitry Andric   // - both GEPs only index through arrays prior to that.
12170b57cec5SDimitry Andric   //
12180b57cec5SDimitry Andric   // This lets us determine that the struct that GEP1 indexes into and the
12190b57cec5SDimitry Andric   // struct that GEP2 indexes into must either precisely overlap or be
12200b57cec5SDimitry Andric   // completely disjoint.  Because they cannot partially overlap, indexing into
12210b57cec5SDimitry Andric   // different non-overlapping fields of the struct will never alias.
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   // Therefore, the only remaining thing needed to show that both GEPs can't
12240b57cec5SDimitry Andric   // alias is that the fields are not overlapping.
12250b57cec5SDimitry Andric   const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
12260b57cec5SDimitry Andric   const uint64_t StructSize = SL->getSizeInBytes();
12270b57cec5SDimitry Andric   const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
12280b57cec5SDimitry Andric   const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
12310b57cec5SDimitry Andric                                       uint64_t V2Off, uint64_t V2Size) {
12320b57cec5SDimitry Andric     return V1Off < V2Off && V1Off + V1Size <= V2Off &&
12330b57cec5SDimitry Andric            ((V2Off + V2Size <= StructSize) ||
12340b57cec5SDimitry Andric             (V2Off + V2Size - StructSize <= V1Off));
12350b57cec5SDimitry Andric   };
12360b57cec5SDimitry Andric 
12370b57cec5SDimitry Andric   if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
12380b57cec5SDimitry Andric       EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
12390b57cec5SDimitry Andric     return NoAlias;
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric   return MayAlias;
12420b57cec5SDimitry Andric }
12430b57cec5SDimitry Andric 
12440b57cec5SDimitry Andric // If a we have (a) a GEP and (b) a pointer based on an alloca, and the
12450b57cec5SDimitry Andric // beginning of the object the GEP points would have a negative offset with
12460b57cec5SDimitry Andric // repsect to the alloca, that means the GEP can not alias pointer (b).
12470b57cec5SDimitry Andric // Note that the pointer based on the alloca may not be a GEP. For
12480b57cec5SDimitry Andric // example, it may be the alloca itself.
12490b57cec5SDimitry Andric // The same applies if (b) is based on a GlobalVariable. Note that just being
12500b57cec5SDimitry Andric // based on isIdentifiedObject() is not enough - we need an identified object
12510b57cec5SDimitry Andric // that does not permit access to negative offsets. For example, a negative
12520b57cec5SDimitry Andric // offset from a noalias argument or call can be inbounds w.r.t the actual
12530b57cec5SDimitry Andric // underlying object.
12540b57cec5SDimitry Andric //
12550b57cec5SDimitry Andric // For example, consider:
12560b57cec5SDimitry Andric //
12570b57cec5SDimitry Andric //   struct { int f0, int f1, ...} foo;
12580b57cec5SDimitry Andric //   foo alloca;
12590b57cec5SDimitry Andric //   foo* random = bar(alloca);
12600b57cec5SDimitry Andric //   int *f0 = &alloca.f0
12610b57cec5SDimitry Andric //   int *f1 = &random->f1;
12620b57cec5SDimitry Andric //
12630b57cec5SDimitry Andric // Which is lowered, approximately, to:
12640b57cec5SDimitry Andric //
12650b57cec5SDimitry Andric //  %alloca = alloca %struct.foo
12660b57cec5SDimitry Andric //  %random = call %struct.foo* @random(%struct.foo* %alloca)
12670b57cec5SDimitry Andric //  %f0 = getelementptr inbounds %struct, %struct.foo* %alloca, i32 0, i32 0
12680b57cec5SDimitry Andric //  %f1 = getelementptr inbounds %struct, %struct.foo* %random, i32 0, i32 1
12690b57cec5SDimitry Andric //
12700b57cec5SDimitry Andric // Assume %f1 and %f0 alias. Then %f1 would point into the object allocated
12710b57cec5SDimitry Andric // by %alloca. Since the %f1 GEP is inbounds, that means %random must also
12720b57cec5SDimitry Andric // point into the same object. But since %f0 points to the beginning of %alloca,
12730b57cec5SDimitry Andric // the highest %f1 can be is (%alloca + 3). This means %random can not be higher
12740b57cec5SDimitry Andric // than (%alloca - 1), and so is not inbounds, a contradiction.
12750b57cec5SDimitry Andric bool BasicAAResult::isGEPBaseAtNegativeOffset(const GEPOperator *GEPOp,
12760b57cec5SDimitry Andric       const DecomposedGEP &DecompGEP, const DecomposedGEP &DecompObject,
12770b57cec5SDimitry Andric       LocationSize MaybeObjectAccessSize) {
12780b57cec5SDimitry Andric   // If the object access size is unknown, or the GEP isn't inbounds, bail.
12790b57cec5SDimitry Andric   if (MaybeObjectAccessSize == LocationSize::unknown() || !GEPOp->isInBounds())
12800b57cec5SDimitry Andric     return false;
12810b57cec5SDimitry Andric 
12820b57cec5SDimitry Andric   const uint64_t ObjectAccessSize = MaybeObjectAccessSize.getValue();
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   // We need the object to be an alloca or a globalvariable, and want to know
12850b57cec5SDimitry Andric   // the offset of the pointer from the object precisely, so no variable
12860b57cec5SDimitry Andric   // indices are allowed.
12870b57cec5SDimitry Andric   if (!(isa<AllocaInst>(DecompObject.Base) ||
12880b57cec5SDimitry Andric         isa<GlobalVariable>(DecompObject.Base)) ||
12890b57cec5SDimitry Andric       !DecompObject.VarIndices.empty())
12900b57cec5SDimitry Andric     return false;
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric   APInt ObjectBaseOffset = DecompObject.StructOffset +
12930b57cec5SDimitry Andric                            DecompObject.OtherOffset;
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric   // If the GEP has no variable indices, we know the precise offset
12960b57cec5SDimitry Andric   // from the base, then use it. If the GEP has variable indices,
12970b57cec5SDimitry Andric   // we can't get exact GEP offset to identify pointer alias. So return
12980b57cec5SDimitry Andric   // false in that case.
12990b57cec5SDimitry Andric   if (!DecompGEP.VarIndices.empty())
13000b57cec5SDimitry Andric     return false;
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric   APInt GEPBaseOffset = DecompGEP.StructOffset;
13030b57cec5SDimitry Andric   GEPBaseOffset += DecompGEP.OtherOffset;
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   return GEPBaseOffset.sge(ObjectBaseOffset + (int64_t)ObjectAccessSize);
13060b57cec5SDimitry Andric }
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
13090b57cec5SDimitry Andric /// another pointer.
13100b57cec5SDimitry Andric ///
13110b57cec5SDimitry Andric /// We know that V1 is a GEP, but we don't know anything about V2.
13120b57cec5SDimitry Andric /// UnderlyingV1 is GetUnderlyingObject(GEP1, DL), UnderlyingV2 is the same for
13130b57cec5SDimitry Andric /// V2.
13140b57cec5SDimitry Andric AliasResult BasicAAResult::aliasGEP(
13150b57cec5SDimitry Andric     const GEPOperator *GEP1, LocationSize V1Size, const AAMDNodes &V1AAInfo,
13160b57cec5SDimitry Andric     const Value *V2, LocationSize V2Size, const AAMDNodes &V2AAInfo,
13170b57cec5SDimitry Andric     const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
13180b57cec5SDimitry Andric   DecomposedGEP DecompGEP1, DecompGEP2;
13190b57cec5SDimitry Andric   unsigned MaxPointerSize = getMaxPointerSize(DL);
13200b57cec5SDimitry Andric   DecompGEP1.StructOffset = DecompGEP1.OtherOffset = APInt(MaxPointerSize, 0);
13210b57cec5SDimitry Andric   DecompGEP2.StructOffset = DecompGEP2.OtherOffset = APInt(MaxPointerSize, 0);
13225ffd83dbSDimitry Andric   DecompGEP1.HasCompileTimeConstantScale =
13235ffd83dbSDimitry Andric       DecompGEP2.HasCompileTimeConstantScale = true;
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   bool GEP1MaxLookupReached =
13260b57cec5SDimitry Andric     DecomposeGEPExpression(GEP1, DecompGEP1, DL, &AC, DT);
13270b57cec5SDimitry Andric   bool GEP2MaxLookupReached =
13280b57cec5SDimitry Andric     DecomposeGEPExpression(V2, DecompGEP2, DL, &AC, DT);
13290b57cec5SDimitry Andric 
13305ffd83dbSDimitry Andric   // Don't attempt to analyze the decomposed GEP if index scale is not a
13315ffd83dbSDimitry Andric   // compile-time constant.
13325ffd83dbSDimitry Andric   if (!DecompGEP1.HasCompileTimeConstantScale ||
13335ffd83dbSDimitry Andric       !DecompGEP2.HasCompileTimeConstantScale)
13345ffd83dbSDimitry Andric     return MayAlias;
13355ffd83dbSDimitry Andric 
13360b57cec5SDimitry Andric   APInt GEP1BaseOffset = DecompGEP1.StructOffset + DecompGEP1.OtherOffset;
13370b57cec5SDimitry Andric   APInt GEP2BaseOffset = DecompGEP2.StructOffset + DecompGEP2.OtherOffset;
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric   assert(DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 &&
13400b57cec5SDimitry Andric          "DecomposeGEPExpression returned a result different from "
13410b57cec5SDimitry Andric          "GetUnderlyingObject");
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric   // If the GEP's offset relative to its base is such that the base would
13440b57cec5SDimitry Andric   // fall below the start of the object underlying V2, then the GEP and V2
13450b57cec5SDimitry Andric   // cannot alias.
13460b57cec5SDimitry Andric   if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
13470b57cec5SDimitry Andric       isGEPBaseAtNegativeOffset(GEP1, DecompGEP1, DecompGEP2, V2Size))
13480b57cec5SDimitry Andric     return NoAlias;
13490b57cec5SDimitry Andric   // If we have two gep instructions with must-alias or not-alias'ing base
13500b57cec5SDimitry Andric   // pointers, figure out if the indexes to the GEP tell us anything about the
13510b57cec5SDimitry Andric   // derived pointer.
13520b57cec5SDimitry Andric   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
13530b57cec5SDimitry Andric     // Check for the GEP base being at a negative offset, this time in the other
13540b57cec5SDimitry Andric     // direction.
13550b57cec5SDimitry Andric     if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
13560b57cec5SDimitry Andric         isGEPBaseAtNegativeOffset(GEP2, DecompGEP2, DecompGEP1, V1Size))
13570b57cec5SDimitry Andric       return NoAlias;
13580b57cec5SDimitry Andric     // Do the base pointers alias?
13590b57cec5SDimitry Andric     AliasResult BaseAlias =
13600b57cec5SDimitry Andric         aliasCheck(UnderlyingV1, LocationSize::unknown(), AAMDNodes(),
13610b57cec5SDimitry Andric                    UnderlyingV2, LocationSize::unknown(), AAMDNodes(), AAQI);
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric     // Check for geps of non-aliasing underlying pointers where the offsets are
13640b57cec5SDimitry Andric     // identical.
13650b57cec5SDimitry Andric     if ((BaseAlias == MayAlias) && V1Size == V2Size) {
13660b57cec5SDimitry Andric       // Do the base pointers alias assuming type and size.
13670b57cec5SDimitry Andric       AliasResult PreciseBaseAlias = aliasCheck(
13680b57cec5SDimitry Andric           UnderlyingV1, V1Size, V1AAInfo, UnderlyingV2, V2Size, V2AAInfo, AAQI);
13690b57cec5SDimitry Andric       if (PreciseBaseAlias == NoAlias) {
13700b57cec5SDimitry Andric         // See if the computed offset from the common pointer tells us about the
13710b57cec5SDimitry Andric         // relation of the resulting pointer.
13720b57cec5SDimitry Andric         // If the max search depth is reached the result is undefined
13730b57cec5SDimitry Andric         if (GEP2MaxLookupReached || GEP1MaxLookupReached)
13740b57cec5SDimitry Andric           return MayAlias;
13750b57cec5SDimitry Andric 
13760b57cec5SDimitry Andric         // Same offsets.
13770b57cec5SDimitry Andric         if (GEP1BaseOffset == GEP2BaseOffset &&
13780b57cec5SDimitry Andric             DecompGEP1.VarIndices == DecompGEP2.VarIndices)
13790b57cec5SDimitry Andric           return NoAlias;
13800b57cec5SDimitry Andric       }
13810b57cec5SDimitry Andric     }
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric     // If we get a No or May, then return it immediately, no amount of analysis
13840b57cec5SDimitry Andric     // will improve this situation.
13850b57cec5SDimitry Andric     if (BaseAlias != MustAlias) {
13860b57cec5SDimitry Andric       assert(BaseAlias == NoAlias || BaseAlias == MayAlias);
13870b57cec5SDimitry Andric       return BaseAlias;
13880b57cec5SDimitry Andric     }
13890b57cec5SDimitry Andric 
13900b57cec5SDimitry Andric     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
13910b57cec5SDimitry Andric     // exactly, see if the computed offset from the common pointer tells us
13920b57cec5SDimitry Andric     // about the relation of the resulting pointer.
13930b57cec5SDimitry Andric     // If we know the two GEPs are based off of the exact same pointer (and not
13940b57cec5SDimitry Andric     // just the same underlying object), see if that tells us anything about
13950b57cec5SDimitry Andric     // the resulting pointers.
13960b57cec5SDimitry Andric     if (GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() ==
13970b57cec5SDimitry Andric             GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() &&
13980b57cec5SDimitry Andric         GEP1->getPointerOperandType() == GEP2->getPointerOperandType()) {
13990b57cec5SDimitry Andric       AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, DL);
14000b57cec5SDimitry Andric       // If we couldn't find anything interesting, don't abandon just yet.
14010b57cec5SDimitry Andric       if (R != MayAlias)
14020b57cec5SDimitry Andric         return R;
14030b57cec5SDimitry Andric     }
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric     // If the max search depth is reached, the result is undefined
14060b57cec5SDimitry Andric     if (GEP2MaxLookupReached || GEP1MaxLookupReached)
14070b57cec5SDimitry Andric       return MayAlias;
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
14100b57cec5SDimitry Andric     // symbolic difference.
14110b57cec5SDimitry Andric     GEP1BaseOffset -= GEP2BaseOffset;
14120b57cec5SDimitry Andric     GetIndexDifference(DecompGEP1.VarIndices, DecompGEP2.VarIndices);
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric   } else {
14150b57cec5SDimitry Andric     // Check to see if these two pointers are related by the getelementptr
14160b57cec5SDimitry Andric     // instruction.  If one pointer is a GEP with a non-zero index of the other
14170b57cec5SDimitry Andric     // pointer, we know they cannot alias.
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric     // If both accesses are unknown size, we can't do anything useful here.
14200b57cec5SDimitry Andric     if (V1Size == LocationSize::unknown() && V2Size == LocationSize::unknown())
14210b57cec5SDimitry Andric       return MayAlias;
14220b57cec5SDimitry Andric 
14230b57cec5SDimitry Andric     AliasResult R = aliasCheck(UnderlyingV1, LocationSize::unknown(),
14240b57cec5SDimitry Andric                                AAMDNodes(), V2, LocationSize::unknown(),
14250b57cec5SDimitry Andric                                V2AAInfo, AAQI, nullptr, UnderlyingV2);
14260b57cec5SDimitry Andric     if (R != MustAlias) {
14270b57cec5SDimitry Andric       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
14280b57cec5SDimitry Andric       // If V2 is known not to alias GEP base pointer, then the two values
14290b57cec5SDimitry Andric       // cannot alias per GEP semantics: "Any memory access must be done through
14300b57cec5SDimitry Andric       // a pointer value associated with an address range of the memory access,
14310b57cec5SDimitry Andric       // otherwise the behavior is undefined.".
14320b57cec5SDimitry Andric       assert(R == NoAlias || R == MayAlias);
14330b57cec5SDimitry Andric       return R;
14340b57cec5SDimitry Andric     }
14350b57cec5SDimitry Andric 
14360b57cec5SDimitry Andric     // If the max search depth is reached the result is undefined
14370b57cec5SDimitry Andric     if (GEP1MaxLookupReached)
14380b57cec5SDimitry Andric       return MayAlias;
14390b57cec5SDimitry Andric   }
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   // In the two GEP Case, if there is no difference in the offsets of the
14420b57cec5SDimitry Andric   // computed pointers, the resultant pointers are a must alias.  This
14430b57cec5SDimitry Andric   // happens when we have two lexically identical GEP's (for example).
14440b57cec5SDimitry Andric   //
14450b57cec5SDimitry Andric   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
14460b57cec5SDimitry Andric   // must aliases the GEP, the end result is a must alias also.
14470b57cec5SDimitry Andric   if (GEP1BaseOffset == 0 && DecompGEP1.VarIndices.empty())
14480b57cec5SDimitry Andric     return MustAlias;
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric   // If there is a constant difference between the pointers, but the difference
14510b57cec5SDimitry Andric   // is less than the size of the associated memory object, then we know
14520b57cec5SDimitry Andric   // that the objects are partially overlapping.  If the difference is
14530b57cec5SDimitry Andric   // greater, we know they do not overlap.
14540b57cec5SDimitry Andric   if (GEP1BaseOffset != 0 && DecompGEP1.VarIndices.empty()) {
14550b57cec5SDimitry Andric     if (GEP1BaseOffset.sge(0)) {
14560b57cec5SDimitry Andric       if (V2Size != LocationSize::unknown()) {
14570b57cec5SDimitry Andric         if (GEP1BaseOffset.ult(V2Size.getValue()))
14580b57cec5SDimitry Andric           return PartialAlias;
14590b57cec5SDimitry Andric         return NoAlias;
14600b57cec5SDimitry Andric       }
14610b57cec5SDimitry Andric     } else {
14620b57cec5SDimitry Andric       // We have the situation where:
14630b57cec5SDimitry Andric       // +                +
14640b57cec5SDimitry Andric       // | BaseOffset     |
14650b57cec5SDimitry Andric       // ---------------->|
14660b57cec5SDimitry Andric       // |-->V1Size       |-------> V2Size
14670b57cec5SDimitry Andric       // GEP1             V2
14680b57cec5SDimitry Andric       // We need to know that V2Size is not unknown, otherwise we might have
14690b57cec5SDimitry Andric       // stripped a gep with negative index ('gep <ptr>, -1, ...).
14700b57cec5SDimitry Andric       if (V1Size != LocationSize::unknown() &&
14710b57cec5SDimitry Andric           V2Size != LocationSize::unknown()) {
14720b57cec5SDimitry Andric         if ((-GEP1BaseOffset).ult(V1Size.getValue()))
14730b57cec5SDimitry Andric           return PartialAlias;
14740b57cec5SDimitry Andric         return NoAlias;
14750b57cec5SDimitry Andric       }
14760b57cec5SDimitry Andric     }
14770b57cec5SDimitry Andric   }
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric   if (!DecompGEP1.VarIndices.empty()) {
14800b57cec5SDimitry Andric     APInt Modulo(MaxPointerSize, 0);
14810b57cec5SDimitry Andric     bool AllPositive = true;
14820b57cec5SDimitry Andric     for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
14830b57cec5SDimitry Andric 
14840b57cec5SDimitry Andric       // Try to distinguish something like &A[i][1] against &A[42][0].
14850b57cec5SDimitry Andric       // Grab the least significant bit set in any of the scales. We
14860b57cec5SDimitry Andric       // don't need std::abs here (even if the scale's negative) as we'll
14870b57cec5SDimitry Andric       // be ^'ing Modulo with itself later.
14880b57cec5SDimitry Andric       Modulo |= DecompGEP1.VarIndices[i].Scale;
14890b57cec5SDimitry Andric 
14900b57cec5SDimitry Andric       if (AllPositive) {
14910b57cec5SDimitry Andric         // If the Value could change between cycles, then any reasoning about
14920b57cec5SDimitry Andric         // the Value this cycle may not hold in the next cycle. We'll just
14930b57cec5SDimitry Andric         // give up if we can't determine conditions that hold for every cycle:
14940b57cec5SDimitry Andric         const Value *V = DecompGEP1.VarIndices[i].V;
14950b57cec5SDimitry Andric 
1496480093f4SDimitry Andric         KnownBits Known =
1497480093f4SDimitry Andric             computeKnownBits(V, DL, 0, &AC, dyn_cast<Instruction>(GEP1), DT);
14980b57cec5SDimitry Andric         bool SignKnownZero = Known.isNonNegative();
14990b57cec5SDimitry Andric         bool SignKnownOne = Known.isNegative();
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric         // Zero-extension widens the variable, and so forces the sign
15020b57cec5SDimitry Andric         // bit to zero.
15030b57cec5SDimitry Andric         bool IsZExt = DecompGEP1.VarIndices[i].ZExtBits > 0 || isa<ZExtInst>(V);
15040b57cec5SDimitry Andric         SignKnownZero |= IsZExt;
15050b57cec5SDimitry Andric         SignKnownOne &= !IsZExt;
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric         // If the variable begins with a zero then we know it's
15080b57cec5SDimitry Andric         // positive, regardless of whether the value is signed or
15090b57cec5SDimitry Andric         // unsigned.
15100b57cec5SDimitry Andric         APInt Scale = DecompGEP1.VarIndices[i].Scale;
15110b57cec5SDimitry Andric         AllPositive =
15120b57cec5SDimitry Andric             (SignKnownZero && Scale.sge(0)) || (SignKnownOne && Scale.slt(0));
15130b57cec5SDimitry Andric       }
15140b57cec5SDimitry Andric     }
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric     Modulo = Modulo ^ (Modulo & (Modulo - 1));
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric     // We can compute the difference between the two addresses
15190b57cec5SDimitry Andric     // mod Modulo. Check whether that difference guarantees that the
15200b57cec5SDimitry Andric     // two locations do not alias.
15210b57cec5SDimitry Andric     APInt ModOffset = GEP1BaseOffset & (Modulo - 1);
15220b57cec5SDimitry Andric     if (V1Size != LocationSize::unknown() &&
15230b57cec5SDimitry Andric         V2Size != LocationSize::unknown() && ModOffset.uge(V2Size.getValue()) &&
15240b57cec5SDimitry Andric         (Modulo - ModOffset).uge(V1Size.getValue()))
15250b57cec5SDimitry Andric       return NoAlias;
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric     // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
15280b57cec5SDimitry Andric     // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
15290b57cec5SDimitry Andric     // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
15300b57cec5SDimitry Andric     if (AllPositive && GEP1BaseOffset.sgt(0) &&
15310b57cec5SDimitry Andric         V2Size != LocationSize::unknown() &&
15320b57cec5SDimitry Andric         GEP1BaseOffset.uge(V2Size.getValue()))
15330b57cec5SDimitry Andric       return NoAlias;
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric     if (constantOffsetHeuristic(DecompGEP1.VarIndices, V1Size, V2Size,
15360b57cec5SDimitry Andric                                 GEP1BaseOffset, &AC, DT))
15370b57cec5SDimitry Andric       return NoAlias;
15380b57cec5SDimitry Andric   }
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric   // Statically, we can see that the base objects are the same, but the
15410b57cec5SDimitry Andric   // pointers have dynamic offsets which we can't resolve. And none of our
15420b57cec5SDimitry Andric   // little tricks above worked.
15430b57cec5SDimitry Andric   return MayAlias;
15440b57cec5SDimitry Andric }
15450b57cec5SDimitry Andric 
15460b57cec5SDimitry Andric static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
15470b57cec5SDimitry Andric   // If the results agree, take it.
15480b57cec5SDimitry Andric   if (A == B)
15490b57cec5SDimitry Andric     return A;
15500b57cec5SDimitry Andric   // A mix of PartialAlias and MustAlias is PartialAlias.
15510b57cec5SDimitry Andric   if ((A == PartialAlias && B == MustAlias) ||
15520b57cec5SDimitry Andric       (B == PartialAlias && A == MustAlias))
15530b57cec5SDimitry Andric     return PartialAlias;
15540b57cec5SDimitry Andric   // Otherwise, we don't know anything.
15550b57cec5SDimitry Andric   return MayAlias;
15560b57cec5SDimitry Andric }
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
15590b57cec5SDimitry Andric /// against another.
15600b57cec5SDimitry Andric AliasResult
15610b57cec5SDimitry Andric BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
15620b57cec5SDimitry Andric                            const AAMDNodes &SIAAInfo, const Value *V2,
15630b57cec5SDimitry Andric                            LocationSize V2Size, const AAMDNodes &V2AAInfo,
15640b57cec5SDimitry Andric                            const Value *UnderV2, AAQueryInfo &AAQI) {
15650b57cec5SDimitry Andric   // If the values are Selects with the same condition, we can do a more precise
15660b57cec5SDimitry Andric   // check: just check for aliases between the values on corresponding arms.
15670b57cec5SDimitry Andric   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
15680b57cec5SDimitry Andric     if (SI->getCondition() == SI2->getCondition()) {
15690b57cec5SDimitry Andric       AliasResult Alias =
15700b57cec5SDimitry Andric           aliasCheck(SI->getTrueValue(), SISize, SIAAInfo, SI2->getTrueValue(),
15710b57cec5SDimitry Andric                      V2Size, V2AAInfo, AAQI);
15720b57cec5SDimitry Andric       if (Alias == MayAlias)
15730b57cec5SDimitry Andric         return MayAlias;
15740b57cec5SDimitry Andric       AliasResult ThisAlias =
15750b57cec5SDimitry Andric           aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
15760b57cec5SDimitry Andric                      SI2->getFalseValue(), V2Size, V2AAInfo, AAQI);
15770b57cec5SDimitry Andric       return MergeAliasResults(ThisAlias, Alias);
15780b57cec5SDimitry Andric     }
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric   // If both arms of the Select node NoAlias or MustAlias V2, then returns
15810b57cec5SDimitry Andric   // NoAlias / MustAlias. Otherwise, returns MayAlias.
15820b57cec5SDimitry Andric   AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(),
15830b57cec5SDimitry Andric                                  SISize, SIAAInfo, AAQI, UnderV2);
15840b57cec5SDimitry Andric   if (Alias == MayAlias)
15850b57cec5SDimitry Andric     return MayAlias;
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric   AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(),
15880b57cec5SDimitry Andric                                      SISize, SIAAInfo, AAQI, UnderV2);
15890b57cec5SDimitry Andric   return MergeAliasResults(ThisAlias, Alias);
15900b57cec5SDimitry Andric }
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
15930b57cec5SDimitry Andric /// another.
15940b57cec5SDimitry Andric AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
15950b57cec5SDimitry Andric                                     const AAMDNodes &PNAAInfo, const Value *V2,
15960b57cec5SDimitry Andric                                     LocationSize V2Size,
15970b57cec5SDimitry Andric                                     const AAMDNodes &V2AAInfo,
15980b57cec5SDimitry Andric                                     const Value *UnderV2, AAQueryInfo &AAQI) {
15990b57cec5SDimitry Andric   // Track phi nodes we have visited. We use this information when we determine
16000b57cec5SDimitry Andric   // value equivalence.
16010b57cec5SDimitry Andric   VisitedPhiBBs.insert(PN->getParent());
16020b57cec5SDimitry Andric 
16030b57cec5SDimitry Andric   // If the values are PHIs in the same block, we can do a more precise
16040b57cec5SDimitry Andric   // as well as efficient check: just check for aliases between the values
16050b57cec5SDimitry Andric   // on corresponding edges.
16060b57cec5SDimitry Andric   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
16070b57cec5SDimitry Andric     if (PN2->getParent() == PN->getParent()) {
16080b57cec5SDimitry Andric       AAQueryInfo::LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
16090b57cec5SDimitry Andric                                 MemoryLocation(V2, V2Size, V2AAInfo));
16100b57cec5SDimitry Andric       if (PN > V2)
16110b57cec5SDimitry Andric         std::swap(Locs.first, Locs.second);
16120b57cec5SDimitry Andric       // Analyse the PHIs' inputs under the assumption that the PHIs are
16130b57cec5SDimitry Andric       // NoAlias.
16140b57cec5SDimitry Andric       // If the PHIs are May/MustAlias there must be (recursively) an input
16150b57cec5SDimitry Andric       // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
16160b57cec5SDimitry Andric       // there must be an operation on the PHIs within the PHIs' value cycle
16170b57cec5SDimitry Andric       // that causes a MayAlias.
16180b57cec5SDimitry Andric       // Pretend the phis do not alias.
16190b57cec5SDimitry Andric       AliasResult Alias = NoAlias;
16200b57cec5SDimitry Andric       AliasResult OrigAliasResult;
16210b57cec5SDimitry Andric       {
16220b57cec5SDimitry Andric         // Limited lifetime iterator invalidated by the aliasCheck call below.
16230b57cec5SDimitry Andric         auto CacheIt = AAQI.AliasCache.find(Locs);
16240b57cec5SDimitry Andric         assert((CacheIt != AAQI.AliasCache.end()) &&
16250b57cec5SDimitry Andric                "There must exist an entry for the phi node");
16260b57cec5SDimitry Andric         OrigAliasResult = CacheIt->second;
16270b57cec5SDimitry Andric         CacheIt->second = NoAlias;
16280b57cec5SDimitry Andric       }
16290b57cec5SDimitry Andric 
16300b57cec5SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
16310b57cec5SDimitry Andric         AliasResult ThisAlias =
16320b57cec5SDimitry Andric             aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
16330b57cec5SDimitry Andric                        PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
16340b57cec5SDimitry Andric                        V2Size, V2AAInfo, AAQI);
16350b57cec5SDimitry Andric         Alias = MergeAliasResults(ThisAlias, Alias);
16360b57cec5SDimitry Andric         if (Alias == MayAlias)
16370b57cec5SDimitry Andric           break;
16380b57cec5SDimitry Andric       }
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric       // Reset if speculation failed.
16410b57cec5SDimitry Andric       if (Alias != NoAlias) {
16420b57cec5SDimitry Andric         auto Pair =
16430b57cec5SDimitry Andric             AAQI.AliasCache.insert(std::make_pair(Locs, OrigAliasResult));
16440b57cec5SDimitry Andric         assert(!Pair.second && "Entry must have existed");
16450b57cec5SDimitry Andric         Pair.first->second = OrigAliasResult;
16460b57cec5SDimitry Andric       }
16470b57cec5SDimitry Andric       return Alias;
16480b57cec5SDimitry Andric     }
16490b57cec5SDimitry Andric 
16500b57cec5SDimitry Andric   SmallVector<Value *, 4> V1Srcs;
16510b57cec5SDimitry Andric   bool isRecursive = false;
16520b57cec5SDimitry Andric   if (PV)  {
16530b57cec5SDimitry Andric     // If we have PhiValues then use it to get the underlying phi values.
16540b57cec5SDimitry Andric     const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN);
16550b57cec5SDimitry Andric     // If we have more phi values than the search depth then return MayAlias
16560b57cec5SDimitry Andric     // conservatively to avoid compile time explosion. The worst possible case
16570b57cec5SDimitry Andric     // is if both sides are PHI nodes. In which case, this is O(m x n) time
16580b57cec5SDimitry Andric     // where 'm' and 'n' are the number of PHI sources.
16590b57cec5SDimitry Andric     if (PhiValueSet.size() > MaxLookupSearchDepth)
16600b57cec5SDimitry Andric       return MayAlias;
16610b57cec5SDimitry Andric     // Add the values to V1Srcs
16620b57cec5SDimitry Andric     for (Value *PV1 : PhiValueSet) {
16630b57cec5SDimitry Andric       if (EnableRecPhiAnalysis) {
16640b57cec5SDimitry Andric         if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
16650b57cec5SDimitry Andric           // Check whether the incoming value is a GEP that advances the pointer
16660b57cec5SDimitry Andric           // result of this PHI node (e.g. in a loop). If this is the case, we
16670b57cec5SDimitry Andric           // would recurse and always get a MayAlias. Handle this case specially
16680b57cec5SDimitry Andric           // below.
16690b57cec5SDimitry Andric           if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
16700b57cec5SDimitry Andric               isa<ConstantInt>(PV1GEP->idx_begin())) {
16710b57cec5SDimitry Andric             isRecursive = true;
16720b57cec5SDimitry Andric             continue;
16730b57cec5SDimitry Andric           }
16740b57cec5SDimitry Andric         }
16750b57cec5SDimitry Andric       }
16760b57cec5SDimitry Andric       V1Srcs.push_back(PV1);
16770b57cec5SDimitry Andric     }
16780b57cec5SDimitry Andric   } else {
16790b57cec5SDimitry Andric     // If we don't have PhiInfo then just look at the operands of the phi itself
16800b57cec5SDimitry Andric     // FIXME: Remove this once we can guarantee that we have PhiInfo always
16810b57cec5SDimitry Andric     SmallPtrSet<Value *, 4> UniqueSrc;
16820b57cec5SDimitry Andric     for (Value *PV1 : PN->incoming_values()) {
16830b57cec5SDimitry Andric       if (isa<PHINode>(PV1))
16840b57cec5SDimitry Andric         // If any of the source itself is a PHI, return MayAlias conservatively
16850b57cec5SDimitry Andric         // to avoid compile time explosion. The worst possible case is if both
16860b57cec5SDimitry Andric         // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
16870b57cec5SDimitry Andric         // and 'n' are the number of PHI sources.
16880b57cec5SDimitry Andric         return MayAlias;
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric       if (EnableRecPhiAnalysis)
16910b57cec5SDimitry Andric         if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
16920b57cec5SDimitry Andric           // Check whether the incoming value is a GEP that advances the pointer
16930b57cec5SDimitry Andric           // result of this PHI node (e.g. in a loop). If this is the case, we
16940b57cec5SDimitry Andric           // would recurse and always get a MayAlias. Handle this case specially
16950b57cec5SDimitry Andric           // below.
16960b57cec5SDimitry Andric           if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
16970b57cec5SDimitry Andric               isa<ConstantInt>(PV1GEP->idx_begin())) {
16980b57cec5SDimitry Andric             isRecursive = true;
16990b57cec5SDimitry Andric             continue;
17000b57cec5SDimitry Andric           }
17010b57cec5SDimitry Andric         }
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric       if (UniqueSrc.insert(PV1).second)
17040b57cec5SDimitry Andric         V1Srcs.push_back(PV1);
17050b57cec5SDimitry Andric     }
17060b57cec5SDimitry Andric   }
17070b57cec5SDimitry Andric 
17080b57cec5SDimitry Andric   // If V1Srcs is empty then that means that the phi has no underlying non-phi
17090b57cec5SDimitry Andric   // value. This should only be possible in blocks unreachable from the entry
17100b57cec5SDimitry Andric   // block, but return MayAlias just in case.
17110b57cec5SDimitry Andric   if (V1Srcs.empty())
17120b57cec5SDimitry Andric     return MayAlias;
17130b57cec5SDimitry Andric 
17140b57cec5SDimitry Andric   // If this PHI node is recursive, set the size of the accessed memory to
17150b57cec5SDimitry Andric   // unknown to represent all the possible values the GEP could advance the
17160b57cec5SDimitry Andric   // pointer to.
17170b57cec5SDimitry Andric   if (isRecursive)
17180b57cec5SDimitry Andric     PNSize = LocationSize::unknown();
17190b57cec5SDimitry Andric 
17200b57cec5SDimitry Andric   AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo, V1Srcs[0], PNSize,
17210b57cec5SDimitry Andric                                  PNAAInfo, AAQI, UnderV2);
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   // Early exit if the check of the first PHI source against V2 is MayAlias.
17240b57cec5SDimitry Andric   // Other results are not possible.
17250b57cec5SDimitry Andric   if (Alias == MayAlias)
17260b57cec5SDimitry Andric     return MayAlias;
17275ffd83dbSDimitry Andric   // With recursive phis we cannot guarantee that MustAlias/PartialAlias will
17285ffd83dbSDimitry Andric   // remain valid to all elements and needs to conservatively return MayAlias.
17295ffd83dbSDimitry Andric   if (isRecursive && Alias != NoAlias)
17305ffd83dbSDimitry Andric     return MayAlias;
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
17330b57cec5SDimitry Andric   // NoAlias / MustAlias. Otherwise, returns MayAlias.
17340b57cec5SDimitry Andric   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
17350b57cec5SDimitry Andric     Value *V = V1Srcs[i];
17360b57cec5SDimitry Andric 
17370b57cec5SDimitry Andric     AliasResult ThisAlias =
17380b57cec5SDimitry Andric         aliasCheck(V2, V2Size, V2AAInfo, V, PNSize, PNAAInfo, AAQI, UnderV2);
17390b57cec5SDimitry Andric     Alias = MergeAliasResults(ThisAlias, Alias);
17400b57cec5SDimitry Andric     if (Alias == MayAlias)
17410b57cec5SDimitry Andric       break;
17420b57cec5SDimitry Andric   }
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric   return Alias;
17450b57cec5SDimitry Andric }
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
17480b57cec5SDimitry Andric /// array references.
17490b57cec5SDimitry Andric AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
17500b57cec5SDimitry Andric                                       AAMDNodes V1AAInfo, const Value *V2,
17510b57cec5SDimitry Andric                                       LocationSize V2Size, AAMDNodes V2AAInfo,
17520b57cec5SDimitry Andric                                       AAQueryInfo &AAQI, const Value *O1,
17530b57cec5SDimitry Andric                                       const Value *O2) {
17540b57cec5SDimitry Andric   // If either of the memory references is empty, it doesn't matter what the
17550b57cec5SDimitry Andric   // pointer values are.
17560b57cec5SDimitry Andric   if (V1Size.isZero() || V2Size.isZero())
17570b57cec5SDimitry Andric     return NoAlias;
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric   // Strip off any casts if they exist.
17600b57cec5SDimitry Andric   V1 = V1->stripPointerCastsAndInvariantGroups();
17610b57cec5SDimitry Andric   V2 = V2->stripPointerCastsAndInvariantGroups();
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
17640b57cec5SDimitry Andric   // value for undef that aliases nothing in the program.
17650b57cec5SDimitry Andric   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
17660b57cec5SDimitry Andric     return NoAlias;
17670b57cec5SDimitry Andric 
17680b57cec5SDimitry Andric   // Are we checking for alias of the same value?
17690b57cec5SDimitry Andric   // Because we look 'through' phi nodes, we could look at "Value" pointers from
17700b57cec5SDimitry Andric   // different iterations. We must therefore make sure that this is not the
17710b57cec5SDimitry Andric   // case. The function isValueEqualInPotentialCycles ensures that this cannot
17720b57cec5SDimitry Andric   // happen by looking at the visited phi nodes and making sure they cannot
17730b57cec5SDimitry Andric   // reach the value.
17740b57cec5SDimitry Andric   if (isValueEqualInPotentialCycles(V1, V2))
17750b57cec5SDimitry Andric     return MustAlias;
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
17780b57cec5SDimitry Andric     return NoAlias; // Scalars cannot alias each other
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric   // Figure out what objects these things are pointing to if we can.
17810b57cec5SDimitry Andric   if (O1 == nullptr)
17820b57cec5SDimitry Andric     O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric   if (O2 == nullptr)
17850b57cec5SDimitry Andric     O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric   // Null values in the default address space don't point to any object, so they
17880b57cec5SDimitry Andric   // don't alias any other pointer.
17890b57cec5SDimitry Andric   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
17900b57cec5SDimitry Andric     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
17910b57cec5SDimitry Andric       return NoAlias;
17920b57cec5SDimitry Andric   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
17930b57cec5SDimitry Andric     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
17940b57cec5SDimitry Andric       return NoAlias;
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric   if (O1 != O2) {
17970b57cec5SDimitry Andric     // If V1/V2 point to two different objects, we know that we have no alias.
17980b57cec5SDimitry Andric     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
17990b57cec5SDimitry Andric       return NoAlias;
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric     // Constant pointers can't alias with non-const isIdentifiedObject objects.
18020b57cec5SDimitry Andric     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
18030b57cec5SDimitry Andric         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
18040b57cec5SDimitry Andric       return NoAlias;
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric     // Function arguments can't alias with things that are known to be
18070b57cec5SDimitry Andric     // unambigously identified at the function level.
18080b57cec5SDimitry Andric     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
18090b57cec5SDimitry Andric         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
18100b57cec5SDimitry Andric       return NoAlias;
18110b57cec5SDimitry Andric 
18120b57cec5SDimitry Andric     // If one pointer is the result of a call/invoke or load and the other is a
18130b57cec5SDimitry Andric     // non-escaping local object within the same function, then we know the
18140b57cec5SDimitry Andric     // object couldn't escape to a point where the call could return it.
18150b57cec5SDimitry Andric     //
18160b57cec5SDimitry Andric     // Note that if the pointers are in different functions, there are a
18170b57cec5SDimitry Andric     // variety of complications. A call with a nocapture argument may still
18180b57cec5SDimitry Andric     // temporary store the nocapture argument's value in a temporary memory
18190b57cec5SDimitry Andric     // location if that memory location doesn't escape. Or it may pass a
18200b57cec5SDimitry Andric     // nocapture value to other functions as long as they don't capture it.
18210b57cec5SDimitry Andric     if (isEscapeSource(O1) &&
18220b57cec5SDimitry Andric         isNonEscapingLocalObject(O2, &AAQI.IsCapturedCache))
18230b57cec5SDimitry Andric       return NoAlias;
18240b57cec5SDimitry Andric     if (isEscapeSource(O2) &&
18250b57cec5SDimitry Andric         isNonEscapingLocalObject(O1, &AAQI.IsCapturedCache))
18260b57cec5SDimitry Andric       return NoAlias;
18270b57cec5SDimitry Andric   }
18280b57cec5SDimitry Andric 
18290b57cec5SDimitry Andric   // If the size of one access is larger than the entire object on the other
18300b57cec5SDimitry Andric   // side, then we know such behavior is undefined and can assume no alias.
18310b57cec5SDimitry Andric   bool NullIsValidLocation = NullPointerIsDefined(&F);
18328bcb0991SDimitry Andric   if ((isObjectSmallerThan(
18338bcb0991SDimitry Andric           O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL,
18348bcb0991SDimitry Andric           TLI, NullIsValidLocation)) ||
18358bcb0991SDimitry Andric       (isObjectSmallerThan(
18368bcb0991SDimitry Andric           O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL,
18378bcb0991SDimitry Andric           TLI, NullIsValidLocation)))
18380b57cec5SDimitry Andric     return NoAlias;
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric   // Check the cache before climbing up use-def chains. This also terminates
18410b57cec5SDimitry Andric   // otherwise infinitely recursive queries.
18420b57cec5SDimitry Andric   AAQueryInfo::LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
18430b57cec5SDimitry Andric                             MemoryLocation(V2, V2Size, V2AAInfo));
18440b57cec5SDimitry Andric   if (V1 > V2)
18450b57cec5SDimitry Andric     std::swap(Locs.first, Locs.second);
18460b57cec5SDimitry Andric   std::pair<AAQueryInfo::AliasCacheT::iterator, bool> Pair =
18470b57cec5SDimitry Andric       AAQI.AliasCache.try_emplace(Locs, MayAlias);
18480b57cec5SDimitry Andric   if (!Pair.second)
18490b57cec5SDimitry Andric     return Pair.first->second;
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
18520b57cec5SDimitry Andric   // GEP can't simplify, we don't even look at the PHI cases.
18530b57cec5SDimitry Andric   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
18540b57cec5SDimitry Andric     std::swap(V1, V2);
18550b57cec5SDimitry Andric     std::swap(V1Size, V2Size);
18560b57cec5SDimitry Andric     std::swap(O1, O2);
18570b57cec5SDimitry Andric     std::swap(V1AAInfo, V2AAInfo);
18580b57cec5SDimitry Andric   }
18590b57cec5SDimitry Andric   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
18600b57cec5SDimitry Andric     AliasResult Result =
18610b57cec5SDimitry Andric         aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2, AAQI);
18620b57cec5SDimitry Andric     if (Result != MayAlias) {
18630b57cec5SDimitry Andric       auto ItInsPair = AAQI.AliasCache.insert(std::make_pair(Locs, Result));
18640b57cec5SDimitry Andric       assert(!ItInsPair.second && "Entry must have existed");
18650b57cec5SDimitry Andric       ItInsPair.first->second = Result;
18660b57cec5SDimitry Andric       return Result;
18670b57cec5SDimitry Andric     }
18680b57cec5SDimitry Andric   }
18690b57cec5SDimitry Andric 
18700b57cec5SDimitry Andric   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
18710b57cec5SDimitry Andric     std::swap(V1, V2);
18720b57cec5SDimitry Andric     std::swap(O1, O2);
18730b57cec5SDimitry Andric     std::swap(V1Size, V2Size);
18740b57cec5SDimitry Andric     std::swap(V1AAInfo, V2AAInfo);
18750b57cec5SDimitry Andric   }
18760b57cec5SDimitry Andric   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
18770b57cec5SDimitry Andric     AliasResult Result =
18780b57cec5SDimitry Andric         aliasPHI(PN, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O2, AAQI);
18790b57cec5SDimitry Andric     if (Result != MayAlias) {
18800b57cec5SDimitry Andric       Pair = AAQI.AliasCache.try_emplace(Locs, Result);
18810b57cec5SDimitry Andric       assert(!Pair.second && "Entry must have existed");
18820b57cec5SDimitry Andric       return Pair.first->second = Result;
18830b57cec5SDimitry Andric     }
18840b57cec5SDimitry Andric   }
18850b57cec5SDimitry Andric 
18860b57cec5SDimitry Andric   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
18870b57cec5SDimitry Andric     std::swap(V1, V2);
18880b57cec5SDimitry Andric     std::swap(O1, O2);
18890b57cec5SDimitry Andric     std::swap(V1Size, V2Size);
18900b57cec5SDimitry Andric     std::swap(V1AAInfo, V2AAInfo);
18910b57cec5SDimitry Andric   }
18920b57cec5SDimitry Andric   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
18930b57cec5SDimitry Andric     AliasResult Result =
18940b57cec5SDimitry Andric         aliasSelect(S1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O2, AAQI);
18950b57cec5SDimitry Andric     if (Result != MayAlias) {
18960b57cec5SDimitry Andric       Pair = AAQI.AliasCache.try_emplace(Locs, Result);
18970b57cec5SDimitry Andric       assert(!Pair.second && "Entry must have existed");
18980b57cec5SDimitry Andric       return Pair.first->second = Result;
18990b57cec5SDimitry Andric     }
19000b57cec5SDimitry Andric   }
19010b57cec5SDimitry Andric 
19020b57cec5SDimitry Andric   // If both pointers are pointing into the same object and one of them
19030b57cec5SDimitry Andric   // accesses the entire object, then the accesses must overlap in some way.
19040b57cec5SDimitry Andric   if (O1 == O2)
19050b57cec5SDimitry Andric     if (V1Size.isPrecise() && V2Size.isPrecise() &&
19060b57cec5SDimitry Andric         (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
19070b57cec5SDimitry Andric          isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation))) {
19080b57cec5SDimitry Andric       Pair = AAQI.AliasCache.try_emplace(Locs, PartialAlias);
19090b57cec5SDimitry Andric       assert(!Pair.second && "Entry must have existed");
19100b57cec5SDimitry Andric       return Pair.first->second = PartialAlias;
19110b57cec5SDimitry Andric     }
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric   // Recurse back into the best AA results we have, potentially with refined
19140b57cec5SDimitry Andric   // memory locations. We have already ensured that BasicAA has a MayAlias
19150b57cec5SDimitry Andric   // cache result for these, so any recursion back into BasicAA won't loop.
19160b57cec5SDimitry Andric   AliasResult Result = getBestAAResults().alias(Locs.first, Locs.second, AAQI);
19170b57cec5SDimitry Andric   Pair = AAQI.AliasCache.try_emplace(Locs, Result);
19180b57cec5SDimitry Andric   assert(!Pair.second && "Entry must have existed");
19190b57cec5SDimitry Andric   return Pair.first->second = Result;
19200b57cec5SDimitry Andric }
19210b57cec5SDimitry Andric 
19220b57cec5SDimitry Andric /// Check whether two Values can be considered equivalent.
19230b57cec5SDimitry Andric ///
19240b57cec5SDimitry Andric /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
19250b57cec5SDimitry Andric /// they can not be part of a cycle in the value graph by looking at all
19260b57cec5SDimitry Andric /// visited phi nodes an making sure that the phis cannot reach the value. We
19270b57cec5SDimitry Andric /// have to do this because we are looking through phi nodes (That is we say
19280b57cec5SDimitry Andric /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
19290b57cec5SDimitry Andric bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
19300b57cec5SDimitry Andric                                                   const Value *V2) {
19310b57cec5SDimitry Andric   if (V != V2)
19320b57cec5SDimitry Andric     return false;
19330b57cec5SDimitry Andric 
19340b57cec5SDimitry Andric   const Instruction *Inst = dyn_cast<Instruction>(V);
19350b57cec5SDimitry Andric   if (!Inst)
19360b57cec5SDimitry Andric     return true;
19370b57cec5SDimitry Andric 
19380b57cec5SDimitry Andric   if (VisitedPhiBBs.empty())
19390b57cec5SDimitry Andric     return true;
19400b57cec5SDimitry Andric 
19410b57cec5SDimitry Andric   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
19420b57cec5SDimitry Andric     return false;
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric   // Make sure that the visited phis cannot reach the Value. This ensures that
19450b57cec5SDimitry Andric   // the Values cannot come from different iterations of a potential cycle the
19460b57cec5SDimitry Andric   // phi nodes could be involved in.
19470b57cec5SDimitry Andric   for (auto *P : VisitedPhiBBs)
19480b57cec5SDimitry Andric     if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT, LI))
19490b57cec5SDimitry Andric       return false;
19500b57cec5SDimitry Andric 
19510b57cec5SDimitry Andric   return true;
19520b57cec5SDimitry Andric }
19530b57cec5SDimitry Andric 
19540b57cec5SDimitry Andric /// Computes the symbolic difference between two de-composed GEPs.
19550b57cec5SDimitry Andric ///
19560b57cec5SDimitry Andric /// Dest and Src are the variable indices from two decomposed GetElementPtr
19570b57cec5SDimitry Andric /// instructions GEP1 and GEP2 which have common base pointers.
19580b57cec5SDimitry Andric void BasicAAResult::GetIndexDifference(
19590b57cec5SDimitry Andric     SmallVectorImpl<VariableGEPIndex> &Dest,
19600b57cec5SDimitry Andric     const SmallVectorImpl<VariableGEPIndex> &Src) {
19610b57cec5SDimitry Andric   if (Src.empty())
19620b57cec5SDimitry Andric     return;
19630b57cec5SDimitry Andric 
19640b57cec5SDimitry Andric   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
19650b57cec5SDimitry Andric     const Value *V = Src[i].V;
19660b57cec5SDimitry Andric     unsigned ZExtBits = Src[i].ZExtBits, SExtBits = Src[i].SExtBits;
19670b57cec5SDimitry Andric     APInt Scale = Src[i].Scale;
19680b57cec5SDimitry Andric 
19690b57cec5SDimitry Andric     // Find V in Dest.  This is N^2, but pointer indices almost never have more
19700b57cec5SDimitry Andric     // than a few variable indexes.
19710b57cec5SDimitry Andric     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
19720b57cec5SDimitry Andric       if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
19730b57cec5SDimitry Andric           Dest[j].ZExtBits != ZExtBits || Dest[j].SExtBits != SExtBits)
19740b57cec5SDimitry Andric         continue;
19750b57cec5SDimitry Andric 
19760b57cec5SDimitry Andric       // If we found it, subtract off Scale V's from the entry in Dest.  If it
19770b57cec5SDimitry Andric       // goes to zero, remove the entry.
19780b57cec5SDimitry Andric       if (Dest[j].Scale != Scale)
19790b57cec5SDimitry Andric         Dest[j].Scale -= Scale;
19800b57cec5SDimitry Andric       else
19810b57cec5SDimitry Andric         Dest.erase(Dest.begin() + j);
19820b57cec5SDimitry Andric       Scale = 0;
19830b57cec5SDimitry Andric       break;
19840b57cec5SDimitry Andric     }
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric     // If we didn't consume this entry, add it to the end of the Dest list.
19870b57cec5SDimitry Andric     if (!!Scale) {
19880b57cec5SDimitry Andric       VariableGEPIndex Entry = {V, ZExtBits, SExtBits, -Scale};
19890b57cec5SDimitry Andric       Dest.push_back(Entry);
19900b57cec5SDimitry Andric     }
19910b57cec5SDimitry Andric   }
19920b57cec5SDimitry Andric }
19930b57cec5SDimitry Andric 
19940b57cec5SDimitry Andric bool BasicAAResult::constantOffsetHeuristic(
19950b57cec5SDimitry Andric     const SmallVectorImpl<VariableGEPIndex> &VarIndices,
19965ffd83dbSDimitry Andric     LocationSize MaybeV1Size, LocationSize MaybeV2Size, const APInt &BaseOffset,
19970b57cec5SDimitry Andric     AssumptionCache *AC, DominatorTree *DT) {
19980b57cec5SDimitry Andric   if (VarIndices.size() != 2 || MaybeV1Size == LocationSize::unknown() ||
19990b57cec5SDimitry Andric       MaybeV2Size == LocationSize::unknown())
20000b57cec5SDimitry Andric     return false;
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric   const uint64_t V1Size = MaybeV1Size.getValue();
20030b57cec5SDimitry Andric   const uint64_t V2Size = MaybeV2Size.getValue();
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric   const VariableGEPIndex &Var0 = VarIndices[0], &Var1 = VarIndices[1];
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric   if (Var0.ZExtBits != Var1.ZExtBits || Var0.SExtBits != Var1.SExtBits ||
20080b57cec5SDimitry Andric       Var0.Scale != -Var1.Scale)
20090b57cec5SDimitry Andric     return false;
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric   unsigned Width = Var1.V->getType()->getIntegerBitWidth();
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric   // We'll strip off the Extensions of Var0 and Var1 and do another round
20140b57cec5SDimitry Andric   // of GetLinearExpression decomposition. In the example above, if Var0
20150b57cec5SDimitry Andric   // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric   APInt V0Scale(Width, 0), V0Offset(Width, 0), V1Scale(Width, 0),
20180b57cec5SDimitry Andric       V1Offset(Width, 0);
20190b57cec5SDimitry Andric   bool NSW = true, NUW = true;
20200b57cec5SDimitry Andric   unsigned V0ZExtBits = 0, V0SExtBits = 0, V1ZExtBits = 0, V1SExtBits = 0;
20210b57cec5SDimitry Andric   const Value *V0 = GetLinearExpression(Var0.V, V0Scale, V0Offset, V0ZExtBits,
20220b57cec5SDimitry Andric                                         V0SExtBits, DL, 0, AC, DT, NSW, NUW);
20230b57cec5SDimitry Andric   NSW = true;
20240b57cec5SDimitry Andric   NUW = true;
20250b57cec5SDimitry Andric   const Value *V1 = GetLinearExpression(Var1.V, V1Scale, V1Offset, V1ZExtBits,
20260b57cec5SDimitry Andric                                         V1SExtBits, DL, 0, AC, DT, NSW, NUW);
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric   if (V0Scale != V1Scale || V0ZExtBits != V1ZExtBits ||
20290b57cec5SDimitry Andric       V0SExtBits != V1SExtBits || !isValueEqualInPotentialCycles(V0, V1))
20300b57cec5SDimitry Andric     return false;
20310b57cec5SDimitry Andric 
20320b57cec5SDimitry Andric   // We have a hit - Var0 and Var1 only differ by a constant offset!
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric   // If we've been sext'ed then zext'd the maximum difference between Var0 and
20350b57cec5SDimitry Andric   // Var1 is possible to calculate, but we're just interested in the absolute
20360b57cec5SDimitry Andric   // minimum difference between the two. The minimum distance may occur due to
20370b57cec5SDimitry Andric   // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
20380b57cec5SDimitry Andric   // the minimum distance between %i and %i + 5 is 3.
20390b57cec5SDimitry Andric   APInt MinDiff = V0Offset - V1Offset, Wrapped = -MinDiff;
20400b57cec5SDimitry Andric   MinDiff = APIntOps::umin(MinDiff, Wrapped);
20410b57cec5SDimitry Andric   APInt MinDiffBytes =
20420b57cec5SDimitry Andric     MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric   // We can't definitely say whether GEP1 is before or after V2 due to wrapping
20450b57cec5SDimitry Andric   // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
20460b57cec5SDimitry Andric   // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
20470b57cec5SDimitry Andric   // V2Size can fit in the MinDiffBytes gap.
20480b57cec5SDimitry Andric   return MinDiffBytes.uge(V1Size + BaseOffset.abs()) &&
20490b57cec5SDimitry Andric          MinDiffBytes.uge(V2Size + BaseOffset.abs());
20500b57cec5SDimitry Andric }
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
20530b57cec5SDimitry Andric // BasicAliasAnalysis Pass
20540b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
20550b57cec5SDimitry Andric 
20560b57cec5SDimitry Andric AnalysisKey BasicAA::Key;
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
20590b57cec5SDimitry Andric   return BasicAAResult(F.getParent()->getDataLayout(),
20600b57cec5SDimitry Andric                        F,
20610b57cec5SDimitry Andric                        AM.getResult<TargetLibraryAnalysis>(F),
20620b57cec5SDimitry Andric                        AM.getResult<AssumptionAnalysis>(F),
20630b57cec5SDimitry Andric                        &AM.getResult<DominatorTreeAnalysis>(F),
20640b57cec5SDimitry Andric                        AM.getCachedResult<LoopAnalysis>(F),
20650b57cec5SDimitry Andric                        AM.getCachedResult<PhiValuesAnalysis>(F));
20660b57cec5SDimitry Andric }
20670b57cec5SDimitry Andric 
20680b57cec5SDimitry Andric BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
20690b57cec5SDimitry Andric   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
20700b57cec5SDimitry Andric }
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric char BasicAAWrapperPass::ID = 0;
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric void BasicAAWrapperPass::anchor() {}
20750b57cec5SDimitry Andric 
20765ffd83dbSDimitry Andric INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa",
2077*b32fb2a4SDimitry Andric                       "Basic Alias Analysis (stateless AA impl)", true, true)
20780b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
20790b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
20800b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2081*b32fb2a4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass)
20825ffd83dbSDimitry Andric INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa",
2083*b32fb2a4SDimitry Andric                     "Basic Alias Analysis (stateless AA impl)", true, true)
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric FunctionPass *llvm::createBasicAAWrapperPass() {
20860b57cec5SDimitry Andric   return new BasicAAWrapperPass();
20870b57cec5SDimitry Andric }
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric bool BasicAAWrapperPass::runOnFunction(Function &F) {
20900b57cec5SDimitry Andric   auto &ACT = getAnalysis<AssumptionCacheTracker>();
20910b57cec5SDimitry Andric   auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
20920b57cec5SDimitry Andric   auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
20930b57cec5SDimitry Andric   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
20940b57cec5SDimitry Andric   auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>();
20950b57cec5SDimitry Andric 
20968bcb0991SDimitry Andric   Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F,
20978bcb0991SDimitry Andric                                  TLIWP.getTLI(F), ACT.getAssumptionCache(F),
20988bcb0991SDimitry Andric                                  &DTWP.getDomTree(),
20990b57cec5SDimitry Andric                                  LIWP ? &LIWP->getLoopInfo() : nullptr,
21000b57cec5SDimitry Andric                                  PVWP ? &PVWP->getResult() : nullptr));
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric   return false;
21030b57cec5SDimitry Andric }
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
21060b57cec5SDimitry Andric   AU.setPreservesAll();
21070b57cec5SDimitry Andric   AU.addRequired<AssumptionCacheTracker>();
21080b57cec5SDimitry Andric   AU.addRequired<DominatorTreeWrapperPass>();
21090b57cec5SDimitry Andric   AU.addRequired<TargetLibraryInfoWrapperPass>();
21100b57cec5SDimitry Andric   AU.addUsedIfAvailable<PhiValuesWrapperPass>();
21110b57cec5SDimitry Andric }
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) {
21140b57cec5SDimitry Andric   return BasicAAResult(
21158bcb0991SDimitry Andric       F.getParent()->getDataLayout(), F,
21168bcb0991SDimitry Andric       P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
21170b57cec5SDimitry Andric       P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
21180b57cec5SDimitry Andric }
2119