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"
17e8d8bef9SDimitry Andric #include "llvm/ADT/ScopeExit.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
200b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
250b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
280b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
29480093f4SDimitry Andric #include "llvm/Analysis/PhiValues.h"
300b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
310b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
320b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
330b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
340b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
350b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
360b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
370b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
380b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
390b57cec5SDimitry Andric #include "llvm/IR/Function.h"
400b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
410b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
420b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
430b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
440b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
450b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
460b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
470b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
480b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
490b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
500b57cec5SDimitry Andric #include "llvm/IR/Type.h"
510b57cec5SDimitry Andric #include "llvm/IR/User.h"
520b57cec5SDimitry Andric #include "llvm/IR/Value.h"
53480093f4SDimitry Andric #include "llvm/InitializePasses.h"
540b57cec5SDimitry Andric #include "llvm/Pass.h"
550b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
560b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
570b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
580b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h"
590b57cec5SDimitry Andric #include <cassert>
600b57cec5SDimitry Andric #include <cstdint>
610b57cec5SDimitry Andric #include <cstdlib>
620b57cec5SDimitry Andric #include <utility>
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric #define DEBUG_TYPE "basicaa"
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric using namespace llvm;
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric /// Enable analysis of recursive PHI nodes.
695ffd83dbSDimitry Andric static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden,
70e8d8bef9SDimitry Andric                                           cl::init(true));
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric /// By default, even on 32-bit architectures we use 64-bit integers for
730b57cec5SDimitry Andric /// calculations. This will allow us to more-aggressively decompose indexing
740b57cec5SDimitry Andric /// expressions calculated using i64 values (e.g., long long in C) which is
750b57cec5SDimitry Andric /// common enough to worry about.
765ffd83dbSDimitry Andric static cl::opt<bool> ForceAtLeast64Bits("basic-aa-force-at-least-64b",
770b57cec5SDimitry Andric                                         cl::Hidden, cl::init(true));
785ffd83dbSDimitry Andric static cl::opt<bool> DoubleCalcBits("basic-aa-double-calc-bits",
790b57cec5SDimitry Andric                                     cl::Hidden, cl::init(false));
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric /// SearchLimitReached / SearchTimes shows how often the limit of
820b57cec5SDimitry Andric /// to decompose GEPs is reached. It will affect the precision
830b57cec5SDimitry Andric /// of basic alias analysis.
840b57cec5SDimitry Andric STATISTIC(SearchLimitReached, "Number of times the limit to "
850b57cec5SDimitry Andric                               "decompose GEPs is reached");
860b57cec5SDimitry Andric STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric /// Cutoff after which to stop analysing a set of phi nodes potentially involved
890b57cec5SDimitry Andric /// in a cycle. Because we are analysing 'through' phi nodes, we need to be
900b57cec5SDimitry Andric /// careful with value equivalence. We use reachability to make sure a value
910b57cec5SDimitry Andric /// cannot be involved in a cycle.
920b57cec5SDimitry Andric const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric // The max limit of the search depth in DecomposeGEPExpression() and
95e8d8bef9SDimitry Andric // getUnderlyingObject(), both functions need to use the same search
960b57cec5SDimitry Andric // depth otherwise the algorithm in aliasGEP will assert.
970b57cec5SDimitry Andric static const unsigned MaxLookupSearchDepth = 6;
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
1000b57cec5SDimitry Andric                                FunctionAnalysisManager::Invalidator &Inv) {
1010b57cec5SDimitry Andric   // We don't care if this analysis itself is preserved, it has no state. But
1020b57cec5SDimitry Andric   // we need to check that the analyses it depends on have been. Note that we
1030b57cec5SDimitry Andric   // may be created without handles to some analyses and in that case don't
1040b57cec5SDimitry Andric   // depend on them.
1050b57cec5SDimitry Andric   if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
1060b57cec5SDimitry Andric       (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
1070b57cec5SDimitry Andric       (LI && Inv.invalidate<LoopAnalysis>(Fn, PA)) ||
1080b57cec5SDimitry Andric       (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA)))
1090b57cec5SDimitry Andric     return true;
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric   // Otherwise this analysis result remains valid.
1120b57cec5SDimitry Andric   return false;
1130b57cec5SDimitry Andric }
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1160b57cec5SDimitry Andric // Useful predicates
1170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric /// Returns true if the pointer is one which would have been considered an
1200b57cec5SDimitry Andric /// escape by isNonEscapingLocalObject.
1210b57cec5SDimitry Andric static bool isEscapeSource(const Value *V) {
1220b57cec5SDimitry Andric   if (isa<CallBase>(V))
1230b57cec5SDimitry Andric     return true;
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   if (isa<Argument>(V))
1260b57cec5SDimitry Andric     return true;
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric   // The load case works because isNonEscapingLocalObject considers all
1290b57cec5SDimitry Andric   // stores to be escapes (it passes true for the StoreCaptures argument
1300b57cec5SDimitry Andric   // to PointerMayBeCaptured).
1310b57cec5SDimitry Andric   if (isa<LoadInst>(V))
1320b57cec5SDimitry Andric     return true;
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric   return false;
1350b57cec5SDimitry Andric }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric /// Returns the size of the object specified by V or UnknownSize if unknown.
1380b57cec5SDimitry Andric static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
1390b57cec5SDimitry Andric                               const TargetLibraryInfo &TLI,
1400b57cec5SDimitry Andric                               bool NullIsValidLoc,
1410b57cec5SDimitry Andric                               bool RoundToAlign = false) {
1420b57cec5SDimitry Andric   uint64_t Size;
1430b57cec5SDimitry Andric   ObjectSizeOpts Opts;
1440b57cec5SDimitry Andric   Opts.RoundToAlign = RoundToAlign;
1450b57cec5SDimitry Andric   Opts.NullIsUnknownSize = NullIsValidLoc;
1460b57cec5SDimitry Andric   if (getObjectSize(V, Size, DL, &TLI, Opts))
1470b57cec5SDimitry Andric     return Size;
1480b57cec5SDimitry Andric   return MemoryLocation::UnknownSize;
1490b57cec5SDimitry Andric }
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V is smaller than
1520b57cec5SDimitry Andric /// Size.
1530b57cec5SDimitry Andric static bool isObjectSmallerThan(const Value *V, uint64_t Size,
1540b57cec5SDimitry Andric                                 const DataLayout &DL,
1550b57cec5SDimitry Andric                                 const TargetLibraryInfo &TLI,
1560b57cec5SDimitry Andric                                 bool NullIsValidLoc) {
1570b57cec5SDimitry Andric   // Note that the meanings of the "object" are slightly different in the
1580b57cec5SDimitry Andric   // following contexts:
1590b57cec5SDimitry Andric   //    c1: llvm::getObjectSize()
1600b57cec5SDimitry Andric   //    c2: llvm.objectsize() intrinsic
1610b57cec5SDimitry Andric   //    c3: isObjectSmallerThan()
1620b57cec5SDimitry Andric   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
1630b57cec5SDimitry Andric   // refers to the "entire object".
1640b57cec5SDimitry Andric   //
1650b57cec5SDimitry Andric   //  Consider this example:
1660b57cec5SDimitry Andric   //     char *p = (char*)malloc(100)
1670b57cec5SDimitry Andric   //     char *q = p+80;
1680b57cec5SDimitry Andric   //
1690b57cec5SDimitry Andric   //  In the context of c1 and c2, the "object" pointed by q refers to the
1700b57cec5SDimitry Andric   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
1710b57cec5SDimitry Andric   //
1720b57cec5SDimitry Andric   //  However, in the context of c3, the "object" refers to the chunk of memory
1730b57cec5SDimitry Andric   // being allocated. So, the "object" has 100 bytes, and q points to the middle
1740b57cec5SDimitry Andric   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
1750b57cec5SDimitry Andric   // parameter, before the llvm::getObjectSize() is called to get the size of
1760b57cec5SDimitry Andric   // entire object, we should:
1770b57cec5SDimitry Andric   //    - either rewind the pointer q to the base-address of the object in
1780b57cec5SDimitry Andric   //      question (in this case rewind to p), or
1790b57cec5SDimitry Andric   //    - just give up. It is up to caller to make sure the pointer is pointing
1800b57cec5SDimitry Andric   //      to the base address the object.
1810b57cec5SDimitry Andric   //
1820b57cec5SDimitry Andric   // We go for 2nd option for simplicity.
1830b57cec5SDimitry Andric   if (!isIdentifiedObject(V))
1840b57cec5SDimitry Andric     return false;
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric   // This function needs to use the aligned object size because we allow
1870b57cec5SDimitry Andric   // reads a bit past the end given sufficient alignment.
1880b57cec5SDimitry Andric   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
1890b57cec5SDimitry Andric                                       /*RoundToAlign*/ true);
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
1948bcb0991SDimitry Andric /// Return the minimal extent from \p V to the end of the underlying object,
1958bcb0991SDimitry Andric /// assuming the result is used in an aliasing query. E.g., we do use the query
1968bcb0991SDimitry Andric /// location size and the fact that null pointers cannot alias here.
1978bcb0991SDimitry Andric static uint64_t getMinimalExtentFrom(const Value &V,
1988bcb0991SDimitry Andric                                      const LocationSize &LocSize,
1998bcb0991SDimitry Andric                                      const DataLayout &DL,
2008bcb0991SDimitry Andric                                      bool NullIsValidLoc) {
2018bcb0991SDimitry Andric   // If we have dereferenceability information we know a lower bound for the
2028bcb0991SDimitry Andric   // extent as accesses for a lower offset would be valid. We need to exclude
2038bcb0991SDimitry Andric   // the "or null" part if null is a valid pointer.
2048bcb0991SDimitry Andric   bool CanBeNull;
2058bcb0991SDimitry Andric   uint64_t DerefBytes = V.getPointerDereferenceableBytes(DL, CanBeNull);
2068bcb0991SDimitry Andric   DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
2078bcb0991SDimitry Andric   // If queried with a precise location size, we assume that location size to be
2088bcb0991SDimitry Andric   // accessed, thus valid.
2098bcb0991SDimitry Andric   if (LocSize.isPrecise())
2108bcb0991SDimitry Andric     DerefBytes = std::max(DerefBytes, LocSize.getValue());
2118bcb0991SDimitry Andric   return DerefBytes;
2128bcb0991SDimitry Andric }
2138bcb0991SDimitry Andric 
2140b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V has size Size.
2150b57cec5SDimitry Andric static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
2160b57cec5SDimitry Andric                          const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
2170b57cec5SDimitry Andric   uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc);
2180b57cec5SDimitry Andric   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
2190b57cec5SDimitry Andric }
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2220b57cec5SDimitry Andric // GetElementPtr Instruction Decomposition and Analysis
2230b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric /// Analyzes the specified value as a linear expression: "A*V + B", where A and
2260b57cec5SDimitry Andric /// B are constant integers.
2270b57cec5SDimitry Andric ///
2280b57cec5SDimitry Andric /// Returns the scale and offset values as APInts and return V as a Value*, and
2290b57cec5SDimitry Andric /// return whether we looked through any sign or zero extends.  The incoming
2300b57cec5SDimitry Andric /// Value is known to have IntegerType, and it may already be sign or zero
2310b57cec5SDimitry Andric /// extended.
2320b57cec5SDimitry Andric ///
2330b57cec5SDimitry Andric /// Note that this looks through extends, so the high bits may not be
2340b57cec5SDimitry Andric /// represented in the result.
2350b57cec5SDimitry Andric /*static*/ const Value *BasicAAResult::GetLinearExpression(
2360b57cec5SDimitry Andric     const Value *V, APInt &Scale, APInt &Offset, unsigned &ZExtBits,
2370b57cec5SDimitry Andric     unsigned &SExtBits, const DataLayout &DL, unsigned Depth,
2380b57cec5SDimitry Andric     AssumptionCache *AC, DominatorTree *DT, bool &NSW, bool &NUW) {
2390b57cec5SDimitry Andric   assert(V->getType()->isIntegerTy() && "Not an integer value");
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   // Limit our recursion depth.
2420b57cec5SDimitry Andric   if (Depth == 6) {
2430b57cec5SDimitry Andric     Scale = 1;
2440b57cec5SDimitry Andric     Offset = 0;
2450b57cec5SDimitry Andric     return V;
2460b57cec5SDimitry Andric   }
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   if (const ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
2490b57cec5SDimitry Andric     // If it's a constant, just convert it to an offset and remove the variable.
2500b57cec5SDimitry Andric     // If we've been called recursively, the Offset bit width will be greater
2510b57cec5SDimitry Andric     // than the constant's (the Offset's always as wide as the outermost call),
2520b57cec5SDimitry Andric     // so we'll zext here and process any extension in the isa<SExtInst> &
2530b57cec5SDimitry Andric     // isa<ZExtInst> cases below.
2540b57cec5SDimitry Andric     Offset += Const->getValue().zextOrSelf(Offset.getBitWidth());
2550b57cec5SDimitry Andric     assert(Scale == 0 && "Constant values don't have a scale");
2560b57cec5SDimitry Andric     return V;
2570b57cec5SDimitry Andric   }
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
2600b57cec5SDimitry Andric     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
2610b57cec5SDimitry Andric       // If we've been called recursively, then Offset and Scale will be wider
2620b57cec5SDimitry Andric       // than the BOp operands. We'll always zext it here as we'll process sign
2630b57cec5SDimitry Andric       // extensions below (see the isa<SExtInst> / isa<ZExtInst> cases).
2640b57cec5SDimitry Andric       APInt RHS = RHSC->getValue().zextOrSelf(Offset.getBitWidth());
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric       switch (BOp->getOpcode()) {
2670b57cec5SDimitry Andric       default:
2680b57cec5SDimitry Andric         // We don't understand this instruction, so we can't decompose it any
2690b57cec5SDimitry Andric         // further.
2700b57cec5SDimitry Andric         Scale = 1;
2710b57cec5SDimitry Andric         Offset = 0;
2720b57cec5SDimitry Andric         return V;
2730b57cec5SDimitry Andric       case Instruction::Or:
2740b57cec5SDimitry Andric         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
2750b57cec5SDimitry Andric         // analyze it.
2760b57cec5SDimitry Andric         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
2770b57cec5SDimitry Andric                                BOp, DT)) {
2780b57cec5SDimitry Andric           Scale = 1;
2790b57cec5SDimitry Andric           Offset = 0;
2800b57cec5SDimitry Andric           return V;
2810b57cec5SDimitry Andric         }
2820b57cec5SDimitry Andric         LLVM_FALLTHROUGH;
2830b57cec5SDimitry Andric       case Instruction::Add:
2840b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
2850b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
2860b57cec5SDimitry Andric         Offset += RHS;
2870b57cec5SDimitry Andric         break;
2880b57cec5SDimitry Andric       case Instruction::Sub:
2890b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
2900b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
2910b57cec5SDimitry Andric         Offset -= RHS;
2920b57cec5SDimitry Andric         break;
2930b57cec5SDimitry Andric       case Instruction::Mul:
2940b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
2950b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
2960b57cec5SDimitry Andric         Offset *= RHS;
2970b57cec5SDimitry Andric         Scale *= RHS;
2980b57cec5SDimitry Andric         break;
2990b57cec5SDimitry Andric       case Instruction::Shl:
3000b57cec5SDimitry Andric         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
3010b57cec5SDimitry Andric                                 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric         // We're trying to linearize an expression of the kind:
3040b57cec5SDimitry Andric         //   shl i8 -128, 36
3050b57cec5SDimitry Andric         // where the shift count exceeds the bitwidth of the type.
3060b57cec5SDimitry Andric         // We can't decompose this further (the expression would return
3070b57cec5SDimitry Andric         // a poison value).
3080b57cec5SDimitry Andric         if (Offset.getBitWidth() < RHS.getLimitedValue() ||
3090b57cec5SDimitry Andric             Scale.getBitWidth() < RHS.getLimitedValue()) {
3100b57cec5SDimitry Andric           Scale = 1;
3110b57cec5SDimitry Andric           Offset = 0;
3120b57cec5SDimitry Andric           return V;
3130b57cec5SDimitry Andric         }
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric         Offset <<= RHS.getLimitedValue();
3160b57cec5SDimitry Andric         Scale <<= RHS.getLimitedValue();
3170b57cec5SDimitry Andric         // the semantics of nsw and nuw for left shifts don't match those of
3180b57cec5SDimitry Andric         // multiplications, so we won't propagate them.
3190b57cec5SDimitry Andric         NSW = NUW = false;
3200b57cec5SDimitry Andric         return V;
3210b57cec5SDimitry Andric       }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric       if (isa<OverflowingBinaryOperator>(BOp)) {
3240b57cec5SDimitry Andric         NUW &= BOp->hasNoUnsignedWrap();
3250b57cec5SDimitry Andric         NSW &= BOp->hasNoSignedWrap();
3260b57cec5SDimitry Andric       }
3270b57cec5SDimitry Andric       return V;
3280b57cec5SDimitry Andric     }
3290b57cec5SDimitry Andric   }
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   // Since GEP indices are sign extended anyway, we don't care about the high
3320b57cec5SDimitry Andric   // bits of a sign or zero extended value - just scales and offsets.  The
3330b57cec5SDimitry Andric   // extensions have to be consistent though.
3340b57cec5SDimitry Andric   if (isa<SExtInst>(V) || isa<ZExtInst>(V)) {
3350b57cec5SDimitry Andric     Value *CastOp = cast<CastInst>(V)->getOperand(0);
3360b57cec5SDimitry Andric     unsigned NewWidth = V->getType()->getPrimitiveSizeInBits();
3370b57cec5SDimitry Andric     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
3380b57cec5SDimitry Andric     unsigned OldZExtBits = ZExtBits, OldSExtBits = SExtBits;
3390b57cec5SDimitry Andric     const Value *Result =
3400b57cec5SDimitry Andric         GetLinearExpression(CastOp, Scale, Offset, ZExtBits, SExtBits, DL,
3410b57cec5SDimitry Andric                             Depth + 1, AC, DT, NSW, NUW);
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric     // zext(zext(%x)) == zext(%x), and similarly for sext; we'll handle this
3440b57cec5SDimitry Andric     // by just incrementing the number of bits we've extended by.
3450b57cec5SDimitry Andric     unsigned ExtendedBy = NewWidth - SmallWidth;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric     if (isa<SExtInst>(V) && ZExtBits == 0) {
3480b57cec5SDimitry Andric       // sext(sext(%x, a), b) == sext(%x, a + b)
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric       if (NSW) {
3510b57cec5SDimitry Andric         // We haven't sign-wrapped, so it's valid to decompose sext(%x + c)
3520b57cec5SDimitry Andric         // into sext(%x) + sext(c). We'll sext the Offset ourselves:
3530b57cec5SDimitry Andric         unsigned OldWidth = Offset.getBitWidth();
3540b57cec5SDimitry Andric         Offset = Offset.trunc(SmallWidth).sext(NewWidth).zextOrSelf(OldWidth);
3550b57cec5SDimitry Andric       } else {
3560b57cec5SDimitry Andric         // We may have signed-wrapped, so don't decompose sext(%x + c) into
3570b57cec5SDimitry Andric         // sext(%x) + sext(c)
3580b57cec5SDimitry Andric         Scale = 1;
3590b57cec5SDimitry Andric         Offset = 0;
3600b57cec5SDimitry Andric         Result = CastOp;
3610b57cec5SDimitry Andric         ZExtBits = OldZExtBits;
3620b57cec5SDimitry Andric         SExtBits = OldSExtBits;
3630b57cec5SDimitry Andric       }
3640b57cec5SDimitry Andric       SExtBits += ExtendedBy;
3650b57cec5SDimitry Andric     } else {
3660b57cec5SDimitry Andric       // sext(zext(%x, a), b) = zext(zext(%x, a), b) = zext(%x, a + b)
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric       if (!NUW) {
3690b57cec5SDimitry Andric         // We may have unsigned-wrapped, so don't decompose zext(%x + c) into
3700b57cec5SDimitry Andric         // zext(%x) + zext(c)
3710b57cec5SDimitry Andric         Scale = 1;
3720b57cec5SDimitry Andric         Offset = 0;
3730b57cec5SDimitry Andric         Result = CastOp;
3740b57cec5SDimitry Andric         ZExtBits = OldZExtBits;
3750b57cec5SDimitry Andric         SExtBits = OldSExtBits;
3760b57cec5SDimitry Andric       }
3770b57cec5SDimitry Andric       ZExtBits += ExtendedBy;
3780b57cec5SDimitry Andric     }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric     return Result;
3810b57cec5SDimitry Andric   }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   Scale = 1;
3840b57cec5SDimitry Andric   Offset = 0;
3850b57cec5SDimitry Andric   return V;
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric /// To ensure a pointer offset fits in an integer of size PointerSize
3890b57cec5SDimitry Andric /// (in bits) when that size is smaller than the maximum pointer size. This is
3900b57cec5SDimitry Andric /// an issue, for example, in particular for 32b pointers with negative indices
3910b57cec5SDimitry Andric /// that rely on two's complement wrap-arounds for precise alias information
3920b57cec5SDimitry Andric /// where the maximum pointer size is 64b.
3935ffd83dbSDimitry Andric static APInt adjustToPointerSize(const APInt &Offset, unsigned PointerSize) {
3940b57cec5SDimitry Andric   assert(PointerSize <= Offset.getBitWidth() && "Invalid PointerSize!");
3950b57cec5SDimitry Andric   unsigned ShiftBits = Offset.getBitWidth() - PointerSize;
3960b57cec5SDimitry Andric   return (Offset << ShiftBits).ashr(ShiftBits);
3970b57cec5SDimitry Andric }
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric static unsigned getMaxPointerSize(const DataLayout &DL) {
4000b57cec5SDimitry Andric   unsigned MaxPointerSize = DL.getMaxPointerSizeInBits();
4010b57cec5SDimitry Andric   if (MaxPointerSize < 64 && ForceAtLeast64Bits) MaxPointerSize = 64;
4020b57cec5SDimitry Andric   if (DoubleCalcBits) MaxPointerSize *= 2;
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric   return MaxPointerSize;
4050b57cec5SDimitry Andric }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric /// If V is a symbolic pointer expression, decompose it into a base pointer
4080b57cec5SDimitry Andric /// with a constant offset and a number of scaled symbolic offsets.
4090b57cec5SDimitry Andric ///
4100b57cec5SDimitry Andric /// The scaled symbolic offsets (represented by pairs of a Value* and a scale
4110b57cec5SDimitry Andric /// in the VarIndices vector) are Value*'s that are known to be scaled by the
4120b57cec5SDimitry Andric /// specified amount, but which may have other unrepresented high bits. As
4130b57cec5SDimitry Andric /// such, the gep cannot necessarily be reconstructed from its decomposed form.
4140b57cec5SDimitry Andric ///
415e8d8bef9SDimitry Andric /// This function is capable of analyzing everything that getUnderlyingObject
416e8d8bef9SDimitry Andric /// can look through. To be able to do that getUnderlyingObject and
417e8d8bef9SDimitry Andric /// DecomposeGEPExpression must use the same search depth
418e8d8bef9SDimitry Andric /// (MaxLookupSearchDepth).
419e8d8bef9SDimitry Andric BasicAAResult::DecomposedGEP
420e8d8bef9SDimitry Andric BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL,
421e8d8bef9SDimitry Andric                                       AssumptionCache *AC, DominatorTree *DT) {
4220b57cec5SDimitry Andric   // Limit recursion depth to limit compile time in crazy cases.
4230b57cec5SDimitry Andric   unsigned MaxLookup = MaxLookupSearchDepth;
4240b57cec5SDimitry Andric   SearchTimes++;
425e8d8bef9SDimitry Andric   const Instruction *CxtI = dyn_cast<Instruction>(V);
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric   unsigned MaxPointerSize = getMaxPointerSize(DL);
428e8d8bef9SDimitry Andric   DecomposedGEP Decomposed;
429e8d8bef9SDimitry Andric   Decomposed.Offset = APInt(MaxPointerSize, 0);
430e8d8bef9SDimitry Andric   Decomposed.HasCompileTimeConstantScale = true;
4310b57cec5SDimitry Andric   do {
4320b57cec5SDimitry Andric     // See if this is a bitcast or GEP.
4330b57cec5SDimitry Andric     const Operator *Op = dyn_cast<Operator>(V);
4340b57cec5SDimitry Andric     if (!Op) {
4350b57cec5SDimitry Andric       // The only non-operator case we can handle are GlobalAliases.
4360b57cec5SDimitry Andric       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
4370b57cec5SDimitry Andric         if (!GA->isInterposable()) {
4380b57cec5SDimitry Andric           V = GA->getAliasee();
4390b57cec5SDimitry Andric           continue;
4400b57cec5SDimitry Andric         }
4410b57cec5SDimitry Andric       }
4420b57cec5SDimitry Andric       Decomposed.Base = V;
443e8d8bef9SDimitry Andric       return Decomposed;
4440b57cec5SDimitry Andric     }
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric     if (Op->getOpcode() == Instruction::BitCast ||
4470b57cec5SDimitry Andric         Op->getOpcode() == Instruction::AddrSpaceCast) {
4480b57cec5SDimitry Andric       V = Op->getOperand(0);
4490b57cec5SDimitry Andric       continue;
4500b57cec5SDimitry Andric     }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
4530b57cec5SDimitry Andric     if (!GEPOp) {
4545ffd83dbSDimitry Andric       if (const auto *PHI = dyn_cast<PHINode>(V)) {
4555ffd83dbSDimitry Andric         // Look through single-arg phi nodes created by LCSSA.
4565ffd83dbSDimitry Andric         if (PHI->getNumIncomingValues() == 1) {
4575ffd83dbSDimitry Andric           V = PHI->getIncomingValue(0);
4585ffd83dbSDimitry Andric           continue;
4595ffd83dbSDimitry Andric         }
4605ffd83dbSDimitry Andric       } else if (const auto *Call = dyn_cast<CallBase>(V)) {
4610b57cec5SDimitry Andric         // CaptureTracking can know about special capturing properties of some
4620b57cec5SDimitry Andric         // intrinsics like launder.invariant.group, that can't be expressed with
4630b57cec5SDimitry Andric         // the attributes, but have properties like returning aliasing pointer.
4640b57cec5SDimitry Andric         // Because some analysis may assume that nocaptured pointer is not
4650b57cec5SDimitry Andric         // returned from some special intrinsic (because function would have to
4660b57cec5SDimitry Andric         // be marked with returns attribute), it is crucial to use this function
4670b57cec5SDimitry Andric         // because it should be in sync with CaptureTracking. Not using it may
4680b57cec5SDimitry Andric         // cause weird miscompilations where 2 aliasing pointers are assumed to
4690b57cec5SDimitry Andric         // noalias.
4708bcb0991SDimitry Andric         if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
4710b57cec5SDimitry Andric           V = RP;
4720b57cec5SDimitry Andric           continue;
4730b57cec5SDimitry Andric         }
4740b57cec5SDimitry Andric       }
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric       Decomposed.Base = V;
477e8d8bef9SDimitry Andric       return Decomposed;
4780b57cec5SDimitry Andric     }
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric     // Don't attempt to analyze GEPs over unsized objects.
4810b57cec5SDimitry Andric     if (!GEPOp->getSourceElementType()->isSized()) {
4820b57cec5SDimitry Andric       Decomposed.Base = V;
483e8d8bef9SDimitry Andric       return Decomposed;
4840b57cec5SDimitry Andric     }
4850b57cec5SDimitry Andric 
4865ffd83dbSDimitry Andric     // Don't attempt to analyze GEPs if index scale is not a compile-time
4875ffd83dbSDimitry Andric     // constant.
4885ffd83dbSDimitry Andric     if (isa<ScalableVectorType>(GEPOp->getSourceElementType())) {
4895ffd83dbSDimitry Andric       Decomposed.Base = V;
4905ffd83dbSDimitry Andric       Decomposed.HasCompileTimeConstantScale = false;
491e8d8bef9SDimitry Andric       return Decomposed;
4925ffd83dbSDimitry Andric     }
4935ffd83dbSDimitry Andric 
4940b57cec5SDimitry Andric     unsigned AS = GEPOp->getPointerAddressSpace();
4950b57cec5SDimitry Andric     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
4960b57cec5SDimitry Andric     gep_type_iterator GTI = gep_type_begin(GEPOp);
4970b57cec5SDimitry Andric     unsigned PointerSize = DL.getPointerSizeInBits(AS);
4980b57cec5SDimitry Andric     // Assume all GEP operands are constants until proven otherwise.
4990b57cec5SDimitry Andric     bool GepHasConstantOffset = true;
5000b57cec5SDimitry Andric     for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
5010b57cec5SDimitry Andric          I != E; ++I, ++GTI) {
5020b57cec5SDimitry Andric       const Value *Index = *I;
5030b57cec5SDimitry Andric       // Compute the (potentially symbolic) offset in bytes for this index.
5040b57cec5SDimitry Andric       if (StructType *STy = GTI.getStructTypeOrNull()) {
5050b57cec5SDimitry Andric         // For a struct, add the member offset.
5060b57cec5SDimitry Andric         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
5070b57cec5SDimitry Andric         if (FieldNo == 0)
5080b57cec5SDimitry Andric           continue;
5090b57cec5SDimitry Andric 
510e8d8bef9SDimitry Andric         Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo);
5110b57cec5SDimitry Andric         continue;
5120b57cec5SDimitry Andric       }
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric       // For an array/pointer, add the element offset, explicitly scaled.
5150b57cec5SDimitry Andric       if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
5160b57cec5SDimitry Andric         if (CIdx->isZero())
5170b57cec5SDimitry Andric           continue;
518e8d8bef9SDimitry Andric         Decomposed.Offset +=
519e8d8bef9SDimitry Andric             DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize() *
520e8d8bef9SDimitry Andric             CIdx->getValue().sextOrTrunc(MaxPointerSize);
5210b57cec5SDimitry Andric         continue;
5220b57cec5SDimitry Andric       }
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric       GepHasConstantOffset = false;
5250b57cec5SDimitry Andric 
5265ffd83dbSDimitry Andric       APInt Scale(MaxPointerSize,
5275ffd83dbSDimitry Andric                   DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize());
5280b57cec5SDimitry Andric       unsigned ZExtBits = 0, SExtBits = 0;
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric       // If the integer type is smaller than the pointer size, it is implicitly
5310b57cec5SDimitry Andric       // sign extended to pointer size.
5320b57cec5SDimitry Andric       unsigned Width = Index->getType()->getIntegerBitWidth();
5330b57cec5SDimitry Andric       if (PointerSize > Width)
5340b57cec5SDimitry Andric         SExtBits += PointerSize - Width;
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
5370b57cec5SDimitry Andric       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
5380b57cec5SDimitry Andric       bool NSW = true, NUW = true;
5390b57cec5SDimitry Andric       const Value *OrigIndex = Index;
5400b57cec5SDimitry Andric       Index = GetLinearExpression(Index, IndexScale, IndexOffset, ZExtBits,
5410b57cec5SDimitry Andric                                   SExtBits, DL, 0, AC, DT, NSW, NUW);
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
5440b57cec5SDimitry Andric       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric       // It can be the case that, even through C1*V+C2 does not overflow for
5470b57cec5SDimitry Andric       // relevant values of V, (C2*Scale) can overflow. In that case, we cannot
5480b57cec5SDimitry Andric       // decompose the expression in this way.
5490b57cec5SDimitry Andric       //
5500b57cec5SDimitry Andric       // FIXME: C1*Scale and the other operations in the decomposed
5510b57cec5SDimitry Andric       // (C1*Scale)*V+C2*Scale can also overflow. We should check for this
5520b57cec5SDimitry Andric       // possibility.
553e8d8bef9SDimitry Andric       bool Overflow;
554e8d8bef9SDimitry Andric       APInt ScaledOffset = IndexOffset.sextOrTrunc(MaxPointerSize)
555e8d8bef9SDimitry Andric                            .smul_ov(Scale, Overflow);
556e8d8bef9SDimitry Andric       if (Overflow) {
5570b57cec5SDimitry Andric         Index = OrigIndex;
5580b57cec5SDimitry Andric         IndexScale = 1;
5590b57cec5SDimitry Andric         IndexOffset = 0;
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric         ZExtBits = SExtBits = 0;
5620b57cec5SDimitry Andric         if (PointerSize > Width)
5630b57cec5SDimitry Andric           SExtBits += PointerSize - Width;
5640b57cec5SDimitry Andric       } else {
565e8d8bef9SDimitry Andric         Decomposed.Offset += ScaledOffset;
5660b57cec5SDimitry Andric         Scale *= IndexScale.sextOrTrunc(MaxPointerSize);
5670b57cec5SDimitry Andric       }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric       // If we already had an occurrence of this index variable, merge this
5700b57cec5SDimitry Andric       // scale into it.  For example, we want to handle:
5710b57cec5SDimitry Andric       //   A[x][x] -> x*16 + x*4 -> x*20
5720b57cec5SDimitry Andric       // This also ensures that 'x' only appears in the index list once.
5730b57cec5SDimitry Andric       for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
5740b57cec5SDimitry Andric         if (Decomposed.VarIndices[i].V == Index &&
5750b57cec5SDimitry Andric             Decomposed.VarIndices[i].ZExtBits == ZExtBits &&
5760b57cec5SDimitry Andric             Decomposed.VarIndices[i].SExtBits == SExtBits) {
5770b57cec5SDimitry Andric           Scale += Decomposed.VarIndices[i].Scale;
5780b57cec5SDimitry Andric           Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
5790b57cec5SDimitry Andric           break;
5800b57cec5SDimitry Andric         }
5810b57cec5SDimitry Andric       }
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric       // Make sure that we have a scale that makes sense for this target's
5840b57cec5SDimitry Andric       // pointer size.
5850b57cec5SDimitry Andric       Scale = adjustToPointerSize(Scale, PointerSize);
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric       if (!!Scale) {
588e8d8bef9SDimitry Andric         VariableGEPIndex Entry = {Index, ZExtBits, SExtBits, Scale, CxtI};
5890b57cec5SDimitry Andric         Decomposed.VarIndices.push_back(Entry);
5900b57cec5SDimitry Andric       }
5910b57cec5SDimitry Andric     }
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric     // Take care of wrap-arounds
594e8d8bef9SDimitry Andric     if (GepHasConstantOffset)
595e8d8bef9SDimitry Andric       Decomposed.Offset = adjustToPointerSize(Decomposed.Offset, PointerSize);
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric     // Analyze the base pointer next.
5980b57cec5SDimitry Andric     V = GEPOp->getOperand(0);
5990b57cec5SDimitry Andric   } while (--MaxLookup);
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   // If the chain of expressions is too deep, just return early.
6020b57cec5SDimitry Andric   Decomposed.Base = V;
6030b57cec5SDimitry Andric   SearchLimitReached++;
604e8d8bef9SDimitry Andric   return Decomposed;
6050b57cec5SDimitry Andric }
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric /// Returns whether the given pointer value points to memory that is local to
6080b57cec5SDimitry Andric /// the function, with global constants being considered local to all
6090b57cec5SDimitry Andric /// functions.
6100b57cec5SDimitry Andric bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
6110b57cec5SDimitry Andric                                            AAQueryInfo &AAQI, bool OrLocal) {
6120b57cec5SDimitry Andric   assert(Visited.empty() && "Visited must be cleared after use!");
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric   unsigned MaxLookup = 8;
6150b57cec5SDimitry Andric   SmallVector<const Value *, 16> Worklist;
6160b57cec5SDimitry Andric   Worklist.push_back(Loc.Ptr);
6170b57cec5SDimitry Andric   do {
618e8d8bef9SDimitry Andric     const Value *V = getUnderlyingObject(Worklist.pop_back_val());
6190b57cec5SDimitry Andric     if (!Visited.insert(V).second) {
6200b57cec5SDimitry Andric       Visited.clear();
6210b57cec5SDimitry Andric       return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
6220b57cec5SDimitry Andric     }
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric     // An alloca instruction defines local memory.
6250b57cec5SDimitry Andric     if (OrLocal && isa<AllocaInst>(V))
6260b57cec5SDimitry Andric       continue;
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric     // A global constant counts as local memory for our purposes.
6290b57cec5SDimitry Andric     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6300b57cec5SDimitry Andric       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
6310b57cec5SDimitry Andric       // global to be marked constant in some modules and non-constant in
6320b57cec5SDimitry Andric       // others.  GV may even be a declaration, not a definition.
6330b57cec5SDimitry Andric       if (!GV->isConstant()) {
6340b57cec5SDimitry Andric         Visited.clear();
6350b57cec5SDimitry Andric         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
6360b57cec5SDimitry Andric       }
6370b57cec5SDimitry Andric       continue;
6380b57cec5SDimitry Andric     }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric     // If both select values point to local memory, then so does the select.
6410b57cec5SDimitry Andric     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
6420b57cec5SDimitry Andric       Worklist.push_back(SI->getTrueValue());
6430b57cec5SDimitry Andric       Worklist.push_back(SI->getFalseValue());
6440b57cec5SDimitry Andric       continue;
6450b57cec5SDimitry Andric     }
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric     // If all values incoming to a phi node point to local memory, then so does
6480b57cec5SDimitry Andric     // the phi.
6490b57cec5SDimitry Andric     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
6500b57cec5SDimitry Andric       // Don't bother inspecting phi nodes with many operands.
6510b57cec5SDimitry Andric       if (PN->getNumIncomingValues() > MaxLookup) {
6520b57cec5SDimitry Andric         Visited.clear();
6530b57cec5SDimitry Andric         return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
6540b57cec5SDimitry Andric       }
655e8d8bef9SDimitry Andric       append_range(Worklist, PN->incoming_values());
6560b57cec5SDimitry Andric       continue;
6570b57cec5SDimitry Andric     }
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric     // Otherwise be conservative.
6600b57cec5SDimitry Andric     Visited.clear();
6610b57cec5SDimitry Andric     return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal);
6620b57cec5SDimitry Andric   } while (!Worklist.empty() && --MaxLookup);
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   Visited.clear();
6650b57cec5SDimitry Andric   return Worklist.empty();
6660b57cec5SDimitry Andric }
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric /// Returns the behavior when calling the given call site.
6690b57cec5SDimitry Andric FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) {
6700b57cec5SDimitry Andric   if (Call->doesNotAccessMemory())
6710b57cec5SDimitry Andric     // Can't do better than this.
6720b57cec5SDimitry Andric     return FMRB_DoesNotAccessMemory;
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   // If the callsite knows it only reads memory, don't return worse
6770b57cec5SDimitry Andric   // than that.
6780b57cec5SDimitry Andric   if (Call->onlyReadsMemory())
6790b57cec5SDimitry Andric     Min = FMRB_OnlyReadsMemory;
6800b57cec5SDimitry Andric   else if (Call->doesNotReadMemory())
6815ffd83dbSDimitry Andric     Min = FMRB_OnlyWritesMemory;
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric   if (Call->onlyAccessesArgMemory())
6840b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
6850b57cec5SDimitry Andric   else if (Call->onlyAccessesInaccessibleMemory())
6860b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
6870b57cec5SDimitry Andric   else if (Call->onlyAccessesInaccessibleMemOrArgMem())
6880b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric   // If the call has operand bundles then aliasing attributes from the function
6910b57cec5SDimitry Andric   // it calls do not directly apply to the call.  This can be made more precise
6920b57cec5SDimitry Andric   // in the future.
6930b57cec5SDimitry Andric   if (!Call->hasOperandBundles())
6940b57cec5SDimitry Andric     if (const Function *F = Call->getCalledFunction())
6950b57cec5SDimitry Andric       Min =
6960b57cec5SDimitry Andric           FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F));
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   return Min;
6990b57cec5SDimitry Andric }
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric /// Returns the behavior when calling the given function. For use when the call
7020b57cec5SDimitry Andric /// site is not known.
7030b57cec5SDimitry Andric FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
7040b57cec5SDimitry Andric   // If the function declares it doesn't access memory, we can't do better.
7050b57cec5SDimitry Andric   if (F->doesNotAccessMemory())
7060b57cec5SDimitry Andric     return FMRB_DoesNotAccessMemory;
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric   // If the function declares it only reads memory, go with that.
7110b57cec5SDimitry Andric   if (F->onlyReadsMemory())
7120b57cec5SDimitry Andric     Min = FMRB_OnlyReadsMemory;
7130b57cec5SDimitry Andric   else if (F->doesNotReadMemory())
7145ffd83dbSDimitry Andric     Min = FMRB_OnlyWritesMemory;
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric   if (F->onlyAccessesArgMemory())
7170b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
7180b57cec5SDimitry Andric   else if (F->onlyAccessesInaccessibleMemory())
7190b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
7200b57cec5SDimitry Andric   else if (F->onlyAccessesInaccessibleMemOrArgMem())
7210b57cec5SDimitry Andric     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   return Min;
7240b57cec5SDimitry Andric }
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric /// Returns true if this is a writeonly (i.e Mod only) parameter.
7270b57cec5SDimitry Andric static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx,
7280b57cec5SDimitry Andric                              const TargetLibraryInfo &TLI) {
7290b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly))
7300b57cec5SDimitry Andric     return true;
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric   // We can bound the aliasing properties of memset_pattern16 just as we can
7330b57cec5SDimitry Andric   // for memcpy/memset.  This is particularly important because the
7340b57cec5SDimitry Andric   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
7350b57cec5SDimitry Andric   // whenever possible.
7360b57cec5SDimitry Andric   // FIXME Consider handling this in InferFunctionAttr.cpp together with other
7370b57cec5SDimitry Andric   // attributes.
7380b57cec5SDimitry Andric   LibFunc F;
7390b57cec5SDimitry Andric   if (Call->getCalledFunction() &&
7400b57cec5SDimitry Andric       TLI.getLibFunc(*Call->getCalledFunction(), F) &&
7410b57cec5SDimitry Andric       F == LibFunc_memset_pattern16 && TLI.has(F))
7420b57cec5SDimitry Andric     if (ArgIdx == 0)
7430b57cec5SDimitry Andric       return true;
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   // TODO: memset_pattern4, memset_pattern8
7460b57cec5SDimitry Andric   // TODO: _chk variants
7470b57cec5SDimitry Andric   // TODO: strcmp, strcpy
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric   return false;
7500b57cec5SDimitry Andric }
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,
7530b57cec5SDimitry Andric                                            unsigned ArgIdx) {
7540b57cec5SDimitry Andric   // Checking for known builtin intrinsics and target library functions.
7550b57cec5SDimitry Andric   if (isWriteOnlyParam(Call, ArgIdx, TLI))
7560b57cec5SDimitry Andric     return ModRefInfo::Mod;
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly))
7590b57cec5SDimitry Andric     return ModRefInfo::Ref;
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone))
7620b57cec5SDimitry Andric     return ModRefInfo::NoModRef;
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   return AAResultBase::getArgModRefInfo(Call, ArgIdx);
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
7680b57cec5SDimitry Andric   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call);
7690b57cec5SDimitry Andric   return II && II->getIntrinsicID() == IID;
7700b57cec5SDimitry Andric }
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric #ifndef NDEBUG
7730b57cec5SDimitry Andric static const Function *getParent(const Value *V) {
7740b57cec5SDimitry Andric   if (const Instruction *inst = dyn_cast<Instruction>(V)) {
7750b57cec5SDimitry Andric     if (!inst->getParent())
7760b57cec5SDimitry Andric       return nullptr;
7770b57cec5SDimitry Andric     return inst->getParent()->getParent();
7780b57cec5SDimitry Andric   }
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric   if (const Argument *arg = dyn_cast<Argument>(V))
7810b57cec5SDimitry Andric     return arg->getParent();
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric   return nullptr;
7840b57cec5SDimitry Andric }
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric static bool notDifferentParent(const Value *O1, const Value *O2) {
7870b57cec5SDimitry Andric 
7880b57cec5SDimitry Andric   const Function *F1 = getParent(O1);
7890b57cec5SDimitry Andric   const Function *F2 = getParent(O2);
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   return !F1 || !F2 || F1 == F2;
7920b57cec5SDimitry Andric }
7930b57cec5SDimitry Andric #endif
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
7960b57cec5SDimitry Andric                                  const MemoryLocation &LocB,
7970b57cec5SDimitry Andric                                  AAQueryInfo &AAQI) {
7980b57cec5SDimitry Andric   assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
7990b57cec5SDimitry Andric          "BasicAliasAnalysis doesn't support interprocedural queries.");
800e8d8bef9SDimitry Andric   return aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr, LocB.Size,
801e8d8bef9SDimitry Andric                     LocB.AATags, AAQI);
8020b57cec5SDimitry Andric }
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric /// Checks to see if the specified callsite can clobber the specified memory
8050b57cec5SDimitry Andric /// object.
8060b57cec5SDimitry Andric ///
8070b57cec5SDimitry Andric /// Since we only look at local properties of this function, we really can't
8080b57cec5SDimitry Andric /// say much about this query.  We do, however, use simple "address taken"
8090b57cec5SDimitry Andric /// analysis on local objects.
8100b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,
8110b57cec5SDimitry Andric                                         const MemoryLocation &Loc,
8120b57cec5SDimitry Andric                                         AAQueryInfo &AAQI) {
8130b57cec5SDimitry Andric   assert(notDifferentParent(Call, Loc.Ptr) &&
8140b57cec5SDimitry Andric          "AliasAnalysis query involving multiple functions!");
8150b57cec5SDimitry Andric 
816e8d8bef9SDimitry Andric   const Value *Object = getUnderlyingObject(Loc.Ptr);
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   // Calls marked 'tail' cannot read or write allocas from the current frame
8190b57cec5SDimitry Andric   // because the current frame might be destroyed by the time they run. However,
8200b57cec5SDimitry Andric   // a tail call may use an alloca with byval. Calling with byval copies the
8210b57cec5SDimitry Andric   // contents of the alloca into argument registers or stack slots, so there is
8220b57cec5SDimitry Andric   // no lifetime issue.
8230b57cec5SDimitry Andric   if (isa<AllocaInst>(Object))
8240b57cec5SDimitry Andric     if (const CallInst *CI = dyn_cast<CallInst>(Call))
8250b57cec5SDimitry Andric       if (CI->isTailCall() &&
8260b57cec5SDimitry Andric           !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
8270b57cec5SDimitry Andric         return ModRefInfo::NoModRef;
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric   // Stack restore is able to modify unescaped dynamic allocas. Assume it may
8300b57cec5SDimitry Andric   // modify them even though the alloca is not escaped.
8310b57cec5SDimitry Andric   if (auto *AI = dyn_cast<AllocaInst>(Object))
8320b57cec5SDimitry Andric     if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))
8330b57cec5SDimitry Andric       return ModRefInfo::Mod;
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric   // If the pointer is to a locally allocated object that does not escape,
8360b57cec5SDimitry Andric   // then the call can not mod/ref the pointer unless the call takes the pointer
8370b57cec5SDimitry Andric   // as an argument, and itself doesn't capture it.
8380b57cec5SDimitry Andric   if (!isa<Constant>(Object) && Call != Object &&
8390b57cec5SDimitry Andric       isNonEscapingLocalObject(Object, &AAQI.IsCapturedCache)) {
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric     // Optimistically assume that call doesn't touch Object and check this
8420b57cec5SDimitry Andric     // assumption in the following loop.
8430b57cec5SDimitry Andric     ModRefInfo Result = ModRefInfo::NoModRef;
8440b57cec5SDimitry Andric     bool IsMustAlias = true;
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric     unsigned OperandNo = 0;
8470b57cec5SDimitry Andric     for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
8480b57cec5SDimitry Andric          CI != CE; ++CI, ++OperandNo) {
8490b57cec5SDimitry Andric       // Only look at the no-capture or byval pointer arguments.  If this
8500b57cec5SDimitry Andric       // pointer were passed to arguments that were neither of these, then it
8510b57cec5SDimitry Andric       // couldn't be no-capture.
8520b57cec5SDimitry Andric       if (!(*CI)->getType()->isPointerTy() ||
8530b57cec5SDimitry Andric           (!Call->doesNotCapture(OperandNo) &&
8540b57cec5SDimitry Andric            OperandNo < Call->getNumArgOperands() &&
8550b57cec5SDimitry Andric            !Call->isByValArgument(OperandNo)))
8560b57cec5SDimitry Andric         continue;
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric       // Call doesn't access memory through this operand, so we don't care
8590b57cec5SDimitry Andric       // if it aliases with Object.
8600b57cec5SDimitry Andric       if (Call->doesNotAccessMemory(OperandNo))
8610b57cec5SDimitry Andric         continue;
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric       // If this is a no-capture pointer argument, see if we can tell that it
8640b57cec5SDimitry Andric       // is impossible to alias the pointer we're checking.
865e8d8bef9SDimitry Andric       AliasResult AR = getBestAAResults().alias(
866e8d8bef9SDimitry Andric           MemoryLocation::getBeforeOrAfter(*CI),
867e8d8bef9SDimitry Andric           MemoryLocation::getBeforeOrAfter(Object), AAQI);
8680b57cec5SDimitry Andric       if (AR != MustAlias)
8690b57cec5SDimitry Andric         IsMustAlias = false;
8700b57cec5SDimitry Andric       // Operand doesn't alias 'Object', continue looking for other aliases
8710b57cec5SDimitry Andric       if (AR == NoAlias)
8720b57cec5SDimitry Andric         continue;
8730b57cec5SDimitry Andric       // Operand aliases 'Object', but call doesn't modify it. Strengthen
8740b57cec5SDimitry Andric       // initial assumption and keep looking in case if there are more aliases.
8750b57cec5SDimitry Andric       if (Call->onlyReadsMemory(OperandNo)) {
8760b57cec5SDimitry Andric         Result = setRef(Result);
8770b57cec5SDimitry Andric         continue;
8780b57cec5SDimitry Andric       }
8790b57cec5SDimitry Andric       // Operand aliases 'Object' but call only writes into it.
8800b57cec5SDimitry Andric       if (Call->doesNotReadMemory(OperandNo)) {
8810b57cec5SDimitry Andric         Result = setMod(Result);
8820b57cec5SDimitry Andric         continue;
8830b57cec5SDimitry Andric       }
8840b57cec5SDimitry Andric       // This operand aliases 'Object' and call reads and writes into it.
8850b57cec5SDimitry Andric       // Setting ModRef will not yield an early return below, MustAlias is not
8860b57cec5SDimitry Andric       // used further.
8870b57cec5SDimitry Andric       Result = ModRefInfo::ModRef;
8880b57cec5SDimitry Andric       break;
8890b57cec5SDimitry Andric     }
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric     // No operand aliases, reset Must bit. Add below if at least one aliases
8920b57cec5SDimitry Andric     // and all aliases found are MustAlias.
8930b57cec5SDimitry Andric     if (isNoModRef(Result))
8940b57cec5SDimitry Andric       IsMustAlias = false;
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric     // Early return if we improved mod ref information
8970b57cec5SDimitry Andric     if (!isModAndRefSet(Result)) {
8980b57cec5SDimitry Andric       if (isNoModRef(Result))
8990b57cec5SDimitry Andric         return ModRefInfo::NoModRef;
9000b57cec5SDimitry Andric       return IsMustAlias ? setMust(Result) : clearMust(Result);
9010b57cec5SDimitry Andric     }
9020b57cec5SDimitry Andric   }
9030b57cec5SDimitry Andric 
9045ffd83dbSDimitry Andric   // If the call is malloc/calloc like, we can assume that it doesn't
9050b57cec5SDimitry Andric   // modify any IR visible value.  This is only valid because we assume these
9060b57cec5SDimitry Andric   // routines do not read values visible in the IR.  TODO: Consider special
9070b57cec5SDimitry Andric   // casing realloc and strdup routines which access only their arguments as
9080b57cec5SDimitry Andric   // well.  Or alternatively, replace all of this with inaccessiblememonly once
9090b57cec5SDimitry Andric   // that's implemented fully.
9100b57cec5SDimitry Andric   if (isMallocOrCallocLikeFn(Call, &TLI)) {
9110b57cec5SDimitry Andric     // Be conservative if the accessed pointer may alias the allocation -
9120b57cec5SDimitry Andric     // fallback to the generic handling below.
913e8d8bef9SDimitry Andric     if (getBestAAResults().alias(MemoryLocation::getBeforeOrAfter(Call),
914e8d8bef9SDimitry Andric                                  Loc, AAQI) == NoAlias)
9150b57cec5SDimitry Andric       return ModRefInfo::NoModRef;
9160b57cec5SDimitry Andric   }
9170b57cec5SDimitry Andric 
918e8d8bef9SDimitry Andric   // The semantics of memcpy intrinsics either exactly overlap or do not
919e8d8bef9SDimitry Andric   // overlap, i.e., source and destination of any given memcpy are either
920e8d8bef9SDimitry Andric   // no-alias or must-alias.
9210b57cec5SDimitry Andric   if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) {
922e8d8bef9SDimitry Andric     AliasResult SrcAA =
923e8d8bef9SDimitry Andric         getBestAAResults().alias(MemoryLocation::getForSource(Inst), Loc, AAQI);
924e8d8bef9SDimitry Andric     AliasResult DestAA =
925e8d8bef9SDimitry Andric         getBestAAResults().alias(MemoryLocation::getForDest(Inst), Loc, AAQI);
9260b57cec5SDimitry Andric     // It's also possible for Loc to alias both src and dest, or neither.
9270b57cec5SDimitry Andric     ModRefInfo rv = ModRefInfo::NoModRef;
9280b57cec5SDimitry Andric     if (SrcAA != NoAlias)
9290b57cec5SDimitry Andric       rv = setRef(rv);
9300b57cec5SDimitry Andric     if (DestAA != NoAlias)
9310b57cec5SDimitry Andric       rv = setMod(rv);
9320b57cec5SDimitry Andric     return rv;
9330b57cec5SDimitry Andric   }
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric   // While the assume intrinsic is marked as arbitrarily writing so that
9360b57cec5SDimitry Andric   // proper control dependencies will be maintained, it never aliases any
9370b57cec5SDimitry Andric   // particular memory location.
9380b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::assume))
9390b57cec5SDimitry Andric     return ModRefInfo::NoModRef;
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   // Like assumes, guard intrinsics are also marked as arbitrarily writing so
9420b57cec5SDimitry Andric   // that proper control dependencies are maintained but they never mods any
9430b57cec5SDimitry Andric   // particular memory location.
9440b57cec5SDimitry Andric   //
9450b57cec5SDimitry Andric   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
9460b57cec5SDimitry Andric   // heap state at the point the guard is issued needs to be consistent in case
9470b57cec5SDimitry Andric   // the guard invokes the "deopt" continuation.
9480b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::experimental_guard))
9490b57cec5SDimitry Andric     return ModRefInfo::Ref;
950e8d8bef9SDimitry Andric   // The same applies to deoptimize which is essentially a guard(false).
951e8d8bef9SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::experimental_deoptimize))
952e8d8bef9SDimitry Andric     return ModRefInfo::Ref;
9530b57cec5SDimitry Andric 
9540b57cec5SDimitry Andric   // Like assumes, invariant.start intrinsics were also marked as arbitrarily
9550b57cec5SDimitry Andric   // writing so that proper control dependencies are maintained but they never
9560b57cec5SDimitry Andric   // mod any particular memory location visible to the IR.
9570b57cec5SDimitry Andric   // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
9580b57cec5SDimitry Andric   // intrinsic is now modeled as reading memory. This prevents hoisting the
9590b57cec5SDimitry Andric   // invariant.start intrinsic over stores. Consider:
9600b57cec5SDimitry Andric   // *ptr = 40;
9610b57cec5SDimitry Andric   // *ptr = 50;
9620b57cec5SDimitry Andric   // invariant_start(ptr)
9630b57cec5SDimitry Andric   // int val = *ptr;
9640b57cec5SDimitry Andric   // print(val);
9650b57cec5SDimitry Andric   //
9660b57cec5SDimitry Andric   // This cannot be transformed to:
9670b57cec5SDimitry Andric   //
9680b57cec5SDimitry Andric   // *ptr = 40;
9690b57cec5SDimitry Andric   // invariant_start(ptr)
9700b57cec5SDimitry Andric   // *ptr = 50;
9710b57cec5SDimitry Andric   // int val = *ptr;
9720b57cec5SDimitry Andric   // print(val);
9730b57cec5SDimitry Andric   //
9740b57cec5SDimitry Andric   // The transformation will cause the second store to be ignored (based on
9750b57cec5SDimitry Andric   // rules of invariant.start)  and print 40, while the first program always
9760b57cec5SDimitry Andric   // prints 50.
9770b57cec5SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::invariant_start))
9780b57cec5SDimitry Andric     return ModRefInfo::Ref;
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   // The AAResultBase base class has some smarts, lets use them.
9810b57cec5SDimitry Andric   return AAResultBase::getModRefInfo(Call, Loc, AAQI);
9820b57cec5SDimitry Andric }
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,
9850b57cec5SDimitry Andric                                         const CallBase *Call2,
9860b57cec5SDimitry Andric                                         AAQueryInfo &AAQI) {
9870b57cec5SDimitry Andric   // While the assume intrinsic is marked as arbitrarily writing so that
9880b57cec5SDimitry Andric   // proper control dependencies will be maintained, it never aliases any
9890b57cec5SDimitry Andric   // particular memory location.
9900b57cec5SDimitry Andric   if (isIntrinsicCall(Call1, Intrinsic::assume) ||
9910b57cec5SDimitry Andric       isIntrinsicCall(Call2, Intrinsic::assume))
9920b57cec5SDimitry Andric     return ModRefInfo::NoModRef;
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   // Like assumes, guard intrinsics are also marked as arbitrarily writing so
9950b57cec5SDimitry Andric   // that proper control dependencies are maintained but they never mod any
9960b57cec5SDimitry Andric   // particular memory location.
9970b57cec5SDimitry Andric   //
9980b57cec5SDimitry Andric   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
9990b57cec5SDimitry Andric   // heap state at the point the guard is issued needs to be consistent in case
10000b57cec5SDimitry Andric   // the guard invokes the "deopt" continuation.
10010b57cec5SDimitry Andric 
10020b57cec5SDimitry Andric   // NB! This function is *not* commutative, so we special case two
10030b57cec5SDimitry Andric   // possibilities for guard intrinsics.
10040b57cec5SDimitry Andric 
10050b57cec5SDimitry Andric   if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))
10060b57cec5SDimitry Andric     return isModSet(createModRefInfo(getModRefBehavior(Call2)))
10070b57cec5SDimitry Andric                ? ModRefInfo::Ref
10080b57cec5SDimitry Andric                : ModRefInfo::NoModRef;
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
10110b57cec5SDimitry Andric     return isModSet(createModRefInfo(getModRefBehavior(Call1)))
10120b57cec5SDimitry Andric                ? ModRefInfo::Mod
10130b57cec5SDimitry Andric                : ModRefInfo::NoModRef;
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric   // The AAResultBase base class has some smarts, lets use them.
10160b57cec5SDimitry Andric   return AAResultBase::getModRefInfo(Call1, Call2, AAQI);
10170b57cec5SDimitry Andric }
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric // If a we have (a) a GEP and (b) a pointer based on an alloca, and the
10200b57cec5SDimitry Andric // beginning of the object the GEP points would have a negative offset with
10210b57cec5SDimitry Andric // repsect to the alloca, that means the GEP can not alias pointer (b).
10220b57cec5SDimitry Andric // Note that the pointer based on the alloca may not be a GEP. For
10230b57cec5SDimitry Andric // example, it may be the alloca itself.
10240b57cec5SDimitry Andric // The same applies if (b) is based on a GlobalVariable. Note that just being
10250b57cec5SDimitry Andric // based on isIdentifiedObject() is not enough - we need an identified object
10260b57cec5SDimitry Andric // that does not permit access to negative offsets. For example, a negative
10270b57cec5SDimitry Andric // offset from a noalias argument or call can be inbounds w.r.t the actual
10280b57cec5SDimitry Andric // underlying object.
10290b57cec5SDimitry Andric //
10300b57cec5SDimitry Andric // For example, consider:
10310b57cec5SDimitry Andric //
10320b57cec5SDimitry Andric //   struct { int f0, int f1, ...} foo;
10330b57cec5SDimitry Andric //   foo alloca;
10340b57cec5SDimitry Andric //   foo* random = bar(alloca);
10350b57cec5SDimitry Andric //   int *f0 = &alloca.f0
10360b57cec5SDimitry Andric //   int *f1 = &random->f1;
10370b57cec5SDimitry Andric //
10380b57cec5SDimitry Andric // Which is lowered, approximately, to:
10390b57cec5SDimitry Andric //
10400b57cec5SDimitry Andric //  %alloca = alloca %struct.foo
10410b57cec5SDimitry Andric //  %random = call %struct.foo* @random(%struct.foo* %alloca)
10420b57cec5SDimitry Andric //  %f0 = getelementptr inbounds %struct, %struct.foo* %alloca, i32 0, i32 0
10430b57cec5SDimitry Andric //  %f1 = getelementptr inbounds %struct, %struct.foo* %random, i32 0, i32 1
10440b57cec5SDimitry Andric //
10450b57cec5SDimitry Andric // Assume %f1 and %f0 alias. Then %f1 would point into the object allocated
10460b57cec5SDimitry Andric // by %alloca. Since the %f1 GEP is inbounds, that means %random must also
10470b57cec5SDimitry Andric // point into the same object. But since %f0 points to the beginning of %alloca,
10480b57cec5SDimitry Andric // the highest %f1 can be is (%alloca + 3). This means %random can not be higher
10490b57cec5SDimitry Andric // than (%alloca - 1), and so is not inbounds, a contradiction.
10500b57cec5SDimitry Andric bool BasicAAResult::isGEPBaseAtNegativeOffset(const GEPOperator *GEPOp,
10510b57cec5SDimitry Andric       const DecomposedGEP &DecompGEP, const DecomposedGEP &DecompObject,
10520b57cec5SDimitry Andric       LocationSize MaybeObjectAccessSize) {
10530b57cec5SDimitry Andric   // If the object access size is unknown, or the GEP isn't inbounds, bail.
1054e8d8bef9SDimitry Andric   if (!MaybeObjectAccessSize.hasValue() || !GEPOp->isInBounds())
10550b57cec5SDimitry Andric     return false;
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   const uint64_t ObjectAccessSize = MaybeObjectAccessSize.getValue();
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric   // We need the object to be an alloca or a globalvariable, and want to know
10600b57cec5SDimitry Andric   // the offset of the pointer from the object precisely, so no variable
10610b57cec5SDimitry Andric   // indices are allowed.
10620b57cec5SDimitry Andric   if (!(isa<AllocaInst>(DecompObject.Base) ||
10630b57cec5SDimitry Andric         isa<GlobalVariable>(DecompObject.Base)) ||
10640b57cec5SDimitry Andric       !DecompObject.VarIndices.empty())
10650b57cec5SDimitry Andric     return false;
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric   // If the GEP has no variable indices, we know the precise offset
10680b57cec5SDimitry Andric   // from the base, then use it. If the GEP has variable indices,
10690b57cec5SDimitry Andric   // we can't get exact GEP offset to identify pointer alias. So return
10700b57cec5SDimitry Andric   // false in that case.
10710b57cec5SDimitry Andric   if (!DecompGEP.VarIndices.empty())
10720b57cec5SDimitry Andric     return false;
10730b57cec5SDimitry Andric 
1074e8d8bef9SDimitry Andric   return DecompGEP.Offset.sge(DecompObject.Offset + (int64_t)ObjectAccessSize);
10750b57cec5SDimitry Andric }
10760b57cec5SDimitry Andric 
10770b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
10780b57cec5SDimitry Andric /// another pointer.
10790b57cec5SDimitry Andric ///
10800b57cec5SDimitry Andric /// We know that V1 is a GEP, but we don't know anything about V2.
1081e8d8bef9SDimitry Andric /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for
10820b57cec5SDimitry Andric /// V2.
10830b57cec5SDimitry Andric AliasResult BasicAAResult::aliasGEP(
10840b57cec5SDimitry Andric     const GEPOperator *GEP1, LocationSize V1Size, const AAMDNodes &V1AAInfo,
10850b57cec5SDimitry Andric     const Value *V2, LocationSize V2Size, const AAMDNodes &V2AAInfo,
10860b57cec5SDimitry Andric     const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
1087e8d8bef9SDimitry Andric   DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT);
1088e8d8bef9SDimitry Andric   DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT);
10890b57cec5SDimitry Andric 
10905ffd83dbSDimitry Andric   // Don't attempt to analyze the decomposed GEP if index scale is not a
10915ffd83dbSDimitry Andric   // compile-time constant.
10925ffd83dbSDimitry Andric   if (!DecompGEP1.HasCompileTimeConstantScale ||
10935ffd83dbSDimitry Andric       !DecompGEP2.HasCompileTimeConstantScale)
10945ffd83dbSDimitry Andric     return MayAlias;
10955ffd83dbSDimitry Andric 
10960b57cec5SDimitry Andric   assert(DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 &&
10970b57cec5SDimitry Andric          "DecomposeGEPExpression returned a result different from "
1098e8d8bef9SDimitry Andric          "getUnderlyingObject");
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric   // If the GEP's offset relative to its base is such that the base would
11010b57cec5SDimitry Andric   // fall below the start of the object underlying V2, then the GEP and V2
11020b57cec5SDimitry Andric   // cannot alias.
1103e8d8bef9SDimitry Andric   if (isGEPBaseAtNegativeOffset(GEP1, DecompGEP1, DecompGEP2, V2Size))
11040b57cec5SDimitry Andric     return NoAlias;
11050b57cec5SDimitry Andric   // If we have two gep instructions with must-alias or not-alias'ing base
11060b57cec5SDimitry Andric   // pointers, figure out if the indexes to the GEP tell us anything about the
11070b57cec5SDimitry Andric   // derived pointer.
11080b57cec5SDimitry Andric   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
11090b57cec5SDimitry Andric     // Check for the GEP base being at a negative offset, this time in the other
11100b57cec5SDimitry Andric     // direction.
1111e8d8bef9SDimitry Andric     if (isGEPBaseAtNegativeOffset(GEP2, DecompGEP2, DecompGEP1, V1Size))
11120b57cec5SDimitry Andric       return NoAlias;
11130b57cec5SDimitry Andric     // Do the base pointers alias?
1114e8d8bef9SDimitry Andric     AliasResult BaseAlias = getBestAAResults().alias(
1115e8d8bef9SDimitry Andric         MemoryLocation::getBeforeOrAfter(UnderlyingV1),
1116e8d8bef9SDimitry Andric         MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI);
11170b57cec5SDimitry Andric 
1118e8d8bef9SDimitry Andric     // For GEPs with identical offsets, we can preserve the size and AAInfo
1119e8d8bef9SDimitry Andric     // when performing the alias check on the underlying objects.
1120e8d8bef9SDimitry Andric     if (BaseAlias == MayAlias && DecompGEP1.Offset == DecompGEP2.Offset &&
1121e8d8bef9SDimitry Andric         DecompGEP1.VarIndices == DecompGEP2.VarIndices) {
1122e8d8bef9SDimitry Andric       AliasResult PreciseBaseAlias = getBestAAResults().alias(
1123e8d8bef9SDimitry Andric           MemoryLocation(UnderlyingV1, V1Size, V1AAInfo),
1124e8d8bef9SDimitry Andric           MemoryLocation(UnderlyingV2, V2Size, V2AAInfo), AAQI);
1125e8d8bef9SDimitry Andric       if (PreciseBaseAlias == NoAlias)
11260b57cec5SDimitry Andric         return NoAlias;
11270b57cec5SDimitry Andric     }
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric     // If we get a No or May, then return it immediately, no amount of analysis
11300b57cec5SDimitry Andric     // will improve this situation.
11310b57cec5SDimitry Andric     if (BaseAlias != MustAlias) {
11320b57cec5SDimitry Andric       assert(BaseAlias == NoAlias || BaseAlias == MayAlias);
11330b57cec5SDimitry Andric       return BaseAlias;
11340b57cec5SDimitry Andric     }
11350b57cec5SDimitry Andric 
11360b57cec5SDimitry Andric     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
11370b57cec5SDimitry Andric     // symbolic difference.
1138e8d8bef9SDimitry Andric     DecompGEP1.Offset -= DecompGEP2.Offset;
11390b57cec5SDimitry Andric     GetIndexDifference(DecompGEP1.VarIndices, DecompGEP2.VarIndices);
11400b57cec5SDimitry Andric 
11410b57cec5SDimitry Andric   } else {
11420b57cec5SDimitry Andric     // Check to see if these two pointers are related by the getelementptr
11430b57cec5SDimitry Andric     // instruction.  If one pointer is a GEP with a non-zero index of the other
11440b57cec5SDimitry Andric     // pointer, we know they cannot alias.
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric     // If both accesses are unknown size, we can't do anything useful here.
1147e8d8bef9SDimitry Andric     if (!V1Size.hasValue() && !V2Size.hasValue())
11480b57cec5SDimitry Andric       return MayAlias;
11490b57cec5SDimitry Andric 
1150e8d8bef9SDimitry Andric     AliasResult R = getBestAAResults().alias(
1151e8d8bef9SDimitry Andric         MemoryLocation::getBeforeOrAfter(UnderlyingV1),
1152e8d8bef9SDimitry Andric         MemoryLocation(V2, V2Size, V2AAInfo), AAQI);
11530b57cec5SDimitry Andric     if (R != MustAlias) {
11540b57cec5SDimitry Andric       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
11550b57cec5SDimitry Andric       // If V2 is known not to alias GEP base pointer, then the two values
11560b57cec5SDimitry Andric       // cannot alias per GEP semantics: "Any memory access must be done through
11570b57cec5SDimitry Andric       // a pointer value associated with an address range of the memory access,
11580b57cec5SDimitry Andric       // otherwise the behavior is undefined.".
11590b57cec5SDimitry Andric       assert(R == NoAlias || R == MayAlias);
11600b57cec5SDimitry Andric       return R;
11610b57cec5SDimitry Andric     }
11620b57cec5SDimitry Andric   }
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric   // In the two GEP Case, if there is no difference in the offsets of the
11650b57cec5SDimitry Andric   // computed pointers, the resultant pointers are a must alias.  This
11660b57cec5SDimitry Andric   // happens when we have two lexically identical GEP's (for example).
11670b57cec5SDimitry Andric   //
11680b57cec5SDimitry Andric   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
11690b57cec5SDimitry Andric   // must aliases the GEP, the end result is a must alias also.
1170e8d8bef9SDimitry Andric   if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty())
11710b57cec5SDimitry Andric     return MustAlias;
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   // If there is a constant difference between the pointers, but the difference
11740b57cec5SDimitry Andric   // is less than the size of the associated memory object, then we know
11750b57cec5SDimitry Andric   // that the objects are partially overlapping.  If the difference is
11760b57cec5SDimitry Andric   // greater, we know they do not overlap.
1177e8d8bef9SDimitry Andric   if (DecompGEP1.Offset != 0 && DecompGEP1.VarIndices.empty()) {
1178e8d8bef9SDimitry Andric     if (DecompGEP1.Offset.sge(0)) {
1179e8d8bef9SDimitry Andric       if (V2Size.hasValue()) {
1180e8d8bef9SDimitry Andric         if (DecompGEP1.Offset.ult(V2Size.getValue()))
11810b57cec5SDimitry Andric           return PartialAlias;
11820b57cec5SDimitry Andric         return NoAlias;
11830b57cec5SDimitry Andric       }
11840b57cec5SDimitry Andric     } else {
11850b57cec5SDimitry Andric       // We have the situation where:
11860b57cec5SDimitry Andric       // +                +
11870b57cec5SDimitry Andric       // | BaseOffset     |
11880b57cec5SDimitry Andric       // ---------------->|
11890b57cec5SDimitry Andric       // |-->V1Size       |-------> V2Size
11900b57cec5SDimitry Andric       // GEP1             V2
1191e8d8bef9SDimitry Andric       if (V1Size.hasValue()) {
1192e8d8bef9SDimitry Andric         if ((-DecompGEP1.Offset).ult(V1Size.getValue()))
11930b57cec5SDimitry Andric           return PartialAlias;
11940b57cec5SDimitry Andric         return NoAlias;
11950b57cec5SDimitry Andric       }
11960b57cec5SDimitry Andric     }
11970b57cec5SDimitry Andric   }
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric   if (!DecompGEP1.VarIndices.empty()) {
1200e8d8bef9SDimitry Andric     APInt GCD;
1201e8d8bef9SDimitry Andric     bool AllNonNegative = DecompGEP1.Offset.isNonNegative();
1202e8d8bef9SDimitry Andric     bool AllNonPositive = DecompGEP1.Offset.isNonPositive();
12030b57cec5SDimitry Andric     for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
1204e8d8bef9SDimitry Andric       const APInt &Scale = DecompGEP1.VarIndices[i].Scale;
1205e8d8bef9SDimitry Andric       if (i == 0)
1206e8d8bef9SDimitry Andric         GCD = Scale.abs();
1207e8d8bef9SDimitry Andric       else
1208e8d8bef9SDimitry Andric         GCD = APIntOps::GreatestCommonDivisor(GCD, Scale.abs());
12090b57cec5SDimitry Andric 
1210e8d8bef9SDimitry Andric       if (AllNonNegative || AllNonPositive) {
12110b57cec5SDimitry Andric         // If the Value could change between cycles, then any reasoning about
12120b57cec5SDimitry Andric         // the Value this cycle may not hold in the next cycle. We'll just
12130b57cec5SDimitry Andric         // give up if we can't determine conditions that hold for every cycle:
12140b57cec5SDimitry Andric         const Value *V = DecompGEP1.VarIndices[i].V;
1215e8d8bef9SDimitry Andric         const Instruction *CxtI = DecompGEP1.VarIndices[i].CxtI;
12160b57cec5SDimitry Andric 
1217e8d8bef9SDimitry Andric         KnownBits Known = computeKnownBits(V, DL, 0, &AC, CxtI, DT);
12180b57cec5SDimitry Andric         bool SignKnownZero = Known.isNonNegative();
12190b57cec5SDimitry Andric         bool SignKnownOne = Known.isNegative();
12200b57cec5SDimitry Andric 
12210b57cec5SDimitry Andric         // Zero-extension widens the variable, and so forces the sign
12220b57cec5SDimitry Andric         // bit to zero.
12230b57cec5SDimitry Andric         bool IsZExt = DecompGEP1.VarIndices[i].ZExtBits > 0 || isa<ZExtInst>(V);
12240b57cec5SDimitry Andric         SignKnownZero |= IsZExt;
12250b57cec5SDimitry Andric         SignKnownOne &= !IsZExt;
12260b57cec5SDimitry Andric 
1227e8d8bef9SDimitry Andric         AllNonNegative &= (SignKnownZero && Scale.isNonNegative()) ||
1228e8d8bef9SDimitry Andric                           (SignKnownOne && Scale.isNonPositive());
1229e8d8bef9SDimitry Andric         AllNonPositive &= (SignKnownZero && Scale.isNonPositive()) ||
1230e8d8bef9SDimitry Andric                           (SignKnownOne && Scale.isNonNegative());
12310b57cec5SDimitry Andric       }
12320b57cec5SDimitry Andric     }
12330b57cec5SDimitry Andric 
1234e8d8bef9SDimitry Andric     // We now have accesses at two offsets from the same base:
1235e8d8bef9SDimitry Andric     //  1. (...)*GCD + DecompGEP1.Offset with size V1Size
1236e8d8bef9SDimitry Andric     //  2. 0 with size V2Size
1237e8d8bef9SDimitry Andric     // Using arithmetic modulo GCD, the accesses are at
1238e8d8bef9SDimitry Andric     // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits
1239e8d8bef9SDimitry Andric     // into the range [V2Size..GCD), then we know they cannot overlap.
1240e8d8bef9SDimitry Andric     APInt ModOffset = DecompGEP1.Offset.srem(GCD);
1241e8d8bef9SDimitry Andric     if (ModOffset.isNegative())
1242e8d8bef9SDimitry Andric       ModOffset += GCD; // We want mod, not rem.
1243e8d8bef9SDimitry Andric     if (V1Size.hasValue() && V2Size.hasValue() &&
1244e8d8bef9SDimitry Andric         ModOffset.uge(V2Size.getValue()) &&
1245e8d8bef9SDimitry Andric         (GCD - ModOffset).uge(V1Size.getValue()))
12460b57cec5SDimitry Andric       return NoAlias;
12470b57cec5SDimitry Andric 
1248e8d8bef9SDimitry Andric     // If we know all the variables are non-negative, then the total offset is
1249e8d8bef9SDimitry Andric     // also non-negative and >= DecompGEP1.Offset. We have the following layout:
1250e8d8bef9SDimitry Andric     // [0, V2Size) ... [TotalOffset, TotalOffer+V1Size]
1251e8d8bef9SDimitry Andric     // If DecompGEP1.Offset >= V2Size, the accesses don't alias.
1252e8d8bef9SDimitry Andric     if (AllNonNegative && V2Size.hasValue() &&
1253e8d8bef9SDimitry Andric         DecompGEP1.Offset.uge(V2Size.getValue()))
12540b57cec5SDimitry Andric       return NoAlias;
1255e8d8bef9SDimitry Andric     // Similarly, if the variables are non-positive, then the total offset is
1256e8d8bef9SDimitry Andric     // also non-positive and <= DecompGEP1.Offset. We have the following layout:
1257e8d8bef9SDimitry Andric     // [TotalOffset, TotalOffset+V1Size) ... [0, V2Size)
1258e8d8bef9SDimitry Andric     // If -DecompGEP1.Offset >= V1Size, the accesses don't alias.
1259e8d8bef9SDimitry Andric     if (AllNonPositive && V1Size.hasValue() &&
1260e8d8bef9SDimitry Andric         (-DecompGEP1.Offset).uge(V1Size.getValue()))
1261e8d8bef9SDimitry Andric       return NoAlias;
1262e8d8bef9SDimitry Andric 
1263e8d8bef9SDimitry Andric     if (V1Size.hasValue() && V2Size.hasValue()) {
1264e8d8bef9SDimitry Andric       // Try to determine whether abs(VarIndex) > 0.
1265e8d8bef9SDimitry Andric       Optional<APInt> MinAbsVarIndex;
1266e8d8bef9SDimitry Andric       if (DecompGEP1.VarIndices.size() == 1) {
1267e8d8bef9SDimitry Andric         // VarIndex = Scale*V. If V != 0 then abs(VarIndex) >= abs(Scale).
1268e8d8bef9SDimitry Andric         const VariableGEPIndex &Var = DecompGEP1.VarIndices[0];
1269e8d8bef9SDimitry Andric         if (isKnownNonZero(Var.V, DL, 0, &AC, Var.CxtI, DT))
1270e8d8bef9SDimitry Andric           MinAbsVarIndex = Var.Scale.abs();
1271e8d8bef9SDimitry Andric       } else if (DecompGEP1.VarIndices.size() == 2) {
1272e8d8bef9SDimitry Andric         // VarIndex = Scale*V0 + (-Scale)*V1.
1273e8d8bef9SDimitry Andric         // If V0 != V1 then abs(VarIndex) >= abs(Scale).
1274e8d8bef9SDimitry Andric         // Check that VisitedPhiBBs is empty, to avoid reasoning about
1275e8d8bef9SDimitry Andric         // inequality of values across loop iterations.
1276e8d8bef9SDimitry Andric         const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0];
1277e8d8bef9SDimitry Andric         const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1];
1278e8d8bef9SDimitry Andric         if (Var0.Scale == -Var1.Scale && Var0.ZExtBits == Var1.ZExtBits &&
1279e8d8bef9SDimitry Andric             Var0.SExtBits == Var1.SExtBits && VisitedPhiBBs.empty() &&
1280e8d8bef9SDimitry Andric             isKnownNonEqual(Var0.V, Var1.V, DL, &AC, /* CxtI */ nullptr, DT))
1281e8d8bef9SDimitry Andric           MinAbsVarIndex = Var0.Scale.abs();
1282e8d8bef9SDimitry Andric       }
1283e8d8bef9SDimitry Andric 
1284e8d8bef9SDimitry Andric       if (MinAbsVarIndex) {
1285e8d8bef9SDimitry Andric         // The constant offset will have added at least +/-MinAbsVarIndex to it.
1286e8d8bef9SDimitry Andric         APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex;
1287e8d8bef9SDimitry Andric         APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex;
1288e8d8bef9SDimitry Andric         // Check that an access at OffsetLo or lower, and an access at OffsetHi
1289e8d8bef9SDimitry Andric         // or higher both do not alias.
1290e8d8bef9SDimitry Andric         if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) &&
1291e8d8bef9SDimitry Andric             OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue()))
1292e8d8bef9SDimitry Andric           return NoAlias;
1293e8d8bef9SDimitry Andric       }
1294e8d8bef9SDimitry Andric     }
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric     if (constantOffsetHeuristic(DecompGEP1.VarIndices, V1Size, V2Size,
1297e8d8bef9SDimitry Andric                                 DecompGEP1.Offset, &AC, DT))
12980b57cec5SDimitry Andric       return NoAlias;
12990b57cec5SDimitry Andric   }
13000b57cec5SDimitry Andric 
13010b57cec5SDimitry Andric   // Statically, we can see that the base objects are the same, but the
13020b57cec5SDimitry Andric   // pointers have dynamic offsets which we can't resolve. And none of our
13030b57cec5SDimitry Andric   // little tricks above worked.
13040b57cec5SDimitry Andric   return MayAlias;
13050b57cec5SDimitry Andric }
13060b57cec5SDimitry Andric 
13070b57cec5SDimitry Andric static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
13080b57cec5SDimitry Andric   // If the results agree, take it.
13090b57cec5SDimitry Andric   if (A == B)
13100b57cec5SDimitry Andric     return A;
13110b57cec5SDimitry Andric   // A mix of PartialAlias and MustAlias is PartialAlias.
13120b57cec5SDimitry Andric   if ((A == PartialAlias && B == MustAlias) ||
13130b57cec5SDimitry Andric       (B == PartialAlias && A == MustAlias))
13140b57cec5SDimitry Andric     return PartialAlias;
13150b57cec5SDimitry Andric   // Otherwise, we don't know anything.
13160b57cec5SDimitry Andric   return MayAlias;
13170b57cec5SDimitry Andric }
13180b57cec5SDimitry Andric 
13190b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
13200b57cec5SDimitry Andric /// against another.
13210b57cec5SDimitry Andric AliasResult
13220b57cec5SDimitry Andric BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
13230b57cec5SDimitry Andric                            const AAMDNodes &SIAAInfo, const Value *V2,
13240b57cec5SDimitry Andric                            LocationSize V2Size, const AAMDNodes &V2AAInfo,
1325e8d8bef9SDimitry Andric                            AAQueryInfo &AAQI) {
13260b57cec5SDimitry Andric   // If the values are Selects with the same condition, we can do a more precise
13270b57cec5SDimitry Andric   // check: just check for aliases between the values on corresponding arms.
13280b57cec5SDimitry Andric   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
13290b57cec5SDimitry Andric     if (SI->getCondition() == SI2->getCondition()) {
1330e8d8bef9SDimitry Andric       AliasResult Alias = getBestAAResults().alias(
1331e8d8bef9SDimitry Andric           MemoryLocation(SI->getTrueValue(), SISize, SIAAInfo),
1332e8d8bef9SDimitry Andric           MemoryLocation(SI2->getTrueValue(), V2Size, V2AAInfo), AAQI);
13330b57cec5SDimitry Andric       if (Alias == MayAlias)
13340b57cec5SDimitry Andric         return MayAlias;
1335e8d8bef9SDimitry Andric       AliasResult ThisAlias = getBestAAResults().alias(
1336e8d8bef9SDimitry Andric           MemoryLocation(SI->getFalseValue(), SISize, SIAAInfo),
1337e8d8bef9SDimitry Andric           MemoryLocation(SI2->getFalseValue(), V2Size, V2AAInfo), AAQI);
13380b57cec5SDimitry Andric       return MergeAliasResults(ThisAlias, Alias);
13390b57cec5SDimitry Andric     }
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric   // If both arms of the Select node NoAlias or MustAlias V2, then returns
13420b57cec5SDimitry Andric   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1343e8d8bef9SDimitry Andric   AliasResult Alias = getBestAAResults().alias(
1344e8d8bef9SDimitry Andric       MemoryLocation(V2, V2Size, V2AAInfo),
1345e8d8bef9SDimitry Andric       MemoryLocation(SI->getTrueValue(), SISize, SIAAInfo), AAQI);
13460b57cec5SDimitry Andric   if (Alias == MayAlias)
13470b57cec5SDimitry Andric     return MayAlias;
13480b57cec5SDimitry Andric 
1349e8d8bef9SDimitry Andric   AliasResult ThisAlias = getBestAAResults().alias(
1350e8d8bef9SDimitry Andric       MemoryLocation(V2, V2Size, V2AAInfo),
1351e8d8bef9SDimitry Andric       MemoryLocation(SI->getFalseValue(), SISize, SIAAInfo), AAQI);
13520b57cec5SDimitry Andric   return MergeAliasResults(ThisAlias, Alias);
13530b57cec5SDimitry Andric }
13540b57cec5SDimitry Andric 
13550b57cec5SDimitry Andric /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
13560b57cec5SDimitry Andric /// another.
13570b57cec5SDimitry Andric AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
13580b57cec5SDimitry Andric                                     const AAMDNodes &PNAAInfo, const Value *V2,
13590b57cec5SDimitry Andric                                     LocationSize V2Size,
13600b57cec5SDimitry Andric                                     const AAMDNodes &V2AAInfo,
1361e8d8bef9SDimitry Andric                                     AAQueryInfo &AAQI) {
13620b57cec5SDimitry Andric   // If the values are PHIs in the same block, we can do a more precise
13630b57cec5SDimitry Andric   // as well as efficient check: just check for aliases between the values
13640b57cec5SDimitry Andric   // on corresponding edges.
13650b57cec5SDimitry Andric   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
13660b57cec5SDimitry Andric     if (PN2->getParent() == PN->getParent()) {
1367e8d8bef9SDimitry Andric       Optional<AliasResult> Alias;
13680b57cec5SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1369e8d8bef9SDimitry Andric         AliasResult ThisAlias = getBestAAResults().alias(
1370e8d8bef9SDimitry Andric             MemoryLocation(PN->getIncomingValue(i), PNSize, PNAAInfo),
1371e8d8bef9SDimitry Andric             MemoryLocation(
1372e8d8bef9SDimitry Andric                 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size,
1373e8d8bef9SDimitry Andric                 V2AAInfo),
1374e8d8bef9SDimitry Andric             AAQI);
1375e8d8bef9SDimitry Andric         if (Alias)
1376e8d8bef9SDimitry Andric           *Alias = MergeAliasResults(*Alias, ThisAlias);
1377e8d8bef9SDimitry Andric         else
1378e8d8bef9SDimitry Andric           Alias = ThisAlias;
1379e8d8bef9SDimitry Andric         if (*Alias == MayAlias)
13800b57cec5SDimitry Andric           break;
13810b57cec5SDimitry Andric       }
1382e8d8bef9SDimitry Andric       return *Alias;
13830b57cec5SDimitry Andric     }
13840b57cec5SDimitry Andric 
13850b57cec5SDimitry Andric   SmallVector<Value *, 4> V1Srcs;
1386e8d8bef9SDimitry Andric   // If a phi operand recurses back to the phi, we can still determine NoAlias
1387e8d8bef9SDimitry Andric   // if we don't alias the underlying objects of the other phi operands, as we
1388e8d8bef9SDimitry Andric   // know that the recursive phi needs to be based on them in some way.
13890b57cec5SDimitry Andric   bool isRecursive = false;
1390979e22ffSDimitry Andric   auto CheckForRecPhi = [&](Value *PV) {
1391979e22ffSDimitry Andric     if (!EnableRecPhiAnalysis)
1392979e22ffSDimitry Andric       return false;
1393e8d8bef9SDimitry Andric     if (getUnderlyingObject(PV) == PN) {
1394979e22ffSDimitry Andric       isRecursive = true;
1395979e22ffSDimitry Andric       return true;
1396979e22ffSDimitry Andric     }
1397979e22ffSDimitry Andric     return false;
1398979e22ffSDimitry Andric   };
1399979e22ffSDimitry Andric 
14000b57cec5SDimitry Andric   if (PV) {
14010b57cec5SDimitry Andric     // If we have PhiValues then use it to get the underlying phi values.
14020b57cec5SDimitry Andric     const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN);
14030b57cec5SDimitry Andric     // If we have more phi values than the search depth then return MayAlias
14040b57cec5SDimitry Andric     // conservatively to avoid compile time explosion. The worst possible case
14050b57cec5SDimitry Andric     // is if both sides are PHI nodes. In which case, this is O(m x n) time
14060b57cec5SDimitry Andric     // where 'm' and 'n' are the number of PHI sources.
14070b57cec5SDimitry Andric     if (PhiValueSet.size() > MaxLookupSearchDepth)
14080b57cec5SDimitry Andric       return MayAlias;
14090b57cec5SDimitry Andric     // Add the values to V1Srcs
14100b57cec5SDimitry Andric     for (Value *PV1 : PhiValueSet) {
1411979e22ffSDimitry Andric       if (CheckForRecPhi(PV1))
14120b57cec5SDimitry Andric         continue;
14130b57cec5SDimitry Andric       V1Srcs.push_back(PV1);
14140b57cec5SDimitry Andric     }
14150b57cec5SDimitry Andric   } else {
14160b57cec5SDimitry Andric     // If we don't have PhiInfo then just look at the operands of the phi itself
14170b57cec5SDimitry Andric     // FIXME: Remove this once we can guarantee that we have PhiInfo always
14180b57cec5SDimitry Andric     SmallPtrSet<Value *, 4> UniqueSrc;
14190b57cec5SDimitry Andric     for (Value *PV1 : PN->incoming_values()) {
14200b57cec5SDimitry Andric       if (isa<PHINode>(PV1))
14210b57cec5SDimitry Andric         // If any of the source itself is a PHI, return MayAlias conservatively
14220b57cec5SDimitry Andric         // to avoid compile time explosion. The worst possible case is if both
14230b57cec5SDimitry Andric         // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
14240b57cec5SDimitry Andric         // and 'n' are the number of PHI sources.
14250b57cec5SDimitry Andric         return MayAlias;
14260b57cec5SDimitry Andric 
1427979e22ffSDimitry Andric       if (CheckForRecPhi(PV1))
14280b57cec5SDimitry Andric         continue;
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric       if (UniqueSrc.insert(PV1).second)
14310b57cec5SDimitry Andric         V1Srcs.push_back(PV1);
14320b57cec5SDimitry Andric     }
14330b57cec5SDimitry Andric   }
14340b57cec5SDimitry Andric 
14350b57cec5SDimitry Andric   // If V1Srcs is empty then that means that the phi has no underlying non-phi
14360b57cec5SDimitry Andric   // value. This should only be possible in blocks unreachable from the entry
14370b57cec5SDimitry Andric   // block, but return MayAlias just in case.
14380b57cec5SDimitry Andric   if (V1Srcs.empty())
14390b57cec5SDimitry Andric     return MayAlias;
14400b57cec5SDimitry Andric 
1441e8d8bef9SDimitry Andric   // If this PHI node is recursive, indicate that the pointer may be moved
1442e8d8bef9SDimitry Andric   // across iterations. We can only prove NoAlias if different underlying
1443e8d8bef9SDimitry Andric   // objects are involved.
14440b57cec5SDimitry Andric   if (isRecursive)
1445e8d8bef9SDimitry Andric     PNSize = LocationSize::beforeOrAfterPointer();
14460b57cec5SDimitry Andric 
1447e8d8bef9SDimitry Andric   // In the recursive alias queries below, we may compare values from two
1448e8d8bef9SDimitry Andric   // different loop iterations. Keep track of visited phi blocks, which will
1449e8d8bef9SDimitry Andric   // be used when determining value equivalence.
1450e8d8bef9SDimitry Andric   bool BlockInserted = VisitedPhiBBs.insert(PN->getParent()).second;
1451e8d8bef9SDimitry Andric   auto _ = make_scope_exit([&]() {
1452e8d8bef9SDimitry Andric     if (BlockInserted)
1453e8d8bef9SDimitry Andric       VisitedPhiBBs.erase(PN->getParent());
1454e8d8bef9SDimitry Andric   });
1455e8d8bef9SDimitry Andric 
1456e8d8bef9SDimitry Andric   // If we inserted a block into VisitedPhiBBs, alias analysis results that
1457e8d8bef9SDimitry Andric   // have been cached earlier may no longer be valid. Perform recursive queries
1458e8d8bef9SDimitry Andric   // with a new AAQueryInfo.
1459e8d8bef9SDimitry Andric   AAQueryInfo NewAAQI;
1460e8d8bef9SDimitry Andric   AAQueryInfo *UseAAQI = BlockInserted ? &NewAAQI : &AAQI;
1461e8d8bef9SDimitry Andric 
1462e8d8bef9SDimitry Andric   AliasResult Alias = getBestAAResults().alias(
1463e8d8bef9SDimitry Andric       MemoryLocation(V2, V2Size, V2AAInfo),
1464e8d8bef9SDimitry Andric       MemoryLocation(V1Srcs[0], PNSize, PNAAInfo), *UseAAQI);
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric   // Early exit if the check of the first PHI source against V2 is MayAlias.
14670b57cec5SDimitry Andric   // Other results are not possible.
14680b57cec5SDimitry Andric   if (Alias == MayAlias)
14690b57cec5SDimitry Andric     return MayAlias;
14705ffd83dbSDimitry Andric   // With recursive phis we cannot guarantee that MustAlias/PartialAlias will
14715ffd83dbSDimitry Andric   // remain valid to all elements and needs to conservatively return MayAlias.
14725ffd83dbSDimitry Andric   if (isRecursive && Alias != NoAlias)
14735ffd83dbSDimitry Andric     return MayAlias;
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
14760b57cec5SDimitry Andric   // NoAlias / MustAlias. Otherwise, returns MayAlias.
14770b57cec5SDimitry Andric   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
14780b57cec5SDimitry Andric     Value *V = V1Srcs[i];
14790b57cec5SDimitry Andric 
1480e8d8bef9SDimitry Andric     AliasResult ThisAlias = getBestAAResults().alias(
1481e8d8bef9SDimitry Andric         MemoryLocation(V2, V2Size, V2AAInfo),
1482e8d8bef9SDimitry Andric         MemoryLocation(V, PNSize, PNAAInfo), *UseAAQI);
14830b57cec5SDimitry Andric     Alias = MergeAliasResults(ThisAlias, Alias);
14840b57cec5SDimitry Andric     if (Alias == MayAlias)
14850b57cec5SDimitry Andric       break;
14860b57cec5SDimitry Andric   }
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric   return Alias;
14890b57cec5SDimitry Andric }
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
14920b57cec5SDimitry Andric /// array references.
14930b57cec5SDimitry Andric AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
1494e8d8bef9SDimitry Andric                                       const AAMDNodes &V1AAInfo,
1495e8d8bef9SDimitry Andric                                       const Value *V2, LocationSize V2Size,
1496e8d8bef9SDimitry Andric                                       const AAMDNodes &V2AAInfo,
1497e8d8bef9SDimitry Andric                                       AAQueryInfo &AAQI) {
14980b57cec5SDimitry Andric   // If either of the memory references is empty, it doesn't matter what the
14990b57cec5SDimitry Andric   // pointer values are.
15000b57cec5SDimitry Andric   if (V1Size.isZero() || V2Size.isZero())
15010b57cec5SDimitry Andric     return NoAlias;
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric   // Strip off any casts if they exist.
15040b57cec5SDimitry Andric   V1 = V1->stripPointerCastsAndInvariantGroups();
15050b57cec5SDimitry Andric   V2 = V2->stripPointerCastsAndInvariantGroups();
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
15080b57cec5SDimitry Andric   // value for undef that aliases nothing in the program.
15090b57cec5SDimitry Andric   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
15100b57cec5SDimitry Andric     return NoAlias;
15110b57cec5SDimitry Andric 
15120b57cec5SDimitry Andric   // Are we checking for alias of the same value?
15130b57cec5SDimitry Andric   // Because we look 'through' phi nodes, we could look at "Value" pointers from
15140b57cec5SDimitry Andric   // different iterations. We must therefore make sure that this is not the
15150b57cec5SDimitry Andric   // case. The function isValueEqualInPotentialCycles ensures that this cannot
15160b57cec5SDimitry Andric   // happen by looking at the visited phi nodes and making sure they cannot
15170b57cec5SDimitry Andric   // reach the value.
15180b57cec5SDimitry Andric   if (isValueEqualInPotentialCycles(V1, V2))
15190b57cec5SDimitry Andric     return MustAlias;
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
15220b57cec5SDimitry Andric     return NoAlias; // Scalars cannot alias each other
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric   // Figure out what objects these things are pointing to if we can.
1525e8d8bef9SDimitry Andric   const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth);
1526e8d8bef9SDimitry Andric   const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth);
15270b57cec5SDimitry Andric 
15280b57cec5SDimitry Andric   // Null values in the default address space don't point to any object, so they
15290b57cec5SDimitry Andric   // don't alias any other pointer.
15300b57cec5SDimitry Andric   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
15310b57cec5SDimitry Andric     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
15320b57cec5SDimitry Andric       return NoAlias;
15330b57cec5SDimitry Andric   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
15340b57cec5SDimitry Andric     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
15350b57cec5SDimitry Andric       return NoAlias;
15360b57cec5SDimitry Andric 
15370b57cec5SDimitry Andric   if (O1 != O2) {
15380b57cec5SDimitry Andric     // If V1/V2 point to two different objects, we know that we have no alias.
15390b57cec5SDimitry Andric     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
15400b57cec5SDimitry Andric       return NoAlias;
15410b57cec5SDimitry Andric 
15420b57cec5SDimitry Andric     // Constant pointers can't alias with non-const isIdentifiedObject objects.
15430b57cec5SDimitry Andric     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
15440b57cec5SDimitry Andric         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
15450b57cec5SDimitry Andric       return NoAlias;
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric     // Function arguments can't alias with things that are known to be
15480b57cec5SDimitry Andric     // unambigously identified at the function level.
15490b57cec5SDimitry Andric     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
15500b57cec5SDimitry Andric         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
15510b57cec5SDimitry Andric       return NoAlias;
15520b57cec5SDimitry Andric 
15530b57cec5SDimitry Andric     // If one pointer is the result of a call/invoke or load and the other is a
15540b57cec5SDimitry Andric     // non-escaping local object within the same function, then we know the
15550b57cec5SDimitry Andric     // object couldn't escape to a point where the call could return it.
15560b57cec5SDimitry Andric     //
15570b57cec5SDimitry Andric     // Note that if the pointers are in different functions, there are a
15580b57cec5SDimitry Andric     // variety of complications. A call with a nocapture argument may still
15590b57cec5SDimitry Andric     // temporary store the nocapture argument's value in a temporary memory
15600b57cec5SDimitry Andric     // location if that memory location doesn't escape. Or it may pass a
15610b57cec5SDimitry Andric     // nocapture value to other functions as long as they don't capture it.
15620b57cec5SDimitry Andric     if (isEscapeSource(O1) &&
15630b57cec5SDimitry Andric         isNonEscapingLocalObject(O2, &AAQI.IsCapturedCache))
15640b57cec5SDimitry Andric       return NoAlias;
15650b57cec5SDimitry Andric     if (isEscapeSource(O2) &&
15660b57cec5SDimitry Andric         isNonEscapingLocalObject(O1, &AAQI.IsCapturedCache))
15670b57cec5SDimitry Andric       return NoAlias;
15680b57cec5SDimitry Andric   }
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric   // If the size of one access is larger than the entire object on the other
15710b57cec5SDimitry Andric   // side, then we know such behavior is undefined and can assume no alias.
15720b57cec5SDimitry Andric   bool NullIsValidLocation = NullPointerIsDefined(&F);
15738bcb0991SDimitry Andric   if ((isObjectSmallerThan(
15748bcb0991SDimitry Andric           O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL,
15758bcb0991SDimitry Andric           TLI, NullIsValidLocation)) ||
15768bcb0991SDimitry Andric       (isObjectSmallerThan(
15778bcb0991SDimitry Andric           O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL,
15788bcb0991SDimitry Andric           TLI, NullIsValidLocation)))
15790b57cec5SDimitry Andric     return NoAlias;
15800b57cec5SDimitry Andric 
1581e8d8bef9SDimitry Andric   // If one the accesses may be before the accessed pointer, canonicalize this
1582e8d8bef9SDimitry Andric   // by using unknown after-pointer sizes for both accesses. This is
1583e8d8bef9SDimitry Andric   // equivalent, because regardless of which pointer is lower, one of them
1584e8d8bef9SDimitry Andric   // will always came after the other, as long as the underlying objects aren't
1585e8d8bef9SDimitry Andric   // disjoint. We do this so that the rest of BasicAA does not have to deal
1586e8d8bef9SDimitry Andric   // with accesses before the base pointer, and to improve cache utilization by
1587e8d8bef9SDimitry Andric   // merging equivalent states.
1588e8d8bef9SDimitry Andric   if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) {
1589e8d8bef9SDimitry Andric     V1Size = LocationSize::afterPointer();
1590e8d8bef9SDimitry Andric     V2Size = LocationSize::afterPointer();
1591e8d8bef9SDimitry Andric   }
1592e8d8bef9SDimitry Andric 
15930b57cec5SDimitry Andric   // Check the cache before climbing up use-def chains. This also terminates
15940b57cec5SDimitry Andric   // otherwise infinitely recursive queries.
15950b57cec5SDimitry Andric   AAQueryInfo::LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
15960b57cec5SDimitry Andric                             MemoryLocation(V2, V2Size, V2AAInfo));
15970b57cec5SDimitry Andric   if (V1 > V2)
15980b57cec5SDimitry Andric     std::swap(Locs.first, Locs.second);
1599e8d8bef9SDimitry Andric   const auto &Pair = AAQI.AliasCache.try_emplace(
1600e8d8bef9SDimitry Andric       Locs, AAQueryInfo::CacheEntry{NoAlias, 0});
1601e8d8bef9SDimitry Andric   if (!Pair.second) {
1602e8d8bef9SDimitry Andric     auto &Entry = Pair.first->second;
1603e8d8bef9SDimitry Andric     if (!Entry.isDefinitive()) {
1604e8d8bef9SDimitry Andric       // Remember that we used an assumption.
1605e8d8bef9SDimitry Andric       ++Entry.NumAssumptionUses;
1606e8d8bef9SDimitry Andric       ++AAQI.NumAssumptionUses;
16070b57cec5SDimitry Andric     }
1608e8d8bef9SDimitry Andric     return Entry.Result;
1609e8d8bef9SDimitry Andric   }
1610e8d8bef9SDimitry Andric 
1611e8d8bef9SDimitry Andric   int OrigNumAssumptionUses = AAQI.NumAssumptionUses;
1612e8d8bef9SDimitry Andric   unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size();
1613e8d8bef9SDimitry Andric   AliasResult Result = aliasCheckRecursive(V1, V1Size, V1AAInfo, V2, V2Size,
1614e8d8bef9SDimitry Andric                                            V2AAInfo, AAQI, O1, O2);
1615e8d8bef9SDimitry Andric 
1616e8d8bef9SDimitry Andric   auto It = AAQI.AliasCache.find(Locs);
1617e8d8bef9SDimitry Andric   assert(It != AAQI.AliasCache.end() && "Must be in cache");
1618e8d8bef9SDimitry Andric   auto &Entry = It->second;
1619e8d8bef9SDimitry Andric 
1620e8d8bef9SDimitry Andric   // Check whether a NoAlias assumption has been used, but disproven.
1621e8d8bef9SDimitry Andric   bool AssumptionDisproven = Entry.NumAssumptionUses > 0 && Result != NoAlias;
1622e8d8bef9SDimitry Andric   if (AssumptionDisproven)
1623e8d8bef9SDimitry Andric     Result = MayAlias;
1624e8d8bef9SDimitry Andric 
1625e8d8bef9SDimitry Andric   // This is a definitive result now, when considered as a root query.
1626e8d8bef9SDimitry Andric   AAQI.NumAssumptionUses -= Entry.NumAssumptionUses;
1627e8d8bef9SDimitry Andric   Entry.Result = Result;
1628e8d8bef9SDimitry Andric   Entry.NumAssumptionUses = -1;
1629e8d8bef9SDimitry Andric 
1630e8d8bef9SDimitry Andric   // If the assumption has been disproven, remove any results that may have
1631e8d8bef9SDimitry Andric   // been based on this assumption. Do this after the Entry updates above to
1632e8d8bef9SDimitry Andric   // avoid iterator invalidation.
1633e8d8bef9SDimitry Andric   if (AssumptionDisproven)
1634e8d8bef9SDimitry Andric     while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults)
1635e8d8bef9SDimitry Andric       AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val());
1636e8d8bef9SDimitry Andric 
1637e8d8bef9SDimitry Andric   // The result may still be based on assumptions higher up in the chain.
1638e8d8bef9SDimitry Andric   // Remember it, so it can be purged from the cache later.
1639e8d8bef9SDimitry Andric   if (OrigNumAssumptionUses != AAQI.NumAssumptionUses && Result != MayAlias)
1640e8d8bef9SDimitry Andric     AAQI.AssumptionBasedResults.push_back(Locs);
1641e8d8bef9SDimitry Andric   return Result;
1642e8d8bef9SDimitry Andric }
1643e8d8bef9SDimitry Andric 
1644e8d8bef9SDimitry Andric AliasResult BasicAAResult::aliasCheckRecursive(
1645e8d8bef9SDimitry Andric     const Value *V1, LocationSize V1Size, const AAMDNodes &V1AAInfo,
1646e8d8bef9SDimitry Andric     const Value *V2, LocationSize V2Size, const AAMDNodes &V2AAInfo,
1647e8d8bef9SDimitry Andric     AAQueryInfo &AAQI, const Value *O1, const Value *O2) {
16480b57cec5SDimitry Andric   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
16490b57cec5SDimitry Andric     AliasResult Result =
16500b57cec5SDimitry Andric         aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2, AAQI);
1651e8d8bef9SDimitry Andric     if (Result != MayAlias)
1652e8d8bef9SDimitry Andric       return Result;
1653e8d8bef9SDimitry Andric   } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) {
1654e8d8bef9SDimitry Andric     AliasResult Result =
1655e8d8bef9SDimitry Andric         aliasGEP(GV2, V2Size, V2AAInfo, V1, V1Size, V1AAInfo, O2, O1, AAQI);
1656e8d8bef9SDimitry Andric     if (Result != MayAlias)
16570b57cec5SDimitry Andric       return Result;
16580b57cec5SDimitry Andric   }
16590b57cec5SDimitry Andric 
16600b57cec5SDimitry Andric   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
16610b57cec5SDimitry Andric     AliasResult Result =
1662e8d8bef9SDimitry Andric         aliasPHI(PN, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, AAQI);
1663e8d8bef9SDimitry Andric     if (Result != MayAlias)
1664e8d8bef9SDimitry Andric       return Result;
1665e8d8bef9SDimitry Andric   } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) {
1666e8d8bef9SDimitry Andric     AliasResult Result =
1667e8d8bef9SDimitry Andric         aliasPHI(PN, V2Size, V2AAInfo, V1, V1Size, V1AAInfo, AAQI);
1668e8d8bef9SDimitry Andric     if (Result != MayAlias)
1669e8d8bef9SDimitry Andric       return Result;
16700b57cec5SDimitry Andric   }
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
16730b57cec5SDimitry Andric     AliasResult Result =
1674e8d8bef9SDimitry Andric         aliasSelect(S1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, AAQI);
1675e8d8bef9SDimitry Andric     if (Result != MayAlias)
1676e8d8bef9SDimitry Andric       return Result;
1677e8d8bef9SDimitry Andric   } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) {
1678e8d8bef9SDimitry Andric     AliasResult Result =
1679e8d8bef9SDimitry Andric         aliasSelect(S2, V2Size, V2AAInfo, V1, V1Size, V1AAInfo, AAQI);
1680e8d8bef9SDimitry Andric     if (Result != MayAlias)
1681e8d8bef9SDimitry Andric       return Result;
16820b57cec5SDimitry Andric   }
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric   // If both pointers are pointing into the same object and one of them
16850b57cec5SDimitry Andric   // accesses the entire object, then the accesses must overlap in some way.
1686e8d8bef9SDimitry Andric   if (O1 == O2) {
1687e8d8bef9SDimitry Andric     bool NullIsValidLocation = NullPointerIsDefined(&F);
16880b57cec5SDimitry Andric     if (V1Size.isPrecise() && V2Size.isPrecise() &&
16890b57cec5SDimitry Andric         (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
1690e8d8bef9SDimitry Andric          isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation)))
1691e8d8bef9SDimitry Andric       return PartialAlias;
16920b57cec5SDimitry Andric   }
16930b57cec5SDimitry Andric 
1694e8d8bef9SDimitry Andric   return MayAlias;
16950b57cec5SDimitry Andric }
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric /// Check whether two Values can be considered equivalent.
16980b57cec5SDimitry Andric ///
16990b57cec5SDimitry Andric /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
17000b57cec5SDimitry Andric /// they can not be part of a cycle in the value graph by looking at all
17010b57cec5SDimitry Andric /// visited phi nodes an making sure that the phis cannot reach the value. We
17020b57cec5SDimitry Andric /// have to do this because we are looking through phi nodes (That is we say
17030b57cec5SDimitry Andric /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
17040b57cec5SDimitry Andric bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
17050b57cec5SDimitry Andric                                                   const Value *V2) {
17060b57cec5SDimitry Andric   if (V != V2)
17070b57cec5SDimitry Andric     return false;
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   const Instruction *Inst = dyn_cast<Instruction>(V);
17100b57cec5SDimitry Andric   if (!Inst)
17110b57cec5SDimitry Andric     return true;
17120b57cec5SDimitry Andric 
17130b57cec5SDimitry Andric   if (VisitedPhiBBs.empty())
17140b57cec5SDimitry Andric     return true;
17150b57cec5SDimitry Andric 
17160b57cec5SDimitry Andric   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
17170b57cec5SDimitry Andric     return false;
17180b57cec5SDimitry Andric 
17190b57cec5SDimitry Andric   // Make sure that the visited phis cannot reach the Value. This ensures that
17200b57cec5SDimitry Andric   // the Values cannot come from different iterations of a potential cycle the
17210b57cec5SDimitry Andric   // phi nodes could be involved in.
17220b57cec5SDimitry Andric   for (auto *P : VisitedPhiBBs)
17230b57cec5SDimitry Andric     if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT, LI))
17240b57cec5SDimitry Andric       return false;
17250b57cec5SDimitry Andric 
17260b57cec5SDimitry Andric   return true;
17270b57cec5SDimitry Andric }
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric /// Computes the symbolic difference between two de-composed GEPs.
17300b57cec5SDimitry Andric ///
17310b57cec5SDimitry Andric /// Dest and Src are the variable indices from two decomposed GetElementPtr
17320b57cec5SDimitry Andric /// instructions GEP1 and GEP2 which have common base pointers.
17330b57cec5SDimitry Andric void BasicAAResult::GetIndexDifference(
17340b57cec5SDimitry Andric     SmallVectorImpl<VariableGEPIndex> &Dest,
17350b57cec5SDimitry Andric     const SmallVectorImpl<VariableGEPIndex> &Src) {
17360b57cec5SDimitry Andric   if (Src.empty())
17370b57cec5SDimitry Andric     return;
17380b57cec5SDimitry Andric 
17390b57cec5SDimitry Andric   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
17400b57cec5SDimitry Andric     const Value *V = Src[i].V;
17410b57cec5SDimitry Andric     unsigned ZExtBits = Src[i].ZExtBits, SExtBits = Src[i].SExtBits;
17420b57cec5SDimitry Andric     APInt Scale = Src[i].Scale;
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric     // Find V in Dest.  This is N^2, but pointer indices almost never have more
17450b57cec5SDimitry Andric     // than a few variable indexes.
17460b57cec5SDimitry Andric     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
17470b57cec5SDimitry Andric       if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
17480b57cec5SDimitry Andric           Dest[j].ZExtBits != ZExtBits || Dest[j].SExtBits != SExtBits)
17490b57cec5SDimitry Andric         continue;
17500b57cec5SDimitry Andric 
17510b57cec5SDimitry Andric       // If we found it, subtract off Scale V's from the entry in Dest.  If it
17520b57cec5SDimitry Andric       // goes to zero, remove the entry.
17530b57cec5SDimitry Andric       if (Dest[j].Scale != Scale)
17540b57cec5SDimitry Andric         Dest[j].Scale -= Scale;
17550b57cec5SDimitry Andric       else
17560b57cec5SDimitry Andric         Dest.erase(Dest.begin() + j);
17570b57cec5SDimitry Andric       Scale = 0;
17580b57cec5SDimitry Andric       break;
17590b57cec5SDimitry Andric     }
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric     // If we didn't consume this entry, add it to the end of the Dest list.
17620b57cec5SDimitry Andric     if (!!Scale) {
1763e8d8bef9SDimitry Andric       VariableGEPIndex Entry = {V, ZExtBits, SExtBits, -Scale, Src[i].CxtI};
17640b57cec5SDimitry Andric       Dest.push_back(Entry);
17650b57cec5SDimitry Andric     }
17660b57cec5SDimitry Andric   }
17670b57cec5SDimitry Andric }
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric bool BasicAAResult::constantOffsetHeuristic(
17700b57cec5SDimitry Andric     const SmallVectorImpl<VariableGEPIndex> &VarIndices,
17715ffd83dbSDimitry Andric     LocationSize MaybeV1Size, LocationSize MaybeV2Size, const APInt &BaseOffset,
17720b57cec5SDimitry Andric     AssumptionCache *AC, DominatorTree *DT) {
1773e8d8bef9SDimitry Andric   if (VarIndices.size() != 2 || !MaybeV1Size.hasValue() ||
1774e8d8bef9SDimitry Andric       !MaybeV2Size.hasValue())
17750b57cec5SDimitry Andric     return false;
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric   const uint64_t V1Size = MaybeV1Size.getValue();
17780b57cec5SDimitry Andric   const uint64_t V2Size = MaybeV2Size.getValue();
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric   const VariableGEPIndex &Var0 = VarIndices[0], &Var1 = VarIndices[1];
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric   if (Var0.ZExtBits != Var1.ZExtBits || Var0.SExtBits != Var1.SExtBits ||
17830b57cec5SDimitry Andric       Var0.Scale != -Var1.Scale)
17840b57cec5SDimitry Andric     return false;
17850b57cec5SDimitry Andric 
17860b57cec5SDimitry Andric   unsigned Width = Var1.V->getType()->getIntegerBitWidth();
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric   // We'll strip off the Extensions of Var0 and Var1 and do another round
17890b57cec5SDimitry Andric   // of GetLinearExpression decomposition. In the example above, if Var0
17900b57cec5SDimitry Andric   // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   APInt V0Scale(Width, 0), V0Offset(Width, 0), V1Scale(Width, 0),
17930b57cec5SDimitry Andric       V1Offset(Width, 0);
17940b57cec5SDimitry Andric   bool NSW = true, NUW = true;
17950b57cec5SDimitry Andric   unsigned V0ZExtBits = 0, V0SExtBits = 0, V1ZExtBits = 0, V1SExtBits = 0;
17960b57cec5SDimitry Andric   const Value *V0 = GetLinearExpression(Var0.V, V0Scale, V0Offset, V0ZExtBits,
17970b57cec5SDimitry Andric                                         V0SExtBits, DL, 0, AC, DT, NSW, NUW);
17980b57cec5SDimitry Andric   NSW = true;
17990b57cec5SDimitry Andric   NUW = true;
18000b57cec5SDimitry Andric   const Value *V1 = GetLinearExpression(Var1.V, V1Scale, V1Offset, V1ZExtBits,
18010b57cec5SDimitry Andric                                         V1SExtBits, DL, 0, AC, DT, NSW, NUW);
18020b57cec5SDimitry Andric 
18030b57cec5SDimitry Andric   if (V0Scale != V1Scale || V0ZExtBits != V1ZExtBits ||
18040b57cec5SDimitry Andric       V0SExtBits != V1SExtBits || !isValueEqualInPotentialCycles(V0, V1))
18050b57cec5SDimitry Andric     return false;
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric   // We have a hit - Var0 and Var1 only differ by a constant offset!
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   // If we've been sext'ed then zext'd the maximum difference between Var0 and
18100b57cec5SDimitry Andric   // Var1 is possible to calculate, but we're just interested in the absolute
18110b57cec5SDimitry Andric   // minimum difference between the two. The minimum distance may occur due to
18120b57cec5SDimitry Andric   // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
18130b57cec5SDimitry Andric   // the minimum distance between %i and %i + 5 is 3.
18140b57cec5SDimitry Andric   APInt MinDiff = V0Offset - V1Offset, Wrapped = -MinDiff;
18150b57cec5SDimitry Andric   MinDiff = APIntOps::umin(MinDiff, Wrapped);
18160b57cec5SDimitry Andric   APInt MinDiffBytes =
18170b57cec5SDimitry Andric     MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   // We can't definitely say whether GEP1 is before or after V2 due to wrapping
18200b57cec5SDimitry Andric   // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
18210b57cec5SDimitry Andric   // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
18220b57cec5SDimitry Andric   // V2Size can fit in the MinDiffBytes gap.
18230b57cec5SDimitry Andric   return MinDiffBytes.uge(V1Size + BaseOffset.abs()) &&
18240b57cec5SDimitry Andric          MinDiffBytes.uge(V2Size + BaseOffset.abs());
18250b57cec5SDimitry Andric }
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
18280b57cec5SDimitry Andric // BasicAliasAnalysis Pass
18290b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric AnalysisKey BasicAA::Key;
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
1834e8d8bef9SDimitry Andric   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1835e8d8bef9SDimitry Andric   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1836e8d8bef9SDimitry Andric   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1837e8d8bef9SDimitry Andric   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
1838e8d8bef9SDimitry Andric   auto *PV = AM.getCachedResult<PhiValuesAnalysis>(F);
1839e8d8bef9SDimitry Andric   return BasicAAResult(F.getParent()->getDataLayout(), F, TLI, AC, DT, LI, PV);
18400b57cec5SDimitry Andric }
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
18430b57cec5SDimitry Andric   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
18440b57cec5SDimitry Andric }
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric char BasicAAWrapperPass::ID = 0;
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric void BasicAAWrapperPass::anchor() {}
18490b57cec5SDimitry Andric 
18505ffd83dbSDimitry Andric INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa",
1851*b32fb2a4SDimitry Andric                       "Basic Alias Analysis (stateless AA impl)", true, true)
18520b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
18530b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
18540b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1855*b32fb2a4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass)
18565ffd83dbSDimitry Andric INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa",
1857*b32fb2a4SDimitry Andric                     "Basic Alias Analysis (stateless AA impl)", true, true)
18580b57cec5SDimitry Andric 
18590b57cec5SDimitry Andric FunctionPass *llvm::createBasicAAWrapperPass() {
18600b57cec5SDimitry Andric   return new BasicAAWrapperPass();
18610b57cec5SDimitry Andric }
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric bool BasicAAWrapperPass::runOnFunction(Function &F) {
18640b57cec5SDimitry Andric   auto &ACT = getAnalysis<AssumptionCacheTracker>();
18650b57cec5SDimitry Andric   auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
18660b57cec5SDimitry Andric   auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
18670b57cec5SDimitry Andric   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
18680b57cec5SDimitry Andric   auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>();
18690b57cec5SDimitry Andric 
18708bcb0991SDimitry Andric   Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F,
18718bcb0991SDimitry Andric                                  TLIWP.getTLI(F), ACT.getAssumptionCache(F),
18728bcb0991SDimitry Andric                                  &DTWP.getDomTree(),
18730b57cec5SDimitry Andric                                  LIWP ? &LIWP->getLoopInfo() : nullptr,
18740b57cec5SDimitry Andric                                  PVWP ? &PVWP->getResult() : nullptr));
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric   return false;
18770b57cec5SDimitry Andric }
18780b57cec5SDimitry Andric 
18790b57cec5SDimitry Andric void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
18800b57cec5SDimitry Andric   AU.setPreservesAll();
1881e8d8bef9SDimitry Andric   AU.addRequiredTransitive<AssumptionCacheTracker>();
1882e8d8bef9SDimitry Andric   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1883e8d8bef9SDimitry Andric   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
18840b57cec5SDimitry Andric   AU.addUsedIfAvailable<PhiValuesWrapperPass>();
18850b57cec5SDimitry Andric }
18860b57cec5SDimitry Andric 
18870b57cec5SDimitry Andric BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) {
18880b57cec5SDimitry Andric   return BasicAAResult(
18898bcb0991SDimitry Andric       F.getParent()->getDataLayout(), F,
18908bcb0991SDimitry Andric       P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
18910b57cec5SDimitry Andric       P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
18920b57cec5SDimitry Andric }
1893