blob: 06e600e8835388b465d2e29e8d02bc1159bcb001 [file] [log] [blame]
Dan Gohmanda85ed82010-10-19 23:09:08 +00001//===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman01808ca2005-04-21 21:13:18 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerd6a2a992003-02-26 19:41:54 +00009//
Dan Gohmanda85ed82010-10-19 23:09:08 +000010// This file defines the primary stateless implementation of the
11// Alias Analysis interface that implements identities (two different
12// globals cannot alias, etc), but does no stateful analysis.
Chris Lattnerd6a2a992003-02-26 19:41:54 +000013//
14//===----------------------------------------------------------------------===//
15
Jeff Cohencede1ce2005-01-08 22:01:16 +000016#include "llvm/Analysis/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000020#include "llvm/Analysis/AssumptionCache.h"
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000021#include "llvm/Analysis/CFG.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/InstructionSimplify.h"
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000024#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000026#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000033#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/GlobalAlias.h"
35#include "llvm/IR/GlobalVariable.h"
36#include "llvm/IR/Instructions.h"
37#include "llvm/IR/IntrinsicInst.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Operator.h"
Chris Lattnerd82256a2004-03-15 03:36:49 +000040#include "llvm/Pass.h"
Torok Edwin56d06592009-07-11 20:10:48 +000041#include "llvm/Support/ErrorHandling.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000042#include <algorithm>
Chris Lattner35997482003-11-25 18:33:40 +000043using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000044
Tobias Edler von Kochd8ce16b2015-07-15 19:32:22 +000045/// Enable analysis of recursive PHI nodes.
46static cl::opt<bool> EnableRecPhiAnalysis("basicaa-recphi",
47 cl::Hidden, cl::init(false));
48
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000049/// Cutoff after which to stop analysing a set of phi nodes potentially involved
50/// in a cycle. Because we are analysing 'through' phi nodes we need to be
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000051/// careful with value equivalence. We use reachability to make sure a value
52/// cannot be involved in a cycle.
53const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000054
Arnold Schwaighofer1a444482014-03-26 21:30:19 +000055// The max limit of the search depth in DecomposeGEPExpression() and
56// GetUnderlyingObject(), both functions need to use the same search
57// depth otherwise the algorithm in aliasGEP will assert.
58static const unsigned MaxLookupSearchDepth = 6;
59
Chris Lattner2d332972008-06-16 06:30:22 +000060//===----------------------------------------------------------------------===//
61// Useful predicates
62//===----------------------------------------------------------------------===//
Devang Patel09f162c2007-05-01 21:15:47 +000063
Chris Lattnerb35d9b52008-06-16 06:19:11 +000064/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
65/// object that never escapes from the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000066static bool isNonEscapingLocalObject(const Value *V) {
Chris Lattnerfa482582008-06-16 06:28:01 +000067 // If this is a local allocation, check to see if it escapes.
Dan Gohman84f90a32010-07-01 20:08:40 +000068 if (isa<AllocaInst>(V) || isNoAliasCall(V))
Dan Gohman94e61762009-11-19 21:57:48 +000069 // Set StoreCaptures to True so that we can assume in our callers that the
70 // pointer is not the result of a load instruction. Currently
71 // PointerMayBeCaptured doesn't have any special analysis for the
72 // StoreCaptures=false case; if it did, our callers could be refined to be
73 // more precise.
74 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Duncan Sands8d65f362009-01-05 21:19:53 +000075
Chris Lattnerfa482582008-06-16 06:28:01 +000076 // If this is an argument that corresponds to a byval or noalias argument,
Duncan Sands8d65f362009-01-05 21:19:53 +000077 // then it has not escaped before entering the function. Check if it escapes
78 // inside the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000079 if (const Argument *A = dyn_cast<Argument>(V))
Richard Osbornea1fffcf2012-11-05 10:48:24 +000080 if (A->hasByValAttr() || A->hasNoAliasAttr())
81 // Note even if the argument is marked nocapture we still need to check
82 // for copies made inside the function. The nocapture attribute only
83 // specifies that there are no copies made that outlive the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000084 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Richard Osbornea1fffcf2012-11-05 10:48:24 +000085
Chris Lattnerb35d9b52008-06-16 06:19:11 +000086 return false;
87}
88
Dan Gohman0824aff2010-06-29 00:50:39 +000089/// isEscapeSource - Return true if the pointer is one which would have
90/// been considered an escape by isNonEscapingLocalObject.
Dan Gohman84f90a32010-07-01 20:08:40 +000091static bool isEscapeSource(const Value *V) {
92 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
93 return true;
Dan Gohman0824aff2010-06-29 00:50:39 +000094
95 // The load case works because isNonEscapingLocalObject considers all
96 // stores to be escapes (it passes true for the StoreCaptures argument
97 // to PointerMayBeCaptured).
98 if (isa<LoadInst>(V))
99 return true;
100
101 return false;
102}
Chris Lattnerb35d9b52008-06-16 06:19:11 +0000103
Dan Gohman44da55b2011-01-18 21:16:06 +0000104/// getObjectSize - Return the size of the object specified by V, or
105/// UnknownSize if unknown.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000106static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000107 const TargetLibraryInfo &TLI,
Eli Friedman8bc169c2012-02-27 20:46:07 +0000108 bool RoundToAlign = false) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000109 uint64_t Size;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000110 if (getObjectSize(V, Size, DL, &TLI, RoundToAlign))
Nuno Lopes55fff832012-06-21 15:45:28 +0000111 return Size;
Chandler Carruthecbd1682015-06-17 07:21:38 +0000112 return MemoryLocation::UnknownSize;
Dan Gohman44da55b2011-01-18 21:16:06 +0000113}
114
115/// isObjectSmallerThan - Return true if we can prove that the object specified
116/// by V is smaller than Size.
117static bool isObjectSmallerThan(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000118 const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000119 const TargetLibraryInfo &TLI) {
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000120 // Note that the meanings of the "object" are slightly different in the
121 // following contexts:
122 // c1: llvm::getObjectSize()
123 // c2: llvm.objectsize() intrinsic
124 // c3: isObjectSmallerThan()
125 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
126 // refers to the "entire object".
127 //
128 // Consider this example:
129 // char *p = (char*)malloc(100)
130 // char *q = p+80;
131 //
132 // In the context of c1 and c2, the "object" pointed by q refers to the
133 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
134 //
135 // However, in the context of c3, the "object" refers to the chunk of memory
136 // being allocated. So, the "object" has 100 bytes, and q points to the middle
137 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
138 // parameter, before the llvm::getObjectSize() is called to get the size of
139 // entire object, we should:
140 // - either rewind the pointer q to the base-address of the object in
141 // question (in this case rewind to p), or
142 // - just give up. It is up to caller to make sure the pointer is pointing
143 // to the base address the object.
Jakub Staszak07f383f2013-08-24 14:16:00 +0000144 //
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000145 // We go for 2nd option for simplicity.
146 if (!isIdentifiedObject(V))
147 return false;
148
Eli Friedman8bc169c2012-02-27 20:46:07 +0000149 // This function needs to use the aligned object size because we allow
150 // reads a bit past the end given sufficient alignment.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000151 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000152
Chandler Carruthecbd1682015-06-17 07:21:38 +0000153 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
Dan Gohman44da55b2011-01-18 21:16:06 +0000154}
155
156/// isObjectSize - Return true if we can prove that the object specified
157/// by V has size Size.
158static bool isObjectSize(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000159 const DataLayout &DL, const TargetLibraryInfo &TLI) {
160 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000161 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
Chris Lattner98ad8162008-06-16 06:10:11 +0000162}
163
Chris Lattner2d332972008-06-16 06:30:22 +0000164//===----------------------------------------------------------------------===//
Chris Lattner9f7500f2010-08-18 22:07:29 +0000165// GetElementPtr Instruction Decomposition and Analysis
166//===----------------------------------------------------------------------===//
167
Chris Lattner1b9c3872010-08-18 22:47:56 +0000168namespace {
Manuel Klimek779cf852015-07-13 13:50:55 +0000169 enum ExtensionKind {
170 EK_NotExtended,
171 EK_SignExt,
172 EK_ZeroExt
173 };
Jakub Staszak07f383f2013-08-24 14:16:00 +0000174
Chris Lattner1b9c3872010-08-18 22:47:56 +0000175 struct VariableGEPIndex {
176 const Value *V;
Manuel Klimek779cf852015-07-13 13:50:55 +0000177 ExtensionKind Extension;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000178 int64_t Scale;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000179
180 bool operator==(const VariableGEPIndex &Other) const {
Manuel Klimek779cf852015-07-13 13:50:55 +0000181 return V == Other.V && Extension == Other.Extension &&
182 Scale == Other.Scale;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000183 }
184
185 bool operator!=(const VariableGEPIndex &Other) const {
186 return !operator==(Other);
187 }
Chris Lattner1b9c3872010-08-18 22:47:56 +0000188 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000189}
Chris Lattner1b9c3872010-08-18 22:47:56 +0000190
Chris Lattner9f7500f2010-08-18 22:07:29 +0000191
192/// GetLinearExpression - Analyze the specified value as a linear expression:
193/// "A*V + B", where A and B are constant integers. Return the scale and offset
Chris Lattner3decde92010-08-18 23:09:49 +0000194/// values as APInts and return V as a Value*, and return whether we looked
195/// through any sign or zero extends. The incoming Value is known to have
196/// IntegerType and it may already be sign or zero extended.
197///
198/// Note that this looks through extends, so the high bits may not be
199/// represented in the result.
Manuel Klimek779cf852015-07-13 13:50:55 +0000200static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
201 ExtensionKind &Extension,
202 const DataLayout &DL, unsigned Depth,
203 AssumptionCache *AC, DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000204 assert(V->getType()->isIntegerTy() && "Not an integer value");
205
206 // Limit our recursion depth.
207 if (Depth == 6) {
208 Scale = 1;
209 Offset = 0;
210 return V;
211 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000212
Manuel Klimek779cf852015-07-13 13:50:55 +0000213 if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
214 // if it's a constant, just convert it to an offset
215 // and remove the variable.
216 Offset += Const->getValue();
Hal Finkel45ba2c12014-11-13 09:16:54 +0000217 assert(Scale == 0 && "Constant values don't have a scale");
218 return V;
219 }
220
Manuel Klimek779cf852015-07-13 13:50:55 +0000221 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000222 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
223 switch (BOp->getOpcode()) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000224 default: break;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000225 case Instruction::Or:
226 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
227 // analyze it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000228 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000229 BOp, DT))
Chris Lattner9f7500f2010-08-18 22:07:29 +0000230 break;
231 // FALL THROUGH.
232 case Instruction::Add:
Manuel Klimek779cf852015-07-13 13:50:55 +0000233 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
234 DL, Depth + 1, AC, DT);
235 Offset += RHSC->getValue();
236 return V;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000237 case Instruction::Mul:
Manuel Klimek779cf852015-07-13 13:50:55 +0000238 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
239 DL, Depth + 1, AC, DT);
240 Offset *= RHSC->getValue();
241 Scale *= RHSC->getValue();
242 return V;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000243 case Instruction::Shl:
Manuel Klimek779cf852015-07-13 13:50:55 +0000244 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
245 DL, Depth + 1, AC, DT);
246 Offset <<= RHSC->getValue().getLimitedValue();
247 Scale <<= RHSC->getValue().getLimitedValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000248 return V;
249 }
250 }
251 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000252
Chris Lattner9f7500f2010-08-18 22:07:29 +0000253 // Since GEP indices are sign extended anyway, we don't care about the high
Chris Lattner3decde92010-08-18 23:09:49 +0000254 // bits of a sign or zero extended value - just scales and offsets. The
255 // extensions have to be consistent though.
Manuel Klimek779cf852015-07-13 13:50:55 +0000256 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
257 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000258 Value *CastOp = cast<CastInst>(V)->getOperand(0);
Manuel Klimek779cf852015-07-13 13:50:55 +0000259 unsigned OldWidth = Scale.getBitWidth();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000260 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
Manuel Klimek779cf852015-07-13 13:50:55 +0000261 Scale = Scale.trunc(SmallWidth);
262 Offset = Offset.trunc(SmallWidth);
263 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
Chris Lattner3decde92010-08-18 23:09:49 +0000264
Manuel Klimek779cf852015-07-13 13:50:55 +0000265 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, DL,
266 Depth + 1, AC, DT);
267 Scale = Scale.zext(OldWidth);
Hal Finkel45ba2c12014-11-13 09:16:54 +0000268
Manuel Klimek779cf852015-07-13 13:50:55 +0000269 // We have to sign-extend even if Extension == EK_ZeroExt as we can't
270 // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
271 Offset = Offset.sext(OldWidth);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000272
Chris Lattner9f7500f2010-08-18 22:07:29 +0000273 return Result;
274 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000275
Chris Lattner9f7500f2010-08-18 22:07:29 +0000276 Scale = 1;
277 Offset = 0;
278 return V;
279}
280
281/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
282/// into a base pointer with a constant offset and a number of scaled symbolic
283/// offsets.
284///
285/// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
286/// the VarIndices vector) are Value*'s that are known to be scaled by the
287/// specified amount, but which may have other unrepresented high bits. As such,
288/// the gep cannot necessarily be reconstructed from its decomposed form.
289///
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000290/// When DataLayout is around, this function is capable of analyzing everything
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000291/// that GetUnderlyingObject can look through. To be able to do that
292/// GetUnderlyingObject and DecomposeGEPExpression must use the same search
293/// depth (MaxLookupSearchDepth).
294/// When DataLayout not is around, it just looks through pointer casts.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000295///
296static const Value *
297DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
Chris Lattner1b9c3872010-08-18 22:47:56 +0000298 SmallVectorImpl<VariableGEPIndex> &VarIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000299 bool &MaxLookupReached, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000300 AssumptionCache *AC, DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000301 // Limit recursion depth to limit compile time in crazy cases.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000302 unsigned MaxLookup = MaxLookupSearchDepth;
303 MaxLookupReached = false;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000304
Chris Lattner9f7500f2010-08-18 22:07:29 +0000305 BaseOffs = 0;
306 do {
307 // See if this is a bitcast or GEP.
308 const Operator *Op = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +0000309 if (!Op) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000310 // The only non-operator case we can handle are GlobalAliases.
311 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
312 if (!GA->mayBeOverridden()) {
313 V = GA->getAliasee();
314 continue;
315 }
316 }
317 return V;
318 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000319
Matt Arsenault70f4db882014-07-15 00:56:40 +0000320 if (Op->getOpcode() == Instruction::BitCast ||
321 Op->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000322 V = Op->getOperand(0);
323 continue;
324 }
Dan Gohman05b18f12010-12-15 20:49:55 +0000325
Chris Lattner9f7500f2010-08-18 22:07:29 +0000326 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
Craig Topper9f008862014-04-15 04:59:12 +0000327 if (!GEPOp) {
Dan Gohman0573b552011-05-24 18:24:08 +0000328 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
329 // can come up with something. This matches what GetUnderlyingObject does.
330 if (const Instruction *I = dyn_cast<Instruction>(V))
Chandler Carruth66b31302015-01-04 12:03:27 +0000331 // TODO: Get a DominatorTree and AssumptionCache and use them here
Hal Finkel60db0582014-09-07 18:57:58 +0000332 // (these are both now available in this function, but this should be
333 // updated when GetUnderlyingObject is updated). TLI should be
334 // provided also.
Dan Gohman0573b552011-05-24 18:24:08 +0000335 if (const Value *Simplified =
Rafael Espindola5f57f462014-02-21 18:34:28 +0000336 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
Dan Gohman0573b552011-05-24 18:24:08 +0000337 V = Simplified;
338 continue;
339 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000340
Chris Lattner9f7500f2010-08-18 22:07:29 +0000341 return V;
Dan Gohman0573b552011-05-24 18:24:08 +0000342 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000343
Chris Lattner9f7500f2010-08-18 22:07:29 +0000344 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000345 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
Chris Lattner9f7500f2010-08-18 22:07:29 +0000346 return V;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000347
Matt Arsenaulta8fe22b2013-11-16 00:36:43 +0000348 unsigned AS = GEPOp->getPointerAddressSpace();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000349 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
350 gep_type_iterator GTI = gep_type_begin(GEPOp);
351 for (User::const_op_iterator I = GEPOp->op_begin()+1,
352 E = GEPOp->op_end(); I != E; ++I) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000353 Value *Index = *I;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000354 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +0000355 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000356 // For a struct, add the member offset.
357 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
358 if (FieldNo == 0) continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000359
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000360 BaseOffs += DL.getStructLayout(STy)->getElementOffset(FieldNo);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000361 continue;
362 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000363
Chris Lattner9f7500f2010-08-18 22:07:29 +0000364 // For an array/pointer, add the element offset, explicitly scaled.
Manuel Klimek779cf852015-07-13 13:50:55 +0000365 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000366 if (CIdx->isZero()) continue;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000367 BaseOffs += DL.getTypeAllocSize(*GTI) * CIdx->getSExtValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000368 continue;
369 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000370
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000371 uint64_t Scale = DL.getTypeAllocSize(*GTI);
Manuel Klimek779cf852015-07-13 13:50:55 +0000372 ExtensionKind Extension = EK_NotExtended;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000373
Chris Lattner3decde92010-08-18 23:09:49 +0000374 // If the integer type is smaller than the pointer size, it is implicitly
375 // sign extended to pointer size.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000376 unsigned Width = Index->getType()->getIntegerBitWidth();
Manuel Klimek779cf852015-07-13 13:50:55 +0000377 if (DL.getPointerSizeInBits(AS) > Width)
378 Extension = EK_SignExt;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000379
Chris Lattner3decde92010-08-18 23:09:49 +0000380 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000381 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
Manuel Klimek779cf852015-07-13 13:50:55 +0000382 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension, DL,
383 0, AC, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000384
Chris Lattner9f7500f2010-08-18 22:07:29 +0000385 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
386 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
Eli Friedmanab3a1282010-09-15 20:08:03 +0000387 BaseOffs += IndexOffset.getSExtValue()*Scale;
388 Scale *= IndexScale.getSExtValue();
Jakub Staszak07f383f2013-08-24 14:16:00 +0000389
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000390 // If we already had an occurrence of this index variable, merge this
Chris Lattner9f7500f2010-08-18 22:07:29 +0000391 // scale into it. For example, we want to handle:
392 // A[x][x] -> x*16 + x*4 -> x*20
393 // This also ensures that 'x' only appears in the index list once.
394 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000395 if (VarIndices[i].V == Index &&
396 VarIndices[i].Extension == Extension) {
Chris Lattner1b9c3872010-08-18 22:47:56 +0000397 Scale += VarIndices[i].Scale;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000398 VarIndices.erase(VarIndices.begin()+i);
399 break;
400 }
401 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000402
Chris Lattner9f7500f2010-08-18 22:07:29 +0000403 // Make sure that we have a scale that makes sense for this target's
404 // pointer size.
Manuel Klimek779cf852015-07-13 13:50:55 +0000405 if (unsigned ShiftBits = 64 - DL.getPointerSizeInBits(AS)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000406 Scale <<= ShiftBits;
Eli Friedmanab3a1282010-09-15 20:08:03 +0000407 Scale = (int64_t)Scale >> ShiftBits;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000408 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000409
Chris Lattner1b9c3872010-08-18 22:47:56 +0000410 if (Scale) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000411 VariableGEPIndex Entry = {Index, Extension,
Jeffrey Yasskin6381c012011-07-27 06:22:51 +0000412 static_cast<int64_t>(Scale)};
Chris Lattner1b9c3872010-08-18 22:47:56 +0000413 VarIndices.push_back(Entry);
414 }
Chris Lattner9f7500f2010-08-18 22:07:29 +0000415 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000416
Chris Lattner9f7500f2010-08-18 22:07:29 +0000417 // Analyze the base pointer next.
418 V = GEPOp->getOperand(0);
419 } while (--MaxLookup);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000420
Chris Lattner9f7500f2010-08-18 22:07:29 +0000421 // If the chain of expressions is too deep, just return early.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000422 MaxLookupReached = true;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000423 return V;
424}
425
Chris Lattner9f7500f2010-08-18 22:07:29 +0000426//===----------------------------------------------------------------------===//
Dan Gohman0824aff2010-06-29 00:50:39 +0000427// BasicAliasAnalysis Pass
Chris Lattner2d332972008-06-16 06:30:22 +0000428//===----------------------------------------------------------------------===//
429
Dan Gohman00ef9322010-07-07 14:27:09 +0000430#ifndef NDEBUG
Dan Gohman0824aff2010-06-29 00:50:39 +0000431static const Function *getParent(const Value *V) {
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000432 if (const Instruction *inst = dyn_cast<Instruction>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000433 return inst->getParent()->getParent();
434
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000435 if (const Argument *arg = dyn_cast<Argument>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000436 return arg->getParent();
437
Craig Topper9f008862014-04-15 04:59:12 +0000438 return nullptr;
Dan Gohman0824aff2010-06-29 00:50:39 +0000439}
440
Dan Gohman84f90a32010-07-01 20:08:40 +0000441static bool notDifferentParent(const Value *O1, const Value *O2) {
442
443 const Function *F1 = getParent(O1);
444 const Function *F2 = getParent(O2);
445
Dan Gohman0824aff2010-06-29 00:50:39 +0000446 return !F1 || !F2 || F1 == F2;
447}
Benjamin Kramer80b7bc02010-06-29 10:03:11 +0000448#endif
Dan Gohman0824aff2010-06-29 00:50:39 +0000449
Chris Lattner2d332972008-06-16 06:30:22 +0000450namespace {
Dan Gohmanda85ed82010-10-19 23:09:08 +0000451 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
452 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
Chris Lattner2d332972008-06-16 06:30:22 +0000453 static char ID; // Class identification, replacement for typeinfo
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000454 BasicAliasAnalysis() : ImmutablePass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000455 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
456 }
Dan Gohman0824aff2010-06-29 00:50:39 +0000457
Mehdi Amini46a43552015-03-04 18:43:29 +0000458 bool doInitialization(Module &M) override;
Dan Gohman02538ac2010-10-18 18:04:47 +0000459
Craig Toppere9ba7592014-03-05 07:30:04 +0000460 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000461 AU.addRequired<AliasAnalysis>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000462 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000463 AU.addRequired<TargetLibraryInfoWrapperPass>();
Dan Gohman02538ac2010-10-18 18:04:47 +0000464 }
465
Chandler Carruthac80dc72015-06-17 07:18:54 +0000466 AliasResult alias(const MemoryLocation &LocA,
467 const MemoryLocation &LocB) override {
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000468 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
Dan Gohman41f14cf2010-09-14 21:25:10 +0000469 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000470 "BasicAliasAnalysis doesn't support interprocedural queries.");
Hal Finkelcc39b672014-07-24 12:16:19 +0000471 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags,
472 LocB.Ptr, LocB.Size, LocB.AATags);
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000473 // AliasCache rarely has more than 1 or 2 elements, always use
474 // shrink_and_clear so it quickly returns to the inline capacity of the
475 // SmallDenseMap if it ever grows larger.
476 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
477 AliasCache.shrink_and_clear();
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000478 VisitedPhiBBs.clear();
Evan Chengb3ccb642009-10-14 06:46:26 +0000479 return Alias;
Evan Chengc10e88d2009-10-13 22:02:20 +0000480 }
Chris Lattner2d332972008-06-16 06:30:22 +0000481
Craig Toppere9ba7592014-03-05 07:30:04 +0000482 ModRefResult getModRefInfo(ImmutableCallSite CS,
Chandler Carruthac80dc72015-06-17 07:18:54 +0000483 const MemoryLocation &Loc) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000484
Craig Toppere9ba7592014-03-05 07:30:04 +0000485 ModRefResult getModRefInfo(ImmutableCallSite CS1,
Hal Finkel93046912014-07-25 21:13:35 +0000486 ImmutableCallSite CS2) override;
Owen Anderson98a36172009-02-05 23:36:27 +0000487
Chris Lattner2d332972008-06-16 06:30:22 +0000488 /// pointsToConstantMemory - Chase pointers until we find a (constant
489 /// global) or not.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000490 bool pointsToConstantMemory(const MemoryLocation &Loc,
491 bool OrLocal) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000492
Hal Finkel354e23b2014-07-17 01:28:25 +0000493 /// Get the location associated with a pointer argument of a callsite.
Chandler Carruthc41404a2015-06-17 07:12:40 +0000494 ModRefResult getArgModRefInfo(ImmutableCallSite CS,
495 unsigned ArgIdx) override;
Hal Finkel354e23b2014-07-17 01:28:25 +0000496
Dan Gohman5f1702e2010-08-06 01:25:49 +0000497 /// getModRefBehavior - Return the behavior when calling the given
498 /// call site.
Craig Toppere9ba7592014-03-05 07:30:04 +0000499 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000500
501 /// getModRefBehavior - Return the behavior when calling the given function.
502 /// For use when the call site is not known.
Craig Toppere9ba7592014-03-05 07:30:04 +0000503 ModRefBehavior getModRefBehavior(const Function *F) override;
Chris Lattner2d332972008-06-16 06:30:22 +0000504
Chris Lattneraf362f02010-01-20 19:26:14 +0000505 /// getAdjustedAnalysisPointer - This method is used when a pass implements
Dan Gohmane0d5c452010-08-05 23:48:14 +0000506 /// an analysis interface through multiple inheritance. If needed, it
507 /// should override this to adjust the this pointer as needed for the
508 /// specified pass info.
Craig Toppere9ba7592014-03-05 07:30:04 +0000509 void *getAdjustedAnalysisPointer(const void *ID) override {
Owen Andersona7aed182010-08-06 18:33:48 +0000510 if (ID == &AliasAnalysis::ID)
Chris Lattneraf362f02010-01-20 19:26:14 +0000511 return (AliasAnalysis*)this;
512 return this;
513 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000514
Chris Lattner2d332972008-06-16 06:30:22 +0000515 private:
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000516 // AliasCache - Track alias queries to guard against recursion.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000517 typedef std::pair<MemoryLocation, MemoryLocation> LocPair;
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000518 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000519 AliasCacheTy AliasCache;
520
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000521 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
522 /// equality as value equality we need to make sure that the "Value" is not
523 /// part of a cycle. Otherwise, two uses could come from different
524 /// "iterations" of a cycle and see different values for the same "Value"
525 /// pointer.
526 /// The following example shows the problem:
527 /// %p = phi(%alloca1, %addr2)
528 /// %l = load %ptr
529 /// %addr1 = gep, %alloca2, 0, %l
530 /// %addr2 = gep %alloca2, 0, (%l + 1)
531 /// alias(%p, %addr1) -> MayAlias !
532 /// store %l, ...
533 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
534
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000535 // Visited - Track instructions visited by pointsToConstantMemory.
Dan Gohman7c34ece2010-06-28 21:16:52 +0000536 SmallPtrSet<const Value*, 16> Visited;
Evan Cheng31565b32009-10-14 05:05:02 +0000537
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000538 /// \brief Check whether two Values can be considered equivalent.
539 ///
540 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
541 /// whether they can not be part of a cycle in the value graph by looking at
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +0000542 /// all visited phi nodes an making sure that the phis cannot reach the
543 /// value. We have to do this because we are looking through phi nodes (That
544 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
545 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000546
547 /// \brief Dest and Src are the variable indices from two decomposed
548 /// GetElementPtr instructions GEP1 and GEP2 which have common base
549 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
550 /// difference between the two pointers.
551 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
552 const SmallVectorImpl<VariableGEPIndex> &Src);
553
Chris Lattner98e253262009-11-23 16:45:27 +0000554 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
555 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000556 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000557 const AAMDNodes &V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000558 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000559 const AAMDNodes &V2AAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000560 const Value *UnderlyingV1, const Value *UnderlyingV2);
Evan Chengc10e88d2009-10-13 22:02:20 +0000561
Chris Lattner98e253262009-11-23 16:45:27 +0000562 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
563 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000564 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
Hal Finkelcc39b672014-07-24 12:16:19 +0000565 const AAMDNodes &PNAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000566 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000567 const AAMDNodes &V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +0000568
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000569 /// aliasSelect - Disambiguate a Select instruction against another value.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000570 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
Hal Finkelcc39b672014-07-24 12:16:19 +0000571 const AAMDNodes &SIAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000572 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000573 const AAMDNodes &V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000574
Dan Gohmanf372cf82010-10-19 22:54:46 +0000575 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000576 AAMDNodes V1AATag,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000577 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000578 AAMDNodes V2AATag);
Chris Lattner2d332972008-06-16 06:30:22 +0000579 };
580} // End of anonymous namespace
581
582// Register this pass...
583char BasicAliasAnalysis::ID = 0;
Owen Anderson653cb032011-09-06 23:33:25 +0000584INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
Dan Gohmanda85ed82010-10-19 23:09:08 +0000585 "Basic Alias Analysis (stateless AA impl)",
Dan Gohman02538ac2010-10-18 18:04:47 +0000586 false, true, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000587INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000588INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson653cb032011-09-06 23:33:25 +0000589INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
590 "Basic Alias Analysis (stateless AA impl)",
591 false, true, false)
592
Chris Lattner2d332972008-06-16 06:30:22 +0000593
594ImmutablePass *llvm::createBasicAliasAnalysisPass() {
595 return new BasicAliasAnalysis();
596}
597
Dan Gohman9130bad2010-11-08 16:45:26 +0000598/// pointsToConstantMemory - Returns whether the given pointer value
599/// points to memory that is local to the function, with global constants being
600/// considered local to all functions.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000601bool BasicAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
602 bool OrLocal) {
Dan Gohman9130bad2010-11-08 16:45:26 +0000603 assert(Visited.empty() && "Visited must be cleared after use!");
Chris Lattner2d332972008-06-16 06:30:22 +0000604
Dan Gohman142ff822010-11-08 20:26:19 +0000605 unsigned MaxLookup = 8;
Dan Gohman9130bad2010-11-08 16:45:26 +0000606 SmallVector<const Value *, 16> Worklist;
607 Worklist.push_back(Loc.Ptr);
608 do {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000609 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), *DL);
David Blaikie70573dc2014-11-19 07:49:26 +0000610 if (!Visited.insert(V).second) {
Dan Gohman9130bad2010-11-08 16:45:26 +0000611 Visited.clear();
612 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
613 }
Dan Gohman5f1702e2010-08-06 01:25:49 +0000614
Dan Gohman9130bad2010-11-08 16:45:26 +0000615 // An alloca instruction defines local memory.
616 if (OrLocal && isa<AllocaInst>(V))
617 continue;
618
619 // A global constant counts as local memory for our purposes.
620 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
621 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
622 // global to be marked constant in some modules and non-constant in
623 // others. GV may even be a declaration, not a definition.
624 if (!GV->isConstant()) {
625 Visited.clear();
626 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
627 }
628 continue;
629 }
630
631 // If both select values point to local memory, then so does the select.
632 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
633 Worklist.push_back(SI->getTrueValue());
634 Worklist.push_back(SI->getFalseValue());
635 continue;
636 }
637
638 // If all values incoming to a phi node point to local memory, then so does
639 // the phi.
640 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
Dan Gohman142ff822010-11-08 20:26:19 +0000641 // Don't bother inspecting phi nodes with many operands.
642 if (PN->getNumIncomingValues() > MaxLookup) {
643 Visited.clear();
644 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
645 }
Pete Cooper833f34d2015-05-12 20:05:31 +0000646 for (Value *IncValue : PN->incoming_values())
647 Worklist.push_back(IncValue);
Dan Gohman9130bad2010-11-08 16:45:26 +0000648 continue;
649 }
650
651 // Otherwise be conservative.
652 Visited.clear();
653 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
654
Dan Gohman142ff822010-11-08 20:26:19 +0000655 } while (!Worklist.empty() && --MaxLookup);
Dan Gohman9130bad2010-11-08 16:45:26 +0000656
657 Visited.clear();
Dan Gohman142ff822010-11-08 20:26:19 +0000658 return Worklist.empty();
Chris Lattner2d332972008-06-16 06:30:22 +0000659}
660
Chandler Carruthc41404a2015-06-17 07:12:40 +0000661// FIXME: This code is duplicated with MemoryLocation and should be hoisted to
662// some common utility location.
Hal Finkel354e23b2014-07-17 01:28:25 +0000663static bool isMemsetPattern16(const Function *MS,
664 const TargetLibraryInfo &TLI) {
665 if (TLI.has(LibFunc::memset_pattern16) &&
666 MS->getName() == "memset_pattern16") {
667 FunctionType *MemsetType = MS->getFunctionType();
668 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
669 isa<PointerType>(MemsetType->getParamType(0)) &&
670 isa<PointerType>(MemsetType->getParamType(1)) &&
671 isa<IntegerType>(MemsetType->getParamType(2)))
672 return true;
673 }
674
675 return false;
676}
677
Dan Gohman5f1702e2010-08-06 01:25:49 +0000678/// getModRefBehavior - Return the behavior when calling the given call site.
679AliasAnalysis::ModRefBehavior
680BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
681 if (CS.doesNotAccessMemory())
682 // Can't do better than this.
683 return DoesNotAccessMemory;
684
685 ModRefBehavior Min = UnknownModRefBehavior;
686
687 // If the callsite knows it only reads memory, don't return worse
688 // than that.
689 if (CS.onlyReadsMemory())
690 Min = OnlyReadsMemory;
691
Igor Laevsky39d662f2015-07-11 10:30:36 +0000692 if (CS.onlyAccessesArgMemory())
693 Min = ModRefBehavior(Min & OnlyAccessesArgumentPointees);
694
Dan Gohman5f1702e2010-08-06 01:25:49 +0000695 // The AliasAnalysis base class has some smarts, lets use them.
Dan Gohman2694e142010-11-10 01:02:18 +0000696 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000697}
698
699/// getModRefBehavior - Return the behavior when calling the given function.
700/// For use when the call site is not known.
701AliasAnalysis::ModRefBehavior
702BasicAliasAnalysis::getModRefBehavior(const Function *F) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000703 // If the function declares it doesn't access memory, we can't do better.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000704 if (F->doesNotAccessMemory())
Dan Gohman5f1702e2010-08-06 01:25:49 +0000705 return DoesNotAccessMemory;
Dan Gohmane461d7d2010-11-08 16:08:43 +0000706
707 // For intrinsics, we can check the table.
Pete Cooper9e1d3352015-05-20 17:16:39 +0000708 if (Intrinsic::ID iid = F->getIntrinsicID()) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000709#define GET_INTRINSIC_MODREF_BEHAVIOR
Chandler Carruthdb25c6c2013-01-02 12:09:16 +0000710#include "llvm/IR/Intrinsics.gen"
Dan Gohmane461d7d2010-11-08 16:08:43 +0000711#undef GET_INTRINSIC_MODREF_BEHAVIOR
712 }
713
Dan Gohman2694e142010-11-10 01:02:18 +0000714 ModRefBehavior Min = UnknownModRefBehavior;
715
Dan Gohmane461d7d2010-11-08 16:08:43 +0000716 // If the function declares it only reads memory, go with that.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000717 if (F->onlyReadsMemory())
Dan Gohman2694e142010-11-10 01:02:18 +0000718 Min = OnlyReadsMemory;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000719
Igor Laevsky39d662f2015-07-11 10:30:36 +0000720 if (F->onlyAccessesArgMemory())
721 Min = ModRefBehavior(Min & OnlyAccessesArgumentPointees);
722
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000723 const TargetLibraryInfo &TLI =
724 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Hal Finkel354e23b2014-07-17 01:28:25 +0000725 if (isMemsetPattern16(F, TLI))
726 Min = OnlyAccessesArgumentPointees;
727
Dan Gohmane461d7d2010-11-08 16:08:43 +0000728 // Otherwise be conservative.
Dan Gohman2694e142010-11-10 01:02:18 +0000729 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000730}
Owen Anderson98a36172009-02-05 23:36:27 +0000731
Chandler Carruthc41404a2015-06-17 07:12:40 +0000732AliasAnalysis::ModRefResult
733BasicAliasAnalysis::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
734 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction()))
Hal Finkel354e23b2014-07-17 01:28:25 +0000735 switch (II->getIntrinsicID()) {
Chandler Carruthc41404a2015-06-17 07:12:40 +0000736 default:
737 break;
Hal Finkel354e23b2014-07-17 01:28:25 +0000738 case Intrinsic::memset:
739 case Intrinsic::memcpy:
Chandler Carruthc41404a2015-06-17 07:12:40 +0000740 case Intrinsic::memmove:
Hal Finkel354e23b2014-07-17 01:28:25 +0000741 assert((ArgIdx == 0 || ArgIdx == 1) &&
742 "Invalid argument index for memory intrinsic");
Chandler Carruthc41404a2015-06-17 07:12:40 +0000743 return ArgIdx ? Ref : Mod;
Hal Finkel354e23b2014-07-17 01:28:25 +0000744 }
745
746 // We can bound the aliasing properties of memset_pattern16 just as we can
747 // for memcpy/memset. This is particularly important because the
748 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
749 // whenever possible.
Chandler Carruthc41404a2015-06-17 07:12:40 +0000750 if (CS.getCalledFunction() &&
751 isMemsetPattern16(CS.getCalledFunction(), *TLI)) {
Hal Finkel354e23b2014-07-17 01:28:25 +0000752 assert((ArgIdx == 0 || ArgIdx == 1) &&
753 "Invalid argument index for memset_pattern16");
Chandler Carruthc41404a2015-06-17 07:12:40 +0000754 return ArgIdx ? Ref : Mod;
Hal Finkel354e23b2014-07-17 01:28:25 +0000755 }
756 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
757
Chandler Carruthc41404a2015-06-17 07:12:40 +0000758 return AliasAnalysis::getArgModRefInfo(CS, ArgIdx);
Hal Finkel354e23b2014-07-17 01:28:25 +0000759}
760
Hal Finkel93046912014-07-25 21:13:35 +0000761static bool isAssumeIntrinsic(ImmutableCallSite CS) {
762 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
763 if (II && II->getIntrinsicID() == Intrinsic::assume)
764 return true;
765
766 return false;
767}
768
Mehdi Amini46a43552015-03-04 18:43:29 +0000769bool BasicAliasAnalysis::doInitialization(Module &M) {
770 InitializeAliasAnalysis(this, &M.getDataLayout());
771 return true;
772}
773
Chris Lattner98e253262009-11-23 16:45:27 +0000774/// getModRefInfo - Check to see if the specified callsite can clobber the
775/// specified memory object. Since we only look at local properties of this
776/// function, we really can't say much about this query. We do, however, use
777/// simple "address taken" analysis on local objects.
Chris Lattner2d332972008-06-16 06:30:22 +0000778AliasAnalysis::ModRefResult
Dan Gohman5442c712010-08-03 21:48:53 +0000779BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
Chandler Carruthac80dc72015-06-17 07:18:54 +0000780 const MemoryLocation &Loc) {
Dan Gohman41f14cf2010-09-14 21:25:10 +0000781 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000782 "AliasAnalysis query involving multiple functions!");
783
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000784 const Value *Object = GetUnderlyingObject(Loc.Ptr, *DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000785
Dan Gohman41f14cf2010-09-14 21:25:10 +0000786 // If this is a tail call and Loc.Ptr points to a stack location, we know that
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000787 // the tail call cannot access or modify the local stack.
788 // We cannot exclude byval arguments here; these belong to the caller of
789 // the current function not to the current function, and a tail callee
790 // may reference them.
791 if (isa<AllocaInst>(Object))
Dan Gohman5442c712010-08-03 21:48:53 +0000792 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000793 if (CI->isTailCall())
794 return NoModRef;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000795
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000796 // If the pointer is to a locally allocated object that does not escape,
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000797 // then the call can not mod/ref the pointer unless the call takes the pointer
798 // as an argument, and itself doesn't capture it.
Chris Lattner1e7b37e2009-11-23 16:46:41 +0000799 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
Dan Gohman84f90a32010-07-01 20:08:40 +0000800 isNonEscapingLocalObject(Object)) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000801 bool PassedAsArg = false;
802 unsigned ArgNo = 0;
Dan Gohman5442c712010-08-03 21:48:53 +0000803 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000804 CI != CE; ++CI, ++ArgNo) {
Chris Lattner026f5e62011-05-23 05:15:43 +0000805 // Only look at the no-capture or byval pointer arguments. If this
806 // pointer were passed to arguments that were neither of these, then it
807 // couldn't be no-capture.
Duncan Sands19d0b472010-02-16 11:11:14 +0000808 if (!(*CI)->getType()->isPointerTy() ||
Nick Lewycky612d70b2011-11-20 19:09:04 +0000809 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000810 continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000811
Dan Gohman41f14cf2010-09-14 21:25:10 +0000812 // If this is a no-capture pointer argument, see if we can tell that it
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000813 // is impossible to alias the pointer we're checking. If not, we have to
814 // assume that the call could touch the pointer, even though it doesn't
815 // escape.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000816 if (!isNoAlias(MemoryLocation(*CI), MemoryLocation(Object))) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000817 PassedAsArg = true;
818 break;
819 }
820 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000821
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000822 if (!PassedAsArg)
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000823 return NoModRef;
824 }
825
Hal Finkel93046912014-07-25 21:13:35 +0000826 // While the assume intrinsic is marked as arbitrarily writing so that
827 // proper control dependencies will be maintained, it never aliases any
828 // particular memory location.
829 if (isAssumeIntrinsic(CS))
830 return NoModRef;
831
Chris Lattner2d332972008-06-16 06:30:22 +0000832 // The AliasAnalysis base class has some smarts, lets use them.
Hal Finkel354e23b2014-07-17 01:28:25 +0000833 return AliasAnalysis::getModRefInfo(CS, Loc);
Dan Gohman64d842e2010-09-08 01:32:20 +0000834}
Chris Lattner2d332972008-06-16 06:30:22 +0000835
Hal Finkel93046912014-07-25 21:13:35 +0000836AliasAnalysis::ModRefResult
837BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
838 ImmutableCallSite CS2) {
839 // While the assume intrinsic is marked as arbitrarily writing so that
840 // proper control dependencies will be maintained, it never aliases any
841 // particular memory location.
842 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
843 return NoModRef;
844
845 // The AliasAnalysis base class has some smarts, lets use them.
846 return AliasAnalysis::getModRefInfo(CS1, CS2);
847}
848
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000849/// \brief Provide ad-hoc rules to disambiguate accesses through two GEP
850/// operators, both having the exact same pointer operand.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000851static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
852 uint64_t V1Size,
853 const GEPOperator *GEP2,
854 uint64_t V2Size,
855 const DataLayout &DL) {
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000856
857 assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
858 "Expected GEPs with the same pointer operand");
859
860 // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
861 // such that the struct field accesses provably cannot alias.
862 // We also need at least two indices (the pointer, and the struct field).
863 if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
864 GEP1->getNumIndices() < 2)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000865 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000866
867 // If we don't know the size of the accesses through both GEPs, we can't
868 // determine whether the struct fields accessed can't alias.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000869 if (V1Size == MemoryLocation::UnknownSize ||
870 V2Size == MemoryLocation::UnknownSize)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000871 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000872
873 ConstantInt *C1 =
874 dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
875 ConstantInt *C2 =
876 dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
877
878 // If the last (struct) indices aren't constants, we can't say anything.
879 // If they're identical, the other indices might be also be dynamically
880 // equal, so the GEPs can alias.
881 if (!C1 || !C2 || C1 == C2)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000882 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000883
884 // Find the last-indexed type of the GEP, i.e., the type you'd get if
885 // you stripped the last index.
886 // On the way, look at each indexed type. If there's something other
887 // than an array, different indices can lead to different final types.
888 SmallVector<Value *, 8> IntermediateIndices;
889
890 // Insert the first index; we don't need to check the type indexed
891 // through it as it only drops the pointer indirection.
892 assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
893 IntermediateIndices.push_back(GEP1->getOperand(1));
894
895 // Insert all the remaining indices but the last one.
896 // Also, check that they all index through arrays.
897 for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
898 if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
David Blaikied288fb82015-03-30 21:41:43 +0000899 GEP1->getSourceElementType(), IntermediateIndices)))
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000900 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000901 IntermediateIndices.push_back(GEP1->getOperand(i + 1));
902 }
903
904 StructType *LastIndexedStruct =
905 dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
David Blaikied288fb82015-03-30 21:41:43 +0000906 GEP1->getSourceElementType(), IntermediateIndices));
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000907
908 if (!LastIndexedStruct)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000909 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000910
911 // We know that:
912 // - both GEPs begin indexing from the exact same pointer;
913 // - the last indices in both GEPs are constants, indexing into a struct;
914 // - said indices are different, hence, the pointed-to fields are different;
915 // - both GEPs only index through arrays prior to that.
916 //
917 // This lets us determine that the struct that GEP1 indexes into and the
918 // struct that GEP2 indexes into must either precisely overlap or be
919 // completely disjoint. Because they cannot partially overlap, indexing into
920 // different non-overlapping fields of the struct will never alias.
921
922 // Therefore, the only remaining thing needed to show that both GEPs can't
923 // alias is that the fields are not overlapping.
924 const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
925 const uint64_t StructSize = SL->getSizeInBytes();
926 const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
927 const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
928
929 auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
930 uint64_t V2Off, uint64_t V2Size) {
931 return V1Off < V2Off && V1Off + V1Size <= V2Off &&
932 ((V2Off + V2Size <= StructSize) ||
933 (V2Off + V2Size - StructSize <= V1Off));
934 };
935
936 if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
937 EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000938 return NoAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000939
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000940 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000941}
942
Chris Lattnera99edbe2009-11-26 02:11:08 +0000943/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
944/// against another pointer. We know that V1 is a GEP, but we don't know
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000945/// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
Chris Lattner5341c962009-11-26 02:14:59 +0000946/// UnderlyingV2 is the same for V2.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000947///
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000948AliasResult BasicAliasAnalysis::aliasGEP(
949 const GEPOperator *GEP1, uint64_t V1Size, const AAMDNodes &V1AAInfo,
950 const Value *V2, uint64_t V2Size, const AAMDNodes &V2AAInfo,
951 const Value *UnderlyingV1, const Value *UnderlyingV2) {
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000952 int64_t GEP1BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000953 bool GEP1MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000954 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000955
Chandler Carruth66b31302015-01-04 12:03:27 +0000956 // We have to get two AssumptionCaches here because GEP1 and V2 may be from
957 // different functions.
958 // FIXME: This really doesn't make any sense. We get a dominator tree below
959 // that can only refer to a single function. But this function (aliasGEP) is
960 // a method on an immutable pass that can be called when there *isn't*
961 // a single function. The old pass management layer makes this "work", but
962 // this isn't really a clean solution.
963 AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
964 AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
965 if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
966 AC1 = &ACT.getAssumptionCache(
967 const_cast<Function &>(*GEP1I->getParent()->getParent()));
968 if (auto *I2 = dyn_cast<Instruction>(V2))
969 AC2 = &ACT.getAssumptionCache(
970 const_cast<Function &>(*I2->getParent()->getParent()));
971
Hal Finkel60db0582014-09-07 18:57:58 +0000972 DominatorTreeWrapperPass *DTWP =
973 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
974 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
975
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000976 // If we have two gep instructions with must-alias or not-alias'ing base
977 // pointers, figure out if the indexes to the GEP tell us anything about the
978 // derived pointer.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000979 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000980 // Do the base pointers alias?
Chandler Carruthecbd1682015-06-17 07:21:38 +0000981 AliasResult BaseAlias =
982 aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize, AAMDNodes(),
983 UnderlyingV2, MemoryLocation::UnknownSize, AAMDNodes());
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000984
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000985 // Check for geps of non-aliasing underlying pointers where the offsets are
986 // identical.
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000987 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000988 // Do the base pointers alias assuming type and size.
989 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000990 V1AAInfo, UnderlyingV2,
991 V2Size, V2AAInfo);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000992 if (PreciseBaseAlias == NoAlias) {
993 // See if the computed offset from the common pointer tells us about the
994 // relation of the resulting pointer.
995 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000996 bool GEP2MaxLookupReached;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000997 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
998 const Value *GEP2BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +0000999 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001000 GEP2MaxLookupReached, *DL, AC2, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001001 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001002 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001003 GEP1MaxLookupReached, *DL, AC1, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001004 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001005 // same result except when DecomposeGEPExpression has no DataLayout.
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001006 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +00001007 assert(!DL &&
1008 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001009 return MayAlias;
1010 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001011 // If the max search depth is reached the result is undefined
1012 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1013 return MayAlias;
1014
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001015 // Same offsets.
1016 if (GEP1BaseOffset == GEP2BaseOffset &&
Benjamin Kramer147644d2014-04-18 19:48:03 +00001017 GEP1VariableIndices == GEP2VariableIndices)
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001018 return NoAlias;
1019 GEP1VariableIndices.clear();
1020 }
1021 }
Jakub Staszak07f383f2013-08-24 14:16:00 +00001022
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001023 // If we get a No or May, then return it immediately, no amount of analysis
1024 // will improve this situation.
1025 if (BaseAlias != MustAlias) return BaseAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001026
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001027 // Otherwise, we have a MustAlias. Since the base pointers alias each other
1028 // exactly, see if the computed offset from the common pointer tells us
1029 // about the relation of the resulting pointer.
1030 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001031 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001032 GEP1MaxLookupReached, *DL, AC1, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001033
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001034 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001035 bool GEP2MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +00001036 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001037 const Value *GEP2BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001038 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001039 GEP2MaxLookupReached, *DL, AC2, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001040
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001041 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001042 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001043 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +00001044 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +00001045 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001046 return MayAlias;
1047 }
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +00001048
1049 // If we know the two GEPs are based off of the exact same pointer (and not
1050 // just the same underlying object), see if that tells us anything about
1051 // the resulting pointers.
1052 if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
1053 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
1054 // If we couldn't find anything interesting, don't abandon just yet.
1055 if (R != MayAlias)
1056 return R;
1057 }
1058
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001059 // If the max search depth is reached the result is undefined
1060 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1061 return MayAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001062
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001063 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1064 // symbolic difference.
1065 GEP1BaseOffset -= GEP2BaseOffset;
Dan Gohmanad867b02010-08-03 20:23:52 +00001066 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001067
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001068 } else {
1069 // Check to see if these two pointers are related by the getelementptr
1070 // instruction. If one pointer is a GEP with a non-zero index of the other
1071 // pointer, we know they cannot alias.
Chris Lattner5c1cfc22009-11-26 16:52:32 +00001072
1073 // If both accesses are unknown size, we can't do anything useful here.
Chandler Carruthecbd1682015-06-17 07:21:38 +00001074 if (V1Size == MemoryLocation::UnknownSize &&
1075 V2Size == MemoryLocation::UnknownSize)
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001076 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001077
Chandler Carruthecbd1682015-06-17 07:21:38 +00001078 AliasResult R = aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize,
1079 AAMDNodes(), V2, V2Size, V2AAInfo);
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001080 if (R != MustAlias)
1081 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
1082 // If V2 is known not to alias GEP base pointer, then the two values
1083 // cannot alias per GEP semantics: "A pointer value formed from a
1084 // getelementptr instruction is associated with the addresses associated
1085 // with the first operand of the getelementptr".
1086 return R;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001087
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001088 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001089 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001090 GEP1MaxLookupReached, *DL, AC1, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001091
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001092 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001093 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001094 if (GEP1BasePtr != UnderlyingV1) {
Craig Topper9f008862014-04-15 04:59:12 +00001095 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +00001096 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001097 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001098 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001099 // If the max search depth is reached the result is undefined
1100 if (GEP1MaxLookupReached)
1101 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001102 }
Jakub Staszak07f383f2013-08-24 14:16:00 +00001103
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001104 // In the two GEP Case, if there is no difference in the offsets of the
1105 // computed pointers, the resultant pointers are a must alias. This
1106 // hapens when we have two lexically identical GEP's (for example).
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001107 //
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001108 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1109 // must aliases the GEP, the end result is a must alias also.
1110 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
Evan Chengc1eed9d2009-10-14 06:41:49 +00001111 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001112
Eli Friedman3d1b3072011-09-08 02:23:31 +00001113 // If there is a constant difference between the pointers, but the difference
1114 // is less than the size of the associated memory object, then we know
1115 // that the objects are partially overlapping. If the difference is
1116 // greater, we know they do not overlap.
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001117 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001118 if (GEP1BaseOffset >= 0) {
Chandler Carruthecbd1682015-06-17 07:21:38 +00001119 if (V2Size != MemoryLocation::UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001120 if ((uint64_t)GEP1BaseOffset < V2Size)
1121 return PartialAlias;
1122 return NoAlias;
1123 }
1124 } else {
Arnold Schwaighofere3ac0992014-01-16 04:53:18 +00001125 // We have the situation where:
1126 // + +
1127 // | BaseOffset |
1128 // ---------------->|
1129 // |-->V1Size |-------> V2Size
1130 // GEP1 V2
1131 // We need to know that V2Size is not unknown, otherwise we might have
1132 // stripped a gep with negative index ('gep <ptr>, -1, ...).
Chandler Carruthecbd1682015-06-17 07:21:38 +00001133 if (V1Size != MemoryLocation::UnknownSize &&
1134 V2Size != MemoryLocation::UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001135 if (-(uint64_t)GEP1BaseOffset < V1Size)
1136 return PartialAlias;
1137 return NoAlias;
1138 }
1139 }
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001140 }
1141
Eli Friedmanb78ac542011-09-08 02:37:07 +00001142 if (!GEP1VariableIndices.empty()) {
1143 uint64_t Modulo = 0;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001144 bool AllPositive = true;
1145 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
1146
1147 // Try to distinguish something like &A[i][1] against &A[42][0].
1148 // Grab the least significant bit set in any of the scales. We
1149 // don't need std::abs here (even if the scale's negative) as we'll
1150 // be ^'ing Modulo with itself later.
1151 Modulo |= (uint64_t) GEP1VariableIndices[i].Scale;
1152
1153 if (AllPositive) {
1154 // If the Value could change between cycles, then any reasoning about
1155 // the Value this cycle may not hold in the next cycle. We'll just
1156 // give up if we can't determine conditions that hold for every cycle:
1157 const Value *V = GEP1VariableIndices[i].V;
1158
1159 bool SignKnownZero, SignKnownOne;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001160 ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, *DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00001161 0, AC1, nullptr, DT);
Hal Finkel45ba2c12014-11-13 09:16:54 +00001162
1163 // Zero-extension widens the variable, and so forces the sign
1164 // bit to zero.
Manuel Klimek779cf852015-07-13 13:50:55 +00001165 bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001166 SignKnownZero |= IsZExt;
1167 SignKnownOne &= !IsZExt;
1168
1169 // If the variable begins with a zero then we know it's
1170 // positive, regardless of whether the value is signed or
1171 // unsigned.
1172 int64_t Scale = GEP1VariableIndices[i].Scale;
1173 AllPositive =
1174 (SignKnownZero && Scale >= 0) ||
1175 (SignKnownOne && Scale < 0);
1176 }
1177 }
1178
Eli Friedmanb78ac542011-09-08 02:37:07 +00001179 Modulo = Modulo ^ (Modulo & (Modulo - 1));
Eli Friedman3d1b3072011-09-08 02:23:31 +00001180
Eli Friedmanb78ac542011-09-08 02:37:07 +00001181 // We can compute the difference between the two addresses
1182 // mod Modulo. Check whether that difference guarantees that the
1183 // two locations do not alias.
1184 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
Chandler Carruthecbd1682015-06-17 07:21:38 +00001185 if (V1Size != MemoryLocation::UnknownSize &&
1186 V2Size != MemoryLocation::UnknownSize && ModOffset >= V2Size &&
1187 V1Size <= Modulo - ModOffset)
Eli Friedmanb78ac542011-09-08 02:37:07 +00001188 return NoAlias;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001189
1190 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1191 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1192 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1193 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
1194 return NoAlias;
Eli Friedmanb78ac542011-09-08 02:37:07 +00001195 }
Eli Friedman3d1b3072011-09-08 02:23:31 +00001196
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001197 // Statically, we can see that the base objects are the same, but the
1198 // pointers have dynamic offsets which we can't resolve. And none of our
1199 // little tricks above worked.
1200 //
1201 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1202 // practical effect of this is protecting TBAA in the case of dynamic
Dan Gohman9017b842012-02-17 18:33:38 +00001203 // indices into arrays of unions or malloc'd memory.
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001204 return PartialAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001205}
1206
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001207static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
Dan Gohman4e7e7952011-06-03 20:17:36 +00001208 // If the results agree, take it.
1209 if (A == B)
1210 return A;
1211 // A mix of PartialAlias and MustAlias is PartialAlias.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001212 if ((A == PartialAlias && B == MustAlias) ||
1213 (B == PartialAlias && A == MustAlias))
1214 return PartialAlias;
Dan Gohman4e7e7952011-06-03 20:17:36 +00001215 // Otherwise, we don't know anything.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001216 return MayAlias;
Dan Gohman4e7e7952011-06-03 20:17:36 +00001217}
1218
Chris Lattner98e253262009-11-23 16:45:27 +00001219/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1220/// instruction against another.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001221AliasResult BasicAliasAnalysis::aliasSelect(const SelectInst *SI,
1222 uint64_t SISize,
1223 const AAMDNodes &SIAAInfo,
1224 const Value *V2, uint64_t V2Size,
1225 const AAMDNodes &V2AAInfo) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001226 // If the values are Selects with the same condition, we can do a more precise
1227 // check: just check for aliases between the values on corresponding arms.
1228 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1229 if (SI->getCondition() == SI2->getCondition()) {
1230 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001231 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1232 SI2->getTrueValue(), V2Size, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001233 if (Alias == MayAlias)
1234 return MayAlias;
1235 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001236 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1237 SI2->getFalseValue(), V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001238 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001239 }
1240
1241 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1242 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1243 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001244 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001245 if (Alias == MayAlias)
1246 return MayAlias;
Dan Gohman7c34ece2010-06-28 21:16:52 +00001247
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001248 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001249 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001250 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001251}
1252
Evan Chengf92f5552009-10-14 05:22:03 +00001253// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
Evan Cheng31565b32009-10-14 05:05:02 +00001254// against another.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001255AliasResult BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1256 const AAMDNodes &PNAAInfo,
1257 const Value *V2, uint64_t V2Size,
1258 const AAMDNodes &V2AAInfo) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001259 // Track phi nodes we have visited. We use this information when we determine
1260 // value equivalence.
1261 VisitedPhiBBs.insert(PN->getParent());
1262
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001263 // If the values are PHIs in the same block, we can do a more precise
1264 // as well as efficient check: just check for aliases between the values
1265 // on corresponding edges.
1266 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1267 if (PN2->getParent() == PN->getParent()) {
Chandler Carruthac80dc72015-06-17 07:18:54 +00001268 LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
1269 MemoryLocation(V2, V2Size, V2AAInfo));
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001270 if (PN > V2)
1271 std::swap(Locs.first, Locs.second);
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001272 // Analyse the PHIs' inputs under the assumption that the PHIs are
1273 // NoAlias.
1274 // If the PHIs are May/MustAlias there must be (recursively) an input
1275 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1276 // there must be an operation on the PHIs within the PHIs' value cycle
1277 // that causes a MayAlias.
1278 // Pretend the phis do not alias.
1279 AliasResult Alias = NoAlias;
1280 assert(AliasCache.count(Locs) &&
1281 "There must exist an entry for the phi node");
1282 AliasResult OrigAliasResult = AliasCache[Locs];
1283 AliasCache[Locs] = NoAlias;
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001284
Hal Finkela6f86fc2012-11-17 02:33:15 +00001285 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001286 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001287 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001288 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
Hal Finkelcc39b672014-07-24 12:16:19 +00001289 V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001290 Alias = MergeAliasResults(ThisAlias, Alias);
1291 if (Alias == MayAlias)
1292 break;
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001293 }
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001294
1295 // Reset if speculation failed.
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001296 if (Alias != NoAlias)
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001297 AliasCache[Locs] = OrigAliasResult;
1298
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001299 return Alias;
1300 }
1301
Evan Cheng8ec25932009-10-16 00:33:09 +00001302 SmallPtrSet<Value*, 4> UniqueSrc;
Evan Chengc10e88d2009-10-13 22:02:20 +00001303 SmallVector<Value*, 4> V1Srcs;
Tobias Edler von Kochd8ce16b2015-07-15 19:32:22 +00001304 bool isRecursive = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00001305 for (Value *PV1 : PN->incoming_values()) {
Evan Chengc10e88d2009-10-13 22:02:20 +00001306 if (isa<PHINode>(PV1))
1307 // If any of the source itself is a PHI, return MayAlias conservatively
Evan Chengc1eed9d2009-10-14 06:41:49 +00001308 // to avoid compile time explosion. The worst possible case is if both
1309 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1310 // and 'n' are the number of PHI sources.
Evan Chengc10e88d2009-10-13 22:02:20 +00001311 return MayAlias;
Tobias Edler von Kochd8ce16b2015-07-15 19:32:22 +00001312
1313 if (EnableRecPhiAnalysis)
1314 if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
1315 // Check whether the incoming value is a GEP that advances the pointer
1316 // result of this PHI node (e.g. in a loop). If this is the case, we
1317 // would recurse and always get a MayAlias. Handle this case specially
1318 // below.
1319 if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
1320 isa<ConstantInt>(PV1GEP->idx_begin())) {
1321 isRecursive = true;
1322 continue;
1323 }
1324 }
1325
David Blaikie70573dc2014-11-19 07:49:26 +00001326 if (UniqueSrc.insert(PV1).second)
Evan Chengc10e88d2009-10-13 22:02:20 +00001327 V1Srcs.push_back(PV1);
1328 }
1329
Tobias Edler von Kochd8ce16b2015-07-15 19:32:22 +00001330 // If this PHI node is recursive, set the size of the accessed memory to
1331 // unknown to represent all the possible values the GEP could advance the
1332 // pointer to.
1333 if (isRecursive)
1334 PNSize = MemoryLocation::UnknownSize;
1335
Hal Finkelcc39b672014-07-24 12:16:19 +00001336 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
1337 V1Srcs[0], PNSize, PNAAInfo);
Tobias Edler von Kochd8ce16b2015-07-15 19:32:22 +00001338
Evan Chengf92f5552009-10-14 05:22:03 +00001339 // Early exit if the check of the first PHI source against V2 is MayAlias.
1340 // Other results are not possible.
1341 if (Alias == MayAlias)
1342 return MayAlias;
1343
Evan Chengc10e88d2009-10-13 22:02:20 +00001344 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1345 // NoAlias / MustAlias. Otherwise, returns MayAlias.
Evan Chengc10e88d2009-10-13 22:02:20 +00001346 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1347 Value *V = V1Srcs[i];
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001348
Hal Finkelcc39b672014-07-24 12:16:19 +00001349 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
1350 V, PNSize, PNAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001351 Alias = MergeAliasResults(ThisAlias, Alias);
1352 if (Alias == MayAlias)
1353 break;
Evan Chengc10e88d2009-10-13 22:02:20 +00001354 }
1355
1356 return Alias;
1357}
1358
1359// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1360// such as array references.
Evan Chengf1f3dd32009-10-13 18:42:04 +00001361//
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001362AliasResult BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1363 AAMDNodes V1AAInfo, const Value *V2,
1364 uint64_t V2Size,
1365 AAMDNodes V2AAInfo) {
Dan Gohmancb45bd92010-04-08 18:11:50 +00001366 // If either of the memory references is empty, it doesn't matter what the
1367 // pointer values are.
1368 if (V1Size == 0 || V2Size == 0)
1369 return NoAlias;
1370
Evan Chengf1f3dd32009-10-13 18:42:04 +00001371 // Strip off any casts if they exist.
1372 V1 = V1->stripPointerCasts();
1373 V2 = V2->stripPointerCasts();
1374
Daniel Berlin3459d6e2015-05-05 18:10:49 +00001375 // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1376 // value for undef that aliases nothing in the program.
1377 if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1378 return NoAlias;
1379
Evan Chengf1f3dd32009-10-13 18:42:04 +00001380 // Are we checking for alias of the same value?
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001381 // Because we look 'through' phi nodes we could look at "Value" pointers from
1382 // different iterations. We must therefore make sure that this is not the
1383 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1384 // happen by looking at the visited phi nodes and making sure they cannot
1385 // reach the value.
1386 if (isValueEqualInPotentialCycles(V1, V2))
1387 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001388
Duncan Sands19d0b472010-02-16 11:11:14 +00001389 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
Evan Chengf1f3dd32009-10-13 18:42:04 +00001390 return NoAlias; // Scalars cannot alias each other
1391
1392 // Figure out what objects these things are pointing to if we can.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001393 const Value *O1 = GetUnderlyingObject(V1, *DL, MaxLookupSearchDepth);
1394 const Value *O2 = GetUnderlyingObject(V2, *DL, MaxLookupSearchDepth);
Evan Chengf1f3dd32009-10-13 18:42:04 +00001395
Dan Gohmanccb45842009-11-09 19:29:11 +00001396 // Null values in the default address space don't point to any object, so they
1397 // don't alias any other pointer.
1398 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1399 if (CPN->getType()->getAddressSpace() == 0)
1400 return NoAlias;
1401 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1402 if (CPN->getType()->getAddressSpace() == 0)
1403 return NoAlias;
1404
Evan Chengf1f3dd32009-10-13 18:42:04 +00001405 if (O1 != O2) {
1406 // If V1/V2 point to two different objects we know that we have no alias.
Dan Gohman00ef9322010-07-07 14:27:09 +00001407 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001408 return NoAlias;
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001409
1410 // Constant pointers can't alias with non-const isIdentifiedObject objects.
Dan Gohman00ef9322010-07-07 14:27:09 +00001411 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1412 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001413 return NoAlias;
1414
Michael Kupersteinf3e663a2013-05-28 08:17:48 +00001415 // Function arguments can't alias with things that are known to be
1416 // unambigously identified at the function level.
1417 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1418 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
Dan Gohman84f90a32010-07-01 20:08:40 +00001419 return NoAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001420
1421 // Most objects can't alias null.
Dan Gohman00ef9322010-07-07 14:27:09 +00001422 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1423 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001424 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001425
Dan Gohman5b0a8a82010-07-07 14:30:04 +00001426 // If one pointer is the result of a call/invoke or load and the other is a
1427 // non-escaping local object within the same function, then we know the
1428 // object couldn't escape to a point where the call could return it.
1429 //
1430 // Note that if the pointers are in different functions, there are a
1431 // variety of complications. A call with a nocapture argument may still
1432 // temporary store the nocapture argument's value in a temporary memory
1433 // location if that memory location doesn't escape. Or it may pass a
1434 // nocapture value to other functions as long as they don't capture it.
1435 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1436 return NoAlias;
1437 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1438 return NoAlias;
1439 }
1440
Evan Chengf1f3dd32009-10-13 18:42:04 +00001441 // If the size of one access is larger than the entire object on the other
1442 // side, then we know such behavior is undefined and can assume no alias.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001443 if (DL)
Chandler Carruthecbd1682015-06-17 07:21:38 +00001444 if ((V1Size != MemoryLocation::UnknownSize &&
1445 isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1446 (V2Size != MemoryLocation::UnknownSize &&
1447 isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001448 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001449
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001450 // Check the cache before climbing up use-def chains. This also terminates
1451 // otherwise infinitely recursive queries.
Chandler Carruthac80dc72015-06-17 07:18:54 +00001452 LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
1453 MemoryLocation(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001454 if (V1 > V2)
1455 std::swap(Locs.first, Locs.second);
1456 std::pair<AliasCacheTy::iterator, bool> Pair =
1457 AliasCache.insert(std::make_pair(Locs, MayAlias));
1458 if (!Pair.second)
1459 return Pair.first->second;
1460
Chris Lattner89288992009-11-26 02:13:03 +00001461 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1462 // GEP can't simplify, we don't even look at the PHI cases.
Chris Lattnerb2647b92009-10-17 23:48:54 +00001463 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001464 std::swap(V1, V2);
1465 std::swap(V1Size, V2Size);
Chris Lattner5341c962009-11-26 02:14:59 +00001466 std::swap(O1, O2);
Hal Finkelcc39b672014-07-24 12:16:19 +00001467 std::swap(V1AAInfo, V2AAInfo);
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001468 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001469 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001470 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001471 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001472 }
Evan Chengc10e88d2009-10-13 22:02:20 +00001473
1474 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1475 std::swap(V1, V2);
1476 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001477 std::swap(V1AAInfo, V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +00001478 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001479 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001480 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1481 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001482 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001483 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001484
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001485 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1486 std::swap(V1, V2);
1487 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001488 std::swap(V1AAInfo, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001489 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001490 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001491 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
1492 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001493 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001494 }
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001495
Dan Gohman44da55b2011-01-18 21:16:06 +00001496 // If both pointers are pointing into the same object and one of them
1497 // accesses is accessing the entire object, then the accesses must
1498 // overlap in some way.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001499 if (DL && O1 == O2)
Chandler Carruthecbd1682015-06-17 07:21:38 +00001500 if ((V1Size != MemoryLocation::UnknownSize &&
1501 isObjectSize(O1, V1Size, *DL, *TLI)) ||
1502 (V2Size != MemoryLocation::UnknownSize &&
1503 isObjectSize(O2, V2Size, *DL, *TLI)))
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001504 return AliasCache[Locs] = PartialAlias;
Dan Gohman44da55b2011-01-18 21:16:06 +00001505
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001506 AliasResult Result =
Chandler Carruthac80dc72015-06-17 07:18:54 +00001507 AliasAnalysis::alias(MemoryLocation(V1, V1Size, V1AAInfo),
1508 MemoryLocation(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001509 return AliasCache[Locs] = Result;
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001510}
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001511
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001512bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1513 const Value *V2) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001514 if (V != V2)
1515 return false;
1516
1517 const Instruction *Inst = dyn_cast<Instruction>(V);
1518 if (!Inst)
1519 return true;
1520
Daniel Berlin9e77de22015-03-20 18:05:49 +00001521 if (VisitedPhiBBs.empty())
1522 return true;
1523
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001524 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1525 return false;
1526
1527 // Use dominance or loop info if available.
Chandler Carruth73523022014-01-13 13:07:17 +00001528 DominatorTreeWrapperPass *DTWP =
1529 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topper9f008862014-04-15 04:59:12 +00001530 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001531 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1532 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001533
1534 // Make sure that the visited phis cannot reach the Value. This ensures that
1535 // the Values cannot come from different iterations of a potential cycle the
1536 // phi nodes could be involved in.
Craig Topper46276792014-08-24 23:23:06 +00001537 for (auto *P : VisitedPhiBBs)
1538 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001539 return false;
1540
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001541 return true;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001542}
1543
1544/// GetIndexDifference - Dest and Src are the variable indices from two
1545/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1546/// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1547/// difference between the two pointers.
1548void BasicAliasAnalysis::GetIndexDifference(
1549 SmallVectorImpl<VariableGEPIndex> &Dest,
1550 const SmallVectorImpl<VariableGEPIndex> &Src) {
1551 if (Src.empty())
1552 return;
1553
1554 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1555 const Value *V = Src[i].V;
Manuel Klimek779cf852015-07-13 13:50:55 +00001556 ExtensionKind Extension = Src[i].Extension;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001557 int64_t Scale = Src[i].Scale;
1558
1559 // Find V in Dest. This is N^2, but pointer indices almost never have more
1560 // than a few variable indexes.
1561 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001562 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
Manuel Klimek779cf852015-07-13 13:50:55 +00001563 Dest[j].Extension != Extension)
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001564 continue;
1565
1566 // If we found it, subtract off Scale V's from the entry in Dest. If it
1567 // goes to zero, remove the entry.
1568 if (Dest[j].Scale != Scale)
1569 Dest[j].Scale -= Scale;
1570 else
1571 Dest.erase(Dest.begin() + j);
1572 Scale = 0;
1573 break;
1574 }
1575
1576 // If we didn't consume this entry, add it to the end of the Dest list.
1577 if (Scale) {
Manuel Klimek779cf852015-07-13 13:50:55 +00001578 VariableGEPIndex Entry = { V, Extension, -Scale };
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001579 Dest.push_back(Entry);
1580 }
1581 }
1582}