blob: 68f766edb301342eedc8c2f23910bdbf6e2db8d0 [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
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000045/// Cutoff after which to stop analysing a set of phi nodes potentially involved
46/// in a cycle. Because we are analysing 'through' phi nodes we need to be
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000047/// careful with value equivalence. We use reachability to make sure a value
48/// cannot be involved in a cycle.
49const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000050
Arnold Schwaighofer1a444482014-03-26 21:30:19 +000051// The max limit of the search depth in DecomposeGEPExpression() and
52// GetUnderlyingObject(), both functions need to use the same search
53// depth otherwise the algorithm in aliasGEP will assert.
54static const unsigned MaxLookupSearchDepth = 6;
55
Chris Lattner2d332972008-06-16 06:30:22 +000056//===----------------------------------------------------------------------===//
57// Useful predicates
58//===----------------------------------------------------------------------===//
Devang Patel09f162c2007-05-01 21:15:47 +000059
Chris Lattnerb35d9b52008-06-16 06:19:11 +000060/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
61/// object that never escapes from the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000062static bool isNonEscapingLocalObject(const Value *V) {
Chris Lattnerfa482582008-06-16 06:28:01 +000063 // If this is a local allocation, check to see if it escapes.
Dan Gohman84f90a32010-07-01 20:08:40 +000064 if (isa<AllocaInst>(V) || isNoAliasCall(V))
Dan Gohman94e61762009-11-19 21:57:48 +000065 // Set StoreCaptures to True so that we can assume in our callers that the
66 // pointer is not the result of a load instruction. Currently
67 // PointerMayBeCaptured doesn't have any special analysis for the
68 // StoreCaptures=false case; if it did, our callers could be refined to be
69 // more precise.
70 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Duncan Sands8d65f362009-01-05 21:19:53 +000071
Chris Lattnerfa482582008-06-16 06:28:01 +000072 // If this is an argument that corresponds to a byval or noalias argument,
Duncan Sands8d65f362009-01-05 21:19:53 +000073 // then it has not escaped before entering the function. Check if it escapes
74 // inside the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000075 if (const Argument *A = dyn_cast<Argument>(V))
Richard Osbornea1fffcf2012-11-05 10:48:24 +000076 if (A->hasByValAttr() || A->hasNoAliasAttr())
77 // Note even if the argument is marked nocapture we still need to check
78 // for copies made inside the function. The nocapture attribute only
79 // specifies that there are no copies made that outlive the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000080 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Richard Osbornea1fffcf2012-11-05 10:48:24 +000081
Chris Lattnerb35d9b52008-06-16 06:19:11 +000082 return false;
83}
84
Dan Gohman0824aff2010-06-29 00:50:39 +000085/// isEscapeSource - Return true if the pointer is one which would have
86/// been considered an escape by isNonEscapingLocalObject.
Dan Gohman84f90a32010-07-01 20:08:40 +000087static bool isEscapeSource(const Value *V) {
88 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
89 return true;
Dan Gohman0824aff2010-06-29 00:50:39 +000090
91 // The load case works because isNonEscapingLocalObject considers all
92 // stores to be escapes (it passes true for the StoreCaptures argument
93 // to PointerMayBeCaptured).
94 if (isa<LoadInst>(V))
95 return true;
96
97 return false;
98}
Chris Lattnerb35d9b52008-06-16 06:19:11 +000099
Dan Gohman44da55b2011-01-18 21:16:06 +0000100/// getObjectSize - Return the size of the object specified by V, or
101/// UnknownSize if unknown.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000102static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000103 const TargetLibraryInfo &TLI,
Eli Friedman8bc169c2012-02-27 20:46:07 +0000104 bool RoundToAlign = false) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000105 uint64_t Size;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000106 if (getObjectSize(V, Size, DL, &TLI, RoundToAlign))
Nuno Lopes55fff832012-06-21 15:45:28 +0000107 return Size;
Chandler Carruthecbd1682015-06-17 07:21:38 +0000108 return MemoryLocation::UnknownSize;
Dan Gohman44da55b2011-01-18 21:16:06 +0000109}
110
111/// isObjectSmallerThan - Return true if we can prove that the object specified
112/// by V is smaller than Size.
113static bool isObjectSmallerThan(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000114 const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000115 const TargetLibraryInfo &TLI) {
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000116 // Note that the meanings of the "object" are slightly different in the
117 // following contexts:
118 // c1: llvm::getObjectSize()
119 // c2: llvm.objectsize() intrinsic
120 // c3: isObjectSmallerThan()
121 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
122 // refers to the "entire object".
123 //
124 // Consider this example:
125 // char *p = (char*)malloc(100)
126 // char *q = p+80;
127 //
128 // In the context of c1 and c2, the "object" pointed by q refers to the
129 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
130 //
131 // However, in the context of c3, the "object" refers to the chunk of memory
132 // being allocated. So, the "object" has 100 bytes, and q points to the middle
133 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
134 // parameter, before the llvm::getObjectSize() is called to get the size of
135 // entire object, we should:
136 // - either rewind the pointer q to the base-address of the object in
137 // question (in this case rewind to p), or
138 // - just give up. It is up to caller to make sure the pointer is pointing
139 // to the base address the object.
Jakub Staszak07f383f2013-08-24 14:16:00 +0000140 //
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000141 // We go for 2nd option for simplicity.
142 if (!isIdentifiedObject(V))
143 return false;
144
Eli Friedman8bc169c2012-02-27 20:46:07 +0000145 // This function needs to use the aligned object size because we allow
146 // reads a bit past the end given sufficient alignment.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000147 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000148
Chandler Carruthecbd1682015-06-17 07:21:38 +0000149 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
Dan Gohman44da55b2011-01-18 21:16:06 +0000150}
151
152/// isObjectSize - Return true if we can prove that the object specified
153/// by V has size Size.
154static bool isObjectSize(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000155 const DataLayout &DL, const TargetLibraryInfo &TLI) {
156 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000157 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
Chris Lattner98ad8162008-06-16 06:10:11 +0000158}
159
Chris Lattner2d332972008-06-16 06:30:22 +0000160//===----------------------------------------------------------------------===//
Chris Lattner9f7500f2010-08-18 22:07:29 +0000161// GetElementPtr Instruction Decomposition and Analysis
162//===----------------------------------------------------------------------===//
163
Chris Lattner1b9c3872010-08-18 22:47:56 +0000164namespace {
Manuel Klimek779cf852015-07-13 13:50:55 +0000165 enum ExtensionKind {
166 EK_NotExtended,
167 EK_SignExt,
168 EK_ZeroExt
169 };
Jakub Staszak07f383f2013-08-24 14:16:00 +0000170
Chris Lattner1b9c3872010-08-18 22:47:56 +0000171 struct VariableGEPIndex {
172 const Value *V;
Manuel Klimek779cf852015-07-13 13:50:55 +0000173 ExtensionKind Extension;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000174 int64_t Scale;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000175
176 bool operator==(const VariableGEPIndex &Other) const {
Manuel Klimek779cf852015-07-13 13:50:55 +0000177 return V == Other.V && Extension == Other.Extension &&
178 Scale == Other.Scale;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000179 }
180
181 bool operator!=(const VariableGEPIndex &Other) const {
182 return !operator==(Other);
183 }
Chris Lattner1b9c3872010-08-18 22:47:56 +0000184 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000185}
Chris Lattner1b9c3872010-08-18 22:47:56 +0000186
Chris Lattner9f7500f2010-08-18 22:07:29 +0000187
188/// GetLinearExpression - Analyze the specified value as a linear expression:
189/// "A*V + B", where A and B are constant integers. Return the scale and offset
Chris Lattner3decde92010-08-18 23:09:49 +0000190/// values as APInts and return V as a Value*, and return whether we looked
191/// through any sign or zero extends. The incoming Value is known to have
192/// IntegerType and it may already be sign or zero extended.
193///
194/// Note that this looks through extends, so the high bits may not be
195/// represented in the result.
Manuel Klimek779cf852015-07-13 13:50:55 +0000196static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
197 ExtensionKind &Extension,
198 const DataLayout &DL, unsigned Depth,
199 AssumptionCache *AC, DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000200 assert(V->getType()->isIntegerTy() && "Not an integer value");
201
202 // Limit our recursion depth.
203 if (Depth == 6) {
204 Scale = 1;
205 Offset = 0;
206 return V;
207 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000208
Manuel Klimek779cf852015-07-13 13:50:55 +0000209 if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
210 // if it's a constant, just convert it to an offset
211 // and remove the variable.
212 Offset += Const->getValue();
Hal Finkel45ba2c12014-11-13 09:16:54 +0000213 assert(Scale == 0 && "Constant values don't have a scale");
214 return V;
215 }
216
Manuel Klimek779cf852015-07-13 13:50:55 +0000217 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000218 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
219 switch (BOp->getOpcode()) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000220 default: break;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000221 case Instruction::Or:
222 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
223 // analyze it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000224 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000225 BOp, DT))
Chris Lattner9f7500f2010-08-18 22:07:29 +0000226 break;
227 // FALL THROUGH.
228 case Instruction::Add:
Manuel Klimek779cf852015-07-13 13:50:55 +0000229 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
230 DL, Depth + 1, AC, DT);
231 Offset += RHSC->getValue();
232 return V;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000233 case Instruction::Mul:
Manuel Klimek779cf852015-07-13 13:50:55 +0000234 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
235 DL, Depth + 1, AC, DT);
236 Offset *= RHSC->getValue();
237 Scale *= RHSC->getValue();
238 return V;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000239 case Instruction::Shl:
Manuel Klimek779cf852015-07-13 13:50:55 +0000240 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
241 DL, Depth + 1, AC, DT);
242 Offset <<= RHSC->getValue().getLimitedValue();
243 Scale <<= RHSC->getValue().getLimitedValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000244 return V;
245 }
246 }
247 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000248
Chris Lattner9f7500f2010-08-18 22:07:29 +0000249 // Since GEP indices are sign extended anyway, we don't care about the high
Chris Lattner3decde92010-08-18 23:09:49 +0000250 // bits of a sign or zero extended value - just scales and offsets. The
251 // extensions have to be consistent though.
Manuel Klimek779cf852015-07-13 13:50:55 +0000252 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
253 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000254 Value *CastOp = cast<CastInst>(V)->getOperand(0);
Manuel Klimek779cf852015-07-13 13:50:55 +0000255 unsigned OldWidth = Scale.getBitWidth();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000256 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
Manuel Klimek779cf852015-07-13 13:50:55 +0000257 Scale = Scale.trunc(SmallWidth);
258 Offset = Offset.trunc(SmallWidth);
259 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
Chris Lattner3decde92010-08-18 23:09:49 +0000260
Manuel Klimek779cf852015-07-13 13:50:55 +0000261 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, DL,
262 Depth + 1, AC, DT);
263 Scale = Scale.zext(OldWidth);
Hal Finkel45ba2c12014-11-13 09:16:54 +0000264
Manuel Klimek779cf852015-07-13 13:50:55 +0000265 // We have to sign-extend even if Extension == EK_ZeroExt as we can't
266 // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
267 Offset = Offset.sext(OldWidth);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000268
Chris Lattner9f7500f2010-08-18 22:07:29 +0000269 return Result;
270 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000271
Chris Lattner9f7500f2010-08-18 22:07:29 +0000272 Scale = 1;
273 Offset = 0;
274 return V;
275}
276
277/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
278/// into a base pointer with a constant offset and a number of scaled symbolic
279/// offsets.
280///
281/// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
282/// the VarIndices vector) are Value*'s that are known to be scaled by the
283/// specified amount, but which may have other unrepresented high bits. As such,
284/// the gep cannot necessarily be reconstructed from its decomposed form.
285///
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000286/// When DataLayout is around, this function is capable of analyzing everything
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000287/// that GetUnderlyingObject can look through. To be able to do that
288/// GetUnderlyingObject and DecomposeGEPExpression must use the same search
289/// depth (MaxLookupSearchDepth).
290/// When DataLayout not is around, it just looks through pointer casts.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000291///
292static const Value *
293DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
Chris Lattner1b9c3872010-08-18 22:47:56 +0000294 SmallVectorImpl<VariableGEPIndex> &VarIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000295 bool &MaxLookupReached, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000296 AssumptionCache *AC, DominatorTree *DT) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000297 // Limit recursion depth to limit compile time in crazy cases.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000298 unsigned MaxLookup = MaxLookupSearchDepth;
299 MaxLookupReached = false;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000300
Chris Lattner9f7500f2010-08-18 22:07:29 +0000301 BaseOffs = 0;
302 do {
303 // See if this is a bitcast or GEP.
304 const Operator *Op = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +0000305 if (!Op) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000306 // The only non-operator case we can handle are GlobalAliases.
307 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
308 if (!GA->mayBeOverridden()) {
309 V = GA->getAliasee();
310 continue;
311 }
312 }
313 return V;
314 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000315
Matt Arsenault70f4db882014-07-15 00:56:40 +0000316 if (Op->getOpcode() == Instruction::BitCast ||
317 Op->getOpcode() == Instruction::AddrSpaceCast) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000318 V = Op->getOperand(0);
319 continue;
320 }
Dan Gohman05b18f12010-12-15 20:49:55 +0000321
Chris Lattner9f7500f2010-08-18 22:07:29 +0000322 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
Craig Topper9f008862014-04-15 04:59:12 +0000323 if (!GEPOp) {
Dan Gohman0573b552011-05-24 18:24:08 +0000324 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
325 // can come up with something. This matches what GetUnderlyingObject does.
326 if (const Instruction *I = dyn_cast<Instruction>(V))
Chandler Carruth66b31302015-01-04 12:03:27 +0000327 // TODO: Get a DominatorTree and AssumptionCache and use them here
Hal Finkel60db0582014-09-07 18:57:58 +0000328 // (these are both now available in this function, but this should be
329 // updated when GetUnderlyingObject is updated). TLI should be
330 // provided also.
Dan Gohman0573b552011-05-24 18:24:08 +0000331 if (const Value *Simplified =
Rafael Espindola5f57f462014-02-21 18:34:28 +0000332 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
Dan Gohman0573b552011-05-24 18:24:08 +0000333 V = Simplified;
334 continue;
335 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000336
Chris Lattner9f7500f2010-08-18 22:07:29 +0000337 return V;
Dan Gohman0573b552011-05-24 18:24:08 +0000338 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000339
Chris Lattner9f7500f2010-08-18 22:07:29 +0000340 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000341 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
Chris Lattner9f7500f2010-08-18 22:07:29 +0000342 return V;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000343
Matt Arsenaulta8fe22b2013-11-16 00:36:43 +0000344 unsigned AS = GEPOp->getPointerAddressSpace();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000345 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
346 gep_type_iterator GTI = gep_type_begin(GEPOp);
347 for (User::const_op_iterator I = GEPOp->op_begin()+1,
348 E = GEPOp->op_end(); I != E; ++I) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000349 Value *Index = *I;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000350 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +0000351 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000352 // For a struct, add the member offset.
353 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
354 if (FieldNo == 0) continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000355
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000356 BaseOffs += DL.getStructLayout(STy)->getElementOffset(FieldNo);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000357 continue;
358 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000359
Chris Lattner9f7500f2010-08-18 22:07:29 +0000360 // For an array/pointer, add the element offset, explicitly scaled.
Manuel Klimek779cf852015-07-13 13:50:55 +0000361 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000362 if (CIdx->isZero()) continue;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000363 BaseOffs += DL.getTypeAllocSize(*GTI) * CIdx->getSExtValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000364 continue;
365 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000366
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000367 uint64_t Scale = DL.getTypeAllocSize(*GTI);
Manuel Klimek779cf852015-07-13 13:50:55 +0000368 ExtensionKind Extension = EK_NotExtended;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000369
Chris Lattner3decde92010-08-18 23:09:49 +0000370 // If the integer type is smaller than the pointer size, it is implicitly
371 // sign extended to pointer size.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000372 unsigned Width = Index->getType()->getIntegerBitWidth();
Manuel Klimek779cf852015-07-13 13:50:55 +0000373 if (DL.getPointerSizeInBits(AS) > Width)
374 Extension = EK_SignExt;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000375
Chris Lattner3decde92010-08-18 23:09:49 +0000376 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000377 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
Manuel Klimek779cf852015-07-13 13:50:55 +0000378 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension, DL,
379 0, AC, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000380
Chris Lattner9f7500f2010-08-18 22:07:29 +0000381 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
382 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
Eli Friedmanab3a1282010-09-15 20:08:03 +0000383 BaseOffs += IndexOffset.getSExtValue()*Scale;
384 Scale *= IndexScale.getSExtValue();
Jakub Staszak07f383f2013-08-24 14:16:00 +0000385
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000386 // If we already had an occurrence of this index variable, merge this
Chris Lattner9f7500f2010-08-18 22:07:29 +0000387 // scale into it. For example, we want to handle:
388 // A[x][x] -> x*16 + x*4 -> x*20
389 // This also ensures that 'x' only appears in the index list once.
390 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000391 if (VarIndices[i].V == Index &&
392 VarIndices[i].Extension == Extension) {
Chris Lattner1b9c3872010-08-18 22:47:56 +0000393 Scale += VarIndices[i].Scale;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000394 VarIndices.erase(VarIndices.begin()+i);
395 break;
396 }
397 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000398
Chris Lattner9f7500f2010-08-18 22:07:29 +0000399 // Make sure that we have a scale that makes sense for this target's
400 // pointer size.
Manuel Klimek779cf852015-07-13 13:50:55 +0000401 if (unsigned ShiftBits = 64 - DL.getPointerSizeInBits(AS)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000402 Scale <<= ShiftBits;
Eli Friedmanab3a1282010-09-15 20:08:03 +0000403 Scale = (int64_t)Scale >> ShiftBits;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000404 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000405
Chris Lattner1b9c3872010-08-18 22:47:56 +0000406 if (Scale) {
Manuel Klimek779cf852015-07-13 13:50:55 +0000407 VariableGEPIndex Entry = {Index, Extension,
Jeffrey Yasskin6381c012011-07-27 06:22:51 +0000408 static_cast<int64_t>(Scale)};
Chris Lattner1b9c3872010-08-18 22:47:56 +0000409 VarIndices.push_back(Entry);
410 }
Chris Lattner9f7500f2010-08-18 22:07:29 +0000411 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000412
Chris Lattner9f7500f2010-08-18 22:07:29 +0000413 // Analyze the base pointer next.
414 V = GEPOp->getOperand(0);
415 } while (--MaxLookup);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000416
Chris Lattner9f7500f2010-08-18 22:07:29 +0000417 // If the chain of expressions is too deep, just return early.
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000418 MaxLookupReached = true;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000419 return V;
420}
421
Chris Lattner9f7500f2010-08-18 22:07:29 +0000422//===----------------------------------------------------------------------===//
Dan Gohman0824aff2010-06-29 00:50:39 +0000423// BasicAliasAnalysis Pass
Chris Lattner2d332972008-06-16 06:30:22 +0000424//===----------------------------------------------------------------------===//
425
Dan Gohman00ef9322010-07-07 14:27:09 +0000426#ifndef NDEBUG
Dan Gohman0824aff2010-06-29 00:50:39 +0000427static const Function *getParent(const Value *V) {
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000428 if (const Instruction *inst = dyn_cast<Instruction>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000429 return inst->getParent()->getParent();
430
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000431 if (const Argument *arg = dyn_cast<Argument>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000432 return arg->getParent();
433
Craig Topper9f008862014-04-15 04:59:12 +0000434 return nullptr;
Dan Gohman0824aff2010-06-29 00:50:39 +0000435}
436
Dan Gohman84f90a32010-07-01 20:08:40 +0000437static bool notDifferentParent(const Value *O1, const Value *O2) {
438
439 const Function *F1 = getParent(O1);
440 const Function *F2 = getParent(O2);
441
Dan Gohman0824aff2010-06-29 00:50:39 +0000442 return !F1 || !F2 || F1 == F2;
443}
Benjamin Kramer80b7bc02010-06-29 10:03:11 +0000444#endif
Dan Gohman0824aff2010-06-29 00:50:39 +0000445
Chris Lattner2d332972008-06-16 06:30:22 +0000446namespace {
Dan Gohmanda85ed82010-10-19 23:09:08 +0000447 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
448 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
Chris Lattner2d332972008-06-16 06:30:22 +0000449 static char ID; // Class identification, replacement for typeinfo
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000450 BasicAliasAnalysis() : ImmutablePass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000451 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
452 }
Dan Gohman0824aff2010-06-29 00:50:39 +0000453
Mehdi Amini46a43552015-03-04 18:43:29 +0000454 bool doInitialization(Module &M) override;
Dan Gohman02538ac2010-10-18 18:04:47 +0000455
Craig Toppere9ba7592014-03-05 07:30:04 +0000456 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000457 AU.addRequired<AliasAnalysis>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000458 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000459 AU.addRequired<TargetLibraryInfoWrapperPass>();
Dan Gohman02538ac2010-10-18 18:04:47 +0000460 }
461
Chandler Carruthac80dc72015-06-17 07:18:54 +0000462 AliasResult alias(const MemoryLocation &LocA,
463 const MemoryLocation &LocB) override {
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000464 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
Dan Gohman41f14cf2010-09-14 21:25:10 +0000465 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000466 "BasicAliasAnalysis doesn't support interprocedural queries.");
Hal Finkelcc39b672014-07-24 12:16:19 +0000467 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags,
468 LocB.Ptr, LocB.Size, LocB.AATags);
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000469 // AliasCache rarely has more than 1 or 2 elements, always use
470 // shrink_and_clear so it quickly returns to the inline capacity of the
471 // SmallDenseMap if it ever grows larger.
472 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
473 AliasCache.shrink_and_clear();
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000474 VisitedPhiBBs.clear();
Evan Chengb3ccb642009-10-14 06:46:26 +0000475 return Alias;
Evan Chengc10e88d2009-10-13 22:02:20 +0000476 }
Chris Lattner2d332972008-06-16 06:30:22 +0000477
Craig Toppere9ba7592014-03-05 07:30:04 +0000478 ModRefResult getModRefInfo(ImmutableCallSite CS,
Chandler Carruthac80dc72015-06-17 07:18:54 +0000479 const MemoryLocation &Loc) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000480
Craig Toppere9ba7592014-03-05 07:30:04 +0000481 ModRefResult getModRefInfo(ImmutableCallSite CS1,
Hal Finkel93046912014-07-25 21:13:35 +0000482 ImmutableCallSite CS2) override;
Owen Anderson98a36172009-02-05 23:36:27 +0000483
Chris Lattner2d332972008-06-16 06:30:22 +0000484 /// pointsToConstantMemory - Chase pointers until we find a (constant
485 /// global) or not.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000486 bool pointsToConstantMemory(const MemoryLocation &Loc,
487 bool OrLocal) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000488
Hal Finkel354e23b2014-07-17 01:28:25 +0000489 /// Get the location associated with a pointer argument of a callsite.
Chandler Carruthc41404a2015-06-17 07:12:40 +0000490 ModRefResult getArgModRefInfo(ImmutableCallSite CS,
491 unsigned ArgIdx) override;
Hal Finkel354e23b2014-07-17 01:28:25 +0000492
Dan Gohman5f1702e2010-08-06 01:25:49 +0000493 /// getModRefBehavior - Return the behavior when calling the given
494 /// call site.
Craig Toppere9ba7592014-03-05 07:30:04 +0000495 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000496
497 /// getModRefBehavior - Return the behavior when calling the given function.
498 /// For use when the call site is not known.
Craig Toppere9ba7592014-03-05 07:30:04 +0000499 ModRefBehavior getModRefBehavior(const Function *F) override;
Chris Lattner2d332972008-06-16 06:30:22 +0000500
Chris Lattneraf362f02010-01-20 19:26:14 +0000501 /// getAdjustedAnalysisPointer - This method is used when a pass implements
Dan Gohmane0d5c452010-08-05 23:48:14 +0000502 /// an analysis interface through multiple inheritance. If needed, it
503 /// should override this to adjust the this pointer as needed for the
504 /// specified pass info.
Craig Toppere9ba7592014-03-05 07:30:04 +0000505 void *getAdjustedAnalysisPointer(const void *ID) override {
Owen Andersona7aed182010-08-06 18:33:48 +0000506 if (ID == &AliasAnalysis::ID)
Chris Lattneraf362f02010-01-20 19:26:14 +0000507 return (AliasAnalysis*)this;
508 return this;
509 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000510
Chris Lattner2d332972008-06-16 06:30:22 +0000511 private:
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000512 // AliasCache - Track alias queries to guard against recursion.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000513 typedef std::pair<MemoryLocation, MemoryLocation> LocPair;
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000514 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000515 AliasCacheTy AliasCache;
516
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000517 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
518 /// equality as value equality we need to make sure that the "Value" is not
519 /// part of a cycle. Otherwise, two uses could come from different
520 /// "iterations" of a cycle and see different values for the same "Value"
521 /// pointer.
522 /// The following example shows the problem:
523 /// %p = phi(%alloca1, %addr2)
524 /// %l = load %ptr
525 /// %addr1 = gep, %alloca2, 0, %l
526 /// %addr2 = gep %alloca2, 0, (%l + 1)
527 /// alias(%p, %addr1) -> MayAlias !
528 /// store %l, ...
529 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
530
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000531 // Visited - Track instructions visited by pointsToConstantMemory.
Dan Gohman7c34ece2010-06-28 21:16:52 +0000532 SmallPtrSet<const Value*, 16> Visited;
Evan Cheng31565b32009-10-14 05:05:02 +0000533
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000534 /// \brief Check whether two Values can be considered equivalent.
535 ///
536 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
537 /// whether they can not be part of a cycle in the value graph by looking at
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +0000538 /// all visited phi nodes an making sure that the phis cannot reach the
539 /// value. We have to do this because we are looking through phi nodes (That
540 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
541 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000542
543 /// \brief Dest and Src are the variable indices from two decomposed
544 /// GetElementPtr instructions GEP1 and GEP2 which have common base
545 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
546 /// difference between the two pointers.
547 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
548 const SmallVectorImpl<VariableGEPIndex> &Src);
549
Chris Lattner98e253262009-11-23 16:45:27 +0000550 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
551 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000552 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000553 const AAMDNodes &V1AAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000554 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000555 const AAMDNodes &V2AAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000556 const Value *UnderlyingV1, const Value *UnderlyingV2);
Evan Chengc10e88d2009-10-13 22:02:20 +0000557
Chris Lattner98e253262009-11-23 16:45:27 +0000558 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
559 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000560 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
Hal Finkelcc39b672014-07-24 12:16:19 +0000561 const AAMDNodes &PNAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000562 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000563 const AAMDNodes &V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +0000564
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000565 /// aliasSelect - Disambiguate a Select instruction against another value.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000566 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
Hal Finkelcc39b672014-07-24 12:16:19 +0000567 const AAMDNodes &SIAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000568 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000569 const AAMDNodes &V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000570
Dan Gohmanf372cf82010-10-19 22:54:46 +0000571 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000572 AAMDNodes V1AATag,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000573 const Value *V2, uint64_t V2Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000574 AAMDNodes V2AATag);
Chris Lattner2d332972008-06-16 06:30:22 +0000575 };
576} // End of anonymous namespace
577
578// Register this pass...
579char BasicAliasAnalysis::ID = 0;
Owen Anderson653cb032011-09-06 23:33:25 +0000580INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
Dan Gohmanda85ed82010-10-19 23:09:08 +0000581 "Basic Alias Analysis (stateless AA impl)",
Dan Gohman02538ac2010-10-18 18:04:47 +0000582 false, true, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000583INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000584INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson653cb032011-09-06 23:33:25 +0000585INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
586 "Basic Alias Analysis (stateless AA impl)",
587 false, true, false)
588
Chris Lattner2d332972008-06-16 06:30:22 +0000589
590ImmutablePass *llvm::createBasicAliasAnalysisPass() {
591 return new BasicAliasAnalysis();
592}
593
Dan Gohman9130bad2010-11-08 16:45:26 +0000594/// pointsToConstantMemory - Returns whether the given pointer value
595/// points to memory that is local to the function, with global constants being
596/// considered local to all functions.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000597bool BasicAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
598 bool OrLocal) {
Dan Gohman9130bad2010-11-08 16:45:26 +0000599 assert(Visited.empty() && "Visited must be cleared after use!");
Chris Lattner2d332972008-06-16 06:30:22 +0000600
Dan Gohman142ff822010-11-08 20:26:19 +0000601 unsigned MaxLookup = 8;
Dan Gohman9130bad2010-11-08 16:45:26 +0000602 SmallVector<const Value *, 16> Worklist;
603 Worklist.push_back(Loc.Ptr);
604 do {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000605 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), *DL);
David Blaikie70573dc2014-11-19 07:49:26 +0000606 if (!Visited.insert(V).second) {
Dan Gohman9130bad2010-11-08 16:45:26 +0000607 Visited.clear();
608 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
609 }
Dan Gohman5f1702e2010-08-06 01:25:49 +0000610
Dan Gohman9130bad2010-11-08 16:45:26 +0000611 // An alloca instruction defines local memory.
612 if (OrLocal && isa<AllocaInst>(V))
613 continue;
614
615 // A global constant counts as local memory for our purposes.
616 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
617 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
618 // global to be marked constant in some modules and non-constant in
619 // others. GV may even be a declaration, not a definition.
620 if (!GV->isConstant()) {
621 Visited.clear();
622 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
623 }
624 continue;
625 }
626
627 // If both select values point to local memory, then so does the select.
628 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
629 Worklist.push_back(SI->getTrueValue());
630 Worklist.push_back(SI->getFalseValue());
631 continue;
632 }
633
634 // If all values incoming to a phi node point to local memory, then so does
635 // the phi.
636 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
Dan Gohman142ff822010-11-08 20:26:19 +0000637 // Don't bother inspecting phi nodes with many operands.
638 if (PN->getNumIncomingValues() > MaxLookup) {
639 Visited.clear();
640 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
641 }
Pete Cooper833f34d2015-05-12 20:05:31 +0000642 for (Value *IncValue : PN->incoming_values())
643 Worklist.push_back(IncValue);
Dan Gohman9130bad2010-11-08 16:45:26 +0000644 continue;
645 }
646
647 // Otherwise be conservative.
648 Visited.clear();
649 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
650
Dan Gohman142ff822010-11-08 20:26:19 +0000651 } while (!Worklist.empty() && --MaxLookup);
Dan Gohman9130bad2010-11-08 16:45:26 +0000652
653 Visited.clear();
Dan Gohman142ff822010-11-08 20:26:19 +0000654 return Worklist.empty();
Chris Lattner2d332972008-06-16 06:30:22 +0000655}
656
Chandler Carruthc41404a2015-06-17 07:12:40 +0000657// FIXME: This code is duplicated with MemoryLocation and should be hoisted to
658// some common utility location.
Hal Finkel354e23b2014-07-17 01:28:25 +0000659static bool isMemsetPattern16(const Function *MS,
660 const TargetLibraryInfo &TLI) {
661 if (TLI.has(LibFunc::memset_pattern16) &&
662 MS->getName() == "memset_pattern16") {
663 FunctionType *MemsetType = MS->getFunctionType();
664 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
665 isa<PointerType>(MemsetType->getParamType(0)) &&
666 isa<PointerType>(MemsetType->getParamType(1)) &&
667 isa<IntegerType>(MemsetType->getParamType(2)))
668 return true;
669 }
670
671 return false;
672}
673
Dan Gohman5f1702e2010-08-06 01:25:49 +0000674/// getModRefBehavior - Return the behavior when calling the given call site.
675AliasAnalysis::ModRefBehavior
676BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
677 if (CS.doesNotAccessMemory())
678 // Can't do better than this.
679 return DoesNotAccessMemory;
680
681 ModRefBehavior Min = UnknownModRefBehavior;
682
683 // If the callsite knows it only reads memory, don't return worse
684 // than that.
685 if (CS.onlyReadsMemory())
686 Min = OnlyReadsMemory;
687
Igor Laevsky39d662f2015-07-11 10:30:36 +0000688 if (CS.onlyAccessesArgMemory())
689 Min = ModRefBehavior(Min & OnlyAccessesArgumentPointees);
690
Dan Gohman5f1702e2010-08-06 01:25:49 +0000691 // The AliasAnalysis base class has some smarts, lets use them.
Dan Gohman2694e142010-11-10 01:02:18 +0000692 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000693}
694
695/// getModRefBehavior - Return the behavior when calling the given function.
696/// For use when the call site is not known.
697AliasAnalysis::ModRefBehavior
698BasicAliasAnalysis::getModRefBehavior(const Function *F) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000699 // If the function declares it doesn't access memory, we can't do better.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000700 if (F->doesNotAccessMemory())
Dan Gohman5f1702e2010-08-06 01:25:49 +0000701 return DoesNotAccessMemory;
Dan Gohmane461d7d2010-11-08 16:08:43 +0000702
703 // For intrinsics, we can check the table.
Pete Cooper9e1d3352015-05-20 17:16:39 +0000704 if (Intrinsic::ID iid = F->getIntrinsicID()) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000705#define GET_INTRINSIC_MODREF_BEHAVIOR
Chandler Carruthdb25c6c2013-01-02 12:09:16 +0000706#include "llvm/IR/Intrinsics.gen"
Dan Gohmane461d7d2010-11-08 16:08:43 +0000707#undef GET_INTRINSIC_MODREF_BEHAVIOR
708 }
709
Dan Gohman2694e142010-11-10 01:02:18 +0000710 ModRefBehavior Min = UnknownModRefBehavior;
711
Dan Gohmane461d7d2010-11-08 16:08:43 +0000712 // If the function declares it only reads memory, go with that.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000713 if (F->onlyReadsMemory())
Dan Gohman2694e142010-11-10 01:02:18 +0000714 Min = OnlyReadsMemory;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000715
Igor Laevsky39d662f2015-07-11 10:30:36 +0000716 if (F->onlyAccessesArgMemory())
717 Min = ModRefBehavior(Min & OnlyAccessesArgumentPointees);
718
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000719 const TargetLibraryInfo &TLI =
720 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Hal Finkel354e23b2014-07-17 01:28:25 +0000721 if (isMemsetPattern16(F, TLI))
722 Min = OnlyAccessesArgumentPointees;
723
Dan Gohmane461d7d2010-11-08 16:08:43 +0000724 // Otherwise be conservative.
Dan Gohman2694e142010-11-10 01:02:18 +0000725 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000726}
Owen Anderson98a36172009-02-05 23:36:27 +0000727
Chandler Carruthc41404a2015-06-17 07:12:40 +0000728AliasAnalysis::ModRefResult
729BasicAliasAnalysis::getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) {
730 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction()))
Hal Finkel354e23b2014-07-17 01:28:25 +0000731 switch (II->getIntrinsicID()) {
Chandler Carruthc41404a2015-06-17 07:12:40 +0000732 default:
733 break;
Hal Finkel354e23b2014-07-17 01:28:25 +0000734 case Intrinsic::memset:
735 case Intrinsic::memcpy:
Chandler Carruthc41404a2015-06-17 07:12:40 +0000736 case Intrinsic::memmove:
Hal Finkel354e23b2014-07-17 01:28:25 +0000737 assert((ArgIdx == 0 || ArgIdx == 1) &&
738 "Invalid argument index for memory intrinsic");
Chandler Carruthc41404a2015-06-17 07:12:40 +0000739 return ArgIdx ? Ref : Mod;
Hal Finkel354e23b2014-07-17 01:28:25 +0000740 }
741
742 // We can bound the aliasing properties of memset_pattern16 just as we can
743 // for memcpy/memset. This is particularly important because the
744 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
745 // whenever possible.
Chandler Carruthc41404a2015-06-17 07:12:40 +0000746 if (CS.getCalledFunction() &&
747 isMemsetPattern16(CS.getCalledFunction(), *TLI)) {
Hal Finkel354e23b2014-07-17 01:28:25 +0000748 assert((ArgIdx == 0 || ArgIdx == 1) &&
749 "Invalid argument index for memset_pattern16");
Chandler Carruthc41404a2015-06-17 07:12:40 +0000750 return ArgIdx ? Ref : Mod;
Hal Finkel354e23b2014-07-17 01:28:25 +0000751 }
752 // FIXME: Handle memset_pattern4 and memset_pattern8 also.
753
Chandler Carruthc41404a2015-06-17 07:12:40 +0000754 return AliasAnalysis::getArgModRefInfo(CS, ArgIdx);
Hal Finkel354e23b2014-07-17 01:28:25 +0000755}
756
Hal Finkel93046912014-07-25 21:13:35 +0000757static bool isAssumeIntrinsic(ImmutableCallSite CS) {
758 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
759 if (II && II->getIntrinsicID() == Intrinsic::assume)
760 return true;
761
762 return false;
763}
764
Mehdi Amini46a43552015-03-04 18:43:29 +0000765bool BasicAliasAnalysis::doInitialization(Module &M) {
766 InitializeAliasAnalysis(this, &M.getDataLayout());
767 return true;
768}
769
Chris Lattner98e253262009-11-23 16:45:27 +0000770/// getModRefInfo - Check to see if the specified callsite can clobber the
771/// specified memory object. Since we only look at local properties of this
772/// function, we really can't say much about this query. We do, however, use
773/// simple "address taken" analysis on local objects.
Chris Lattner2d332972008-06-16 06:30:22 +0000774AliasAnalysis::ModRefResult
Dan Gohman5442c712010-08-03 21:48:53 +0000775BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
Chandler Carruthac80dc72015-06-17 07:18:54 +0000776 const MemoryLocation &Loc) {
Dan Gohman41f14cf2010-09-14 21:25:10 +0000777 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000778 "AliasAnalysis query involving multiple functions!");
779
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000780 const Value *Object = GetUnderlyingObject(Loc.Ptr, *DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000781
Dan Gohman41f14cf2010-09-14 21:25:10 +0000782 // If this is a tail call and Loc.Ptr points to a stack location, we know that
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000783 // the tail call cannot access or modify the local stack.
784 // We cannot exclude byval arguments here; these belong to the caller of
785 // the current function not to the current function, and a tail callee
786 // may reference them.
787 if (isa<AllocaInst>(Object))
Dan Gohman5442c712010-08-03 21:48:53 +0000788 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000789 if (CI->isTailCall())
790 return NoModRef;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000791
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000792 // If the pointer is to a locally allocated object that does not escape,
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000793 // then the call can not mod/ref the pointer unless the call takes the pointer
794 // as an argument, and itself doesn't capture it.
Chris Lattner1e7b37e2009-11-23 16:46:41 +0000795 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
Dan Gohman84f90a32010-07-01 20:08:40 +0000796 isNonEscapingLocalObject(Object)) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000797 bool PassedAsArg = false;
798 unsigned ArgNo = 0;
Dan Gohman5442c712010-08-03 21:48:53 +0000799 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000800 CI != CE; ++CI, ++ArgNo) {
Chris Lattner026f5e62011-05-23 05:15:43 +0000801 // Only look at the no-capture or byval pointer arguments. If this
802 // pointer were passed to arguments that were neither of these, then it
803 // couldn't be no-capture.
Duncan Sands19d0b472010-02-16 11:11:14 +0000804 if (!(*CI)->getType()->isPointerTy() ||
Nick Lewycky612d70b2011-11-20 19:09:04 +0000805 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000806 continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000807
Dan Gohman41f14cf2010-09-14 21:25:10 +0000808 // If this is a no-capture pointer argument, see if we can tell that it
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000809 // is impossible to alias the pointer we're checking. If not, we have to
810 // assume that the call could touch the pointer, even though it doesn't
811 // escape.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000812 if (!isNoAlias(MemoryLocation(*CI), MemoryLocation(Object))) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000813 PassedAsArg = true;
814 break;
815 }
816 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000817
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000818 if (!PassedAsArg)
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000819 return NoModRef;
820 }
821
Hal Finkel93046912014-07-25 21:13:35 +0000822 // While the assume intrinsic is marked as arbitrarily writing so that
823 // proper control dependencies will be maintained, it never aliases any
824 // particular memory location.
825 if (isAssumeIntrinsic(CS))
826 return NoModRef;
827
Chris Lattner2d332972008-06-16 06:30:22 +0000828 // The AliasAnalysis base class has some smarts, lets use them.
Hal Finkel354e23b2014-07-17 01:28:25 +0000829 return AliasAnalysis::getModRefInfo(CS, Loc);
Dan Gohman64d842e2010-09-08 01:32:20 +0000830}
Chris Lattner2d332972008-06-16 06:30:22 +0000831
Hal Finkel93046912014-07-25 21:13:35 +0000832AliasAnalysis::ModRefResult
833BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
834 ImmutableCallSite CS2) {
835 // While the assume intrinsic is marked as arbitrarily writing so that
836 // proper control dependencies will be maintained, it never aliases any
837 // particular memory location.
838 if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
839 return NoModRef;
840
841 // The AliasAnalysis base class has some smarts, lets use them.
842 return AliasAnalysis::getModRefInfo(CS1, CS2);
843}
844
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000845/// \brief Provide ad-hoc rules to disambiguate accesses through two GEP
846/// operators, both having the exact same pointer operand.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000847static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
848 uint64_t V1Size,
849 const GEPOperator *GEP2,
850 uint64_t V2Size,
851 const DataLayout &DL) {
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000852
853 assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
854 "Expected GEPs with the same pointer operand");
855
856 // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
857 // such that the struct field accesses provably cannot alias.
858 // We also need at least two indices (the pointer, and the struct field).
859 if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
860 GEP1->getNumIndices() < 2)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000861 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000862
863 // If we don't know the size of the accesses through both GEPs, we can't
864 // determine whether the struct fields accessed can't alias.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000865 if (V1Size == MemoryLocation::UnknownSize ||
866 V2Size == MemoryLocation::UnknownSize)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000867 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000868
869 ConstantInt *C1 =
870 dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
871 ConstantInt *C2 =
872 dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
873
874 // If the last (struct) indices aren't constants, we can't say anything.
875 // If they're identical, the other indices might be also be dynamically
876 // equal, so the GEPs can alias.
877 if (!C1 || !C2 || C1 == C2)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000878 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000879
880 // Find the last-indexed type of the GEP, i.e., the type you'd get if
881 // you stripped the last index.
882 // On the way, look at each indexed type. If there's something other
883 // than an array, different indices can lead to different final types.
884 SmallVector<Value *, 8> IntermediateIndices;
885
886 // Insert the first index; we don't need to check the type indexed
887 // through it as it only drops the pointer indirection.
888 assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
889 IntermediateIndices.push_back(GEP1->getOperand(1));
890
891 // Insert all the remaining indices but the last one.
892 // Also, check that they all index through arrays.
893 for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
894 if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
David Blaikied288fb82015-03-30 21:41:43 +0000895 GEP1->getSourceElementType(), IntermediateIndices)))
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000896 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000897 IntermediateIndices.push_back(GEP1->getOperand(i + 1));
898 }
899
900 StructType *LastIndexedStruct =
901 dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
David Blaikied288fb82015-03-30 21:41:43 +0000902 GEP1->getSourceElementType(), IntermediateIndices));
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000903
904 if (!LastIndexedStruct)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000905 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000906
907 // We know that:
908 // - both GEPs begin indexing from the exact same pointer;
909 // - the last indices in both GEPs are constants, indexing into a struct;
910 // - said indices are different, hence, the pointed-to fields are different;
911 // - both GEPs only index through arrays prior to that.
912 //
913 // This lets us determine that the struct that GEP1 indexes into and the
914 // struct that GEP2 indexes into must either precisely overlap or be
915 // completely disjoint. Because they cannot partially overlap, indexing into
916 // different non-overlapping fields of the struct will never alias.
917
918 // Therefore, the only remaining thing needed to show that both GEPs can't
919 // alias is that the fields are not overlapping.
920 const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
921 const uint64_t StructSize = SL->getSizeInBytes();
922 const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
923 const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
924
925 auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
926 uint64_t V2Off, uint64_t V2Size) {
927 return V1Off < V2Off && V1Off + V1Size <= V2Off &&
928 ((V2Off + V2Size <= StructSize) ||
929 (V2Off + V2Size - StructSize <= V1Off));
930 };
931
932 if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
933 EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000934 return NoAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000935
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000936 return MayAlias;
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +0000937}
938
Chris Lattnera99edbe2009-11-26 02:11:08 +0000939/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
940/// against another pointer. We know that V1 is a GEP, but we don't know
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000941/// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
Chris Lattner5341c962009-11-26 02:14:59 +0000942/// UnderlyingV2 is the same for V2.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000943///
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000944AliasResult BasicAliasAnalysis::aliasGEP(
945 const GEPOperator *GEP1, uint64_t V1Size, const AAMDNodes &V1AAInfo,
946 const Value *V2, uint64_t V2Size, const AAMDNodes &V2AAInfo,
947 const Value *UnderlyingV1, const Value *UnderlyingV2) {
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000948 int64_t GEP1BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000949 bool GEP1MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000950 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000951
Chandler Carruth66b31302015-01-04 12:03:27 +0000952 // We have to get two AssumptionCaches here because GEP1 and V2 may be from
953 // different functions.
954 // FIXME: This really doesn't make any sense. We get a dominator tree below
955 // that can only refer to a single function. But this function (aliasGEP) is
956 // a method on an immutable pass that can be called when there *isn't*
957 // a single function. The old pass management layer makes this "work", but
958 // this isn't really a clean solution.
959 AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
960 AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
961 if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
962 AC1 = &ACT.getAssumptionCache(
963 const_cast<Function &>(*GEP1I->getParent()->getParent()));
964 if (auto *I2 = dyn_cast<Instruction>(V2))
965 AC2 = &ACT.getAssumptionCache(
966 const_cast<Function &>(*I2->getParent()->getParent()));
967
Hal Finkel60db0582014-09-07 18:57:58 +0000968 DominatorTreeWrapperPass *DTWP =
969 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
970 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
971
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000972 // If we have two gep instructions with must-alias or not-alias'ing base
973 // pointers, figure out if the indexes to the GEP tell us anything about the
974 // derived pointer.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000975 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000976 // Do the base pointers alias?
Chandler Carruthecbd1682015-06-17 07:21:38 +0000977 AliasResult BaseAlias =
978 aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize, AAMDNodes(),
979 UnderlyingV2, MemoryLocation::UnknownSize, AAMDNodes());
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000980
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000981 // Check for geps of non-aliasing underlying pointers where the offsets are
982 // identical.
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000983 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000984 // Do the base pointers alias assuming type and size.
985 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
Hal Finkelcc39b672014-07-24 12:16:19 +0000986 V1AAInfo, UnderlyingV2,
987 V2Size, V2AAInfo);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000988 if (PreciseBaseAlias == NoAlias) {
989 // See if the computed offset from the common pointer tells us about the
990 // relation of the resulting pointer.
991 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +0000992 bool GEP2MaxLookupReached;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000993 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
994 const Value *GEP2BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +0000995 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000996 GEP2MaxLookupReached, *DL, AC2, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000997 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +0000998 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000999 GEP1MaxLookupReached, *DL, AC1, DT);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001000 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001001 // same result except when DecomposeGEPExpression has no DataLayout.
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001002 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +00001003 assert(!DL &&
1004 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001005 return MayAlias;
1006 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001007 // If the max search depth is reached the result is undefined
1008 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1009 return MayAlias;
1010
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001011 // Same offsets.
1012 if (GEP1BaseOffset == GEP2BaseOffset &&
Benjamin Kramer147644d2014-04-18 19:48:03 +00001013 GEP1VariableIndices == GEP2VariableIndices)
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001014 return NoAlias;
1015 GEP1VariableIndices.clear();
1016 }
1017 }
Jakub Staszak07f383f2013-08-24 14:16:00 +00001018
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001019 // If we get a No or May, then return it immediately, no amount of analysis
1020 // will improve this situation.
1021 if (BaseAlias != MustAlias) return BaseAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001022
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001023 // Otherwise, we have a MustAlias. Since the base pointers alias each other
1024 // exactly, see if the computed offset from the common pointer tells us
1025 // about the relation of the resulting pointer.
1026 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001027 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001028 GEP1MaxLookupReached, *DL, AC1, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001029
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001030 int64_t GEP2BaseOffset;
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001031 bool GEP2MaxLookupReached;
Chris Lattner1b9c3872010-08-18 22:47:56 +00001032 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001033 const Value *GEP2BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001034 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001035 GEP2MaxLookupReached, *DL, AC2, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001036
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001037 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001038 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001039 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Craig Topper9f008862014-04-15 04:59:12 +00001040 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +00001041 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001042 return MayAlias;
1043 }
Ahmed Bougacha29efe3b2015-02-07 17:04:29 +00001044
1045 // If we know the two GEPs are based off of the exact same pointer (and not
1046 // just the same underlying object), see if that tells us anything about
1047 // the resulting pointers.
1048 if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
1049 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
1050 // If we couldn't find anything interesting, don't abandon just yet.
1051 if (R != MayAlias)
1052 return R;
1053 }
1054
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001055 // If the max search depth is reached the result is undefined
1056 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1057 return MayAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001058
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001059 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1060 // symbolic difference.
1061 GEP1BaseOffset -= GEP2BaseOffset;
Dan Gohmanad867b02010-08-03 20:23:52 +00001062 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001063
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001064 } else {
1065 // Check to see if these two pointers are related by the getelementptr
1066 // instruction. If one pointer is a GEP with a non-zero index of the other
1067 // pointer, we know they cannot alias.
Chris Lattner5c1cfc22009-11-26 16:52:32 +00001068
1069 // If both accesses are unknown size, we can't do anything useful here.
Chandler Carruthecbd1682015-06-17 07:21:38 +00001070 if (V1Size == MemoryLocation::UnknownSize &&
1071 V2Size == MemoryLocation::UnknownSize)
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001072 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001073
Chandler Carruthecbd1682015-06-17 07:21:38 +00001074 AliasResult R = aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize,
1075 AAMDNodes(), V2, V2Size, V2AAInfo);
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001076 if (R != MustAlias)
1077 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
1078 // If V2 is known not to alias GEP base pointer, then the two values
1079 // cannot alias per GEP semantics: "A pointer value formed from a
1080 // getelementptr instruction is associated with the addresses associated
1081 // with the first operand of the getelementptr".
1082 return R;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001083
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001084 const Value *GEP1BasePtr =
Chandler Carruth66b31302015-01-04 12:03:27 +00001085 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001086 GEP1MaxLookupReached, *DL, AC1, DT);
Jakub Staszak07f383f2013-08-24 14:16:00 +00001087
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001088 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001089 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001090 if (GEP1BasePtr != UnderlyingV1) {
Craig Topper9f008862014-04-15 04:59:12 +00001091 assert(!DL &&
Dan Gohmana4fcd242010-12-15 20:02:24 +00001092 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001093 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001094 }
Arnold Schwaighofer1a444482014-03-26 21:30:19 +00001095 // If the max search depth is reached the result is undefined
1096 if (GEP1MaxLookupReached)
1097 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +00001098 }
Jakub Staszak07f383f2013-08-24 14:16:00 +00001099
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001100 // In the two GEP Case, if there is no difference in the offsets of the
1101 // computed pointers, the resultant pointers are a must alias. This
1102 // hapens when we have two lexically identical GEP's (for example).
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001103 //
Chris Lattner7a5b56a2009-11-26 02:17:34 +00001104 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1105 // must aliases the GEP, the end result is a must alias also.
1106 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
Evan Chengc1eed9d2009-10-14 06:41:49 +00001107 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001108
Eli Friedman3d1b3072011-09-08 02:23:31 +00001109 // If there is a constant difference between the pointers, but the difference
1110 // is less than the size of the associated memory object, then we know
1111 // that the objects are partially overlapping. If the difference is
1112 // greater, we know they do not overlap.
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001113 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001114 if (GEP1BaseOffset >= 0) {
Chandler Carruthecbd1682015-06-17 07:21:38 +00001115 if (V2Size != MemoryLocation::UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001116 if ((uint64_t)GEP1BaseOffset < V2Size)
1117 return PartialAlias;
1118 return NoAlias;
1119 }
1120 } else {
Arnold Schwaighofere3ac0992014-01-16 04:53:18 +00001121 // We have the situation where:
1122 // + +
1123 // | BaseOffset |
1124 // ---------------->|
1125 // |-->V1Size |-------> V2Size
1126 // GEP1 V2
1127 // We need to know that V2Size is not unknown, otherwise we might have
1128 // stripped a gep with negative index ('gep <ptr>, -1, ...).
Chandler Carruthecbd1682015-06-17 07:21:38 +00001129 if (V1Size != MemoryLocation::UnknownSize &&
1130 V2Size != MemoryLocation::UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001131 if (-(uint64_t)GEP1BaseOffset < V1Size)
1132 return PartialAlias;
1133 return NoAlias;
1134 }
1135 }
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001136 }
1137
Eli Friedmanb78ac542011-09-08 02:37:07 +00001138 if (!GEP1VariableIndices.empty()) {
1139 uint64_t Modulo = 0;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001140 bool AllPositive = true;
1141 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
1142
1143 // Try to distinguish something like &A[i][1] against &A[42][0].
1144 // Grab the least significant bit set in any of the scales. We
1145 // don't need std::abs here (even if the scale's negative) as we'll
1146 // be ^'ing Modulo with itself later.
1147 Modulo |= (uint64_t) GEP1VariableIndices[i].Scale;
1148
1149 if (AllPositive) {
1150 // If the Value could change between cycles, then any reasoning about
1151 // the Value this cycle may not hold in the next cycle. We'll just
1152 // give up if we can't determine conditions that hold for every cycle:
1153 const Value *V = GEP1VariableIndices[i].V;
1154
1155 bool SignKnownZero, SignKnownOne;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001156 ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, *DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00001157 0, AC1, nullptr, DT);
Hal Finkel45ba2c12014-11-13 09:16:54 +00001158
1159 // Zero-extension widens the variable, and so forces the sign
1160 // bit to zero.
Manuel Klimek779cf852015-07-13 13:50:55 +00001161 bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001162 SignKnownZero |= IsZExt;
1163 SignKnownOne &= !IsZExt;
1164
1165 // If the variable begins with a zero then we know it's
1166 // positive, regardless of whether the value is signed or
1167 // unsigned.
1168 int64_t Scale = GEP1VariableIndices[i].Scale;
1169 AllPositive =
1170 (SignKnownZero && Scale >= 0) ||
1171 (SignKnownOne && Scale < 0);
1172 }
1173 }
1174
Eli Friedmanb78ac542011-09-08 02:37:07 +00001175 Modulo = Modulo ^ (Modulo & (Modulo - 1));
Eli Friedman3d1b3072011-09-08 02:23:31 +00001176
Eli Friedmanb78ac542011-09-08 02:37:07 +00001177 // We can compute the difference between the two addresses
1178 // mod Modulo. Check whether that difference guarantees that the
1179 // two locations do not alias.
1180 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
Chandler Carruthecbd1682015-06-17 07:21:38 +00001181 if (V1Size != MemoryLocation::UnknownSize &&
1182 V2Size != MemoryLocation::UnknownSize && ModOffset >= V2Size &&
1183 V1Size <= Modulo - ModOffset)
Eli Friedmanb78ac542011-09-08 02:37:07 +00001184 return NoAlias;
Hal Finkel45ba2c12014-11-13 09:16:54 +00001185
1186 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1187 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1188 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1189 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t) GEP1BaseOffset)
1190 return NoAlias;
Eli Friedmanb78ac542011-09-08 02:37:07 +00001191 }
Eli Friedman3d1b3072011-09-08 02:23:31 +00001192
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001193 // Statically, we can see that the base objects are the same, but the
1194 // pointers have dynamic offsets which we can't resolve. And none of our
1195 // little tricks above worked.
1196 //
1197 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1198 // practical effect of this is protecting TBAA in the case of dynamic
Dan Gohman9017b842012-02-17 18:33:38 +00001199 // indices into arrays of unions or malloc'd memory.
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001200 return PartialAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001201}
1202
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001203static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
Dan Gohman4e7e7952011-06-03 20:17:36 +00001204 // If the results agree, take it.
1205 if (A == B)
1206 return A;
1207 // A mix of PartialAlias and MustAlias is PartialAlias.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001208 if ((A == PartialAlias && B == MustAlias) ||
1209 (B == PartialAlias && A == MustAlias))
1210 return PartialAlias;
Dan Gohman4e7e7952011-06-03 20:17:36 +00001211 // Otherwise, we don't know anything.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001212 return MayAlias;
Dan Gohman4e7e7952011-06-03 20:17:36 +00001213}
1214
Chris Lattner98e253262009-11-23 16:45:27 +00001215/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1216/// instruction against another.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001217AliasResult BasicAliasAnalysis::aliasSelect(const SelectInst *SI,
1218 uint64_t SISize,
1219 const AAMDNodes &SIAAInfo,
1220 const Value *V2, uint64_t V2Size,
1221 const AAMDNodes &V2AAInfo) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001222 // If the values are Selects with the same condition, we can do a more precise
1223 // check: just check for aliases between the values on corresponding arms.
1224 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1225 if (SI->getCondition() == SI2->getCondition()) {
1226 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001227 aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1228 SI2->getTrueValue(), V2Size, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001229 if (Alias == MayAlias)
1230 return MayAlias;
1231 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001232 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1233 SI2->getFalseValue(), V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001234 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001235 }
1236
1237 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1238 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1239 AliasResult Alias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001240 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001241 if (Alias == MayAlias)
1242 return MayAlias;
Dan Gohman7c34ece2010-06-28 21:16:52 +00001243
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001244 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001245 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001246 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001247}
1248
Evan Chengf92f5552009-10-14 05:22:03 +00001249// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
Evan Cheng31565b32009-10-14 05:05:02 +00001250// against another.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001251AliasResult BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1252 const AAMDNodes &PNAAInfo,
1253 const Value *V2, uint64_t V2Size,
1254 const AAMDNodes &V2AAInfo) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001255 // Track phi nodes we have visited. We use this information when we determine
1256 // value equivalence.
1257 VisitedPhiBBs.insert(PN->getParent());
1258
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001259 // If the values are PHIs in the same block, we can do a more precise
1260 // as well as efficient check: just check for aliases between the values
1261 // on corresponding edges.
1262 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1263 if (PN2->getParent() == PN->getParent()) {
Chandler Carruthac80dc72015-06-17 07:18:54 +00001264 LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
1265 MemoryLocation(V2, V2Size, V2AAInfo));
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001266 if (PN > V2)
1267 std::swap(Locs.first, Locs.second);
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001268 // Analyse the PHIs' inputs under the assumption that the PHIs are
1269 // NoAlias.
1270 // If the PHIs are May/MustAlias there must be (recursively) an input
1271 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1272 // there must be an operation on the PHIs within the PHIs' value cycle
1273 // that causes a MayAlias.
1274 // Pretend the phis do not alias.
1275 AliasResult Alias = NoAlias;
1276 assert(AliasCache.count(Locs) &&
1277 "There must exist an entry for the phi node");
1278 AliasResult OrigAliasResult = AliasCache[Locs];
1279 AliasCache[Locs] = NoAlias;
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001280
Hal Finkela6f86fc2012-11-17 02:33:15 +00001281 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001282 AliasResult ThisAlias =
Hal Finkelcc39b672014-07-24 12:16:19 +00001283 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001284 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
Hal Finkelcc39b672014-07-24 12:16:19 +00001285 V2Size, V2AAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001286 Alias = MergeAliasResults(ThisAlias, Alias);
1287 if (Alias == MayAlias)
1288 break;
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001289 }
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001290
1291 // Reset if speculation failed.
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001292 if (Alias != NoAlias)
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001293 AliasCache[Locs] = OrigAliasResult;
1294
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001295 return Alias;
1296 }
1297
Evan Cheng8ec25932009-10-16 00:33:09 +00001298 SmallPtrSet<Value*, 4> UniqueSrc;
Evan Chengc10e88d2009-10-13 22:02:20 +00001299 SmallVector<Value*, 4> V1Srcs;
Pete Cooper833f34d2015-05-12 20:05:31 +00001300 for (Value *PV1 : PN->incoming_values()) {
Evan Chengc10e88d2009-10-13 22:02:20 +00001301 if (isa<PHINode>(PV1))
1302 // If any of the source itself is a PHI, return MayAlias conservatively
Evan Chengc1eed9d2009-10-14 06:41:49 +00001303 // to avoid compile time explosion. The worst possible case is if both
1304 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1305 // and 'n' are the number of PHI sources.
Evan Chengc10e88d2009-10-13 22:02:20 +00001306 return MayAlias;
David Blaikie70573dc2014-11-19 07:49:26 +00001307 if (UniqueSrc.insert(PV1).second)
Evan Chengc10e88d2009-10-13 22:02:20 +00001308 V1Srcs.push_back(PV1);
1309 }
1310
Hal Finkelcc39b672014-07-24 12:16:19 +00001311 AliasResult Alias = aliasCheck(V2, V2Size, V2AAInfo,
1312 V1Srcs[0], PNSize, PNAAInfo);
Evan Chengf92f5552009-10-14 05:22:03 +00001313 // Early exit if the check of the first PHI source against V2 is MayAlias.
1314 // Other results are not possible.
1315 if (Alias == MayAlias)
1316 return MayAlias;
1317
Evan Chengc10e88d2009-10-13 22:02:20 +00001318 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1319 // NoAlias / MustAlias. Otherwise, returns MayAlias.
Evan Chengc10e88d2009-10-13 22:02:20 +00001320 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1321 Value *V = V1Srcs[i];
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001322
Hal Finkelcc39b672014-07-24 12:16:19 +00001323 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2AAInfo,
1324 V, PNSize, PNAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001325 Alias = MergeAliasResults(ThisAlias, Alias);
1326 if (Alias == MayAlias)
1327 break;
Evan Chengc10e88d2009-10-13 22:02:20 +00001328 }
1329
1330 return Alias;
1331}
1332
1333// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1334// such as array references.
Evan Chengf1f3dd32009-10-13 18:42:04 +00001335//
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001336AliasResult BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1337 AAMDNodes V1AAInfo, const Value *V2,
1338 uint64_t V2Size,
1339 AAMDNodes V2AAInfo) {
Dan Gohmancb45bd92010-04-08 18:11:50 +00001340 // If either of the memory references is empty, it doesn't matter what the
1341 // pointer values are.
1342 if (V1Size == 0 || V2Size == 0)
1343 return NoAlias;
1344
Evan Chengf1f3dd32009-10-13 18:42:04 +00001345 // Strip off any casts if they exist.
1346 V1 = V1->stripPointerCasts();
1347 V2 = V2->stripPointerCasts();
1348
Daniel Berlin3459d6e2015-05-05 18:10:49 +00001349 // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1350 // value for undef that aliases nothing in the program.
1351 if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1352 return NoAlias;
1353
Evan Chengf1f3dd32009-10-13 18:42:04 +00001354 // Are we checking for alias of the same value?
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001355 // Because we look 'through' phi nodes we could look at "Value" pointers from
1356 // different iterations. We must therefore make sure that this is not the
1357 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1358 // happen by looking at the visited phi nodes and making sure they cannot
1359 // reach the value.
1360 if (isValueEqualInPotentialCycles(V1, V2))
1361 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001362
Duncan Sands19d0b472010-02-16 11:11:14 +00001363 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
Evan Chengf1f3dd32009-10-13 18:42:04 +00001364 return NoAlias; // Scalars cannot alias each other
1365
1366 // Figure out what objects these things are pointing to if we can.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001367 const Value *O1 = GetUnderlyingObject(V1, *DL, MaxLookupSearchDepth);
1368 const Value *O2 = GetUnderlyingObject(V2, *DL, MaxLookupSearchDepth);
Evan Chengf1f3dd32009-10-13 18:42:04 +00001369
Dan Gohmanccb45842009-11-09 19:29:11 +00001370 // Null values in the default address space don't point to any object, so they
1371 // don't alias any other pointer.
1372 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1373 if (CPN->getType()->getAddressSpace() == 0)
1374 return NoAlias;
1375 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1376 if (CPN->getType()->getAddressSpace() == 0)
1377 return NoAlias;
1378
Evan Chengf1f3dd32009-10-13 18:42:04 +00001379 if (O1 != O2) {
1380 // If V1/V2 point to two different objects we know that we have no alias.
Dan Gohman00ef9322010-07-07 14:27:09 +00001381 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001382 return NoAlias;
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001383
1384 // Constant pointers can't alias with non-const isIdentifiedObject objects.
Dan Gohman00ef9322010-07-07 14:27:09 +00001385 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1386 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001387 return NoAlias;
1388
Michael Kupersteinf3e663a2013-05-28 08:17:48 +00001389 // Function arguments can't alias with things that are known to be
1390 // unambigously identified at the function level.
1391 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1392 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
Dan Gohman84f90a32010-07-01 20:08:40 +00001393 return NoAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001394
1395 // Most objects can't alias null.
Dan Gohman00ef9322010-07-07 14:27:09 +00001396 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1397 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001398 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001399
Dan Gohman5b0a8a82010-07-07 14:30:04 +00001400 // If one pointer is the result of a call/invoke or load and the other is a
1401 // non-escaping local object within the same function, then we know the
1402 // object couldn't escape to a point where the call could return it.
1403 //
1404 // Note that if the pointers are in different functions, there are a
1405 // variety of complications. A call with a nocapture argument may still
1406 // temporary store the nocapture argument's value in a temporary memory
1407 // location if that memory location doesn't escape. Or it may pass a
1408 // nocapture value to other functions as long as they don't capture it.
1409 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1410 return NoAlias;
1411 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1412 return NoAlias;
1413 }
1414
Evan Chengf1f3dd32009-10-13 18:42:04 +00001415 // If the size of one access is larger than the entire object on the other
1416 // side, then we know such behavior is undefined and can assume no alias.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001417 if (DL)
Chandler Carruthecbd1682015-06-17 07:21:38 +00001418 if ((V1Size != MemoryLocation::UnknownSize &&
1419 isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1420 (V2Size != MemoryLocation::UnknownSize &&
1421 isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001422 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001423
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001424 // Check the cache before climbing up use-def chains. This also terminates
1425 // otherwise infinitely recursive queries.
Chandler Carruthac80dc72015-06-17 07:18:54 +00001426 LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
1427 MemoryLocation(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001428 if (V1 > V2)
1429 std::swap(Locs.first, Locs.second);
1430 std::pair<AliasCacheTy::iterator, bool> Pair =
1431 AliasCache.insert(std::make_pair(Locs, MayAlias));
1432 if (!Pair.second)
1433 return Pair.first->second;
1434
Chris Lattner89288992009-11-26 02:13:03 +00001435 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1436 // GEP can't simplify, we don't even look at the PHI cases.
Chris Lattnerb2647b92009-10-17 23:48:54 +00001437 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001438 std::swap(V1, V2);
1439 std::swap(V1Size, V2Size);
Chris Lattner5341c962009-11-26 02:14:59 +00001440 std::swap(O1, O2);
Hal Finkelcc39b672014-07-24 12:16:19 +00001441 std::swap(V1AAInfo, V2AAInfo);
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001442 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001443 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001444 AliasResult Result = aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001445 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001446 }
Evan Chengc10e88d2009-10-13 22:02:20 +00001447
1448 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1449 std::swap(V1, V2);
1450 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001451 std::swap(V1AAInfo, V2AAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +00001452 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001453 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001454 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1455 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001456 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001457 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001458
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001459 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1460 std::swap(V1, V2);
1461 std::swap(V1Size, V2Size);
Hal Finkelcc39b672014-07-24 12:16:19 +00001462 std::swap(V1AAInfo, V2AAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001463 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001464 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001465 AliasResult Result = aliasSelect(S1, V1Size, V1AAInfo,
1466 V2, V2Size, V2AAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001467 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001468 }
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001469
Dan Gohman44da55b2011-01-18 21:16:06 +00001470 // If both pointers are pointing into the same object and one of them
1471 // accesses is accessing the entire object, then the accesses must
1472 // overlap in some way.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001473 if (DL && O1 == O2)
Chandler Carruthecbd1682015-06-17 07:21:38 +00001474 if ((V1Size != MemoryLocation::UnknownSize &&
1475 isObjectSize(O1, V1Size, *DL, *TLI)) ||
1476 (V2Size != MemoryLocation::UnknownSize &&
1477 isObjectSize(O2, V2Size, *DL, *TLI)))
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001478 return AliasCache[Locs] = PartialAlias;
Dan Gohman44da55b2011-01-18 21:16:06 +00001479
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001480 AliasResult Result =
Chandler Carruthac80dc72015-06-17 07:18:54 +00001481 AliasAnalysis::alias(MemoryLocation(V1, V1Size, V1AAInfo),
1482 MemoryLocation(V2, V2Size, V2AAInfo));
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001483 return AliasCache[Locs] = Result;
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001484}
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001485
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001486bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1487 const Value *V2) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001488 if (V != V2)
1489 return false;
1490
1491 const Instruction *Inst = dyn_cast<Instruction>(V);
1492 if (!Inst)
1493 return true;
1494
Daniel Berlin9e77de22015-03-20 18:05:49 +00001495 if (VisitedPhiBBs.empty())
1496 return true;
1497
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001498 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1499 return false;
1500
1501 // Use dominance or loop info if available.
Chandler Carruth73523022014-01-13 13:07:17 +00001502 DominatorTreeWrapperPass *DTWP =
1503 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topper9f008862014-04-15 04:59:12 +00001504 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001505 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1506 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001507
1508 // Make sure that the visited phis cannot reach the Value. This ensures that
1509 // the Values cannot come from different iterations of a potential cycle the
1510 // phi nodes could be involved in.
Craig Topper46276792014-08-24 23:23:06 +00001511 for (auto *P : VisitedPhiBBs)
1512 if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001513 return false;
1514
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001515 return true;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001516}
1517
1518/// GetIndexDifference - Dest and Src are the variable indices from two
1519/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1520/// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1521/// difference between the two pointers.
1522void BasicAliasAnalysis::GetIndexDifference(
1523 SmallVectorImpl<VariableGEPIndex> &Dest,
1524 const SmallVectorImpl<VariableGEPIndex> &Src) {
1525 if (Src.empty())
1526 return;
1527
1528 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1529 const Value *V = Src[i].V;
Manuel Klimek779cf852015-07-13 13:50:55 +00001530 ExtensionKind Extension = Src[i].Extension;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001531 int64_t Scale = Src[i].Scale;
1532
1533 // Find V in Dest. This is N^2, but pointer indices almost never have more
1534 // than a few variable indexes.
1535 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001536 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
Manuel Klimek779cf852015-07-13 13:50:55 +00001537 Dest[j].Extension != Extension)
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001538 continue;
1539
1540 // If we found it, subtract off Scale V's from the entry in Dest. If it
1541 // goes to zero, remove the entry.
1542 if (Dest[j].Scale != Scale)
1543 Dest[j].Scale -= Scale;
1544 else
1545 Dest.erase(Dest.begin() + j);
1546 Scale = 0;
1547 break;
1548 }
1549
1550 // If we didn't consume this entry, add it to the end of the Dest list.
1551 if (Scale) {
Manuel Klimek779cf852015-07-13 13:50:55 +00001552 VariableGEPIndex Entry = { V, Extension, -Scale };
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001553 Dest.push_back(Entry);
1554 }
1555 }
1556}