xref: /src/contrib/llvm-project/llvm/lib/Analysis/BasicAliasAnalysis.cpp (revision 36b606ae6aa4b24061096ba18582e0a08ccd5dba)
1cf099d11SDimitry Andric //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9cf099d11SDimitry Andric // This file defines the primary stateless implementation of the
10cf099d11SDimitry Andric // Alias Analysis interface that implements identities (two different
11cf099d11SDimitry Andric // globals cannot alias, etc), but does no stateful analysis.
12009b1c42SEd Schouten //
13009b1c42SEd Schouten //===----------------------------------------------------------------------===//
14009b1c42SEd Schouten 
15dd58ef01SDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
16044eb2f6SDimitry Andric #include "llvm/ADT/APInt.h"
17b60736ecSDimitry Andric #include "llvm/ADT/ScopeExit.h"
18044eb2f6SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
19009b1c42SEd Schouten #include "llvm/ADT/SmallVector.h"
20dd58ef01SDimitry Andric #include "llvm/ADT/Statistic.h"
214a16efa3SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
226b3f41edSDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
2368bcb7dbSDimitry Andric #include "llvm/Analysis/CFG.h"
245ca98fd9SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
254a16efa3SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h"
26044eb2f6SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
27044eb2f6SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
284a16efa3SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
29044eb2f6SDimitry Andric #include "llvm/IR/Argument.h"
30044eb2f6SDimitry Andric #include "llvm/IR/Attributes.h"
31044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
32c0981da4SDimitry Andric #include "llvm/IR/ConstantRange.h"
334a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
344a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
354a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
365ca98fd9SDimitry Andric #include "llvm/IR/Dominators.h"
37044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
38044eb2f6SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
394a16efa3SDimitry Andric #include "llvm/IR/GlobalAlias.h"
404a16efa3SDimitry Andric #include "llvm/IR/GlobalVariable.h"
41044eb2f6SDimitry Andric #include "llvm/IR/InstrTypes.h"
42044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
434a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
444a16efa3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
45044eb2f6SDimitry Andric #include "llvm/IR/Intrinsics.h"
464a16efa3SDimitry Andric #include "llvm/IR/Operator.h"
47ac9a064cSDimitry Andric #include "llvm/IR/PatternMatch.h"
48044eb2f6SDimitry Andric #include "llvm/IR/Type.h"
49044eb2f6SDimitry Andric #include "llvm/IR/User.h"
50044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
51706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
524a16efa3SDimitry Andric #include "llvm/Pass.h"
53044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
54044eb2f6SDimitry Andric #include "llvm/Support/CommandLine.h"
55044eb2f6SDimitry Andric #include "llvm/Support/Compiler.h"
566b3f41edSDimitry Andric #include "llvm/Support/KnownBits.h"
57e3b55780SDimitry Andric #include "llvm/Support/SaveAndRestore.h"
58044eb2f6SDimitry Andric #include <cassert>
59044eb2f6SDimitry Andric #include <cstdint>
60044eb2f6SDimitry Andric #include <cstdlib>
61e3b55780SDimitry Andric #include <optional>
62044eb2f6SDimitry Andric #include <utility>
6301095a5dSDimitry Andric 
6401095a5dSDimitry Andric #define DEBUG_TYPE "basicaa"
6501095a5dSDimitry Andric 
66009b1c42SEd Schouten using namespace llvm;
67009b1c42SEd Schouten 
68dd58ef01SDimitry Andric /// Enable analysis of recursive PHI nodes.
69cfca06d7SDimitry Andric static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden,
70b60736ecSDimitry Andric                                           cl::init(true));
71d8e91e46SDimitry Andric 
72e3b55780SDimitry Andric static cl::opt<bool> EnableSeparateStorageAnalysis("basic-aa-separate-storage",
73aca2e42cSDimitry Andric                                                    cl::Hidden, cl::init(true));
74e3b55780SDimitry Andric 
75dd58ef01SDimitry Andric /// SearchLimitReached / SearchTimes shows how often the limit of
76dd58ef01SDimitry Andric /// to decompose GEPs is reached. It will affect the precision
77dd58ef01SDimitry Andric /// of basic alias analysis.
78dd58ef01SDimitry Andric STATISTIC(SearchLimitReached, "Number of times the limit to "
79dd58ef01SDimitry Andric                               "decompose GEPs is reached");
80dd58ef01SDimitry Andric STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
81dd58ef01SDimitry Andric 
825ca98fd9SDimitry Andric // The max limit of the search depth in DecomposeGEPExpression() and
83c0981da4SDimitry Andric // getUnderlyingObject().
845ca98fd9SDimitry Andric static const unsigned MaxLookupSearchDepth = 6;
855ca98fd9SDimitry Andric 
invalidate(Function & Fn,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator & Inv)86eb11fae6SDimitry Andric bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
87b915e9e0SDimitry Andric                                FunctionAnalysisManager::Invalidator &Inv) {
88b915e9e0SDimitry Andric   // We don't care if this analysis itself is preserved, it has no state. But
89b915e9e0SDimitry Andric   // we need to check that the analyses it depends on have been. Note that we
90b915e9e0SDimitry Andric   // may be created without handles to some analyses and in that case don't
91b915e9e0SDimitry Andric   // depend on them.
92eb11fae6SDimitry Andric   if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
93ac9a064cSDimitry Andric       (DT_ && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)))
94b915e9e0SDimitry Andric     return true;
95b915e9e0SDimitry Andric 
96b915e9e0SDimitry Andric   // Otherwise this analysis result remains valid.
97b915e9e0SDimitry Andric   return false;
98b915e9e0SDimitry Andric }
99b915e9e0SDimitry Andric 
100009b1c42SEd Schouten //===----------------------------------------------------------------------===//
101009b1c42SEd Schouten // Useful predicates
102009b1c42SEd Schouten //===----------------------------------------------------------------------===//
103009b1c42SEd Schouten 
10401095a5dSDimitry Andric /// Returns the size of the object specified by V or UnknownSize if unknown.
getObjectSize(const Value * V,const DataLayout & DL,const TargetLibraryInfo & TLI,bool NullIsValidLoc,bool RoundToAlign=false)105b1c73532SDimitry Andric static std::optional<TypeSize> getObjectSize(const Value *V,
106b1c73532SDimitry Andric                                              const DataLayout &DL,
107522600a2SDimitry Andric                                              const TargetLibraryInfo &TLI,
108eb11fae6SDimitry Andric                                              bool NullIsValidLoc,
10963faed5bSDimitry Andric                                              bool RoundToAlign = false) {
11058b69754SDimitry Andric   uint64_t Size;
11171d5a254SDimitry Andric   ObjectSizeOpts Opts;
11271d5a254SDimitry Andric   Opts.RoundToAlign = RoundToAlign;
113eb11fae6SDimitry Andric   Opts.NullIsUnknownSize = NullIsValidLoc;
11471d5a254SDimitry Andric   if (getObjectSize(V, Size, DL, &TLI, Opts))
115b1c73532SDimitry Andric     return TypeSize::getFixed(Size);
116b1c73532SDimitry Andric   return std::nullopt;
117009b1c42SEd Schouten }
118009b1c42SEd Schouten 
119dd58ef01SDimitry Andric /// Returns true if we can prove that the object specified by V is smaller than
120dd58ef01SDimitry Andric /// Size.
isObjectSmallerThan(const Value * V,TypeSize Size,const DataLayout & DL,const TargetLibraryInfo & TLI,bool NullIsValidLoc)121b1c73532SDimitry Andric static bool isObjectSmallerThan(const Value *V, TypeSize Size,
1225ca98fd9SDimitry Andric                                 const DataLayout &DL,
123eb11fae6SDimitry Andric                                 const TargetLibraryInfo &TLI,
124eb11fae6SDimitry Andric                                 bool NullIsValidLoc) {
12559d6cff9SDimitry Andric   // Note that the meanings of the "object" are slightly different in the
12659d6cff9SDimitry Andric   // following contexts:
12759d6cff9SDimitry Andric   //    c1: llvm::getObjectSize()
12859d6cff9SDimitry Andric   //    c2: llvm.objectsize() intrinsic
12959d6cff9SDimitry Andric   //    c3: isObjectSmallerThan()
13059d6cff9SDimitry Andric   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
13159d6cff9SDimitry Andric   // refers to the "entire object".
13259d6cff9SDimitry Andric   //
13359d6cff9SDimitry Andric   //  Consider this example:
13459d6cff9SDimitry Andric   //     char *p = (char*)malloc(100)
13559d6cff9SDimitry Andric   //     char *q = p+80;
13659d6cff9SDimitry Andric   //
13759d6cff9SDimitry Andric   //  In the context of c1 and c2, the "object" pointed by q refers to the
13859d6cff9SDimitry Andric   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
13959d6cff9SDimitry Andric   //
14059d6cff9SDimitry Andric   //  However, in the context of c3, the "object" refers to the chunk of memory
14159d6cff9SDimitry Andric   // being allocated. So, the "object" has 100 bytes, and q points to the middle
14259d6cff9SDimitry Andric   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
14359d6cff9SDimitry Andric   // parameter, before the llvm::getObjectSize() is called to get the size of
14459d6cff9SDimitry Andric   // entire object, we should:
14559d6cff9SDimitry Andric   //    - either rewind the pointer q to the base-address of the object in
14659d6cff9SDimitry Andric   //      question (in this case rewind to p), or
14759d6cff9SDimitry Andric   //    - just give up. It is up to caller to make sure the pointer is pointing
14859d6cff9SDimitry Andric   //      to the base address the object.
14959d6cff9SDimitry Andric   //
15059d6cff9SDimitry Andric   // We go for 2nd option for simplicity.
15159d6cff9SDimitry Andric   if (!isIdentifiedObject(V))
15259d6cff9SDimitry Andric     return false;
15359d6cff9SDimitry Andric 
15463faed5bSDimitry Andric   // This function needs to use the aligned object size because we allow
15563faed5bSDimitry Andric   // reads a bit past the end given sufficient alignment.
156b1c73532SDimitry Andric   std::optional<TypeSize> ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
157eb11fae6SDimitry Andric                                                      /*RoundToAlign*/ true);
15863faed5bSDimitry Andric 
159b1c73532SDimitry Andric   return ObjectSize && TypeSize::isKnownLT(*ObjectSize, Size);
160009b1c42SEd Schouten }
161009b1c42SEd Schouten 
1621d5ae102SDimitry Andric /// Return the minimal extent from \p V to the end of the underlying object,
1631d5ae102SDimitry Andric /// assuming the result is used in an aliasing query. E.g., we do use the query
1641d5ae102SDimitry Andric /// location size and the fact that null pointers cannot alias here.
getMinimalExtentFrom(const Value & V,const LocationSize & LocSize,const DataLayout & DL,bool NullIsValidLoc)165b1c73532SDimitry Andric static TypeSize getMinimalExtentFrom(const Value &V,
1661d5ae102SDimitry Andric                                      const LocationSize &LocSize,
1671d5ae102SDimitry Andric                                      const DataLayout &DL,
1681d5ae102SDimitry Andric                                      bool NullIsValidLoc) {
1691d5ae102SDimitry Andric   // If we have dereferenceability information we know a lower bound for the
1701d5ae102SDimitry Andric   // extent as accesses for a lower offset would be valid. We need to exclude
171c0981da4SDimitry Andric   // the "or null" part if null is a valid pointer. We can ignore frees, as an
172c0981da4SDimitry Andric   // access after free would be undefined behavior.
173344a3780SDimitry Andric   bool CanBeNull, CanBeFreed;
174344a3780SDimitry Andric   uint64_t DerefBytes =
175344a3780SDimitry Andric     V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
1761d5ae102SDimitry Andric   DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;
1771d5ae102SDimitry Andric   // If queried with a precise location size, we assume that location size to be
1781d5ae102SDimitry Andric   // accessed, thus valid.
1791d5ae102SDimitry Andric   if (LocSize.isPrecise())
180b1c73532SDimitry Andric     DerefBytes = std::max(DerefBytes, LocSize.getValue().getKnownMinValue());
181b1c73532SDimitry Andric   return TypeSize::getFixed(DerefBytes);
1821d5ae102SDimitry Andric }
1831d5ae102SDimitry Andric 
184dd58ef01SDimitry Andric /// Returns true if we can prove that the object specified by V has size Size.
isObjectSize(const Value * V,TypeSize Size,const DataLayout & DL,const TargetLibraryInfo & TLI,bool NullIsValidLoc)185b1c73532SDimitry Andric static bool isObjectSize(const Value *V, TypeSize Size, const DataLayout &DL,
186eb11fae6SDimitry Andric                          const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
187b1c73532SDimitry Andric   std::optional<TypeSize> ObjectSize =
188b1c73532SDimitry Andric       getObjectSize(V, DL, TLI, NullIsValidLoc);
189b1c73532SDimitry Andric   return ObjectSize && *ObjectSize == Size;
190009b1c42SEd Schouten }
191009b1c42SEd Schouten 
192ac9a064cSDimitry Andric /// Return true if both V1 and V2 are VScale
areBothVScale(const Value * V1,const Value * V2)193ac9a064cSDimitry Andric static bool areBothVScale(const Value *V1, const Value *V2) {
194ac9a064cSDimitry Andric   return PatternMatch::match(V1, PatternMatch::m_VScale()) &&
195ac9a064cSDimitry Andric          PatternMatch::match(V2, PatternMatch::m_VScale());
196ac9a064cSDimitry Andric }
197ac9a064cSDimitry Andric 
198009b1c42SEd Schouten //===----------------------------------------------------------------------===//
199c0981da4SDimitry Andric // CaptureInfo implementations
200c0981da4SDimitry Andric //===----------------------------------------------------------------------===//
201c0981da4SDimitry Andric 
202c0981da4SDimitry Andric CaptureInfo::~CaptureInfo() = default;
203c0981da4SDimitry Andric 
isNotCapturedBefore(const Value * Object,const Instruction * I,bool OrAt)204b1c73532SDimitry Andric bool SimpleCaptureInfo::isNotCapturedBefore(const Value *Object,
205b1c73532SDimitry Andric                                             const Instruction *I, bool OrAt) {
206c0981da4SDimitry Andric   return isNonEscapingLocalObject(Object, &IsCapturedCache);
207c0981da4SDimitry Andric }
208c0981da4SDimitry Andric 
isNotInCycle(const Instruction * I,const DominatorTree * DT,const LoopInfo * LI)209b1c73532SDimitry Andric static bool isNotInCycle(const Instruction *I, const DominatorTree *DT,
210b1c73532SDimitry Andric                          const LoopInfo *LI) {
211b1c73532SDimitry Andric   BasicBlock *BB = const_cast<BasicBlock *>(I->getParent());
212b1c73532SDimitry Andric   SmallVector<BasicBlock *> Succs(successors(BB));
213b1c73532SDimitry Andric   return Succs.empty() ||
214b1c73532SDimitry Andric          !isPotentiallyReachableFromMany(Succs, BB, nullptr, DT, LI);
215b1c73532SDimitry Andric }
216b1c73532SDimitry Andric 
isNotCapturedBefore(const Value * Object,const Instruction * I,bool OrAt)217b1c73532SDimitry Andric bool EarliestEscapeInfo::isNotCapturedBefore(const Value *Object,
218b1c73532SDimitry Andric                                              const Instruction *I, bool OrAt) {
219c0981da4SDimitry Andric   if (!isIdentifiedFunctionLocal(Object))
220c0981da4SDimitry Andric     return false;
221c0981da4SDimitry Andric 
222c0981da4SDimitry Andric   auto Iter = EarliestEscapes.insert({Object, nullptr});
223c0981da4SDimitry Andric   if (Iter.second) {
224c0981da4SDimitry Andric     Instruction *EarliestCapture = FindEarliestCapture(
2254df029ccSDimitry Andric         Object, *const_cast<Function *>(DT.getRoot()->getParent()),
226b1c73532SDimitry Andric         /*ReturnCaptures=*/false, /*StoreCaptures=*/true, DT);
227c0981da4SDimitry Andric     if (EarliestCapture) {
228c0981da4SDimitry Andric       auto Ins = Inst2Obj.insert({EarliestCapture, {}});
229c0981da4SDimitry Andric       Ins.first->second.push_back(Object);
230c0981da4SDimitry Andric     }
231c0981da4SDimitry Andric     Iter.first->second = EarliestCapture;
232c0981da4SDimitry Andric   }
233c0981da4SDimitry Andric 
234c0981da4SDimitry Andric   // No capturing instruction.
235c0981da4SDimitry Andric   if (!Iter.first->second)
236c0981da4SDimitry Andric     return true;
237c0981da4SDimitry Andric 
2384df029ccSDimitry Andric   // No context instruction means any use is capturing.
2394df029ccSDimitry Andric   if (!I)
2404df029ccSDimitry Andric     return false;
2414df029ccSDimitry Andric 
242b1c73532SDimitry Andric   if (I == Iter.first->second) {
243b1c73532SDimitry Andric     if (OrAt)
244b1c73532SDimitry Andric       return false;
245b1c73532SDimitry Andric     return isNotInCycle(I, &DT, LI);
246b1c73532SDimitry Andric   }
247b1c73532SDimitry Andric 
248b1c73532SDimitry Andric   return !isPotentiallyReachable(Iter.first->second, I, nullptr, &DT, LI);
249c0981da4SDimitry Andric }
250c0981da4SDimitry Andric 
removeInstruction(Instruction * I)251c0981da4SDimitry Andric void EarliestEscapeInfo::removeInstruction(Instruction *I) {
252c0981da4SDimitry Andric   auto Iter = Inst2Obj.find(I);
253c0981da4SDimitry Andric   if (Iter != Inst2Obj.end()) {
254c0981da4SDimitry Andric     for (const Value *Obj : Iter->second)
255c0981da4SDimitry Andric       EarliestEscapes.erase(Obj);
256c0981da4SDimitry Andric     Inst2Obj.erase(I);
257c0981da4SDimitry Andric   }
258c0981da4SDimitry Andric }
259c0981da4SDimitry Andric 
260c0981da4SDimitry Andric //===----------------------------------------------------------------------===//
261d39c594dSDimitry Andric // GetElementPtr Instruction Decomposition and Analysis
262d39c594dSDimitry Andric //===----------------------------------------------------------------------===//
263d39c594dSDimitry Andric 
264344a3780SDimitry Andric namespace {
265c0981da4SDimitry Andric /// Represents zext(sext(trunc(V))).
266c0981da4SDimitry Andric struct CastedValue {
267344a3780SDimitry Andric   const Value *V;
268c0981da4SDimitry Andric   unsigned ZExtBits = 0;
269c0981da4SDimitry Andric   unsigned SExtBits = 0;
270c0981da4SDimitry Andric   unsigned TruncBits = 0;
271ac9a064cSDimitry Andric   /// Whether trunc(V) is non-negative.
272ac9a064cSDimitry Andric   bool IsNonNegative = false;
273344a3780SDimitry Andric 
CastedValue__anoncf261da80111::CastedValue274c0981da4SDimitry Andric   explicit CastedValue(const Value *V) : V(V) {}
CastedValue__anoncf261da80111::CastedValue275c0981da4SDimitry Andric   explicit CastedValue(const Value *V, unsigned ZExtBits, unsigned SExtBits,
276ac9a064cSDimitry Andric                        unsigned TruncBits, bool IsNonNegative)
277ac9a064cSDimitry Andric       : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits), TruncBits(TruncBits),
278ac9a064cSDimitry Andric         IsNonNegative(IsNonNegative) {}
279344a3780SDimitry Andric 
getBitWidth__anoncf261da80111::CastedValue280344a3780SDimitry Andric   unsigned getBitWidth() const {
281c0981da4SDimitry Andric     return V->getType()->getPrimitiveSizeInBits() - TruncBits + ZExtBits +
282c0981da4SDimitry Andric            SExtBits;
283344a3780SDimitry Andric   }
284344a3780SDimitry Andric 
withValue__anoncf261da80111::CastedValue285ac9a064cSDimitry Andric   CastedValue withValue(const Value *NewV, bool PreserveNonNeg) const {
286ac9a064cSDimitry Andric     return CastedValue(NewV, ZExtBits, SExtBits, TruncBits,
287ac9a064cSDimitry Andric                        IsNonNegative && PreserveNonNeg);
288344a3780SDimitry Andric   }
289344a3780SDimitry Andric 
290c0981da4SDimitry Andric   /// Replace V with zext(NewV)
withZExtOfValue__anoncf261da80111::CastedValue291ac9a064cSDimitry Andric   CastedValue withZExtOfValue(const Value *NewV, bool ZExtNonNegative) const {
292344a3780SDimitry Andric     unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
293344a3780SDimitry Andric                         NewV->getType()->getPrimitiveSizeInBits();
294c0981da4SDimitry Andric     if (ExtendBy <= TruncBits)
295ac9a064cSDimitry Andric       // zext<nneg>(trunc(zext(NewV))) == zext<nneg>(trunc(NewV))
296ac9a064cSDimitry Andric       // The nneg can be preserved on the outer zext here.
297ac9a064cSDimitry Andric       return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy,
298ac9a064cSDimitry Andric                          IsNonNegative);
299c0981da4SDimitry Andric 
300344a3780SDimitry Andric     // zext(sext(zext(NewV))) == zext(zext(zext(NewV)))
301c0981da4SDimitry Andric     ExtendBy -= TruncBits;
302ac9a064cSDimitry Andric     // zext<nneg>(zext(NewV)) == zext(NewV)
303ac9a064cSDimitry Andric     // zext(zext<nneg>(NewV)) == zext<nneg>(NewV)
304ac9a064cSDimitry Andric     // The nneg can be preserved from the inner zext here but must be dropped
305ac9a064cSDimitry Andric     // from the outer.
306ac9a064cSDimitry Andric     return CastedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0, 0,
307ac9a064cSDimitry Andric                        ZExtNonNegative);
308344a3780SDimitry Andric   }
309344a3780SDimitry Andric 
310c0981da4SDimitry Andric   /// Replace V with sext(NewV)
withSExtOfValue__anoncf261da80111::CastedValue311c0981da4SDimitry Andric   CastedValue withSExtOfValue(const Value *NewV) const {
312344a3780SDimitry Andric     unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -
313344a3780SDimitry Andric                         NewV->getType()->getPrimitiveSizeInBits();
314c0981da4SDimitry Andric     if (ExtendBy <= TruncBits)
315ac9a064cSDimitry Andric       // zext<nneg>(trunc(sext(NewV))) == zext<nneg>(trunc(NewV))
316ac9a064cSDimitry Andric       // The nneg can be preserved on the outer zext here
317ac9a064cSDimitry Andric       return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy,
318ac9a064cSDimitry Andric                          IsNonNegative);
319c0981da4SDimitry Andric 
320344a3780SDimitry Andric     // zext(sext(sext(NewV)))
321c0981da4SDimitry Andric     ExtendBy -= TruncBits;
322ac9a064cSDimitry Andric     // zext<nneg>(sext(sext(NewV))) = zext<nneg>(sext(NewV))
323ac9a064cSDimitry Andric     // The nneg can be preserved on the outer zext here
324ac9a064cSDimitry Andric     return CastedValue(NewV, ZExtBits, SExtBits + ExtendBy, 0, IsNonNegative);
325344a3780SDimitry Andric   }
326344a3780SDimitry Andric 
evaluateWith__anoncf261da80111::CastedValue327344a3780SDimitry Andric   APInt evaluateWith(APInt N) const {
328344a3780SDimitry Andric     assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
329344a3780SDimitry Andric            "Incompatible bit width");
330c0981da4SDimitry Andric     if (TruncBits) N = N.trunc(N.getBitWidth() - TruncBits);
331344a3780SDimitry Andric     if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits);
332344a3780SDimitry Andric     if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits);
333344a3780SDimitry Andric     return N;
334344a3780SDimitry Andric   }
335344a3780SDimitry Andric 
evaluateWith__anoncf261da80111::CastedValue336c0981da4SDimitry Andric   ConstantRange evaluateWith(ConstantRange N) const {
337c0981da4SDimitry Andric     assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&
338c0981da4SDimitry Andric            "Incompatible bit width");
339c0981da4SDimitry Andric     if (TruncBits) N = N.truncate(N.getBitWidth() - TruncBits);
340c0981da4SDimitry Andric     if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits);
341c0981da4SDimitry Andric     if (ZExtBits) N = N.zeroExtend(N.getBitWidth() + ZExtBits);
342c0981da4SDimitry Andric     return N;
343c0981da4SDimitry Andric   }
344c0981da4SDimitry Andric 
canDistributeOver__anoncf261da80111::CastedValue345344a3780SDimitry Andric   bool canDistributeOver(bool NUW, bool NSW) const {
346344a3780SDimitry Andric     // zext(x op<nuw> y) == zext(x) op<nuw> zext(y)
347344a3780SDimitry Andric     // sext(x op<nsw> y) == sext(x) op<nsw> sext(y)
348c0981da4SDimitry Andric     // trunc(x op y) == trunc(x) op trunc(y)
349344a3780SDimitry Andric     return (!ZExtBits || NUW) && (!SExtBits || NSW);
350344a3780SDimitry Andric   }
351c0981da4SDimitry Andric 
hasSameCastsAs__anoncf261da80111::CastedValue352c0981da4SDimitry Andric   bool hasSameCastsAs(const CastedValue &Other) const {
353ac9a064cSDimitry Andric     if (ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits &&
354ac9a064cSDimitry Andric         TruncBits == Other.TruncBits)
355ac9a064cSDimitry Andric       return true;
356ac9a064cSDimitry Andric     // If either CastedValue has a nneg zext then the sext/zext bits are
357ac9a064cSDimitry Andric     // interchangable for that value.
358ac9a064cSDimitry Andric     if (IsNonNegative || Other.IsNonNegative)
359ac9a064cSDimitry Andric       return (ZExtBits + SExtBits == Other.ZExtBits + Other.SExtBits &&
360ac9a064cSDimitry Andric               TruncBits == Other.TruncBits);
361ac9a064cSDimitry Andric     return false;
362c0981da4SDimitry Andric   }
363344a3780SDimitry Andric };
364344a3780SDimitry Andric 
365c0981da4SDimitry Andric /// Represents zext(sext(trunc(V))) * Scale + Offset.
366344a3780SDimitry Andric struct LinearExpression {
367c0981da4SDimitry Andric   CastedValue Val;
368344a3780SDimitry Andric   APInt Scale;
369344a3780SDimitry Andric   APInt Offset;
370344a3780SDimitry Andric 
371344a3780SDimitry Andric   /// True if all operations in this expression are NSW.
372344a3780SDimitry Andric   bool IsNSW;
373344a3780SDimitry Andric 
LinearExpression__anoncf261da80111::LinearExpression374c0981da4SDimitry Andric   LinearExpression(const CastedValue &Val, const APInt &Scale,
375344a3780SDimitry Andric                    const APInt &Offset, bool IsNSW)
376344a3780SDimitry Andric       : Val(Val), Scale(Scale), Offset(Offset), IsNSW(IsNSW) {}
377344a3780SDimitry Andric 
LinearExpression__anoncf261da80111::LinearExpression378c0981da4SDimitry Andric   LinearExpression(const CastedValue &Val) : Val(Val), IsNSW(true) {
379344a3780SDimitry Andric     unsigned BitWidth = Val.getBitWidth();
380344a3780SDimitry Andric     Scale = APInt(BitWidth, 1);
381344a3780SDimitry Andric     Offset = APInt(BitWidth, 0);
382344a3780SDimitry Andric   }
383c0981da4SDimitry Andric 
mul__anoncf261da80111::LinearExpression384c0981da4SDimitry Andric   LinearExpression mul(const APInt &Other, bool MulIsNSW) const {
385c0981da4SDimitry Andric     // The check for zero offset is necessary, because generally
386c0981da4SDimitry Andric     // (X +nsw Y) *nsw Z does not imply (X *nsw Z) +nsw (Y *nsw Z).
387c0981da4SDimitry Andric     bool NSW = IsNSW && (Other.isOne() || (MulIsNSW && Offset.isZero()));
388c0981da4SDimitry Andric     return LinearExpression(Val, Scale * Other, Offset * Other, NSW);
389c0981da4SDimitry Andric   }
390344a3780SDimitry Andric };
391344a3780SDimitry Andric }
392344a3780SDimitry Andric 
393dd58ef01SDimitry Andric /// Analyzes the specified value as a linear expression: "A*V + B", where A and
394dd58ef01SDimitry Andric /// B are constant integers.
GetLinearExpression(const CastedValue & Val,const DataLayout & DL,unsigned Depth,AssumptionCache * AC,DominatorTree * DT)395344a3780SDimitry Andric static LinearExpression GetLinearExpression(
396c0981da4SDimitry Andric     const CastedValue &Val,  const DataLayout &DL, unsigned Depth,
397344a3780SDimitry Andric     AssumptionCache *AC, DominatorTree *DT) {
398d39c594dSDimitry Andric   // Limit our recursion depth.
399344a3780SDimitry Andric   if (Depth == 6)
400344a3780SDimitry Andric     return Val;
401d39c594dSDimitry Andric 
402344a3780SDimitry Andric   if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V))
403344a3780SDimitry Andric     return LinearExpression(Val, APInt(Val.getBitWidth(), 0),
404344a3780SDimitry Andric                             Val.evaluateWith(Const->getValue()), true);
405dd58ef01SDimitry Andric 
406344a3780SDimitry Andric   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) {
407d39c594dSDimitry Andric     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
408344a3780SDimitry Andric       APInt RHS = Val.evaluateWith(RHSC->getValue());
409344a3780SDimitry Andric       // The only non-OBO case we deal with is or, and only limited to the
410344a3780SDimitry Andric       // case where it is both nuw and nsw.
411344a3780SDimitry Andric       bool NUW = true, NSW = true;
412344a3780SDimitry Andric       if (isa<OverflowingBinaryOperator>(BOp)) {
413344a3780SDimitry Andric         NUW &= BOp->hasNoUnsignedWrap();
414344a3780SDimitry Andric         NSW &= BOp->hasNoSignedWrap();
415344a3780SDimitry Andric       }
416344a3780SDimitry Andric       if (!Val.canDistributeOver(NUW, NSW))
417344a3780SDimitry Andric         return Val;
418dd58ef01SDimitry Andric 
419c0981da4SDimitry Andric       // While we can distribute over trunc, we cannot preserve nowrap flags
420c0981da4SDimitry Andric       // in that case.
421c0981da4SDimitry Andric       if (Val.TruncBits)
422c0981da4SDimitry Andric         NUW = NSW = false;
423c0981da4SDimitry Andric 
424344a3780SDimitry Andric       LinearExpression E(Val);
425d39c594dSDimitry Andric       switch (BOp->getOpcode()) {
426dd58ef01SDimitry Andric       default:
427dd58ef01SDimitry Andric         // We don't understand this instruction, so we can't decompose it any
428dd58ef01SDimitry Andric         // further.
429344a3780SDimitry Andric         return Val;
430d39c594dSDimitry Andric       case Instruction::Or:
4314df029ccSDimitry Andric         // X|C == X+C if it is disjoint.  Otherwise we can't analyze it.
4324df029ccSDimitry Andric         if (!cast<PossiblyDisjointInst>(BOp)->isDisjoint())
433344a3780SDimitry Andric           return Val;
434eb11fae6SDimitry Andric 
435e3b55780SDimitry Andric         [[fallthrough]];
436344a3780SDimitry Andric       case Instruction::Add: {
437ac9a064cSDimitry Andric         E = GetLinearExpression(Val.withValue(BOp->getOperand(0), false), DL,
438344a3780SDimitry Andric                                 Depth + 1, AC, DT);
439344a3780SDimitry Andric         E.Offset += RHS;
440344a3780SDimitry Andric         E.IsNSW &= NSW;
441344a3780SDimitry Andric         break;
442344a3780SDimitry Andric       }
443344a3780SDimitry Andric       case Instruction::Sub: {
444ac9a064cSDimitry Andric         E = GetLinearExpression(Val.withValue(BOp->getOperand(0), false), DL,
445344a3780SDimitry Andric                                 Depth + 1, AC, DT);
446344a3780SDimitry Andric         E.Offset -= RHS;
447344a3780SDimitry Andric         E.IsNSW &= NSW;
448344a3780SDimitry Andric         break;
449344a3780SDimitry Andric       }
450c0981da4SDimitry Andric       case Instruction::Mul:
451ac9a064cSDimitry Andric         E = GetLinearExpression(Val.withValue(BOp->getOperand(0), false), DL,
452c0981da4SDimitry Andric                                 Depth + 1, AC, DT)
453c0981da4SDimitry Andric                 .mul(RHS, NSW);
454344a3780SDimitry Andric         break;
455344a3780SDimitry Andric       case Instruction::Shl:
456eb11fae6SDimitry Andric         // We're trying to linearize an expression of the kind:
457eb11fae6SDimitry Andric         //   shl i8 -128, 36
458eb11fae6SDimitry Andric         // where the shift count exceeds the bitwidth of the type.
459eb11fae6SDimitry Andric         // We can't decompose this further (the expression would return
460eb11fae6SDimitry Andric         // a poison value).
461344a3780SDimitry Andric         if (RHS.getLimitedValue() > Val.getBitWidth())
462344a3780SDimitry Andric           return Val;
463eb11fae6SDimitry Andric 
464ac9a064cSDimitry Andric         E = GetLinearExpression(Val.withValue(BOp->getOperand(0), NSW), DL,
465344a3780SDimitry Andric                                 Depth + 1, AC, DT);
466344a3780SDimitry Andric         E.Offset <<= RHS.getLimitedValue();
467344a3780SDimitry Andric         E.Scale <<= RHS.getLimitedValue();
468344a3780SDimitry Andric         E.IsNSW &= NSW;
469344a3780SDimitry Andric         break;
470dd58ef01SDimitry Andric       }
471344a3780SDimitry Andric       return E;
472d39c594dSDimitry Andric     }
473d39c594dSDimitry Andric   }
474d39c594dSDimitry Andric 
475ac9a064cSDimitry Andric   if (const auto *ZExt = dyn_cast<ZExtInst>(Val.V))
476344a3780SDimitry Andric     return GetLinearExpression(
477ac9a064cSDimitry Andric         Val.withZExtOfValue(ZExt->getOperand(0), ZExt->hasNonNeg()), DL,
478ac9a064cSDimitry Andric         Depth + 1, AC, DT);
479d39c594dSDimitry Andric 
480344a3780SDimitry Andric   if (isa<SExtInst>(Val.V))
481344a3780SDimitry Andric     return GetLinearExpression(
482344a3780SDimitry Andric         Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)),
483344a3780SDimitry Andric         DL, Depth + 1, AC, DT);
484dd58ef01SDimitry Andric 
485344a3780SDimitry Andric   return Val;
486d39c594dSDimitry Andric }
487d39c594dSDimitry Andric 
488c0981da4SDimitry Andric /// To ensure a pointer offset fits in an integer of size IndexSize
489c0981da4SDimitry Andric /// (in bits) when that size is smaller than the maximum index size. This is
490d8e91e46SDimitry Andric /// an issue, for example, in particular for 32b pointers with negative indices
491d8e91e46SDimitry Andric /// that rely on two's complement wrap-arounds for precise alias information
492c0981da4SDimitry Andric /// where the maximum index size is 64b.
adjustToIndexSize(APInt & Offset,unsigned IndexSize)493b1c73532SDimitry Andric static void adjustToIndexSize(APInt &Offset, unsigned IndexSize) {
494c0981da4SDimitry Andric   assert(IndexSize <= Offset.getBitWidth() && "Invalid IndexSize!");
495c0981da4SDimitry Andric   unsigned ShiftBits = Offset.getBitWidth() - IndexSize;
496b1c73532SDimitry Andric   if (ShiftBits != 0) {
497b1c73532SDimitry Andric     Offset <<= ShiftBits;
498b1c73532SDimitry Andric     Offset.ashrInPlace(ShiftBits);
499b1c73532SDimitry Andric   }
500d8e91e46SDimitry Andric }
501d8e91e46SDimitry Andric 
502c0981da4SDimitry Andric namespace {
503c0981da4SDimitry Andric // A linear transformation of a Value; this class represents
504c0981da4SDimitry Andric // ZExt(SExt(Trunc(V, TruncBits), SExtBits), ZExtBits) * Scale.
505c0981da4SDimitry Andric struct VariableGEPIndex {
506c0981da4SDimitry Andric   CastedValue Val;
507c0981da4SDimitry Andric   APInt Scale;
508d8e91e46SDimitry Andric 
509c0981da4SDimitry Andric   // Context instruction to use when querying information about this index.
510c0981da4SDimitry Andric   const Instruction *CxtI;
511c0981da4SDimitry Andric 
512c0981da4SDimitry Andric   /// True if all operations in this expression are NSW.
513c0981da4SDimitry Andric   bool IsNSW;
514c0981da4SDimitry Andric 
5157fa27ce4SDimitry Andric   /// True if the index should be subtracted rather than added. We don't simply
5167fa27ce4SDimitry Andric   /// negate the Scale, to avoid losing the NSW flag: X - INT_MIN*1 may be
5177fa27ce4SDimitry Andric   /// non-wrapping, while X + INT_MIN*(-1) wraps.
5187fa27ce4SDimitry Andric   bool IsNegated;
5197fa27ce4SDimitry Andric 
hasNegatedScaleOf__anoncf261da80211::VariableGEPIndex5207fa27ce4SDimitry Andric   bool hasNegatedScaleOf(const VariableGEPIndex &Other) const {
5217fa27ce4SDimitry Andric     if (IsNegated == Other.IsNegated)
5227fa27ce4SDimitry Andric       return Scale == -Other.Scale;
5237fa27ce4SDimitry Andric     return Scale == Other.Scale;
5247fa27ce4SDimitry Andric   }
5257fa27ce4SDimitry Andric 
dump__anoncf261da80211::VariableGEPIndex526c0981da4SDimitry Andric   void dump() const {
527c0981da4SDimitry Andric     print(dbgs());
528c0981da4SDimitry Andric     dbgs() << "\n";
52901095a5dSDimitry Andric   }
print__anoncf261da80211::VariableGEPIndex530c0981da4SDimitry Andric   void print(raw_ostream &OS) const {
531c0981da4SDimitry Andric     OS << "(V=" << Val.V->getName()
532c0981da4SDimitry Andric        << ", zextbits=" << Val.ZExtBits
533c0981da4SDimitry Andric        << ", sextbits=" << Val.SExtBits
534c0981da4SDimitry Andric        << ", truncbits=" << Val.TruncBits
5357fa27ce4SDimitry Andric        << ", scale=" << Scale
5367fa27ce4SDimitry Andric        << ", nsw=" << IsNSW
5377fa27ce4SDimitry Andric        << ", negated=" << IsNegated << ")";
538c0981da4SDimitry Andric   }
539c0981da4SDimitry Andric };
540c0981da4SDimitry Andric }
541c0981da4SDimitry Andric 
542c0981da4SDimitry Andric // Represents the internal structure of a GEP, decomposed into a base pointer,
543c0981da4SDimitry Andric // constant offsets, and variable scaled indices.
544c0981da4SDimitry Andric struct BasicAAResult::DecomposedGEP {
545c0981da4SDimitry Andric   // Base pointer of the GEP
546c0981da4SDimitry Andric   const Value *Base;
547c0981da4SDimitry Andric   // Total constant offset from base.
548c0981da4SDimitry Andric   APInt Offset;
549c0981da4SDimitry Andric   // Scaled variable (non-constant) indices.
550c0981da4SDimitry Andric   SmallVector<VariableGEPIndex, 4> VarIndices;
551c0981da4SDimitry Andric   // Are all operations inbounds GEPs or non-indexing operations?
552e3b55780SDimitry Andric   // (std::nullopt iff expression doesn't involve any geps)
553e3b55780SDimitry Andric   std::optional<bool> InBounds;
554c0981da4SDimitry Andric 
dumpBasicAAResult::DecomposedGEP555c0981da4SDimitry Andric   void dump() const {
556c0981da4SDimitry Andric     print(dbgs());
557c0981da4SDimitry Andric     dbgs() << "\n";
558c0981da4SDimitry Andric   }
printBasicAAResult::DecomposedGEP559c0981da4SDimitry Andric   void print(raw_ostream &OS) const {
560c0981da4SDimitry Andric     OS << "(DecomposedGEP Base=" << Base->getName()
561c0981da4SDimitry Andric        << ", Offset=" << Offset
562c0981da4SDimitry Andric        << ", VarIndices=[";
563c0981da4SDimitry Andric     for (size_t i = 0; i < VarIndices.size(); i++) {
564c0981da4SDimitry Andric       if (i != 0)
565c0981da4SDimitry Andric         OS << ", ";
566c0981da4SDimitry Andric       VarIndices[i].print(OS);
567c0981da4SDimitry Andric     }
568c0981da4SDimitry Andric     OS << "])";
569c0981da4SDimitry Andric   }
570c0981da4SDimitry Andric };
571c0981da4SDimitry Andric 
57201095a5dSDimitry Andric 
573dd58ef01SDimitry Andric /// If V is a symbolic pointer expression, decompose it into a base pointer
574dd58ef01SDimitry Andric /// with a constant offset and a number of scaled symbolic offsets.
575d39c594dSDimitry Andric ///
576dd58ef01SDimitry Andric /// The scaled symbolic offsets (represented by pairs of a Value* and a scale
577dd58ef01SDimitry Andric /// in the VarIndices vector) are Value*'s that are known to be scaled by the
578dd58ef01SDimitry Andric /// specified amount, but which may have other unrepresented high bits. As
579dd58ef01SDimitry Andric /// such, the gep cannot necessarily be reconstructed from its decomposed form.
580b60736ecSDimitry Andric BasicAAResult::DecomposedGEP
DecomposeGEPExpression(const Value * V,const DataLayout & DL,AssumptionCache * AC,DominatorTree * DT)581b60736ecSDimitry Andric BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL,
582b60736ecSDimitry Andric                                       AssumptionCache *AC, DominatorTree *DT) {
583d39c594dSDimitry Andric   // Limit recursion depth to limit compile time in crazy cases.
5845ca98fd9SDimitry Andric   unsigned MaxLookup = MaxLookupSearchDepth;
585dd58ef01SDimitry Andric   SearchTimes++;
586b60736ecSDimitry Andric   const Instruction *CxtI = dyn_cast<Instruction>(V);
587d39c594dSDimitry Andric 
588c0981da4SDimitry Andric   unsigned MaxIndexSize = DL.getMaxIndexSizeInBits();
589b60736ecSDimitry Andric   DecomposedGEP Decomposed;
590c0981da4SDimitry Andric   Decomposed.Offset = APInt(MaxIndexSize, 0);
591d39c594dSDimitry Andric   do {
592d39c594dSDimitry Andric     // See if this is a bitcast or GEP.
593d39c594dSDimitry Andric     const Operator *Op = dyn_cast<Operator>(V);
5945ca98fd9SDimitry Andric     if (!Op) {
595d39c594dSDimitry Andric       // The only non-operator case we can handle are GlobalAliases.
596d39c594dSDimitry Andric       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
59701095a5dSDimitry Andric         if (!GA->isInterposable()) {
598d39c594dSDimitry Andric           V = GA->getAliasee();
599d39c594dSDimitry Andric           continue;
600d39c594dSDimitry Andric         }
601d39c594dSDimitry Andric       }
60201095a5dSDimitry Andric       Decomposed.Base = V;
603b60736ecSDimitry Andric       return Decomposed;
604d39c594dSDimitry Andric     }
605d39c594dSDimitry Andric 
6065ca98fd9SDimitry Andric     if (Op->getOpcode() == Instruction::BitCast ||
6075ca98fd9SDimitry Andric         Op->getOpcode() == Instruction::AddrSpaceCast) {
608d39c594dSDimitry Andric       V = Op->getOperand(0);
609d39c594dSDimitry Andric       continue;
610d39c594dSDimitry Andric     }
611d39c594dSDimitry Andric 
61256fe8f14SDimitry Andric     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
6135ca98fd9SDimitry Andric     if (!GEPOp) {
614cfca06d7SDimitry Andric       if (const auto *PHI = dyn_cast<PHINode>(V)) {
615cfca06d7SDimitry Andric         // Look through single-arg phi nodes created by LCSSA.
616cfca06d7SDimitry Andric         if (PHI->getNumIncomingValues() == 1) {
617cfca06d7SDimitry Andric           V = PHI->getIncomingValue(0);
618cfca06d7SDimitry Andric           continue;
619cfca06d7SDimitry Andric         }
620cfca06d7SDimitry Andric       } else if (const auto *Call = dyn_cast<CallBase>(V)) {
621eb11fae6SDimitry Andric         // CaptureTracking can know about special capturing properties of some
622eb11fae6SDimitry Andric         // intrinsics like launder.invariant.group, that can't be expressed with
623eb11fae6SDimitry Andric         // the attributes, but have properties like returning aliasing pointer.
624eb11fae6SDimitry Andric         // Because some analysis may assume that nocaptured pointer is not
625eb11fae6SDimitry Andric         // returned from some special intrinsic (because function would have to
626eb11fae6SDimitry Andric         // be marked with returns attribute), it is crucial to use this function
627eb11fae6SDimitry Andric         // because it should be in sync with CaptureTracking. Not using it may
628eb11fae6SDimitry Andric         // cause weird miscompilations where 2 aliasing pointers are assumed to
629eb11fae6SDimitry Andric         // noalias.
6301d5ae102SDimitry Andric         if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
631eb11fae6SDimitry Andric           V = RP;
63201095a5dSDimitry Andric           continue;
63301095a5dSDimitry Andric         }
634eb11fae6SDimitry Andric       }
63501095a5dSDimitry Andric 
63601095a5dSDimitry Andric       Decomposed.Base = V;
637b60736ecSDimitry Andric       return Decomposed;
63856fe8f14SDimitry Andric     }
639d39c594dSDimitry Andric 
640344a3780SDimitry Andric     // Track whether we've seen at least one in bounds gep, and if so, whether
641344a3780SDimitry Andric     // all geps parsed were in bounds.
642e3b55780SDimitry Andric     if (Decomposed.InBounds == std::nullopt)
643344a3780SDimitry Andric       Decomposed.InBounds = GEPOp->isInBounds();
644344a3780SDimitry Andric     else if (!GEPOp->isInBounds())
645344a3780SDimitry Andric       Decomposed.InBounds = false;
646344a3780SDimitry Andric 
647c0981da4SDimitry Andric     assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized");
648d39c594dSDimitry Andric 
649f8af5cf6SDimitry Andric     unsigned AS = GEPOp->getPointerAddressSpace();
650d39c594dSDimitry Andric     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
651d39c594dSDimitry Andric     gep_type_iterator GTI = gep_type_begin(GEPOp);
652c0981da4SDimitry Andric     unsigned IndexSize = DL.getIndexSizeInBits(AS);
653b915e9e0SDimitry Andric     // Assume all GEP operands are constants until proven otherwise.
654b915e9e0SDimitry Andric     bool GepHasConstantOffset = true;
655dd58ef01SDimitry Andric     for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
656b915e9e0SDimitry Andric          I != E; ++I, ++GTI) {
657dd58ef01SDimitry Andric       const Value *Index = *I;
658d39c594dSDimitry Andric       // Compute the (potentially symbolic) offset in bytes for this index.
659b915e9e0SDimitry Andric       if (StructType *STy = GTI.getStructTypeOrNull()) {
660d39c594dSDimitry Andric         // For a struct, add the member offset.
661d39c594dSDimitry Andric         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
662dd58ef01SDimitry Andric         if (FieldNo == 0)
663dd58ef01SDimitry Andric           continue;
664d39c594dSDimitry Andric 
665b60736ecSDimitry Andric         Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo);
666d39c594dSDimitry Andric         continue;
667d39c594dSDimitry Andric       }
668d39c594dSDimitry Andric 
669d39c594dSDimitry Andric       // For an array/pointer, add the element offset, explicitly scaled.
670dd58ef01SDimitry Andric       if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
671dd58ef01SDimitry Andric         if (CIdx->isZero())
672dd58ef01SDimitry Andric           continue;
673e3b55780SDimitry Andric 
674e3b55780SDimitry Andric         // Don't attempt to analyze GEPs if the scalable index is not zero.
675aca2e42cSDimitry Andric         TypeSize AllocTypeSize = GTI.getSequentialElementStride(DL);
676e3b55780SDimitry Andric         if (AllocTypeSize.isScalable()) {
677e3b55780SDimitry Andric           Decomposed.Base = V;
678e3b55780SDimitry Andric           return Decomposed;
679e3b55780SDimitry Andric         }
680e3b55780SDimitry Andric 
681e3b55780SDimitry Andric         Decomposed.Offset += AllocTypeSize.getFixedValue() *
682c0981da4SDimitry Andric                              CIdx->getValue().sextOrTrunc(MaxIndexSize);
683d39c594dSDimitry Andric         continue;
684d39c594dSDimitry Andric       }
685d39c594dSDimitry Andric 
686aca2e42cSDimitry Andric       TypeSize AllocTypeSize = GTI.getSequentialElementStride(DL);
687e3b55780SDimitry Andric       if (AllocTypeSize.isScalable()) {
688e3b55780SDimitry Andric         Decomposed.Base = V;
689e3b55780SDimitry Andric         return Decomposed;
690e3b55780SDimitry Andric       }
691e3b55780SDimitry Andric 
692b915e9e0SDimitry Andric       GepHasConstantOffset = false;
693b915e9e0SDimitry Andric 
694c0981da4SDimitry Andric       // If the integer type is smaller than the index size, it is implicitly
695c0981da4SDimitry Andric       // sign extended or truncated to index size.
696f8af5cf6SDimitry Andric       unsigned Width = Index->getType()->getIntegerBitWidth();
697c0981da4SDimitry Andric       unsigned SExtBits = IndexSize > Width ? IndexSize - Width : 0;
698c0981da4SDimitry Andric       unsigned TruncBits = IndexSize < Width ? Width - IndexSize : 0;
699344a3780SDimitry Andric       LinearExpression LE = GetLinearExpression(
700ac9a064cSDimitry Andric           CastedValue(Index, 0, SExtBits, TruncBits, false), DL, 0, AC, DT);
701d39c594dSDimitry Andric 
702c0981da4SDimitry Andric       // Scale by the type size.
703e3b55780SDimitry Andric       unsigned TypeSize = AllocTypeSize.getFixedValue();
704c0981da4SDimitry Andric       LE = LE.mul(APInt(IndexSize, TypeSize), GEPOp->isInBounds());
705145449b1SDimitry Andric       Decomposed.Offset += LE.Offset.sext(MaxIndexSize);
706145449b1SDimitry Andric       APInt Scale = LE.Scale.sext(MaxIndexSize);
707d39c594dSDimitry Andric 
7086b943ff3SDimitry Andric       // If we already had an occurrence of this index variable, merge this
709d39c594dSDimitry Andric       // scale into it.  For example, we want to handle:
710d39c594dSDimitry Andric       //   A[x][x] -> x*16 + x*4 -> x*20
711d39c594dSDimitry Andric       // This also ensures that 'x' only appears in the index list once.
71201095a5dSDimitry Andric       for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
713ac9a064cSDimitry Andric         if ((Decomposed.VarIndices[i].Val.V == LE.Val.V ||
714ac9a064cSDimitry Andric              areBothVScale(Decomposed.VarIndices[i].Val.V, LE.Val.V)) &&
715c0981da4SDimitry Andric             Decomposed.VarIndices[i].Val.hasSameCastsAs(LE.Val)) {
71601095a5dSDimitry Andric           Scale += Decomposed.VarIndices[i].Scale;
717b1c73532SDimitry Andric           LE.IsNSW = false; // We cannot guarantee nsw for the merge.
71801095a5dSDimitry Andric           Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
719d39c594dSDimitry Andric           break;
720d39c594dSDimitry Andric         }
721d39c594dSDimitry Andric       }
722d39c594dSDimitry Andric 
723d39c594dSDimitry Andric       // Make sure that we have a scale that makes sense for this target's
724c0981da4SDimitry Andric       // index size.
725b1c73532SDimitry Andric       adjustToIndexSize(Scale, IndexSize);
726d39c594dSDimitry Andric 
727d8e91e46SDimitry Andric       if (!!Scale) {
7287fa27ce4SDimitry Andric         VariableGEPIndex Entry = {LE.Val, Scale, CxtI, LE.IsNSW,
7297fa27ce4SDimitry Andric                                   /* IsNegated */ false};
73001095a5dSDimitry Andric         Decomposed.VarIndices.push_back(Entry);
731d39c594dSDimitry Andric       }
732d39c594dSDimitry Andric     }
733d39c594dSDimitry Andric 
73401095a5dSDimitry Andric     // Take care of wrap-arounds
735b60736ecSDimitry Andric     if (GepHasConstantOffset)
736b1c73532SDimitry Andric       adjustToIndexSize(Decomposed.Offset, IndexSize);
73701095a5dSDimitry Andric 
738d39c594dSDimitry Andric     // Analyze the base pointer next.
739d39c594dSDimitry Andric     V = GEPOp->getOperand(0);
740d39c594dSDimitry Andric   } while (--MaxLookup);
741d39c594dSDimitry Andric 
742d39c594dSDimitry Andric   // If the chain of expressions is too deep, just return early.
74301095a5dSDimitry Andric   Decomposed.Base = V;
744dd58ef01SDimitry Andric   SearchLimitReached++;
745b60736ecSDimitry Andric   return Decomposed;
746d39c594dSDimitry Andric }
747d39c594dSDimitry Andric 
getModRefInfoMask(const MemoryLocation & Loc,AAQueryInfo & AAQI,bool IgnoreLocals)748e3b55780SDimitry Andric ModRefInfo BasicAAResult::getModRefInfoMask(const MemoryLocation &Loc,
749e3b55780SDimitry Andric                                             AAQueryInfo &AAQI,
750e3b55780SDimitry Andric                                             bool IgnoreLocals) {
751cf099d11SDimitry Andric   assert(Visited.empty() && "Visited must be cleared after use!");
752e3b55780SDimitry Andric   auto _ = make_scope_exit([&] { Visited.clear(); });
753009b1c42SEd Schouten 
754cf099d11SDimitry Andric   unsigned MaxLookup = 8;
755cf099d11SDimitry Andric   SmallVector<const Value *, 16> Worklist;
756cf099d11SDimitry Andric   Worklist.push_back(Loc.Ptr);
757e3b55780SDimitry Andric   ModRefInfo Result = ModRefInfo::NoModRef;
758e3b55780SDimitry Andric 
759cf099d11SDimitry Andric   do {
760b60736ecSDimitry Andric     const Value *V = getUnderlyingObject(Worklist.pop_back_val());
761e3b55780SDimitry Andric     if (!Visited.insert(V).second)
762cf099d11SDimitry Andric       continue;
763cf099d11SDimitry Andric 
764e3b55780SDimitry Andric     // Ignore allocas if we were instructed to do so.
765e3b55780SDimitry Andric     if (IgnoreLocals && isa<AllocaInst>(V))
766e3b55780SDimitry Andric       continue;
767e3b55780SDimitry Andric 
768e3b55780SDimitry Andric     // If the location points to memory that is known to be invariant for
769e3b55780SDimitry Andric     // the life of the underlying SSA value, then we can exclude Mod from
770e3b55780SDimitry Andric     // the set of valid memory effects.
771e3b55780SDimitry Andric     //
772e3b55780SDimitry Andric     // An argument that is marked readonly and noalias is known to be
773e3b55780SDimitry Andric     // invariant while that function is executing.
774e3b55780SDimitry Andric     if (const Argument *Arg = dyn_cast<Argument>(V)) {
775e3b55780SDimitry Andric       if (Arg->hasNoAliasAttr() && Arg->onlyReadsMemory()) {
776e3b55780SDimitry Andric         Result |= ModRefInfo::Ref;
777e3b55780SDimitry Andric         continue;
778e3b55780SDimitry Andric       }
779e3b55780SDimitry Andric     }
780e3b55780SDimitry Andric 
781e3b55780SDimitry Andric     // A global constant can't be mutated.
782cf099d11SDimitry Andric     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
78306f9d401SRoman Divacky       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
784cf099d11SDimitry Andric       // global to be marked constant in some modules and non-constant in
785cf099d11SDimitry Andric       // others.  GV may even be a declaration, not a definition.
786e3b55780SDimitry Andric       if (!GV->isConstant())
787b1c73532SDimitry Andric         return ModRefInfo::ModRef;
788cf099d11SDimitry Andric       continue;
789cf099d11SDimitry Andric     }
790d39c594dSDimitry Andric 
791cf099d11SDimitry Andric     // If both select values point to local memory, then so does the select.
792cf099d11SDimitry Andric     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
793cf099d11SDimitry Andric       Worklist.push_back(SI->getTrueValue());
794cf099d11SDimitry Andric       Worklist.push_back(SI->getFalseValue());
795cf099d11SDimitry Andric       continue;
796cf099d11SDimitry Andric     }
797cf099d11SDimitry Andric 
798cf099d11SDimitry Andric     // If all values incoming to a phi node point to local memory, then so does
799cf099d11SDimitry Andric     // the phi.
800cf099d11SDimitry Andric     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
801cf099d11SDimitry Andric       // Don't bother inspecting phi nodes with many operands.
802e3b55780SDimitry Andric       if (PN->getNumIncomingValues() > MaxLookup)
803b1c73532SDimitry Andric         return ModRefInfo::ModRef;
804b60736ecSDimitry Andric       append_range(Worklist, PN->incoming_values());
805cf099d11SDimitry Andric       continue;
806cf099d11SDimitry Andric     }
807cf099d11SDimitry Andric 
808cf099d11SDimitry Andric     // Otherwise be conservative.
809b1c73532SDimitry Andric     return ModRefInfo::ModRef;
810cf099d11SDimitry Andric   } while (!Worklist.empty() && --MaxLookup);
811cf099d11SDimitry Andric 
812e3b55780SDimitry Andric   // If we hit the maximum number of instructions to examine, be conservative.
813e3b55780SDimitry Andric   if (!Worklist.empty())
814b1c73532SDimitry Andric     return ModRefInfo::ModRef;
815e3b55780SDimitry Andric 
816e3b55780SDimitry Andric   return Result;
817009b1c42SEd Schouten }
818009b1c42SEd Schouten 
isIntrinsicCall(const CallBase * Call,Intrinsic::ID IID)819344a3780SDimitry Andric static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {
820344a3780SDimitry Andric   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call);
821344a3780SDimitry Andric   return II && II->getIntrinsicID() == IID;
822344a3780SDimitry Andric }
823344a3780SDimitry Andric 
824dd58ef01SDimitry Andric /// Returns the behavior when calling the given call site.
getMemoryEffects(const CallBase * Call,AAQueryInfo & AAQI)825e3b55780SDimitry Andric MemoryEffects BasicAAResult::getMemoryEffects(const CallBase *Call,
826e3b55780SDimitry Andric                                               AAQueryInfo &AAQI) {
827e3b55780SDimitry Andric   MemoryEffects Min = Call->getAttributes().getMemoryEffects();
828d39c594dSDimitry Andric 
829e3b55780SDimitry Andric   if (const Function *F = dyn_cast<Function>(Call->getCalledOperand())) {
830e3b55780SDimitry Andric     MemoryEffects FuncME = AAQI.AAR.getMemoryEffects(F);
831e3b55780SDimitry Andric     // Operand bundles on the call may also read or write memory, in addition
832e3b55780SDimitry Andric     // to the behavior of the called function.
833e3b55780SDimitry Andric     if (Call->hasReadingOperandBundles())
834e3b55780SDimitry Andric       FuncME |= MemoryEffects::readOnly();
835e3b55780SDimitry Andric     if (Call->hasClobberingOperandBundles())
836e3b55780SDimitry Andric       FuncME |= MemoryEffects::writeOnly();
837e3b55780SDimitry Andric     Min &= FuncME;
838e3b55780SDimitry Andric   }
83901095a5dSDimitry Andric 
84001095a5dSDimitry Andric   return Min;
841d39c594dSDimitry Andric }
842d39c594dSDimitry Andric 
843dd58ef01SDimitry Andric /// Returns the behavior when calling the given function. For use when the call
844dd58ef01SDimitry Andric /// site is not known.
getMemoryEffects(const Function * F)845e3b55780SDimitry Andric MemoryEffects BasicAAResult::getMemoryEffects(const Function *F) {
846e3b55780SDimitry Andric   switch (F->getIntrinsicID()) {
847e3b55780SDimitry Andric   case Intrinsic::experimental_guard:
848e3b55780SDimitry Andric   case Intrinsic::experimental_deoptimize:
849e3b55780SDimitry Andric     // These intrinsics can read arbitrary memory, and additionally modref
850e3b55780SDimitry Andric     // inaccessible memory to model control dependence.
851e3b55780SDimitry Andric     return MemoryEffects::readOnly() |
852e3b55780SDimitry Andric            MemoryEffects::inaccessibleMemOnly(ModRefInfo::ModRef);
853d39c594dSDimitry Andric   }
854009b1c42SEd Schouten 
855e3b55780SDimitry Andric   return F->getMemoryEffects();
856050e163aSDimitry Andric }
857050e163aSDimitry Andric 
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)858d8e91e46SDimitry Andric ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,
859050e163aSDimitry Andric                                            unsigned ArgIdx) {
860e3b55780SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly))
861044eb2f6SDimitry Andric     return ModRefInfo::Mod;
8625ca98fd9SDimitry Andric 
863d8e91e46SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly))
864044eb2f6SDimitry Andric     return ModRefInfo::Ref;
865dd58ef01SDimitry Andric 
866d8e91e46SDimitry Andric   if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone))
867044eb2f6SDimitry Andric     return ModRefInfo::NoModRef;
868dd58ef01SDimitry Andric 
869b1c73532SDimitry Andric   return ModRefInfo::ModRef;
8705ca98fd9SDimitry Andric }
8715ca98fd9SDimitry Andric 
872dd58ef01SDimitry Andric #ifndef NDEBUG
getParent(const Value * V)873dd58ef01SDimitry Andric static const Function *getParent(const Value *V) {
874b5630dbaSDimitry Andric   if (const Instruction *inst = dyn_cast<Instruction>(V)) {
875b5630dbaSDimitry Andric     if (!inst->getParent())
876b5630dbaSDimitry Andric       return nullptr;
877dd58ef01SDimitry Andric     return inst->getParent()->getParent();
878b5630dbaSDimitry Andric   }
879dd58ef01SDimitry Andric 
880dd58ef01SDimitry Andric   if (const Argument *arg = dyn_cast<Argument>(V))
881dd58ef01SDimitry Andric     return arg->getParent();
882dd58ef01SDimitry Andric 
883dd58ef01SDimitry Andric   return nullptr;
8845a5ac124SDimitry Andric }
8855a5ac124SDimitry Andric 
notDifferentParent(const Value * O1,const Value * O2)886dd58ef01SDimitry Andric static bool notDifferentParent(const Value *O1, const Value *O2) {
887dd58ef01SDimitry Andric 
888dd58ef01SDimitry Andric   const Function *F1 = getParent(O1);
889dd58ef01SDimitry Andric   const Function *F2 = getParent(O2);
890dd58ef01SDimitry Andric 
891dd58ef01SDimitry Andric   return !F1 || !F2 || F1 == F2;
892dd58ef01SDimitry Andric }
893dd58ef01SDimitry Andric #endif
894dd58ef01SDimitry Andric 
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI,const Instruction * CtxI)895dd58ef01SDimitry Andric AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
896e3b55780SDimitry Andric                                  const MemoryLocation &LocB, AAQueryInfo &AAQI,
897e3b55780SDimitry Andric                                  const Instruction *CtxI) {
898dd58ef01SDimitry Andric   assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
899dd58ef01SDimitry Andric          "BasicAliasAnalysis doesn't support interprocedural queries.");
900e3b55780SDimitry Andric   return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI, CtxI);
901dd58ef01SDimitry Andric }
902dd58ef01SDimitry Andric 
903dd58ef01SDimitry Andric /// Checks to see if the specified callsite can clobber the specified memory
904dd58ef01SDimitry Andric /// object.
905dd58ef01SDimitry Andric ///
906dd58ef01SDimitry Andric /// Since we only look at local properties of this function, we really can't
907dd58ef01SDimitry Andric /// say much about this query.  We do, however, use simple "address taken"
908dd58ef01SDimitry Andric /// analysis on local objects.
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc,AAQueryInfo & AAQI)909d8e91e46SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,
910e6d15924SDimitry Andric                                         const MemoryLocation &Loc,
911e6d15924SDimitry Andric                                         AAQueryInfo &AAQI) {
912d8e91e46SDimitry Andric   assert(notDifferentParent(Call, Loc.Ptr) &&
91366e41e3cSRoman Divacky          "AliasAnalysis query involving multiple functions!");
91466e41e3cSRoman Divacky 
915b60736ecSDimitry Andric   const Value *Object = getUnderlyingObject(Loc.Ptr);
916009b1c42SEd Schouten 
917d8e91e46SDimitry Andric   // Calls marked 'tail' cannot read or write allocas from the current frame
918d8e91e46SDimitry Andric   // because the current frame might be destroyed by the time they run. However,
919d8e91e46SDimitry Andric   // a tail call may use an alloca with byval. Calling with byval copies the
920d8e91e46SDimitry Andric   // contents of the alloca into argument registers or stack slots, so there is
921d8e91e46SDimitry Andric   // no lifetime issue.
922009b1c42SEd Schouten   if (isa<AllocaInst>(Object))
923d8e91e46SDimitry Andric     if (const CallInst *CI = dyn_cast<CallInst>(Call))
924d8e91e46SDimitry Andric       if (CI->isTailCall() &&
925d8e91e46SDimitry Andric           !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))
926044eb2f6SDimitry Andric         return ModRefInfo::NoModRef;
927009b1c42SEd Schouten 
928d8e91e46SDimitry Andric   // Stack restore is able to modify unescaped dynamic allocas. Assume it may
929d8e91e46SDimitry Andric   // modify them even though the alloca is not escaped.
930d8e91e46SDimitry Andric   if (auto *AI = dyn_cast<AllocaInst>(Object))
931d8e91e46SDimitry Andric     if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))
932d8e91e46SDimitry Andric       return ModRefInfo::Mod;
933d8e91e46SDimitry Andric 
9347fa27ce4SDimitry Andric   // A call can access a locally allocated object either because it is passed as
9357fa27ce4SDimitry Andric   // an argument to the call, or because it has escaped prior to the call.
9367fa27ce4SDimitry Andric   //
9377fa27ce4SDimitry Andric   // Make sure the object has not escaped here, and then check that none of the
9387fa27ce4SDimitry Andric   // call arguments alias the object below.
939d8e91e46SDimitry Andric   if (!isa<Constant>(Object) && Call != Object &&
940b1c73532SDimitry Andric       AAQI.CI->isNotCapturedBefore(Object, Call, /*OrAt*/ false)) {
94171d5a254SDimitry Andric 
94271d5a254SDimitry Andric     // Optimistically assume that call doesn't touch Object and check this
94371d5a254SDimitry Andric     // assumption in the following loop.
944044eb2f6SDimitry Andric     ModRefInfo Result = ModRefInfo::NoModRef;
94571d5a254SDimitry Andric 
94601095a5dSDimitry Andric     unsigned OperandNo = 0;
947d8e91e46SDimitry Andric     for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();
94801095a5dSDimitry Andric          CI != CE; ++CI, ++OperandNo) {
9497fa27ce4SDimitry Andric       if (!(*CI)->getType()->isPointerTy())
95006f9d401SRoman Divacky         continue;
951009b1c42SEd Schouten 
95271d5a254SDimitry Andric       // Call doesn't access memory through this operand, so we don't care
95371d5a254SDimitry Andric       // if it aliases with Object.
954d8e91e46SDimitry Andric       if (Call->doesNotAccessMemory(OperandNo))
95571d5a254SDimitry Andric         continue;
95671d5a254SDimitry Andric 
95706f9d401SRoman Divacky       // If this is a no-capture pointer argument, see if we can tell that it
95871d5a254SDimitry Andric       // is impossible to alias the pointer we're checking.
959e3b55780SDimitry Andric       AliasResult AR =
960e3b55780SDimitry Andric           AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(*CI),
961b60736ecSDimitry Andric                          MemoryLocation::getBeforeOrAfter(Object), AAQI);
962e6d15924SDimitry Andric       // Operand doesn't alias 'Object', continue looking for other aliases
963344a3780SDimitry Andric       if (AR == AliasResult::NoAlias)
96471d5a254SDimitry Andric         continue;
96571d5a254SDimitry Andric       // Operand aliases 'Object', but call doesn't modify it. Strengthen
96671d5a254SDimitry Andric       // initial assumption and keep looking in case if there are more aliases.
967d8e91e46SDimitry Andric       if (Call->onlyReadsMemory(OperandNo)) {
968e3b55780SDimitry Andric         Result |= ModRefInfo::Ref;
96971d5a254SDimitry Andric         continue;
97071d5a254SDimitry Andric       }
97171d5a254SDimitry Andric       // Operand aliases 'Object' but call only writes into it.
9726f8fc217SDimitry Andric       if (Call->onlyWritesMemory(OperandNo)) {
973e3b55780SDimitry Andric         Result |= ModRefInfo::Mod;
97471d5a254SDimitry Andric         continue;
97571d5a254SDimitry Andric       }
97671d5a254SDimitry Andric       // This operand aliases 'Object' and call reads and writes into it.
977c7dac04cSDimitry Andric       // Setting ModRef will not yield an early return below, MustAlias is not
978c7dac04cSDimitry Andric       // used further.
979044eb2f6SDimitry Andric       Result = ModRefInfo::ModRef;
98006f9d401SRoman Divacky       break;
98106f9d401SRoman Divacky     }
98206f9d401SRoman Divacky 
98371d5a254SDimitry Andric     // Early return if we improved mod ref information
984e3b55780SDimitry Andric     if (!isModAndRefSet(Result))
985e3b55780SDimitry Andric       return Result;
986eb11fae6SDimitry Andric   }
98759850d08SRoman Divacky 
988cfca06d7SDimitry Andric   // If the call is malloc/calloc like, we can assume that it doesn't
98901095a5dSDimitry Andric   // modify any IR visible value.  This is only valid because we assume these
99001095a5dSDimitry Andric   // routines do not read values visible in the IR.  TODO: Consider special
99101095a5dSDimitry Andric   // casing realloc and strdup routines which access only their arguments as
99201095a5dSDimitry Andric   // well.  Or alternatively, replace all of this with inaccessiblememonly once
99301095a5dSDimitry Andric   // that's implemented fully.
994d8e91e46SDimitry Andric   if (isMallocOrCallocLikeFn(Call, &TLI)) {
99501095a5dSDimitry Andric     // Be conservative if the accessed pointer may alias the allocation -
99601095a5dSDimitry Andric     // fallback to the generic handling below.
997e3b55780SDimitry Andric     if (AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(Call), Loc, AAQI) ==
998e3b55780SDimitry Andric         AliasResult::NoAlias)
999044eb2f6SDimitry Andric       return ModRefInfo::NoModRef;
100001095a5dSDimitry Andric   }
100101095a5dSDimitry Andric 
1002b915e9e0SDimitry Andric   // Like assumes, invariant.start intrinsics were also marked as arbitrarily
1003b915e9e0SDimitry Andric   // writing so that proper control dependencies are maintained but they never
1004b915e9e0SDimitry Andric   // mod any particular memory location visible to the IR.
1005b915e9e0SDimitry Andric   // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
1006b915e9e0SDimitry Andric   // intrinsic is now modeled as reading memory. This prevents hoisting the
1007b915e9e0SDimitry Andric   // invariant.start intrinsic over stores. Consider:
1008b915e9e0SDimitry Andric   // *ptr = 40;
1009b915e9e0SDimitry Andric   // *ptr = 50;
1010b915e9e0SDimitry Andric   // invariant_start(ptr)
1011b915e9e0SDimitry Andric   // int val = *ptr;
1012b915e9e0SDimitry Andric   // print(val);
1013b915e9e0SDimitry Andric   //
1014b915e9e0SDimitry Andric   // This cannot be transformed to:
1015b915e9e0SDimitry Andric   //
1016b915e9e0SDimitry Andric   // *ptr = 40;
1017b915e9e0SDimitry Andric   // invariant_start(ptr)
1018b915e9e0SDimitry Andric   // *ptr = 50;
1019b915e9e0SDimitry Andric   // int val = *ptr;
1020b915e9e0SDimitry Andric   // print(val);
1021b915e9e0SDimitry Andric   //
1022b915e9e0SDimitry Andric   // The transformation will cause the second store to be ignored (based on
1023b915e9e0SDimitry Andric   // rules of invariant.start)  and print 40, while the first program always
1024b915e9e0SDimitry Andric   // prints 50.
1025d8e91e46SDimitry Andric   if (isIntrinsicCall(Call, Intrinsic::invariant_start))
1026044eb2f6SDimitry Andric     return ModRefInfo::Ref;
1027b915e9e0SDimitry Andric 
1028b1c73532SDimitry Andric   // Be conservative.
1029b1c73532SDimitry Andric   return ModRefInfo::ModRef;
1030522600a2SDimitry Andric }
1031522600a2SDimitry Andric 
getModRefInfo(const CallBase * Call1,const CallBase * Call2,AAQueryInfo & AAQI)1032d8e91e46SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,
1033e6d15924SDimitry Andric                                         const CallBase *Call2,
1034e6d15924SDimitry Andric                                         AAQueryInfo &AAQI) {
1035344a3780SDimitry Andric   // Guard intrinsics are marked as arbitrarily writing so that proper control
1036344a3780SDimitry Andric   // dependencies are maintained but they never mods any particular memory
1037344a3780SDimitry Andric   // location.
103801095a5dSDimitry Andric   //
103901095a5dSDimitry Andric   // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
104001095a5dSDimitry Andric   // heap state at the point the guard is issued needs to be consistent in case
104101095a5dSDimitry Andric   // the guard invokes the "deopt" continuation.
104201095a5dSDimitry Andric 
1043e6d15924SDimitry Andric   // NB! This function is *not* commutative, so we special case two
104401095a5dSDimitry Andric   // possibilities for guard intrinsics.
104501095a5dSDimitry Andric 
1046d8e91e46SDimitry Andric   if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))
1047e3b55780SDimitry Andric     return isModSet(getMemoryEffects(Call2, AAQI).getModRef())
1048044eb2f6SDimitry Andric                ? ModRefInfo::Ref
1049044eb2f6SDimitry Andric                : ModRefInfo::NoModRef;
105001095a5dSDimitry Andric 
1051d8e91e46SDimitry Andric   if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))
1052e3b55780SDimitry Andric     return isModSet(getMemoryEffects(Call1, AAQI).getModRef())
1053044eb2f6SDimitry Andric                ? ModRefInfo::Mod
1054044eb2f6SDimitry Andric                : ModRefInfo::NoModRef;
105501095a5dSDimitry Andric 
1056b1c73532SDimitry Andric   // Be conservative.
1057b1c73532SDimitry Andric   return ModRefInfo::ModRef;
105867c32a98SDimitry Andric }
105967c32a98SDimitry Andric 
1060344a3780SDimitry Andric /// Return true if we know V to the base address of the corresponding memory
1061344a3780SDimitry Andric /// object.  This implies that any address less than V must be out of bounds
1062344a3780SDimitry Andric /// for the underlying object.  Note that just being isIdentifiedObject() is
1063344a3780SDimitry Andric /// not enough - For example, a negative offset from a noalias argument or call
1064344a3780SDimitry Andric /// can be inbounds w.r.t the actual underlying object.
isBaseOfObject(const Value * V)1065344a3780SDimitry Andric static bool isBaseOfObject(const Value *V) {
1066344a3780SDimitry Andric   // TODO: We can handle other cases here
1067344a3780SDimitry Andric   // 1) For GC languages, arguments to functions are often required to be
1068344a3780SDimitry Andric   //    base pointers.
1069344a3780SDimitry Andric   // 2) Result of allocation routines are often base pointers.  Leverage TLI.
1070344a3780SDimitry Andric   return (isa<AllocaInst>(V) || isa<GlobalVariable>(V));
107101095a5dSDimitry Andric }
107201095a5dSDimitry Andric 
1073dd58ef01SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
1074dd58ef01SDimitry Andric /// another pointer.
107506f9d401SRoman Divacky ///
1076dd58ef01SDimitry Andric /// We know that V1 is a GEP, but we don't know anything about V2.
1077b60736ecSDimitry Andric /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for
1078dd58ef01SDimitry Andric /// V2.
aliasGEP(const GEPOperator * GEP1,LocationSize V1Size,const Value * V2,LocationSize V2Size,const Value * UnderlyingV1,const Value * UnderlyingV2,AAQueryInfo & AAQI)1079e6d15924SDimitry Andric AliasResult BasicAAResult::aliasGEP(
1080344a3780SDimitry Andric     const GEPOperator *GEP1, LocationSize V1Size,
1081344a3780SDimitry Andric     const Value *V2, LocationSize V2Size,
1082e6d15924SDimitry Andric     const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {
1083344a3780SDimitry Andric   if (!V1Size.hasValue() && !V2Size.hasValue()) {
1084344a3780SDimitry Andric     // TODO: This limitation exists for compile-time reasons. Relax it if we
1085344a3780SDimitry Andric     // can avoid exponential pathological cases.
1086344a3780SDimitry Andric     if (!isa<GEPOperator>(V2))
1087344a3780SDimitry Andric       return AliasResult::MayAlias;
1088344a3780SDimitry Andric 
1089344a3780SDimitry Andric     // If both accesses have unknown size, we can only check whether the base
1090344a3780SDimitry Andric     // objects don't alias.
1091e3b55780SDimitry Andric     AliasResult BaseAlias =
1092e3b55780SDimitry Andric         AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(UnderlyingV1),
1093344a3780SDimitry Andric                        MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI);
1094344a3780SDimitry Andric     return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias
1095344a3780SDimitry Andric                                              : AliasResult::MayAlias;
1096344a3780SDimitry Andric   }
1097344a3780SDimitry Andric 
1098ac9a064cSDimitry Andric   DominatorTree *DT = getDT(AAQI);
1099b60736ecSDimitry Andric   DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT);
1100b60736ecSDimitry Andric   DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT);
110106f9d401SRoman Divacky 
1102c0981da4SDimitry Andric   // Bail if we were not able to decompose anything.
1103c0981da4SDimitry Andric   if (DecompGEP1.Base == GEP1 && DecompGEP2.Base == V2)
1104344a3780SDimitry Andric     return AliasResult::MayAlias;
1105cfca06d7SDimitry Andric 
110606f9d401SRoman Divacky   // Subtract the GEP2 pointer from the GEP1 pointer to find out their
110706f9d401SRoman Divacky   // symbolic difference.
1108e3b55780SDimitry Andric   subtractDecomposedGEPs(DecompGEP1, DecompGEP2, AAQI);
110906f9d401SRoman Divacky 
1110344a3780SDimitry Andric   // If an inbounds GEP would have to start from an out of bounds address
1111344a3780SDimitry Andric   // for the two to alias, then we can assume noalias.
1112b1c73532SDimitry Andric   // TODO: Remove !isScalable() once BasicAA fully support scalable location
1113b1c73532SDimitry Andric   // size
1114344a3780SDimitry Andric   if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() &&
1115b1c73532SDimitry Andric       V2Size.hasValue() && !V2Size.isScalable() &&
1116b1c73532SDimitry Andric       DecompGEP1.Offset.sge(V2Size.getValue()) &&
1117344a3780SDimitry Andric       isBaseOfObject(DecompGEP2.Base))
1118344a3780SDimitry Andric     return AliasResult::NoAlias;
111906f9d401SRoman Divacky 
1120344a3780SDimitry Andric   if (isa<GEPOperator>(V2)) {
1121344a3780SDimitry Andric     // Symmetric case to above.
1122344a3780SDimitry Andric     if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() &&
1123b1c73532SDimitry Andric         V1Size.hasValue() && !V1Size.isScalable() &&
1124b1c73532SDimitry Andric         DecompGEP1.Offset.sle(-V1Size.getValue()) &&
1125344a3780SDimitry Andric         isBaseOfObject(DecompGEP1.Base))
1126344a3780SDimitry Andric       return AliasResult::NoAlias;
1127009b1c42SEd Schouten   }
1128009b1c42SEd Schouten 
1129344a3780SDimitry Andric   // For GEPs with identical offsets, we can preserve the size and AAInfo
1130344a3780SDimitry Andric   // when performing the alias check on the underlying objects.
1131b60736ecSDimitry Andric   if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty())
1132e3b55780SDimitry Andric     return AAQI.AAR.alias(MemoryLocation(DecompGEP1.Base, V1Size),
1133e3b55780SDimitry Andric                           MemoryLocation(DecompGEP2.Base, V2Size), AAQI);
1134344a3780SDimitry Andric 
1135344a3780SDimitry Andric   // Do the base pointers alias?
1136e3b55780SDimitry Andric   AliasResult BaseAlias =
1137e3b55780SDimitry Andric       AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(DecompGEP1.Base),
1138c0981da4SDimitry Andric                      MemoryLocation::getBeforeOrAfter(DecompGEP2.Base), AAQI);
1139344a3780SDimitry Andric 
1140344a3780SDimitry Andric   // If we get a No or May, then return it immediately, no amount of analysis
1141344a3780SDimitry Andric   // will improve this situation.
1142344a3780SDimitry Andric   if (BaseAlias != AliasResult::MustAlias) {
1143344a3780SDimitry Andric     assert(BaseAlias == AliasResult::NoAlias ||
1144344a3780SDimitry Andric            BaseAlias == AliasResult::MayAlias);
1145344a3780SDimitry Andric     return BaseAlias;
1146344a3780SDimitry Andric   }
1147009b1c42SEd Schouten 
114830815c53SDimitry Andric   // If there is a constant difference between the pointers, but the difference
114930815c53SDimitry Andric   // is less than the size of the associated memory object, then we know
115030815c53SDimitry Andric   // that the objects are partially overlapping.  If the difference is
115130815c53SDimitry Andric   // greater, we know they do not overlap.
1152c0981da4SDimitry Andric   if (DecompGEP1.VarIndices.empty()) {
1153344a3780SDimitry Andric     APInt &Off = DecompGEP1.Offset;
1154344a3780SDimitry Andric 
1155344a3780SDimitry Andric     // Initialize for Off >= 0 (V2 <= GEP1) case.
1156344a3780SDimitry Andric     const Value *LeftPtr = V2;
1157344a3780SDimitry Andric     const Value *RightPtr = GEP1;
1158344a3780SDimitry Andric     LocationSize VLeftSize = V2Size;
1159344a3780SDimitry Andric     LocationSize VRightSize = V1Size;
1160344a3780SDimitry Andric     const bool Swapped = Off.isNegative();
1161344a3780SDimitry Andric 
1162344a3780SDimitry Andric     if (Swapped) {
1163344a3780SDimitry Andric       // Swap if we have the situation where:
116468bcb7dbSDimitry Andric       // +                +
116568bcb7dbSDimitry Andric       // | BaseOffset     |
116668bcb7dbSDimitry Andric       // ---------------->|
116768bcb7dbSDimitry Andric       // |-->V1Size       |-------> V2Size
116868bcb7dbSDimitry Andric       // GEP1             V2
1169344a3780SDimitry Andric       std::swap(LeftPtr, RightPtr);
1170344a3780SDimitry Andric       std::swap(VLeftSize, VRightSize);
1171344a3780SDimitry Andric       Off = -Off;
117230815c53SDimitry Andric     }
1173344a3780SDimitry Andric 
1174c0981da4SDimitry Andric     if (!VLeftSize.hasValue())
1175c0981da4SDimitry Andric       return AliasResult::MayAlias;
1176c0981da4SDimitry Andric 
1177ac9a064cSDimitry Andric     const TypeSize LSize = VLeftSize.getValue();
1178ac9a064cSDimitry Andric     if (!LSize.isScalable()) {
1179344a3780SDimitry Andric       if (Off.ult(LSize)) {
1180344a3780SDimitry Andric         // Conservatively drop processing if a phi was visited and/or offset is
1181344a3780SDimitry Andric         // too big.
1182344a3780SDimitry Andric         AliasResult AR = AliasResult::PartialAlias;
1183ac9a064cSDimitry Andric         if (VRightSize.hasValue() && !VRightSize.isScalable() &&
1184ac9a064cSDimitry Andric             Off.ule(INT32_MAX) && (Off + VRightSize.getValue()).ule(LSize)) {
1185344a3780SDimitry Andric           // Memory referenced by right pointer is nested. Save the offset in
1186344a3780SDimitry Andric           // cache. Note that originally offset estimated as GEP1-V2, but
1187344a3780SDimitry Andric           // AliasResult contains the shift that represents GEP1+Offset=V2.
1188344a3780SDimitry Andric           AR.setOffset(-Off.getSExtValue());
1189344a3780SDimitry Andric           AR.swap(Swapped);
1190344a3780SDimitry Andric         }
1191344a3780SDimitry Andric         return AR;
1192344a3780SDimitry Andric       }
1193344a3780SDimitry Andric       return AliasResult::NoAlias;
1194ac9a064cSDimitry Andric     } else {
1195ac9a064cSDimitry Andric       // We can use the getVScaleRange to prove that Off >= (CR.upper * LSize).
1196ac9a064cSDimitry Andric       ConstantRange CR = getVScaleRange(&F, Off.getBitWidth());
1197ac9a064cSDimitry Andric       bool Overflow;
1198ac9a064cSDimitry Andric       APInt UpperRange = CR.getUnsignedMax().umul_ov(
1199ac9a064cSDimitry Andric           APInt(Off.getBitWidth(), LSize.getKnownMinValue()), Overflow);
1200ac9a064cSDimitry Andric       if (!Overflow && Off.uge(UpperRange))
1201ac9a064cSDimitry Andric         return AliasResult::NoAlias;
120230815c53SDimitry Andric     }
1203ac9a064cSDimitry Andric   }
1204ac9a064cSDimitry Andric 
1205ac9a064cSDimitry Andric   // VScale Alias Analysis - Given one scalable offset between accesses and a
1206ac9a064cSDimitry Andric   // scalable typesize, we can divide each side by vscale, treating both values
1207ac9a064cSDimitry Andric   // as a constant. We prove that Offset/vscale >= TypeSize/vscale.
1208ac9a064cSDimitry Andric   if (DecompGEP1.VarIndices.size() == 1 &&
1209ac9a064cSDimitry Andric       DecompGEP1.VarIndices[0].Val.TruncBits == 0 &&
1210ac9a064cSDimitry Andric       DecompGEP1.Offset.isZero() &&
1211ac9a064cSDimitry Andric       PatternMatch::match(DecompGEP1.VarIndices[0].Val.V,
1212ac9a064cSDimitry Andric                           PatternMatch::m_VScale())) {
1213ac9a064cSDimitry Andric     const VariableGEPIndex &ScalableVar = DecompGEP1.VarIndices[0];
1214ac9a064cSDimitry Andric     APInt Scale =
1215ac9a064cSDimitry Andric         ScalableVar.IsNegated ? -ScalableVar.Scale : ScalableVar.Scale;
1216ac9a064cSDimitry Andric     LocationSize VLeftSize = Scale.isNegative() ? V1Size : V2Size;
1217ac9a064cSDimitry Andric 
1218ac9a064cSDimitry Andric     // Check if the offset is known to not overflow, if it does then attempt to
1219ac9a064cSDimitry Andric     // prove it with the known values of vscale_range.
1220ac9a064cSDimitry Andric     bool Overflows = !DecompGEP1.VarIndices[0].IsNSW;
1221ac9a064cSDimitry Andric     if (Overflows) {
1222ac9a064cSDimitry Andric       ConstantRange CR = getVScaleRange(&F, Scale.getBitWidth());
1223ac9a064cSDimitry Andric       (void)CR.getSignedMax().smul_ov(Scale, Overflows);
1224ac9a064cSDimitry Andric     }
1225ac9a064cSDimitry Andric 
1226ac9a064cSDimitry Andric     if (!Overflows) {
1227ac9a064cSDimitry Andric       // Note that we do not check that the typesize is scalable, as vscale >= 1
1228ac9a064cSDimitry Andric       // so noalias still holds so long as the dependency distance is at least
1229ac9a064cSDimitry Andric       // as big as the typesize.
1230ac9a064cSDimitry Andric       if (VLeftSize.hasValue() &&
1231ac9a064cSDimitry Andric           Scale.abs().uge(VLeftSize.getValue().getKnownMinValue()))
1232ac9a064cSDimitry Andric         return AliasResult::NoAlias;
1233ac9a064cSDimitry Andric     }
1234ac9a064cSDimitry Andric   }
1235ac9a064cSDimitry Andric 
1236ac9a064cSDimitry Andric   // Bail on analysing scalable LocationSize
1237ac9a064cSDimitry Andric   if (V1Size.isScalable() || V2Size.isScalable())
1238ac9a064cSDimitry Andric     return AliasResult::MayAlias;
1239cf099d11SDimitry Andric 
1240c0981da4SDimitry Andric   // We need to know both acess sizes for all the following heuristics.
1241c0981da4SDimitry Andric   if (!V1Size.hasValue() || !V2Size.hasValue())
1242c0981da4SDimitry Andric     return AliasResult::MayAlias;
1243c0981da4SDimitry Andric 
1244b60736ecSDimitry Andric   APInt GCD;
1245c0981da4SDimitry Andric   ConstantRange OffsetRange = ConstantRange(DecompGEP1.Offset);
124601095a5dSDimitry Andric   for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
1247c0981da4SDimitry Andric     const VariableGEPIndex &Index = DecompGEP1.VarIndices[i];
1248c0981da4SDimitry Andric     const APInt &Scale = Index.Scale;
1249c0981da4SDimitry Andric     APInt ScaleForGCD = Scale;
1250c0981da4SDimitry Andric     if (!Index.IsNSW)
12517fa27ce4SDimitry Andric       ScaleForGCD =
12527fa27ce4SDimitry Andric           APInt::getOneBitSet(Scale.getBitWidth(), Scale.countr_zero());
1253344a3780SDimitry Andric 
1254b60736ecSDimitry Andric     if (i == 0)
1255344a3780SDimitry Andric       GCD = ScaleForGCD.abs();
1256b60736ecSDimitry Andric     else
1257344a3780SDimitry Andric       GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs());
1258dd58ef01SDimitry Andric 
12596f8fc217SDimitry Andric     ConstantRange CR = computeConstantRange(Index.Val.V, /* ForSigned */ false,
12606f8fc217SDimitry Andric                                             true, &AC, Index.CxtI);
1261c0981da4SDimitry Andric     KnownBits Known =
1262c0981da4SDimitry Andric         computeKnownBits(Index.Val.V, DL, 0, &AC, Index.CxtI, DT);
1263c0981da4SDimitry Andric     CR = CR.intersectWith(
1264c0981da4SDimitry Andric         ConstantRange::fromKnownBits(Known, /* Signed */ true),
1265c0981da4SDimitry Andric         ConstantRange::Signed);
1266c0981da4SDimitry Andric     CR = Index.Val.evaluateWith(CR).sextOrTrunc(OffsetRange.getBitWidth());
1267dd58ef01SDimitry Andric 
1268c0981da4SDimitry Andric     assert(OffsetRange.getBitWidth() == Scale.getBitWidth() &&
1269c0981da4SDimitry Andric            "Bit widths are normalized to MaxIndexSize");
1270c0981da4SDimitry Andric     if (Index.IsNSW)
12717fa27ce4SDimitry Andric       CR = CR.smul_sat(ConstantRange(Scale));
1272c0981da4SDimitry Andric     else
12737fa27ce4SDimitry Andric       CR = CR.smul_fast(ConstantRange(Scale));
12747fa27ce4SDimitry Andric 
12757fa27ce4SDimitry Andric     if (Index.IsNegated)
12767fa27ce4SDimitry Andric       OffsetRange = OffsetRange.sub(CR);
12777fa27ce4SDimitry Andric     else
12787fa27ce4SDimitry Andric       OffsetRange = OffsetRange.add(CR);
1279dd58ef01SDimitry Andric   }
1280dd58ef01SDimitry Andric 
1281b60736ecSDimitry Andric   // We now have accesses at two offsets from the same base:
1282b60736ecSDimitry Andric   //  1. (...)*GCD + DecompGEP1.Offset with size V1Size
1283b60736ecSDimitry Andric   //  2. 0 with size V2Size
1284b60736ecSDimitry Andric   // Using arithmetic modulo GCD, the accesses are at
1285b60736ecSDimitry Andric   // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits
1286b60736ecSDimitry Andric   // into the range [V2Size..GCD), then we know they cannot overlap.
1287b60736ecSDimitry Andric   APInt ModOffset = DecompGEP1.Offset.srem(GCD);
1288b60736ecSDimitry Andric   if (ModOffset.isNegative())
1289b60736ecSDimitry Andric     ModOffset += GCD; // We want mod, not rem.
1290c0981da4SDimitry Andric   if (ModOffset.uge(V2Size.getValue()) &&
1291b60736ecSDimitry Andric       (GCD - ModOffset).uge(V1Size.getValue()))
1292344a3780SDimitry Andric     return AliasResult::NoAlias;
1293dd58ef01SDimitry Andric 
1294c0981da4SDimitry Andric   // Compute ranges of potentially accessed bytes for both accesses. If the
1295c0981da4SDimitry Andric   // interseciton is empty, there can be no overlap.
1296c0981da4SDimitry Andric   unsigned BW = OffsetRange.getBitWidth();
1297c0981da4SDimitry Andric   ConstantRange Range1 = OffsetRange.add(
1298c0981da4SDimitry Andric       ConstantRange(APInt(BW, 0), APInt(BW, V1Size.getValue())));
1299c0981da4SDimitry Andric   ConstantRange Range2 =
1300c0981da4SDimitry Andric       ConstantRange(APInt(BW, 0), APInt(BW, V2Size.getValue()));
1301c0981da4SDimitry Andric   if (Range1.intersectWith(Range2).isEmptySet())
1302344a3780SDimitry Andric     return AliasResult::NoAlias;
1303b60736ecSDimitry Andric 
1304c0981da4SDimitry Andric   // Try to determine the range of values for VarIndex such that
1305c0981da4SDimitry Andric   // VarIndex <= -MinAbsVarIndex || MinAbsVarIndex <= VarIndex.
1306e3b55780SDimitry Andric   std::optional<APInt> MinAbsVarIndex;
1307b60736ecSDimitry Andric   if (DecompGEP1.VarIndices.size() == 1) {
1308c0981da4SDimitry Andric     // VarIndex = Scale*V.
1309b60736ecSDimitry Andric     const VariableGEPIndex &Var = DecompGEP1.VarIndices[0];
1310c0981da4SDimitry Andric     if (Var.Val.TruncBits == 0 &&
1311ac9a064cSDimitry Andric         isKnownNonZero(Var.Val.V, SimplifyQuery(DL, DT, &AC, Var.CxtI))) {
1312145449b1SDimitry Andric       // Check if abs(V*Scale) >= abs(Scale) holds in the presence of
1313145449b1SDimitry Andric       // potentially wrapping math.
1314145449b1SDimitry Andric       auto MultiplyByScaleNoWrap = [](const VariableGEPIndex &Var) {
1315145449b1SDimitry Andric         if (Var.IsNSW)
1316145449b1SDimitry Andric           return true;
1317145449b1SDimitry Andric 
1318145449b1SDimitry Andric         int ValOrigBW = Var.Val.V->getType()->getPrimitiveSizeInBits();
1319145449b1SDimitry Andric         // If Scale is small enough so that abs(V*Scale) >= abs(Scale) holds.
1320145449b1SDimitry Andric         // The max value of abs(V) is 2^ValOrigBW - 1. Multiplying with a
1321145449b1SDimitry Andric         // constant smaller than 2^(bitwidth(Val) - ValOrigBW) won't wrap.
1322145449b1SDimitry Andric         int MaxScaleValueBW = Var.Val.getBitWidth() - ValOrigBW;
1323145449b1SDimitry Andric         if (MaxScaleValueBW <= 0)
1324145449b1SDimitry Andric           return false;
1325145449b1SDimitry Andric         return Var.Scale.ule(
1326145449b1SDimitry Andric             APInt::getMaxValue(MaxScaleValueBW).zext(Var.Scale.getBitWidth()));
1327145449b1SDimitry Andric       };
1328145449b1SDimitry Andric       // Refine MinAbsVarIndex, if abs(Scale*V) >= abs(Scale) holds in the
1329145449b1SDimitry Andric       // presence of potentially wrapping math.
1330145449b1SDimitry Andric       if (MultiplyByScaleNoWrap(Var)) {
1331c0981da4SDimitry Andric         // If V != 0 then abs(VarIndex) >= abs(Scale).
1332b60736ecSDimitry Andric         MinAbsVarIndex = Var.Scale.abs();
1333c0981da4SDimitry Andric       }
1334145449b1SDimitry Andric     }
1335b60736ecSDimitry Andric   } else if (DecompGEP1.VarIndices.size() == 2) {
1336b60736ecSDimitry Andric     // VarIndex = Scale*V0 + (-Scale)*V1.
1337b60736ecSDimitry Andric     // If V0 != V1 then abs(VarIndex) >= abs(Scale).
1338e3b55780SDimitry Andric     // Check that MayBeCrossIteration is false, to avoid reasoning about
1339b60736ecSDimitry Andric     // inequality of values across loop iterations.
1340b60736ecSDimitry Andric     const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0];
1341b60736ecSDimitry Andric     const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1];
13427fa27ce4SDimitry Andric     if (Var0.hasNegatedScaleOf(Var1) && Var0.Val.TruncBits == 0 &&
1343e3b55780SDimitry Andric         Var0.Val.hasSameCastsAs(Var1.Val) && !AAQI.MayBeCrossIteration &&
1344c0981da4SDimitry Andric         isKnownNonEqual(Var0.Val.V, Var1.Val.V, DL, &AC, /* CxtI */ nullptr,
1345c0981da4SDimitry Andric                         DT))
1346b60736ecSDimitry Andric       MinAbsVarIndex = Var0.Scale.abs();
1347b60736ecSDimitry Andric   }
1348b60736ecSDimitry Andric 
1349b60736ecSDimitry Andric   if (MinAbsVarIndex) {
1350b60736ecSDimitry Andric     // The constant offset will have added at least +/-MinAbsVarIndex to it.
1351b60736ecSDimitry Andric     APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex;
1352b60736ecSDimitry Andric     APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex;
1353c0981da4SDimitry Andric     // We know that Offset <= OffsetLo || Offset >= OffsetHi
1354b60736ecSDimitry Andric     if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) &&
1355b60736ecSDimitry Andric         OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue()))
1356344a3780SDimitry Andric       return AliasResult::NoAlias;
1357b60736ecSDimitry Andric   }
1358dd58ef01SDimitry Andric 
1359e3b55780SDimitry Andric   if (constantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT, AAQI))
1360344a3780SDimitry Andric     return AliasResult::NoAlias;
136159850d08SRoman Divacky 
136256fe8f14SDimitry Andric   // Statically, we can see that the base objects are the same, but the
136356fe8f14SDimitry Andric   // pointers have dynamic offsets which we can't resolve. And none of our
136456fe8f14SDimitry Andric   // little tricks above worked.
1365344a3780SDimitry Andric   return AliasResult::MayAlias;
136656fe8f14SDimitry Andric }
136756fe8f14SDimitry Andric 
MergeAliasResults(AliasResult A,AliasResult B)13681a82d4c0SDimitry Andric static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
136956fe8f14SDimitry Andric   // If the results agree, take it.
137056fe8f14SDimitry Andric   if (A == B)
137156fe8f14SDimitry Andric     return A;
137256fe8f14SDimitry Andric   // A mix of PartialAlias and MustAlias is PartialAlias.
1373344a3780SDimitry Andric   if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) ||
1374344a3780SDimitry Andric       (B == AliasResult::PartialAlias && A == AliasResult::MustAlias))
1375344a3780SDimitry Andric     return AliasResult::PartialAlias;
137656fe8f14SDimitry Andric   // Otherwise, we don't know anything.
1377344a3780SDimitry Andric   return AliasResult::MayAlias;
1378009b1c42SEd Schouten }
137959850d08SRoman Divacky 
1380dd58ef01SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
1381dd58ef01SDimitry Andric /// against another.
1382e6d15924SDimitry Andric AliasResult
aliasSelect(const SelectInst * SI,LocationSize SISize,const Value * V2,LocationSize V2Size,AAQueryInfo & AAQI)1383e6d15924SDimitry Andric BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,
1384344a3780SDimitry Andric                            const Value *V2, LocationSize V2Size,
1385b60736ecSDimitry Andric                            AAQueryInfo &AAQI) {
138636bf506aSRoman Divacky   // If the values are Selects with the same condition, we can do a more precise
138736bf506aSRoman Divacky   // check: just check for aliases between the values on corresponding arms.
138836bf506aSRoman Divacky   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1389e3b55780SDimitry Andric     if (isValueEqualInPotentialCycles(SI->getCondition(), SI2->getCondition(),
1390e3b55780SDimitry Andric                                       AAQI)) {
1391e3b55780SDimitry Andric       AliasResult Alias =
1392e3b55780SDimitry Andric           AAQI.AAR.alias(MemoryLocation(SI->getTrueValue(), SISize),
1393344a3780SDimitry Andric                          MemoryLocation(SI2->getTrueValue(), V2Size), AAQI);
1394344a3780SDimitry Andric       if (Alias == AliasResult::MayAlias)
1395344a3780SDimitry Andric         return AliasResult::MayAlias;
1396e3b55780SDimitry Andric       AliasResult ThisAlias =
1397e3b55780SDimitry Andric           AAQI.AAR.alias(MemoryLocation(SI->getFalseValue(), SISize),
1398344a3780SDimitry Andric                          MemoryLocation(SI2->getFalseValue(), V2Size), AAQI);
139956fe8f14SDimitry Andric       return MergeAliasResults(ThisAlias, Alias);
140036bf506aSRoman Divacky     }
140136bf506aSRoman Divacky 
140236bf506aSRoman Divacky   // If both arms of the Select node NoAlias or MustAlias V2, then returns
140336bf506aSRoman Divacky   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1404e3b55780SDimitry Andric   AliasResult Alias = AAQI.AAR.alias(MemoryLocation(SI->getTrueValue(), SISize),
1405145449b1SDimitry Andric                                      MemoryLocation(V2, V2Size), AAQI);
1406344a3780SDimitry Andric   if (Alias == AliasResult::MayAlias)
1407344a3780SDimitry Andric     return AliasResult::MayAlias;
140866e41e3cSRoman Divacky 
1409145449b1SDimitry Andric   AliasResult ThisAlias =
1410e3b55780SDimitry Andric       AAQI.AAR.alias(MemoryLocation(SI->getFalseValue(), SISize),
1411145449b1SDimitry Andric                      MemoryLocation(V2, V2Size), AAQI);
141256fe8f14SDimitry Andric   return MergeAliasResults(ThisAlias, Alias);
141336bf506aSRoman Divacky }
141436bf506aSRoman Divacky 
1415dd58ef01SDimitry Andric /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
1416dd58ef01SDimitry Andric /// another.
aliasPHI(const PHINode * PN,LocationSize PNSize,const Value * V2,LocationSize V2Size,AAQueryInfo & AAQI)1417eb11fae6SDimitry Andric AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
1418344a3780SDimitry Andric                                     const Value *V2, LocationSize V2Size,
1419b60736ecSDimitry Andric                                     AAQueryInfo &AAQI) {
1420344a3780SDimitry Andric   if (!PN->getNumIncomingValues())
1421344a3780SDimitry Andric     return AliasResult::NoAlias;
142236bf506aSRoman Divacky   // If the values are PHIs in the same block, we can do a more precise
142336bf506aSRoman Divacky   // as well as efficient check: just check for aliases between the values
142436bf506aSRoman Divacky   // on corresponding edges.
142536bf506aSRoman Divacky   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
142636bf506aSRoman Divacky     if (PN2->getParent() == PN->getParent()) {
1427e3b55780SDimitry Andric       std::optional<AliasResult> Alias;
14284a16efa3SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1429e3b55780SDimitry Andric         AliasResult ThisAlias = AAQI.AAR.alias(
1430344a3780SDimitry Andric             MemoryLocation(PN->getIncomingValue(i), PNSize),
1431b60736ecSDimitry Andric             MemoryLocation(
1432344a3780SDimitry Andric                 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size),
1433b60736ecSDimitry Andric             AAQI);
1434b60736ecSDimitry Andric         if (Alias)
1435b60736ecSDimitry Andric           *Alias = MergeAliasResults(*Alias, ThisAlias);
1436b60736ecSDimitry Andric         else
1437b60736ecSDimitry Andric           Alias = ThisAlias;
1438344a3780SDimitry Andric         if (*Alias == AliasResult::MayAlias)
143956fe8f14SDimitry Andric           break;
144036bf506aSRoman Divacky       }
1441b60736ecSDimitry Andric       return *Alias;
144236bf506aSRoman Divacky     }
144336bf506aSRoman Divacky 
144459850d08SRoman Divacky   SmallVector<Value *, 4> V1Srcs;
1445b60736ecSDimitry Andric   // If a phi operand recurses back to the phi, we can still determine NoAlias
1446b60736ecSDimitry Andric   // if we don't alias the underlying objects of the other phi operands, as we
1447b60736ecSDimitry Andric   // know that the recursive phi needs to be based on them in some way.
1448dd58ef01SDimitry Andric   bool isRecursive = false;
1449b60736ecSDimitry Andric   auto CheckForRecPhi = [&](Value *PV) {
1450b60736ecSDimitry Andric     if (!EnableRecPhiAnalysis)
1451b60736ecSDimitry Andric       return false;
1452b60736ecSDimitry Andric     if (getUnderlyingObject(PV) == PN) {
1453b60736ecSDimitry Andric       isRecursive = true;
1454b60736ecSDimitry Andric       return true;
1455b60736ecSDimitry Andric     }
1456b60736ecSDimitry Andric     return false;
1457b60736ecSDimitry Andric   };
1458b60736ecSDimitry Andric 
1459b7eb8e35SDimitry Andric   SmallPtrSet<Value *, 4> UniqueSrc;
1460344a3780SDimitry Andric   Value *OnePhi = nullptr;
14615a5ac124SDimitry Andric   for (Value *PV1 : PN->incoming_values()) {
1462e3b55780SDimitry Andric     // Skip the phi itself being the incoming value.
1463e3b55780SDimitry Andric     if (PV1 == PN)
1464e3b55780SDimitry Andric       continue;
1465e3b55780SDimitry Andric 
1466344a3780SDimitry Andric     if (isa<PHINode>(PV1)) {
1467344a3780SDimitry Andric       if (OnePhi && OnePhi != PV1) {
1468344a3780SDimitry Andric         // To control potential compile time explosion, we choose to be
1469344a3780SDimitry Andric         // conserviate when we have more than one Phi input.  It is important
1470344a3780SDimitry Andric         // that we handle the single phi case as that lets us handle LCSSA
1471344a3780SDimitry Andric         // phi nodes and (combined with the recursive phi handling) simple
1472344a3780SDimitry Andric         // pointer induction variable patterns.
1473344a3780SDimitry Andric         return AliasResult::MayAlias;
1474344a3780SDimitry Andric       }
1475344a3780SDimitry Andric       OnePhi = PV1;
1476344a3780SDimitry Andric     }
1477dd58ef01SDimitry Andric 
1478b60736ecSDimitry Andric     if (CheckForRecPhi(PV1))
1479dd58ef01SDimitry Andric       continue;
1480dd58ef01SDimitry Andric 
148167c32a98SDimitry Andric     if (UniqueSrc.insert(PV1).second)
148259850d08SRoman Divacky       V1Srcs.push_back(PV1);
1483009b1c42SEd Schouten   }
1484344a3780SDimitry Andric 
1485344a3780SDimitry Andric   if (OnePhi && UniqueSrc.size() > 1)
1486344a3780SDimitry Andric     // Out of an abundance of caution, allow only the trivial lcssa and
1487344a3780SDimitry Andric     // recursive phi cases.
1488344a3780SDimitry Andric     return AliasResult::MayAlias;
1489b7eb8e35SDimitry Andric 
1490b7eb8e35SDimitry Andric   // If V1Srcs is empty then that means that the phi has no underlying non-phi
1491b7eb8e35SDimitry Andric   // value. This should only be possible in blocks unreachable from the entry
1492b7eb8e35SDimitry Andric   // block, but return MayAlias just in case.
1493b7eb8e35SDimitry Andric   if (V1Srcs.empty())
1494344a3780SDimitry Andric     return AliasResult::MayAlias;
1495009b1c42SEd Schouten 
1496b60736ecSDimitry Andric   // If this PHI node is recursive, indicate that the pointer may be moved
1497b60736ecSDimitry Andric   // across iterations. We can only prove NoAlias if different underlying
1498b60736ecSDimitry Andric   // objects are involved.
1499dd58ef01SDimitry Andric   if (isRecursive)
1500b60736ecSDimitry Andric     PNSize = LocationSize::beforeOrAfterPointer();
1501dd58ef01SDimitry Andric 
1502b60736ecSDimitry Andric   // In the recursive alias queries below, we may compare values from two
1503e3b55780SDimitry Andric   // different loop iterations.
1504e3b55780SDimitry Andric   SaveAndRestore SavedMayBeCrossIteration(AAQI.MayBeCrossIteration, true);
1505b60736ecSDimitry Andric 
1506e3b55780SDimitry Andric   AliasResult Alias = AAQI.AAR.alias(MemoryLocation(V1Srcs[0], PNSize),
1507e3b55780SDimitry Andric                                      MemoryLocation(V2, V2Size), AAQI);
1508dd58ef01SDimitry Andric 
150959850d08SRoman Divacky   // Early exit if the check of the first PHI source against V2 is MayAlias.
151059850d08SRoman Divacky   // Other results are not possible.
1511344a3780SDimitry Andric   if (Alias == AliasResult::MayAlias)
1512344a3780SDimitry Andric     return AliasResult::MayAlias;
1513cfca06d7SDimitry Andric   // With recursive phis we cannot guarantee that MustAlias/PartialAlias will
1514cfca06d7SDimitry Andric   // remain valid to all elements and needs to conservatively return MayAlias.
1515344a3780SDimitry Andric   if (isRecursive && Alias != AliasResult::NoAlias)
1516344a3780SDimitry Andric     return AliasResult::MayAlias;
151759850d08SRoman Divacky 
151859850d08SRoman Divacky   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
151959850d08SRoman Divacky   // NoAlias / MustAlias. Otherwise, returns MayAlias.
152059850d08SRoman Divacky   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
152159850d08SRoman Divacky     Value *V = V1Srcs[i];
152236bf506aSRoman Divacky 
1523e3b55780SDimitry Andric     AliasResult ThisAlias = AAQI.AAR.alias(
1524e3b55780SDimitry Andric         MemoryLocation(V, PNSize), MemoryLocation(V2, V2Size), AAQI);
152556fe8f14SDimitry Andric     Alias = MergeAliasResults(ThisAlias, Alias);
1526344a3780SDimitry Andric     if (Alias == AliasResult::MayAlias)
152756fe8f14SDimitry Andric       break;
152859850d08SRoman Divacky   }
152959850d08SRoman Divacky 
153059850d08SRoman Divacky   return Alias;
153159850d08SRoman Divacky }
153259850d08SRoman Divacky 
1533dd58ef01SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
1534dd58ef01SDimitry Andric /// array references.
aliasCheck(const Value * V1,LocationSize V1Size,const Value * V2,LocationSize V2Size,AAQueryInfo & AAQI,const Instruction * CtxI)1535eb11fae6SDimitry Andric AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
1536b60736ecSDimitry Andric                                       const Value *V2, LocationSize V2Size,
1537e3b55780SDimitry Andric                                       AAQueryInfo &AAQI,
1538e3b55780SDimitry Andric                                       const Instruction *CtxI) {
1539d7f7719eSRoman Divacky   // If either of the memory references is empty, it doesn't matter what the
1540d7f7719eSRoman Divacky   // pointer values are.
1541d8e91e46SDimitry Andric   if (V1Size.isZero() || V2Size.isZero())
1542344a3780SDimitry Andric     return AliasResult::NoAlias;
1543d7f7719eSRoman Divacky 
154459850d08SRoman Divacky   // Strip off any casts if they exist.
1545344a3780SDimitry Andric   V1 = V1->stripPointerCastsForAliasAnalysis();
1546344a3780SDimitry Andric   V2 = V2->stripPointerCastsForAliasAnalysis();
154759850d08SRoman Divacky 
15485a5ac124SDimitry Andric   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
15495a5ac124SDimitry Andric   // value for undef that aliases nothing in the program.
15505a5ac124SDimitry Andric   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1551344a3780SDimitry Andric     return AliasResult::NoAlias;
15525a5ac124SDimitry Andric 
155359850d08SRoman Divacky   // Are we checking for alias of the same value?
155401095a5dSDimitry Andric   // Because we look 'through' phi nodes, we could look at "Value" pointers from
155568bcb7dbSDimitry Andric   // different iterations. We must therefore make sure that this is not the
155668bcb7dbSDimitry Andric   // case. The function isValueEqualInPotentialCycles ensures that this cannot
155768bcb7dbSDimitry Andric   // happen by looking at the visited phi nodes and making sure they cannot
155868bcb7dbSDimitry Andric   // reach the value.
1559e3b55780SDimitry Andric   if (isValueEqualInPotentialCycles(V1, V2, AAQI))
1560344a3780SDimitry Andric     return AliasResult::MustAlias;
156159850d08SRoman Divacky 
156267a71b31SRoman Divacky   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1563344a3780SDimitry Andric     return AliasResult::NoAlias; // Scalars cannot alias each other
156459850d08SRoman Divacky 
156559850d08SRoman Divacky   // Figure out what objects these things are pointing to if we can.
1566b60736ecSDimitry Andric   const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth);
1567b60736ecSDimitry Andric   const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth);
156859850d08SRoman Divacky 
1569907da171SRoman Divacky   // Null values in the default address space don't point to any object, so they
1570907da171SRoman Divacky   // don't alias any other pointer.
1571907da171SRoman Divacky   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1572eb11fae6SDimitry Andric     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1573344a3780SDimitry Andric       return AliasResult::NoAlias;
1574907da171SRoman Divacky   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1575eb11fae6SDimitry Andric     if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1576344a3780SDimitry Andric       return AliasResult::NoAlias;
1577907da171SRoman Divacky 
157859850d08SRoman Divacky   if (O1 != O2) {
157901095a5dSDimitry Andric     // If V1/V2 point to two different objects, we know that we have no alias.
158059850d08SRoman Divacky     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1581344a3780SDimitry Andric       return AliasResult::NoAlias;
158259850d08SRoman Divacky 
1583f8af5cf6SDimitry Andric     // Function arguments can't alias with things that are known to be
1584f8af5cf6SDimitry Andric     // unambigously identified at the function level.
1585f8af5cf6SDimitry Andric     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1586f8af5cf6SDimitry Andric         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1587344a3780SDimitry Andric       return AliasResult::NoAlias;
158859850d08SRoman Divacky 
158966e41e3cSRoman Divacky     // If one pointer is the result of a call/invoke or load and the other is a
159066e41e3cSRoman Divacky     // non-escaping local object within the same function, then we know the
159166e41e3cSRoman Divacky     // object couldn't escape to a point where the call could return it.
159266e41e3cSRoman Divacky     //
159366e41e3cSRoman Divacky     // Note that if the pointers are in different functions, there are a
159466e41e3cSRoman Divacky     // variety of complications. A call with a nocapture argument may still
159566e41e3cSRoman Divacky     // temporary store the nocapture argument's value in a temporary memory
159666e41e3cSRoman Divacky     // location if that memory location doesn't escape. Or it may pass a
159766e41e3cSRoman Divacky     // nocapture value to other functions as long as they don't capture it.
15984df029ccSDimitry Andric     if (isEscapeSource(O1) && AAQI.CI->isNotCapturedBefore(
15994df029ccSDimitry Andric                                   O2, dyn_cast<Instruction>(O1), /*OrAt*/ true))
1600344a3780SDimitry Andric       return AliasResult::NoAlias;
16014df029ccSDimitry Andric     if (isEscapeSource(O2) && AAQI.CI->isNotCapturedBefore(
16024df029ccSDimitry Andric                                   O1, dyn_cast<Instruction>(O2), /*OrAt*/ true))
1603344a3780SDimitry Andric       return AliasResult::NoAlias;
160459850d08SRoman Divacky   }
160559850d08SRoman Divacky 
160659850d08SRoman Divacky   // If the size of one access is larger than the entire object on the other
160759850d08SRoman Divacky   // side, then we know such behavior is undefined and can assume no alias.
1608eb11fae6SDimitry Andric   bool NullIsValidLocation = NullPointerIsDefined(&F);
16091d5ae102SDimitry Andric   if ((isObjectSmallerThan(
16101d5ae102SDimitry Andric           O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL,
16111d5ae102SDimitry Andric           TLI, NullIsValidLocation)) ||
16121d5ae102SDimitry Andric       (isObjectSmallerThan(
16131d5ae102SDimitry Andric           O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL,
16141d5ae102SDimitry Andric           TLI, NullIsValidLocation)))
1615344a3780SDimitry Andric     return AliasResult::NoAlias;
161659850d08SRoman Divacky 
1617aca2e42cSDimitry Andric   if (EnableSeparateStorageAnalysis) {
1618aca2e42cSDimitry Andric     for (AssumptionCache::ResultElem &Elem : AC.assumptionsFor(O1)) {
1619aca2e42cSDimitry Andric       if (!Elem || Elem.Index == AssumptionCache::ExprResultIdx)
1620e3b55780SDimitry Andric         continue;
1621e3b55780SDimitry Andric 
1622aca2e42cSDimitry Andric       AssumeInst *Assume = cast<AssumeInst>(Elem);
1623aca2e42cSDimitry Andric       OperandBundleUse OBU = Assume->getOperandBundleAt(Elem.Index);
1624e3b55780SDimitry Andric       if (OBU.getTagName() == "separate_storage") {
1625e3b55780SDimitry Andric         assert(OBU.Inputs.size() == 2);
1626e3b55780SDimitry Andric         const Value *Hint1 = OBU.Inputs[0].get();
1627e3b55780SDimitry Andric         const Value *Hint2 = OBU.Inputs[1].get();
16287fa27ce4SDimitry Andric         // This is often a no-op; instcombine rewrites this for us. No-op
16297fa27ce4SDimitry Andric         // getUnderlyingObject calls are fast, though.
1630e3b55780SDimitry Andric         const Value *HintO1 = getUnderlyingObject(Hint1);
1631e3b55780SDimitry Andric         const Value *HintO2 = getUnderlyingObject(Hint2);
1632e3b55780SDimitry Andric 
1633ac9a064cSDimitry Andric         DominatorTree *DT = getDT(AAQI);
1634aca2e42cSDimitry Andric         auto ValidAssumeForPtrContext = [&](const Value *Ptr) {
1635aca2e42cSDimitry Andric           if (const Instruction *PtrI = dyn_cast<Instruction>(Ptr)) {
1636aca2e42cSDimitry Andric             return isValidAssumeForContext(Assume, PtrI, DT,
1637aca2e42cSDimitry Andric                                            /* AllowEphemerals */ true);
1638aca2e42cSDimitry Andric           }
1639aca2e42cSDimitry Andric           if (const Argument *PtrA = dyn_cast<Argument>(Ptr)) {
1640aca2e42cSDimitry Andric             const Instruction *FirstI =
1641aca2e42cSDimitry Andric                 &*PtrA->getParent()->getEntryBlock().begin();
1642aca2e42cSDimitry Andric             return isValidAssumeForContext(Assume, FirstI, DT,
1643aca2e42cSDimitry Andric                                            /* AllowEphemerals */ true);
1644aca2e42cSDimitry Andric           }
1645aca2e42cSDimitry Andric           return false;
1646aca2e42cSDimitry Andric         };
1647aca2e42cSDimitry Andric 
1648aca2e42cSDimitry Andric         if ((O1 == HintO1 && O2 == HintO2) || (O1 == HintO2 && O2 == HintO1)) {
1649aca2e42cSDimitry Andric           // Note that we go back to V1 and V2 for the
1650aca2e42cSDimitry Andric           // ValidAssumeForPtrContext checks; they're dominated by O1 and O2,
1651aca2e42cSDimitry Andric           // so strictly more assumptions are valid for them.
1652aca2e42cSDimitry Andric           if ((CtxI && isValidAssumeForContext(Assume, CtxI, DT,
1653aca2e42cSDimitry Andric                                                /* AllowEphemerals */ true)) ||
1654aca2e42cSDimitry Andric               ValidAssumeForPtrContext(V1) || ValidAssumeForPtrContext(V2)) {
1655e3b55780SDimitry Andric             return AliasResult::NoAlias;
1656e3b55780SDimitry Andric           }
1657e3b55780SDimitry Andric         }
1658e3b55780SDimitry Andric       }
1659e3b55780SDimitry Andric     }
1660aca2e42cSDimitry Andric   }
1661e3b55780SDimitry Andric 
1662b60736ecSDimitry Andric   // If one the accesses may be before the accessed pointer, canonicalize this
1663b60736ecSDimitry Andric   // by using unknown after-pointer sizes for both accesses. This is
1664b60736ecSDimitry Andric   // equivalent, because regardless of which pointer is lower, one of them
1665b60736ecSDimitry Andric   // will always came after the other, as long as the underlying objects aren't
1666b60736ecSDimitry Andric   // disjoint. We do this so that the rest of BasicAA does not have to deal
1667b60736ecSDimitry Andric   // with accesses before the base pointer, and to improve cache utilization by
1668b60736ecSDimitry Andric   // merging equivalent states.
1669b60736ecSDimitry Andric   if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) {
1670b60736ecSDimitry Andric     V1Size = LocationSize::afterPointer();
1671b60736ecSDimitry Andric     V2Size = LocationSize::afterPointer();
1672b60736ecSDimitry Andric   }
1673b60736ecSDimitry Andric 
1674344a3780SDimitry Andric   // FIXME: If this depth limit is hit, then we may cache sub-optimal results
1675344a3780SDimitry Andric   // for recursive queries. For this reason, this limit is chosen to be large
1676344a3780SDimitry Andric   // enough to be very rarely hit, while still being small enough to avoid
1677344a3780SDimitry Andric   // stack overflows.
1678344a3780SDimitry Andric   if (AAQI.Depth >= 512)
1679344a3780SDimitry Andric     return AliasResult::MayAlias;
1680344a3780SDimitry Andric 
168156fe8f14SDimitry Andric   // Check the cache before climbing up use-def chains. This also terminates
1682e3b55780SDimitry Andric   // otherwise infinitely recursive queries. Include MayBeCrossIteration in the
1683e3b55780SDimitry Andric   // cache key, because some cases where MayBeCrossIteration==false returns
1684e3b55780SDimitry Andric   // MustAlias or NoAlias may become MayAlias under MayBeCrossIteration==true.
1685e3b55780SDimitry Andric   AAQueryInfo::LocPair Locs({V1, V1Size, AAQI.MayBeCrossIteration},
1686e3b55780SDimitry Andric                             {V2, V2Size, AAQI.MayBeCrossIteration});
1687344a3780SDimitry Andric   const bool Swapped = V1 > V2;
1688344a3780SDimitry Andric   if (Swapped)
168956fe8f14SDimitry Andric     std::swap(Locs.first, Locs.second);
1690b60736ecSDimitry Andric   const auto &Pair = AAQI.AliasCache.try_emplace(
1691344a3780SDimitry Andric       Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0});
1692b60736ecSDimitry Andric   if (!Pair.second) {
1693b60736ecSDimitry Andric     auto &Entry = Pair.first->second;
1694b60736ecSDimitry Andric     if (!Entry.isDefinitive()) {
1695c76260f3SDimitry Andric       // Remember that we used an assumption. This may either be a direct use
1696c76260f3SDimitry Andric       // of an assumption, or a use of an entry that may itself be based on an
1697c76260f3SDimitry Andric       // assumption.
1698b60736ecSDimitry Andric       ++AAQI.NumAssumptionUses;
1699c76260f3SDimitry Andric       if (Entry.isAssumption())
1700c76260f3SDimitry Andric         ++Entry.NumAssumptionUses;
170159850d08SRoman Divacky     }
1702344a3780SDimitry Andric     // Cache contains sorted {V1,V2} pairs but we should return original order.
1703344a3780SDimitry Andric     auto Result = Entry.Result;
1704344a3780SDimitry Andric     Result.swap(Swapped);
1705344a3780SDimitry Andric     return Result;
1706b60736ecSDimitry Andric   }
1707b60736ecSDimitry Andric 
1708b60736ecSDimitry Andric   int OrigNumAssumptionUses = AAQI.NumAssumptionUses;
1709b60736ecSDimitry Andric   unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size();
1710344a3780SDimitry Andric   AliasResult Result =
1711344a3780SDimitry Andric       aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2);
1712b60736ecSDimitry Andric 
1713b60736ecSDimitry Andric   auto It = AAQI.AliasCache.find(Locs);
1714b60736ecSDimitry Andric   assert(It != AAQI.AliasCache.end() && "Must be in cache");
1715b60736ecSDimitry Andric   auto &Entry = It->second;
1716b60736ecSDimitry Andric 
1717b60736ecSDimitry Andric   // Check whether a NoAlias assumption has been used, but disproven.
1718344a3780SDimitry Andric   bool AssumptionDisproven =
1719344a3780SDimitry Andric       Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias;
1720b60736ecSDimitry Andric   if (AssumptionDisproven)
1721344a3780SDimitry Andric     Result = AliasResult::MayAlias;
1722b60736ecSDimitry Andric 
1723b60736ecSDimitry Andric   // This is a definitive result now, when considered as a root query.
1724b60736ecSDimitry Andric   AAQI.NumAssumptionUses -= Entry.NumAssumptionUses;
1725b60736ecSDimitry Andric   Entry.Result = Result;
1726344a3780SDimitry Andric   // Cache contains sorted {V1,V2} pairs.
1727344a3780SDimitry Andric   Entry.Result.swap(Swapped);
1728b60736ecSDimitry Andric 
1729b60736ecSDimitry Andric   // If the assumption has been disproven, remove any results that may have
1730b60736ecSDimitry Andric   // been based on this assumption. Do this after the Entry updates above to
1731b60736ecSDimitry Andric   // avoid iterator invalidation.
1732b60736ecSDimitry Andric   if (AssumptionDisproven)
1733b60736ecSDimitry Andric     while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults)
1734b60736ecSDimitry Andric       AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val());
1735b60736ecSDimitry Andric 
1736b60736ecSDimitry Andric   // The result may still be based on assumptions higher up in the chain.
1737b60736ecSDimitry Andric   // Remember it, so it can be purged from the cache later.
1738344a3780SDimitry Andric   if (OrigNumAssumptionUses != AAQI.NumAssumptionUses &&
1739c76260f3SDimitry Andric       Result != AliasResult::MayAlias) {
1740b60736ecSDimitry Andric     AAQI.AssumptionBasedResults.push_back(Locs);
1741c76260f3SDimitry Andric     Entry.NumAssumptionUses = AAQueryInfo::CacheEntry::AssumptionBased;
1742c76260f3SDimitry Andric   } else {
1743c76260f3SDimitry Andric     Entry.NumAssumptionUses = AAQueryInfo::CacheEntry::Definitive;
1744c76260f3SDimitry Andric   }
1745c76260f3SDimitry Andric 
1746c76260f3SDimitry Andric   // Depth is incremented before this function is called, so Depth==1 indicates
1747c76260f3SDimitry Andric   // a root query.
1748c76260f3SDimitry Andric   if (AAQI.Depth == 1) {
1749c76260f3SDimitry Andric     // Any remaining assumption based results must be based on proven
1750c76260f3SDimitry Andric     // assumptions, so convert them to definitive results.
1751c76260f3SDimitry Andric     for (const auto &Loc : AAQI.AssumptionBasedResults) {
1752c76260f3SDimitry Andric       auto It = AAQI.AliasCache.find(Loc);
1753c76260f3SDimitry Andric       if (It != AAQI.AliasCache.end())
1754c76260f3SDimitry Andric         It->second.NumAssumptionUses = AAQueryInfo::CacheEntry::Definitive;
1755c76260f3SDimitry Andric     }
1756c76260f3SDimitry Andric     AAQI.AssumptionBasedResults.clear();
1757c76260f3SDimitry Andric     AAQI.NumAssumptionUses = 0;
1758c76260f3SDimitry Andric   }
1759b60736ecSDimitry Andric   return Result;
1760b60736ecSDimitry Andric }
1761b60736ecSDimitry Andric 
aliasCheckRecursive(const Value * V1,LocationSize V1Size,const Value * V2,LocationSize V2Size,AAQueryInfo & AAQI,const Value * O1,const Value * O2)1762b60736ecSDimitry Andric AliasResult BasicAAResult::aliasCheckRecursive(
1763344a3780SDimitry Andric     const Value *V1, LocationSize V1Size,
1764344a3780SDimitry Andric     const Value *V2, LocationSize V2Size,
1765b60736ecSDimitry Andric     AAQueryInfo &AAQI, const Value *O1, const Value *O2) {
1766cf099d11SDimitry Andric   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1767344a3780SDimitry Andric     AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI);
1768344a3780SDimitry Andric     if (Result != AliasResult::MayAlias)
1769b60736ecSDimitry Andric       return Result;
1770b60736ecSDimitry Andric   } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) {
1771344a3780SDimitry Andric     AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI);
177277fc4c14SDimitry Andric     Result.swap();
1773344a3780SDimitry Andric     if (Result != AliasResult::MayAlias)
1774e6d15924SDimitry Andric       return Result;
1775e6d15924SDimitry Andric   }
177659850d08SRoman Divacky 
1777cf099d11SDimitry Andric   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1778344a3780SDimitry Andric     AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI);
1779344a3780SDimitry Andric     if (Result != AliasResult::MayAlias)
1780b60736ecSDimitry Andric       return Result;
1781b60736ecSDimitry Andric   } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) {
1782344a3780SDimitry Andric     AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI);
178377fc4c14SDimitry Andric     Result.swap();
1784344a3780SDimitry Andric     if (Result != AliasResult::MayAlias)
1785b60736ecSDimitry Andric       return Result;
1786cf099d11SDimitry Andric   }
178759850d08SRoman Divacky 
1788cf099d11SDimitry Andric   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1789344a3780SDimitry Andric     AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI);
1790344a3780SDimitry Andric     if (Result != AliasResult::MayAlias)
1791b60736ecSDimitry Andric       return Result;
1792b60736ecSDimitry Andric   } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) {
1793344a3780SDimitry Andric     AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI);
179477fc4c14SDimitry Andric     Result.swap();
1795344a3780SDimitry Andric     if (Result != AliasResult::MayAlias)
1796b60736ecSDimitry Andric       return Result;
1797009b1c42SEd Schouten   }
1798009b1c42SEd Schouten 
1799cf099d11SDimitry Andric   // If both pointers are pointing into the same object and one of them
180001095a5dSDimitry Andric   // accesses the entire object, then the accesses must overlap in some way.
1801b60736ecSDimitry Andric   if (O1 == O2) {
1802b60736ecSDimitry Andric     bool NullIsValidLocation = NullPointerIsDefined(&F);
1803d8e91e46SDimitry Andric     if (V1Size.isPrecise() && V2Size.isPrecise() &&
1804d8e91e46SDimitry Andric         (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||
1805b60736ecSDimitry Andric          isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation)))
1806344a3780SDimitry Andric       return AliasResult::PartialAlias;
1807e6d15924SDimitry Andric   }
1808cf099d11SDimitry Andric 
1809344a3780SDimitry Andric   return AliasResult::MayAlias;
1810cf099d11SDimitry Andric }
181168bcb7dbSDimitry Andric 
1812dd58ef01SDimitry Andric /// Check whether two Values can be considered equivalent.
1813dd58ef01SDimitry Andric ///
1814e3b55780SDimitry Andric /// If the values may come from different cycle iterations, this will also
1815e3b55780SDimitry Andric /// check that the values are not part of cycle. We have to do this because we
1816e3b55780SDimitry Andric /// are looking through phi nodes, that is we say
1817dd58ef01SDimitry Andric /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
isValueEqualInPotentialCycles(const Value * V,const Value * V2,const AAQueryInfo & AAQI)1818dd58ef01SDimitry Andric bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
1819e3b55780SDimitry Andric                                                   const Value *V2,
1820e3b55780SDimitry Andric                                                   const AAQueryInfo &AAQI) {
182168bcb7dbSDimitry Andric   if (V != V2)
182268bcb7dbSDimitry Andric     return false;
182368bcb7dbSDimitry Andric 
1824e3b55780SDimitry Andric   if (!AAQI.MayBeCrossIteration)
1825e3b55780SDimitry Andric     return true;
1826e3b55780SDimitry Andric 
1827e3b55780SDimitry Andric   // Non-instructions and instructions in the entry block cannot be part of
1828e3b55780SDimitry Andric   // a loop.
182968bcb7dbSDimitry Andric   const Instruction *Inst = dyn_cast<Instruction>(V);
1830e3b55780SDimitry Andric   if (!Inst || Inst->getParent()->isEntryBlock())
183168bcb7dbSDimitry Andric     return true;
183268bcb7dbSDimitry Andric 
1833ac9a064cSDimitry Andric   return isNotInCycle(Inst, getDT(AAQI), /*LI*/ nullptr);
183468bcb7dbSDimitry Andric }
183568bcb7dbSDimitry Andric 
1836dd58ef01SDimitry Andric /// Computes the symbolic difference between two de-composed GEPs.
subtractDecomposedGEPs(DecomposedGEP & DestGEP,const DecomposedGEP & SrcGEP,const AAQueryInfo & AAQI)1837c0981da4SDimitry Andric void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP,
1838e3b55780SDimitry Andric                                            const DecomposedGEP &SrcGEP,
1839e3b55780SDimitry Andric                                            const AAQueryInfo &AAQI) {
1840c0981da4SDimitry Andric   DestGEP.Offset -= SrcGEP.Offset;
1841c0981da4SDimitry Andric   for (const VariableGEPIndex &Src : SrcGEP.VarIndices) {
184268bcb7dbSDimitry Andric     // Find V in Dest.  This is N^2, but pointer indices almost never have more
184368bcb7dbSDimitry Andric     // than a few variable indexes.
1844c0981da4SDimitry Andric     bool Found = false;
1845c0981da4SDimitry Andric     for (auto I : enumerate(DestGEP.VarIndices)) {
1846c0981da4SDimitry Andric       VariableGEPIndex &Dest = I.value();
1847ac9a064cSDimitry Andric       if ((!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V, AAQI) &&
1848ac9a064cSDimitry Andric            !areBothVScale(Dest.Val.V, Src.Val.V)) ||
1849c0981da4SDimitry Andric           !Dest.Val.hasSameCastsAs(Src.Val))
185068bcb7dbSDimitry Andric         continue;
185168bcb7dbSDimitry Andric 
18527fa27ce4SDimitry Andric       // Normalize IsNegated if we're going to lose the NSW flag anyway.
18537fa27ce4SDimitry Andric       if (Dest.IsNegated) {
18547fa27ce4SDimitry Andric         Dest.Scale = -Dest.Scale;
18557fa27ce4SDimitry Andric         Dest.IsNegated = false;
18567fa27ce4SDimitry Andric         Dest.IsNSW = false;
18577fa27ce4SDimitry Andric       }
18587fa27ce4SDimitry Andric 
185968bcb7dbSDimitry Andric       // If we found it, subtract off Scale V's from the entry in Dest.  If it
186068bcb7dbSDimitry Andric       // goes to zero, remove the entry.
1861c0981da4SDimitry Andric       if (Dest.Scale != Src.Scale) {
1862c0981da4SDimitry Andric         Dest.Scale -= Src.Scale;
1863c0981da4SDimitry Andric         Dest.IsNSW = false;
1864c0981da4SDimitry Andric       } else {
1865c0981da4SDimitry Andric         DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index());
1866c0981da4SDimitry Andric       }
1867c0981da4SDimitry Andric       Found = true;
186868bcb7dbSDimitry Andric       break;
186968bcb7dbSDimitry Andric     }
187068bcb7dbSDimitry Andric 
187168bcb7dbSDimitry Andric     // If we didn't consume this entry, add it to the end of the Dest list.
1872c0981da4SDimitry Andric     if (!Found) {
18737fa27ce4SDimitry Andric       VariableGEPIndex Entry = {Src.Val, Src.Scale, Src.CxtI, Src.IsNSW,
18747fa27ce4SDimitry Andric                                 /* IsNegated */ true};
1875c0981da4SDimitry Andric       DestGEP.VarIndices.push_back(Entry);
187668bcb7dbSDimitry Andric     }
187768bcb7dbSDimitry Andric   }
187868bcb7dbSDimitry Andric }
1879dd58ef01SDimitry Andric 
constantOffsetHeuristic(const DecomposedGEP & GEP,LocationSize MaybeV1Size,LocationSize MaybeV2Size,AssumptionCache * AC,DominatorTree * DT,const AAQueryInfo & AAQI)1880e3b55780SDimitry Andric bool BasicAAResult::constantOffsetHeuristic(const DecomposedGEP &GEP,
1881e3b55780SDimitry Andric                                             LocationSize MaybeV1Size,
1882e3b55780SDimitry Andric                                             LocationSize MaybeV2Size,
1883e3b55780SDimitry Andric                                             AssumptionCache *AC,
1884e3b55780SDimitry Andric                                             DominatorTree *DT,
1885e3b55780SDimitry Andric                                             const AAQueryInfo &AAQI) {
1886c0981da4SDimitry Andric   if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() ||
1887b60736ecSDimitry Andric       !MaybeV2Size.hasValue())
1888dd58ef01SDimitry Andric     return false;
1889dd58ef01SDimitry Andric 
1890d8e91e46SDimitry Andric   const uint64_t V1Size = MaybeV1Size.getValue();
1891d8e91e46SDimitry Andric   const uint64_t V2Size = MaybeV2Size.getValue();
1892d8e91e46SDimitry Andric 
1893c0981da4SDimitry Andric   const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1];
1894dd58ef01SDimitry Andric 
1895c0981da4SDimitry Andric   if (Var0.Val.TruncBits != 0 || !Var0.Val.hasSameCastsAs(Var1.Val) ||
18967fa27ce4SDimitry Andric       !Var0.hasNegatedScaleOf(Var1) ||
1897c0981da4SDimitry Andric       Var0.Val.V->getType() != Var1.Val.V->getType())
1898dd58ef01SDimitry Andric     return false;
1899dd58ef01SDimitry Andric 
1900dd58ef01SDimitry Andric   // We'll strip off the Extensions of Var0 and Var1 and do another round
1901dd58ef01SDimitry Andric   // of GetLinearExpression decomposition. In the example above, if Var0
1902dd58ef01SDimitry Andric   // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
1903dd58ef01SDimitry Andric 
1904344a3780SDimitry Andric   LinearExpression E0 =
1905c0981da4SDimitry Andric       GetLinearExpression(CastedValue(Var0.Val.V), DL, 0, AC, DT);
1906344a3780SDimitry Andric   LinearExpression E1 =
1907c0981da4SDimitry Andric       GetLinearExpression(CastedValue(Var1.Val.V), DL, 0, AC, DT);
1908c0981da4SDimitry Andric   if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(E1.Val) ||
1909e3b55780SDimitry Andric       !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V, AAQI))
1910dd58ef01SDimitry Andric     return false;
1911dd58ef01SDimitry Andric 
1912dd58ef01SDimitry Andric   // We have a hit - Var0 and Var1 only differ by a constant offset!
1913dd58ef01SDimitry Andric 
1914dd58ef01SDimitry Andric   // If we've been sext'ed then zext'd the maximum difference between Var0 and
1915dd58ef01SDimitry Andric   // Var1 is possible to calculate, but we're just interested in the absolute
1916dd58ef01SDimitry Andric   // minimum difference between the two. The minimum distance may occur due to
1917dd58ef01SDimitry Andric   // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
1918dd58ef01SDimitry Andric   // the minimum distance between %i and %i + 5 is 3.
1919344a3780SDimitry Andric   APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff;
1920dd58ef01SDimitry Andric   MinDiff = APIntOps::umin(MinDiff, Wrapped);
1921d8e91e46SDimitry Andric   APInt MinDiffBytes =
1922d8e91e46SDimitry Andric     MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();
1923dd58ef01SDimitry Andric 
1924dd58ef01SDimitry Andric   // We can't definitely say whether GEP1 is before or after V2 due to wrapping
1925dd58ef01SDimitry Andric   // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
1926dd58ef01SDimitry Andric   // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
1927dd58ef01SDimitry Andric   // V2Size can fit in the MinDiffBytes gap.
1928c0981da4SDimitry Andric   return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) &&
1929c0981da4SDimitry Andric          MinDiffBytes.uge(V2Size + GEP.Offset.abs());
1930dd58ef01SDimitry Andric }
1931dd58ef01SDimitry Andric 
1932dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
1933dd58ef01SDimitry Andric // BasicAliasAnalysis Pass
1934dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
1935dd58ef01SDimitry Andric 
1936b915e9e0SDimitry Andric AnalysisKey BasicAA::Key;
1937dd58ef01SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)1938b915e9e0SDimitry Andric BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
1939b60736ecSDimitry Andric   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1940b60736ecSDimitry Andric   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1941b60736ecSDimitry Andric   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1942ac9a064cSDimitry Andric   return BasicAAResult(F.getDataLayout(), F, TLI, AC, DT);
1943dd58ef01SDimitry Andric }
1944dd58ef01SDimitry Andric 
BasicAAWrapperPass()1945dd58ef01SDimitry Andric BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
1946dd58ef01SDimitry Andric   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
1947dd58ef01SDimitry Andric }
1948dd58ef01SDimitry Andric 
1949dd58ef01SDimitry Andric char BasicAAWrapperPass::ID = 0;
1950044eb2f6SDimitry Andric 
anchor()1951dd58ef01SDimitry Andric void BasicAAWrapperPass::anchor() {}
1952dd58ef01SDimitry Andric 
1953cfca06d7SDimitry Andric INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa",
1954cfca06d7SDimitry Andric                       "Basic Alias Analysis (stateless AA impl)", true, true)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)1955dd58ef01SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
195601095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1957dd58ef01SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1958cfca06d7SDimitry Andric INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa",
1959cfca06d7SDimitry Andric                     "Basic Alias Analysis (stateless AA impl)", true, true)
1960dd58ef01SDimitry Andric 
1961dd58ef01SDimitry Andric FunctionPass *llvm::createBasicAAWrapperPass() {
1962dd58ef01SDimitry Andric   return new BasicAAWrapperPass();
1963dd58ef01SDimitry Andric }
1964dd58ef01SDimitry Andric 
runOnFunction(Function & F)1965dd58ef01SDimitry Andric bool BasicAAWrapperPass::runOnFunction(Function &F) {
1966dd58ef01SDimitry Andric   auto &ACT = getAnalysis<AssumptionCacheTracker>();
1967dd58ef01SDimitry Andric   auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
196801095a5dSDimitry Andric   auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
1969dd58ef01SDimitry Andric 
1970ac9a064cSDimitry Andric   Result.reset(new BasicAAResult(F.getDataLayout(), F,
19711d5ae102SDimitry Andric                                  TLIWP.getTLI(F), ACT.getAssumptionCache(F),
1972e3b55780SDimitry Andric                                  &DTWP.getDomTree()));
1973dd58ef01SDimitry Andric 
1974dd58ef01SDimitry Andric   return false;
1975dd58ef01SDimitry Andric }
1976dd58ef01SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const1977dd58ef01SDimitry Andric void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1978dd58ef01SDimitry Andric   AU.setPreservesAll();
1979b60736ecSDimitry Andric   AU.addRequiredTransitive<AssumptionCacheTracker>();
1980b60736ecSDimitry Andric   AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1981b60736ecSDimitry Andric   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
1982dd58ef01SDimitry Andric }
1983