blob: 4f13999098284b1dd8c7d75e89ca016a784dd38b [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"
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000020#include "llvm/Analysis/CFG.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000023#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/MemoryBuiltins.h"
25#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000031#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/GlobalAlias.h"
33#include "llvm/IR/GlobalVariable.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Operator.h"
Chris Lattnerd82256a2004-03-15 03:36:49 +000038#include "llvm/Pass.h"
Torok Edwin56d06592009-07-11 20:10:48 +000039#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Target/TargetLibraryInfo.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000041#include <algorithm>
Chris Lattner35997482003-11-25 18:33:40 +000042using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000043
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000044/// Cutoff after which to stop analysing a set of phi nodes potentially involved
45/// in a cycle. Because we are analysing 'through' phi nodes we need to be
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +000046/// careful with value equivalence. We use reachability to make sure a value
47/// cannot be involved in a cycle.
48const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +000049
Chris Lattner2d332972008-06-16 06:30:22 +000050//===----------------------------------------------------------------------===//
51// Useful predicates
52//===----------------------------------------------------------------------===//
Devang Patel09f162c2007-05-01 21:15:47 +000053
Chris Lattnerb35d9b52008-06-16 06:19:11 +000054/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
55/// object that never escapes from the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000056static bool isNonEscapingLocalObject(const Value *V) {
Chris Lattnerfa482582008-06-16 06:28:01 +000057 // If this is a local allocation, check to see if it escapes.
Dan Gohman84f90a32010-07-01 20:08:40 +000058 if (isa<AllocaInst>(V) || isNoAliasCall(V))
Dan Gohman94e61762009-11-19 21:57:48 +000059 // Set StoreCaptures to True so that we can assume in our callers that the
60 // pointer is not the result of a load instruction. Currently
61 // PointerMayBeCaptured doesn't have any special analysis for the
62 // StoreCaptures=false case; if it did, our callers could be refined to be
63 // more precise.
64 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Duncan Sands8d65f362009-01-05 21:19:53 +000065
Chris Lattnerfa482582008-06-16 06:28:01 +000066 // If this is an argument that corresponds to a byval or noalias argument,
Duncan Sands8d65f362009-01-05 21:19:53 +000067 // then it has not escaped before entering the function. Check if it escapes
68 // inside the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000069 if (const Argument *A = dyn_cast<Argument>(V))
Richard Osbornea1fffcf2012-11-05 10:48:24 +000070 if (A->hasByValAttr() || A->hasNoAliasAttr())
71 // Note even if the argument is marked nocapture we still need to check
72 // for copies made inside the function. The nocapture attribute only
73 // specifies that there are no copies made that outlive the function.
Dan Gohman84f90a32010-07-01 20:08:40 +000074 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Richard Osbornea1fffcf2012-11-05 10:48:24 +000075
Chris Lattnerb35d9b52008-06-16 06:19:11 +000076 return false;
77}
78
Dan Gohman0824aff2010-06-29 00:50:39 +000079/// isEscapeSource - Return true if the pointer is one which would have
80/// been considered an escape by isNonEscapingLocalObject.
Dan Gohman84f90a32010-07-01 20:08:40 +000081static bool isEscapeSource(const Value *V) {
82 if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
83 return true;
Dan Gohman0824aff2010-06-29 00:50:39 +000084
85 // The load case works because isNonEscapingLocalObject considers all
86 // stores to be escapes (it passes true for the StoreCaptures argument
87 // to PointerMayBeCaptured).
88 if (isa<LoadInst>(V))
89 return true;
90
91 return false;
92}
Chris Lattnerb35d9b52008-06-16 06:19:11 +000093
Dan Gohman44da55b2011-01-18 21:16:06 +000094/// getObjectSize - Return the size of the object specified by V, or
95/// UnknownSize if unknown.
Rafael Espindola5f57f462014-02-21 18:34:28 +000096static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000097 const TargetLibraryInfo &TLI,
Eli Friedman8bc169c2012-02-27 20:46:07 +000098 bool RoundToAlign = false) {
Nuno Lopes55fff832012-06-21 15:45:28 +000099 uint64_t Size;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000100 if (getObjectSize(V, Size, &DL, &TLI, RoundToAlign))
Nuno Lopes55fff832012-06-21 15:45:28 +0000101 return Size;
102 return AliasAnalysis::UnknownSize;
Dan Gohman44da55b2011-01-18 21:16:06 +0000103}
104
105/// isObjectSmallerThan - Return true if we can prove that the object specified
106/// by V is smaller than Size.
107static bool isObjectSmallerThan(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000108 const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000109 const TargetLibraryInfo &TLI) {
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000110 // Note that the meanings of the "object" are slightly different in the
111 // following contexts:
112 // c1: llvm::getObjectSize()
113 // c2: llvm.objectsize() intrinsic
114 // c3: isObjectSmallerThan()
115 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
116 // refers to the "entire object".
117 //
118 // Consider this example:
119 // char *p = (char*)malloc(100)
120 // char *q = p+80;
121 //
122 // In the context of c1 and c2, the "object" pointed by q refers to the
123 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
124 //
125 // However, in the context of c3, the "object" refers to the chunk of memory
126 // being allocated. So, the "object" has 100 bytes, and q points to the middle
127 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
128 // parameter, before the llvm::getObjectSize() is called to get the size of
129 // entire object, we should:
130 // - either rewind the pointer q to the base-address of the object in
131 // question (in this case rewind to p), or
132 // - just give up. It is up to caller to make sure the pointer is pointing
133 // to the base address the object.
Jakub Staszak07f383f2013-08-24 14:16:00 +0000134 //
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000135 // We go for 2nd option for simplicity.
136 if (!isIdentifiedObject(V))
137 return false;
138
Eli Friedman8bc169c2012-02-27 20:46:07 +0000139 // This function needs to use the aligned object size because we allow
140 // reads a bit past the end given sufficient alignment.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000141 uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/true);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000142
Dan Gohman44da55b2011-01-18 21:16:06 +0000143 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize < Size;
144}
145
146/// isObjectSize - Return true if we can prove that the object specified
147/// by V has size Size.
148static bool isObjectSize(const Value *V, uint64_t Size,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000149 const DataLayout &DL, const TargetLibraryInfo &TLI) {
150 uint64_t ObjectSize = getObjectSize(V, DL, TLI);
Dan Gohman44da55b2011-01-18 21:16:06 +0000151 return ObjectSize != AliasAnalysis::UnknownSize && ObjectSize == Size;
Chris Lattner98ad8162008-06-16 06:10:11 +0000152}
153
Michael Kupersteinf3e663a2013-05-28 08:17:48 +0000154/// isIdentifiedFunctionLocal - Return true if V is umabigously identified
155/// at the function-level. Different IdentifiedFunctionLocals can't alias.
156/// Further, an IdentifiedFunctionLocal can not alias with any function
Alp Tokercb402912014-01-24 17:20:08 +0000157/// arguments other than itself, which is not necessarily true for
Michael Kupersteinf3e663a2013-05-28 08:17:48 +0000158/// IdentifiedObjects.
159static bool isIdentifiedFunctionLocal(const Value *V)
160{
161 return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasArgument(V);
162}
163
164
Chris Lattner2d332972008-06-16 06:30:22 +0000165//===----------------------------------------------------------------------===//
Chris Lattner9f7500f2010-08-18 22:07:29 +0000166// GetElementPtr Instruction Decomposition and Analysis
167//===----------------------------------------------------------------------===//
168
Chris Lattner1b9c3872010-08-18 22:47:56 +0000169namespace {
170 enum ExtensionKind {
171 EK_NotExtended,
172 EK_SignExt,
173 EK_ZeroExt
174 };
Jakub Staszak07f383f2013-08-24 14:16:00 +0000175
Chris Lattner1b9c3872010-08-18 22:47:56 +0000176 struct VariableGEPIndex {
177 const Value *V;
178 ExtensionKind Extension;
179 int64_t Scale;
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000180
181 bool operator==(const VariableGEPIndex &Other) const {
182 return V == Other.V && Extension == Other.Extension &&
183 Scale == Other.Scale;
184 }
185
186 bool operator!=(const VariableGEPIndex &Other) const {
187 return !operator==(Other);
188 }
Chris Lattner1b9c3872010-08-18 22:47:56 +0000189 };
190}
191
Chris Lattner9f7500f2010-08-18 22:07:29 +0000192
193/// GetLinearExpression - Analyze the specified value as a linear expression:
194/// "A*V + B", where A and B are constant integers. Return the scale and offset
Chris Lattner3decde92010-08-18 23:09:49 +0000195/// values as APInts and return V as a Value*, and return whether we looked
196/// through any sign or zero extends. The incoming Value is known to have
197/// IntegerType and it may already be sign or zero extended.
198///
199/// Note that this looks through extends, so the high bits may not be
200/// represented in the result.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000201static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
Chris Lattner3decde92010-08-18 23:09:49 +0000202 ExtensionKind &Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000203 const DataLayout &DL, unsigned Depth) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000204 assert(V->getType()->isIntegerTy() && "Not an integer value");
205
206 // Limit our recursion depth.
207 if (Depth == 6) {
208 Scale = 1;
209 Offset = 0;
210 return V;
211 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000212
Chris Lattner9f7500f2010-08-18 22:07:29 +0000213 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
214 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
215 switch (BOp->getOpcode()) {
216 default: break;
217 case Instruction::Or:
218 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
219 // analyze it.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000220 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), &DL))
Chris Lattner9f7500f2010-08-18 22:07:29 +0000221 break;
222 // FALL THROUGH.
223 case Instruction::Add:
Chris Lattner3decde92010-08-18 23:09:49 +0000224 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000225 DL, Depth+1);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000226 Offset += RHSC->getValue();
227 return V;
228 case Instruction::Mul:
Chris Lattner3decde92010-08-18 23:09:49 +0000229 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000230 DL, Depth+1);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000231 Offset *= RHSC->getValue();
232 Scale *= RHSC->getValue();
233 return V;
234 case Instruction::Shl:
Chris Lattner3decde92010-08-18 23:09:49 +0000235 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000236 DL, Depth+1);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000237 Offset <<= RHSC->getValue().getLimitedValue();
238 Scale <<= RHSC->getValue().getLimitedValue();
239 return V;
240 }
241 }
242 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000243
Chris Lattner9f7500f2010-08-18 22:07:29 +0000244 // Since GEP indices are sign extended anyway, we don't care about the high
Chris Lattner3decde92010-08-18 23:09:49 +0000245 // bits of a sign or zero extended value - just scales and offsets. The
246 // extensions have to be consistent though.
247 if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
248 (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000249 Value *CastOp = cast<CastInst>(V)->getOperand(0);
250 unsigned OldWidth = Scale.getBitWidth();
251 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
Jay Foad583abbc2010-12-07 08:25:19 +0000252 Scale = Scale.trunc(SmallWidth);
253 Offset = Offset.trunc(SmallWidth);
Chris Lattner3decde92010-08-18 23:09:49 +0000254 Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
255
256 Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000257 DL, Depth+1);
Jay Foad583abbc2010-12-07 08:25:19 +0000258 Scale = Scale.zext(OldWidth);
259 Offset = Offset.zext(OldWidth);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000260
Chris Lattner9f7500f2010-08-18 22:07:29 +0000261 return Result;
262 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000263
Chris Lattner9f7500f2010-08-18 22:07:29 +0000264 Scale = 1;
265 Offset = 0;
266 return V;
267}
268
269/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
270/// into a base pointer with a constant offset and a number of scaled symbolic
271/// offsets.
272///
273/// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
274/// the VarIndices vector) are Value*'s that are known to be scaled by the
275/// specified amount, but which may have other unrepresented high bits. As such,
276/// the gep cannot necessarily be reconstructed from its decomposed form.
277///
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000278/// When DataLayout is around, this function is capable of analyzing everything
Dan Gohmana4fcd242010-12-15 20:02:24 +0000279/// that GetUnderlyingObject can look through. When not, it just looks
Chris Lattner9f7500f2010-08-18 22:07:29 +0000280/// through pointer casts.
281///
282static const Value *
283DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
Chris Lattner1b9c3872010-08-18 22:47:56 +0000284 SmallVectorImpl<VariableGEPIndex> &VarIndices,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000285 const DataLayout *DL) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000286 // Limit recursion depth to limit compile time in crazy cases.
287 unsigned MaxLookup = 6;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000288
Chris Lattner9f7500f2010-08-18 22:07:29 +0000289 BaseOffs = 0;
290 do {
291 // See if this is a bitcast or GEP.
292 const Operator *Op = dyn_cast<Operator>(V);
293 if (Op == 0) {
294 // The only non-operator case we can handle are GlobalAliases.
295 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
296 if (!GA->mayBeOverridden()) {
297 V = GA->getAliasee();
298 continue;
299 }
300 }
301 return V;
302 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000303
Chris Lattner9f7500f2010-08-18 22:07:29 +0000304 if (Op->getOpcode() == Instruction::BitCast) {
305 V = Op->getOperand(0);
306 continue;
307 }
Dan Gohman05b18f12010-12-15 20:49:55 +0000308
Chris Lattner9f7500f2010-08-18 22:07:29 +0000309 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
Dan Gohman0573b552011-05-24 18:24:08 +0000310 if (GEPOp == 0) {
311 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
312 // can come up with something. This matches what GetUnderlyingObject does.
313 if (const Instruction *I = dyn_cast<Instruction>(V))
314 // TODO: Get a DominatorTree and use it here.
315 if (const Value *Simplified =
Rafael Espindola5f57f462014-02-21 18:34:28 +0000316 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
Dan Gohman0573b552011-05-24 18:24:08 +0000317 V = Simplified;
318 continue;
319 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000320
Chris Lattner9f7500f2010-08-18 22:07:29 +0000321 return V;
Dan Gohman0573b552011-05-24 18:24:08 +0000322 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000323
Chris Lattner9f7500f2010-08-18 22:07:29 +0000324 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000325 if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
Chris Lattner9f7500f2010-08-18 22:07:29 +0000326 return V;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000327
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000328 // If we are lacking DataLayout information, we can't compute the offets of
Chris Lattner9f7500f2010-08-18 22:07:29 +0000329 // elements computed by GEPs. However, we can handle bitcast equivalent
330 // GEPs.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000331 if (DL == 0) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000332 if (!GEPOp->hasAllZeroIndices())
333 return V;
334 V = GEPOp->getOperand(0);
335 continue;
336 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000337
Matt Arsenaulta8fe22b2013-11-16 00:36:43 +0000338 unsigned AS = GEPOp->getPointerAddressSpace();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000339 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
340 gep_type_iterator GTI = gep_type_begin(GEPOp);
341 for (User::const_op_iterator I = GEPOp->op_begin()+1,
342 E = GEPOp->op_end(); I != E; ++I) {
343 Value *Index = *I;
344 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +0000345 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000346 // For a struct, add the member offset.
347 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
348 if (FieldNo == 0) continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000349
Rafael Espindola5f57f462014-02-21 18:34:28 +0000350 BaseOffs += DL->getStructLayout(STy)->getElementOffset(FieldNo);
Chris Lattner9f7500f2010-08-18 22:07:29 +0000351 continue;
352 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000353
Chris Lattner9f7500f2010-08-18 22:07:29 +0000354 // For an array/pointer, add the element offset, explicitly scaled.
355 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
356 if (CIdx->isZero()) continue;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000357 BaseOffs += DL->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
Chris Lattner9f7500f2010-08-18 22:07:29 +0000358 continue;
359 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000360
Rafael Espindola5f57f462014-02-21 18:34:28 +0000361 uint64_t Scale = DL->getTypeAllocSize(*GTI);
Chris Lattner1b9c3872010-08-18 22:47:56 +0000362 ExtensionKind Extension = EK_NotExtended;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000363
Chris Lattner3decde92010-08-18 23:09:49 +0000364 // If the integer type is smaller than the pointer size, it is implicitly
365 // sign extended to pointer size.
Matt Arsenaultfa252722013-09-27 22:18:51 +0000366 unsigned Width = Index->getType()->getIntegerBitWidth();
Rafael Espindola5f57f462014-02-21 18:34:28 +0000367 if (DL->getPointerSizeInBits(AS) > Width)
Chris Lattner3decde92010-08-18 23:09:49 +0000368 Extension = EK_SignExt;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000369
Chris Lattner3decde92010-08-18 23:09:49 +0000370 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
Chris Lattner9f7500f2010-08-18 22:07:29 +0000371 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
Chris Lattner3decde92010-08-18 23:09:49 +0000372 Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension,
Rafael Espindola5f57f462014-02-21 18:34:28 +0000373 *DL, 0);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000374
Chris Lattner9f7500f2010-08-18 22:07:29 +0000375 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
376 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
Eli Friedmanab3a1282010-09-15 20:08:03 +0000377 BaseOffs += IndexOffset.getSExtValue()*Scale;
378 Scale *= IndexScale.getSExtValue();
Jakub Staszak07f383f2013-08-24 14:16:00 +0000379
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000380 // If we already had an occurrence of this index variable, merge this
Chris Lattner9f7500f2010-08-18 22:07:29 +0000381 // scale into it. For example, we want to handle:
382 // A[x][x] -> x*16 + x*4 -> x*20
383 // This also ensures that 'x' only appears in the index list once.
384 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
Chris Lattner1b9c3872010-08-18 22:47:56 +0000385 if (VarIndices[i].V == Index &&
386 VarIndices[i].Extension == Extension) {
387 Scale += VarIndices[i].Scale;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000388 VarIndices.erase(VarIndices.begin()+i);
389 break;
390 }
391 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000392
Chris Lattner9f7500f2010-08-18 22:07:29 +0000393 // Make sure that we have a scale that makes sense for this target's
394 // pointer size.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000395 if (unsigned ShiftBits = 64 - DL->getPointerSizeInBits(AS)) {
Chris Lattner9f7500f2010-08-18 22:07:29 +0000396 Scale <<= ShiftBits;
Eli Friedmanab3a1282010-09-15 20:08:03 +0000397 Scale = (int64_t)Scale >> ShiftBits;
Chris Lattner9f7500f2010-08-18 22:07:29 +0000398 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000399
Chris Lattner1b9c3872010-08-18 22:47:56 +0000400 if (Scale) {
Jeffrey Yasskin6381c012011-07-27 06:22:51 +0000401 VariableGEPIndex Entry = {Index, Extension,
402 static_cast<int64_t>(Scale)};
Chris Lattner1b9c3872010-08-18 22:47:56 +0000403 VarIndices.push_back(Entry);
404 }
Chris Lattner9f7500f2010-08-18 22:07:29 +0000405 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000406
Chris Lattner9f7500f2010-08-18 22:07:29 +0000407 // Analyze the base pointer next.
408 V = GEPOp->getOperand(0);
409 } while (--MaxLookup);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000410
Chris Lattner9f7500f2010-08-18 22:07:29 +0000411 // If the chain of expressions is too deep, just return early.
412 return V;
413}
414
Chris Lattner9f7500f2010-08-18 22:07:29 +0000415//===----------------------------------------------------------------------===//
Dan Gohman0824aff2010-06-29 00:50:39 +0000416// BasicAliasAnalysis Pass
Chris Lattner2d332972008-06-16 06:30:22 +0000417//===----------------------------------------------------------------------===//
418
Dan Gohman00ef9322010-07-07 14:27:09 +0000419#ifndef NDEBUG
Dan Gohman0824aff2010-06-29 00:50:39 +0000420static const Function *getParent(const Value *V) {
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000421 if (const Instruction *inst = dyn_cast<Instruction>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000422 return inst->getParent()->getParent();
423
Dan Gohman1be9e7c2010-06-29 18:12:34 +0000424 if (const Argument *arg = dyn_cast<Argument>(V))
Dan Gohman0824aff2010-06-29 00:50:39 +0000425 return arg->getParent();
426
427 return NULL;
428}
429
Dan Gohman84f90a32010-07-01 20:08:40 +0000430static bool notDifferentParent(const Value *O1, const Value *O2) {
431
432 const Function *F1 = getParent(O1);
433 const Function *F2 = getParent(O2);
434
Dan Gohman0824aff2010-06-29 00:50:39 +0000435 return !F1 || !F2 || F1 == F2;
436}
Benjamin Kramer80b7bc02010-06-29 10:03:11 +0000437#endif
Dan Gohman0824aff2010-06-29 00:50:39 +0000438
Chris Lattner2d332972008-06-16 06:30:22 +0000439namespace {
Dan Gohmanda85ed82010-10-19 23:09:08 +0000440 /// BasicAliasAnalysis - This is the primary alias analysis implementation.
441 struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
Chris Lattner2d332972008-06-16 06:30:22 +0000442 static char ID; // Class identification, replacement for typeinfo
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000443 BasicAliasAnalysis() : ImmutablePass(ID) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000444 initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
445 }
Dan Gohman0824aff2010-06-29 00:50:39 +0000446
Craig Toppere9ba7592014-03-05 07:30:04 +0000447 void initializePass() override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000448 InitializeAliasAnalysis(this);
449 }
450
Craig Toppere9ba7592014-03-05 07:30:04 +0000451 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman02538ac2010-10-18 18:04:47 +0000452 AU.addRequired<AliasAnalysis>();
Owen Anderson653cb032011-09-06 23:33:25 +0000453 AU.addRequired<TargetLibraryInfo>();
Dan Gohman02538ac2010-10-18 18:04:47 +0000454 }
455
Craig Toppere9ba7592014-03-05 07:30:04 +0000456 AliasResult alias(const Location &LocA, const Location &LocB) override {
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000457 assert(AliasCache.empty() && "AliasCache must be cleared after use!");
Dan Gohman41f14cf2010-09-14 21:25:10 +0000458 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000459 "BasicAliasAnalysis doesn't support interprocedural queries.");
Dan Gohmanf3702452010-10-18 18:45:11 +0000460 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.TBAATag,
461 LocB.Ptr, LocB.Size, LocB.TBAATag);
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000462 // AliasCache rarely has more than 1 or 2 elements, always use
463 // shrink_and_clear so it quickly returns to the inline capacity of the
464 // SmallDenseMap if it ever grows larger.
465 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
466 AliasCache.shrink_and_clear();
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000467 VisitedPhiBBs.clear();
Evan Chengb3ccb642009-10-14 06:46:26 +0000468 return Alias;
Evan Chengc10e88d2009-10-13 22:02:20 +0000469 }
Chris Lattner2d332972008-06-16 06:30:22 +0000470
Craig Toppere9ba7592014-03-05 07:30:04 +0000471 ModRefResult getModRefInfo(ImmutableCallSite CS,
472 const Location &Loc) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000473
Craig Toppere9ba7592014-03-05 07:30:04 +0000474 ModRefResult getModRefInfo(ImmutableCallSite CS1,
475 ImmutableCallSite CS2) override {
Dan Gohman5f1702e2010-08-06 01:25:49 +0000476 // The AliasAnalysis base class has some smarts, lets use them.
477 return AliasAnalysis::getModRefInfo(CS1, CS2);
478 }
Owen Anderson98a36172009-02-05 23:36:27 +0000479
Chris Lattner2d332972008-06-16 06:30:22 +0000480 /// pointsToConstantMemory - Chase pointers until we find a (constant
481 /// global) or not.
Craig Toppere9ba7592014-03-05 07:30:04 +0000482 bool pointsToConstantMemory(const Location &Loc, bool OrLocal) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000483
484 /// getModRefBehavior - Return the behavior when calling the given
485 /// call site.
Craig Toppere9ba7592014-03-05 07:30:04 +0000486 ModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000487
488 /// getModRefBehavior - Return the behavior when calling the given function.
489 /// For use when the call site is not known.
Craig Toppere9ba7592014-03-05 07:30:04 +0000490 ModRefBehavior getModRefBehavior(const Function *F) override;
Chris Lattner2d332972008-06-16 06:30:22 +0000491
Chris Lattneraf362f02010-01-20 19:26:14 +0000492 /// getAdjustedAnalysisPointer - This method is used when a pass implements
Dan Gohmane0d5c452010-08-05 23:48:14 +0000493 /// an analysis interface through multiple inheritance. If needed, it
494 /// should override this to adjust the this pointer as needed for the
495 /// specified pass info.
Craig Toppere9ba7592014-03-05 07:30:04 +0000496 void *getAdjustedAnalysisPointer(const void *ID) override {
Owen Andersona7aed182010-08-06 18:33:48 +0000497 if (ID == &AliasAnalysis::ID)
Chris Lattneraf362f02010-01-20 19:26:14 +0000498 return (AliasAnalysis*)this;
499 return this;
500 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000501
Chris Lattner2d332972008-06-16 06:30:22 +0000502 private:
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000503 // AliasCache - Track alias queries to guard against recursion.
504 typedef std::pair<Location, Location> LocPair;
Benjamin Kramer6c2649c2012-09-05 16:49:37 +0000505 typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000506 AliasCacheTy AliasCache;
507
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000508 /// \brief Track phi nodes we have visited. When interpret "Value" pointer
509 /// equality as value equality we need to make sure that the "Value" is not
510 /// part of a cycle. Otherwise, two uses could come from different
511 /// "iterations" of a cycle and see different values for the same "Value"
512 /// pointer.
513 /// The following example shows the problem:
514 /// %p = phi(%alloca1, %addr2)
515 /// %l = load %ptr
516 /// %addr1 = gep, %alloca2, 0, %l
517 /// %addr2 = gep %alloca2, 0, (%l + 1)
518 /// alias(%p, %addr1) -> MayAlias !
519 /// store %l, ...
520 SmallPtrSet<const BasicBlock*, 8> VisitedPhiBBs;
521
Dan Gohmanfb02cec2011-06-04 00:31:50 +0000522 // Visited - Track instructions visited by pointsToConstantMemory.
Dan Gohman7c34ece2010-06-28 21:16:52 +0000523 SmallPtrSet<const Value*, 16> Visited;
Evan Cheng31565b32009-10-14 05:05:02 +0000524
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000525 /// \brief Check whether two Values can be considered equivalent.
526 ///
527 /// In addition to pointer equivalence of \p V1 and \p V2 this checks
528 /// whether they can not be part of a cycle in the value graph by looking at
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +0000529 /// all visited phi nodes an making sure that the phis cannot reach the
530 /// value. We have to do this because we are looking through phi nodes (That
531 /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
532 bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +0000533
534 /// \brief Dest and Src are the variable indices from two decomposed
535 /// GetElementPtr instructions GEP1 and GEP2 which have common base
536 /// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
537 /// difference between the two pointers.
538 void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
539 const SmallVectorImpl<VariableGEPIndex> &Src);
540
Chris Lattner98e253262009-11-23 16:45:27 +0000541 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
542 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000543 AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000544 const MDNode *V1TBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000545 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000546 const MDNode *V2TBAAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000547 const Value *UnderlyingV1, const Value *UnderlyingV2);
Evan Chengc10e88d2009-10-13 22:02:20 +0000548
Chris Lattner98e253262009-11-23 16:45:27 +0000549 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
550 // instruction against another.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000551 AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
Dan Gohmanf3702452010-10-18 18:45:11 +0000552 const MDNode *PNTBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000553 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000554 const MDNode *V2TBAAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +0000555
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000556 /// aliasSelect - Disambiguate a Select instruction against another value.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000557 AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
Dan Gohmanf3702452010-10-18 18:45:11 +0000558 const MDNode *SITBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000559 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000560 const MDNode *V2TBAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +0000561
Dan Gohmanf372cf82010-10-19 22:54:46 +0000562 AliasResult aliasCheck(const Value *V1, uint64_t V1Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000563 const MDNode *V1TBAATag,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000564 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000565 const MDNode *V2TBAATag);
Chris Lattner2d332972008-06-16 06:30:22 +0000566 };
567} // End of anonymous namespace
568
569// Register this pass...
570char BasicAliasAnalysis::ID = 0;
Owen Anderson653cb032011-09-06 23:33:25 +0000571INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
Dan Gohmanda85ed82010-10-19 23:09:08 +0000572 "Basic Alias Analysis (stateless AA impl)",
Dan Gohman02538ac2010-10-18 18:04:47 +0000573 false, true, false)
Owen Anderson653cb032011-09-06 23:33:25 +0000574INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
575INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
576 "Basic Alias Analysis (stateless AA impl)",
577 false, true, false)
578
Chris Lattner2d332972008-06-16 06:30:22 +0000579
580ImmutablePass *llvm::createBasicAliasAnalysisPass() {
581 return new BasicAliasAnalysis();
582}
583
Dan Gohman9130bad2010-11-08 16:45:26 +0000584/// pointsToConstantMemory - Returns whether the given pointer value
585/// points to memory that is local to the function, with global constants being
586/// considered local to all functions.
587bool
588BasicAliasAnalysis::pointsToConstantMemory(const Location &Loc, bool OrLocal) {
589 assert(Visited.empty() && "Visited must be cleared after use!");
Chris Lattner2d332972008-06-16 06:30:22 +0000590
Dan Gohman142ff822010-11-08 20:26:19 +0000591 unsigned MaxLookup = 8;
Dan Gohman9130bad2010-11-08 16:45:26 +0000592 SmallVector<const Value *, 16> Worklist;
593 Worklist.push_back(Loc.Ptr);
594 do {
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000595 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
Dan Gohman9130bad2010-11-08 16:45:26 +0000596 if (!Visited.insert(V)) {
597 Visited.clear();
598 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
599 }
Dan Gohman5f1702e2010-08-06 01:25:49 +0000600
Dan Gohman9130bad2010-11-08 16:45:26 +0000601 // An alloca instruction defines local memory.
602 if (OrLocal && isa<AllocaInst>(V))
603 continue;
604
605 // A global constant counts as local memory for our purposes.
606 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
607 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
608 // global to be marked constant in some modules and non-constant in
609 // others. GV may even be a declaration, not a definition.
610 if (!GV->isConstant()) {
611 Visited.clear();
612 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
613 }
614 continue;
615 }
616
617 // If both select values point to local memory, then so does the select.
618 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
619 Worklist.push_back(SI->getTrueValue());
620 Worklist.push_back(SI->getFalseValue());
621 continue;
622 }
623
624 // If all values incoming to a phi node point to local memory, then so does
625 // the phi.
626 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
Dan Gohman142ff822010-11-08 20:26:19 +0000627 // Don't bother inspecting phi nodes with many operands.
628 if (PN->getNumIncomingValues() > MaxLookup) {
629 Visited.clear();
630 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
631 }
Dan Gohman9130bad2010-11-08 16:45:26 +0000632 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
633 Worklist.push_back(PN->getIncomingValue(i));
634 continue;
635 }
636
637 // Otherwise be conservative.
638 Visited.clear();
639 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
640
Dan Gohman142ff822010-11-08 20:26:19 +0000641 } while (!Worklist.empty() && --MaxLookup);
Dan Gohman9130bad2010-11-08 16:45:26 +0000642
643 Visited.clear();
Dan Gohman142ff822010-11-08 20:26:19 +0000644 return Worklist.empty();
Chris Lattner2d332972008-06-16 06:30:22 +0000645}
646
Dan Gohman5f1702e2010-08-06 01:25:49 +0000647/// getModRefBehavior - Return the behavior when calling the given call site.
648AliasAnalysis::ModRefBehavior
649BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
650 if (CS.doesNotAccessMemory())
651 // Can't do better than this.
652 return DoesNotAccessMemory;
653
654 ModRefBehavior Min = UnknownModRefBehavior;
655
656 // If the callsite knows it only reads memory, don't return worse
657 // than that.
658 if (CS.onlyReadsMemory())
659 Min = OnlyReadsMemory;
660
661 // The AliasAnalysis base class has some smarts, lets use them.
Dan Gohman2694e142010-11-10 01:02:18 +0000662 return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000663}
664
665/// getModRefBehavior - Return the behavior when calling the given function.
666/// For use when the call site is not known.
667AliasAnalysis::ModRefBehavior
668BasicAliasAnalysis::getModRefBehavior(const Function *F) {
Dan Gohmane461d7d2010-11-08 16:08:43 +0000669 // If the function declares it doesn't access memory, we can't do better.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000670 if (F->doesNotAccessMemory())
Dan Gohman5f1702e2010-08-06 01:25:49 +0000671 return DoesNotAccessMemory;
Dan Gohmane461d7d2010-11-08 16:08:43 +0000672
673 // For intrinsics, we can check the table.
674 if (unsigned iid = F->getIntrinsicID()) {
675#define GET_INTRINSIC_MODREF_BEHAVIOR
Chandler Carruthdb25c6c2013-01-02 12:09:16 +0000676#include "llvm/IR/Intrinsics.gen"
Dan Gohmane461d7d2010-11-08 16:08:43 +0000677#undef GET_INTRINSIC_MODREF_BEHAVIOR
678 }
679
Dan Gohman2694e142010-11-10 01:02:18 +0000680 ModRefBehavior Min = UnknownModRefBehavior;
681
Dan Gohmane461d7d2010-11-08 16:08:43 +0000682 // If the function declares it only reads memory, go with that.
Dan Gohman5f1702e2010-08-06 01:25:49 +0000683 if (F->onlyReadsMemory())
Dan Gohman2694e142010-11-10 01:02:18 +0000684 Min = OnlyReadsMemory;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000685
Dan Gohmane461d7d2010-11-08 16:08:43 +0000686 // Otherwise be conservative.
Dan Gohman2694e142010-11-10 01:02:18 +0000687 return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000688}
Owen Anderson98a36172009-02-05 23:36:27 +0000689
Chris Lattner98e253262009-11-23 16:45:27 +0000690/// getModRefInfo - Check to see if the specified callsite can clobber the
691/// specified memory object. Since we only look at local properties of this
692/// function, we really can't say much about this query. We do, however, use
693/// simple "address taken" analysis on local objects.
Chris Lattner2d332972008-06-16 06:30:22 +0000694AliasAnalysis::ModRefResult
Dan Gohman5442c712010-08-03 21:48:53 +0000695BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
Dan Gohman41f14cf2010-09-14 21:25:10 +0000696 const Location &Loc) {
697 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
Dan Gohman00ef9322010-07-07 14:27:09 +0000698 "AliasAnalysis query involving multiple functions!");
699
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000700 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000701
Dan Gohman41f14cf2010-09-14 21:25:10 +0000702 // If this is a tail call and Loc.Ptr points to a stack location, we know that
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000703 // the tail call cannot access or modify the local stack.
704 // We cannot exclude byval arguments here; these belong to the caller of
705 // the current function not to the current function, and a tail callee
706 // may reference them.
707 if (isa<AllocaInst>(Object))
Dan Gohman5442c712010-08-03 21:48:53 +0000708 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000709 if (CI->isTailCall())
710 return NoModRef;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000711
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000712 // If the pointer is to a locally allocated object that does not escape,
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000713 // then the call can not mod/ref the pointer unless the call takes the pointer
714 // as an argument, and itself doesn't capture it.
Chris Lattner1e7b37e2009-11-23 16:46:41 +0000715 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
Dan Gohman84f90a32010-07-01 20:08:40 +0000716 isNonEscapingLocalObject(Object)) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000717 bool PassedAsArg = false;
718 unsigned ArgNo = 0;
Dan Gohman5442c712010-08-03 21:48:53 +0000719 for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000720 CI != CE; ++CI, ++ArgNo) {
Chris Lattner026f5e62011-05-23 05:15:43 +0000721 // Only look at the no-capture or byval pointer arguments. If this
722 // pointer were passed to arguments that were neither of these, then it
723 // couldn't be no-capture.
Duncan Sands19d0b472010-02-16 11:11:14 +0000724 if (!(*CI)->getType()->isPointerTy() ||
Nick Lewycky612d70b2011-11-20 19:09:04 +0000725 (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000726 continue;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000727
Dan Gohman41f14cf2010-09-14 21:25:10 +0000728 // If this is a no-capture pointer argument, see if we can tell that it
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000729 // is impossible to alias the pointer we're checking. If not, we have to
730 // assume that the call could touch the pointer, even though it doesn't
731 // escape.
Eli Friedman5f476dc2011-09-28 00:34:27 +0000732 if (!isNoAlias(Location(*CI), Location(Object))) {
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000733 PassedAsArg = true;
734 break;
735 }
736 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000737
Chris Lattner84ed59ab2009-11-23 16:44:43 +0000738 if (!PassedAsArg)
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000739 return NoModRef;
740 }
741
Owen Anderson653cb032011-09-06 23:33:25 +0000742 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfo>();
Dan Gohman2694e142010-11-10 01:02:18 +0000743 ModRefResult Min = ModRef;
744
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000745 // Finally, handle specific knowledge of intrinsics.
Dan Gohman5442c712010-08-03 21:48:53 +0000746 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
Dan Gohman5f1702e2010-08-06 01:25:49 +0000747 if (II != 0)
748 switch (II->getIntrinsicID()) {
749 default: break;
750 case Intrinsic::memcpy:
751 case Intrinsic::memmove: {
Dan Gohmanf372cf82010-10-19 22:54:46 +0000752 uint64_t Len = UnknownSize;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000753 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2)))
754 Len = LenCI->getZExtValue();
Gabor Greif1abbde32010-06-23 23:38:07 +0000755 Value *Dest = II->getArgOperand(0);
Dan Gohman5f1702e2010-08-06 01:25:49 +0000756 Value *Src = II->getArgOperand(1);
Chris Lattner90c49472010-11-30 00:43:16 +0000757 // If it can't overlap the source dest, then it doesn't modref the loc.
Dan Gohman41f14cf2010-09-14 21:25:10 +0000758 if (isNoAlias(Location(Dest, Len), Loc)) {
759 if (isNoAlias(Location(Src, Len), Loc))
Dan Gohman5f1702e2010-08-06 01:25:49 +0000760 return NoModRef;
Chris Lattner90c49472010-11-30 00:43:16 +0000761 // If it can't overlap the dest, then worst case it reads the loc.
Dan Gohman2694e142010-11-10 01:02:18 +0000762 Min = Ref;
Chris Lattner90c49472010-11-30 00:43:16 +0000763 } else if (isNoAlias(Location(Src, Len), Loc)) {
764 // If it can't overlap the source, then worst case it mutates the loc.
765 Min = Mod;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000766 }
767 break;
Chris Lattner2d332972008-06-16 06:30:22 +0000768 }
Dan Gohman5f1702e2010-08-06 01:25:49 +0000769 case Intrinsic::memset:
770 // Since memset is 'accesses arguments' only, the AliasAnalysis base class
771 // will handle it for the variable length case.
772 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
Dan Gohmanf372cf82010-10-19 22:54:46 +0000773 uint64_t Len = LenCI->getZExtValue();
Dan Gohman5f1702e2010-08-06 01:25:49 +0000774 Value *Dest = II->getArgOperand(0);
Dan Gohman41f14cf2010-09-14 21:25:10 +0000775 if (isNoAlias(Location(Dest, Len), Loc))
Dan Gohman5f1702e2010-08-06 01:25:49 +0000776 return NoModRef;
777 }
Chris Lattner9a146372010-11-30 00:28:45 +0000778 // We know that memset doesn't load anything.
779 Min = Mod;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000780 break;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000781 case Intrinsic::lifetime_start:
782 case Intrinsic::lifetime_end:
783 case Intrinsic::invariant_start: {
Dan Gohmanf372cf82010-10-19 22:54:46 +0000784 uint64_t PtrSize =
Dan Gohman5f1702e2010-08-06 01:25:49 +0000785 cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
Dan Gohman41f14cf2010-09-14 21:25:10 +0000786 if (isNoAlias(Location(II->getArgOperand(1),
787 PtrSize,
788 II->getMetadata(LLVMContext::MD_tbaa)),
789 Loc))
Chris Lattnerd6a49ad2009-11-22 16:05:05 +0000790 return NoModRef;
Dan Gohman5f1702e2010-08-06 01:25:49 +0000791 break;
Nick Lewyckye2782c72009-10-13 07:48:38 +0000792 }
Dan Gohman5f1702e2010-08-06 01:25:49 +0000793 case Intrinsic::invariant_end: {
Dan Gohmanf372cf82010-10-19 22:54:46 +0000794 uint64_t PtrSize =
Dan Gohman5f1702e2010-08-06 01:25:49 +0000795 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue();
Dan Gohman41f14cf2010-09-14 21:25:10 +0000796 if (isNoAlias(Location(II->getArgOperand(2),
797 PtrSize,
798 II->getMetadata(LLVMContext::MD_tbaa)),
799 Loc))
Dan Gohman5f1702e2010-08-06 01:25:49 +0000800 return NoModRef;
801 break;
802 }
Dan Gohman5394c702011-04-27 20:44:28 +0000803 case Intrinsic::arm_neon_vld1: {
804 // LLVM's vld1 and vst1 intrinsics currently only support a single
805 // vector register.
806 uint64_t Size =
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000807 DL ? DL->getTypeStoreSize(II->getType()) : UnknownSize;
Dan Gohman5394c702011-04-27 20:44:28 +0000808 if (isNoAlias(Location(II->getArgOperand(0), Size,
809 II->getMetadata(LLVMContext::MD_tbaa)),
810 Loc))
811 return NoModRef;
812 break;
813 }
814 case Intrinsic::arm_neon_vst1: {
815 uint64_t Size =
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000816 DL ? DL->getTypeStoreSize(II->getArgOperand(1)->getType()) : UnknownSize;
Dan Gohman5394c702011-04-27 20:44:28 +0000817 if (isNoAlias(Location(II->getArgOperand(0), Size,
818 II->getMetadata(LLVMContext::MD_tbaa)),
819 Loc))
820 return NoModRef;
821 break;
822 }
Dan Gohman5f1702e2010-08-06 01:25:49 +0000823 }
Chris Lattner2d332972008-06-16 06:30:22 +0000824
Owen Anderson653cb032011-09-06 23:33:25 +0000825 // We can bound the aliasing properties of memset_pattern16 just as we can
Jakub Staszak07f383f2013-08-24 14:16:00 +0000826 // for memcpy/memset. This is particularly important because the
Owen Anderson653cb032011-09-06 23:33:25 +0000827 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
828 // whenever possible.
829 else if (TLI.has(LibFunc::memset_pattern16) &&
830 CS.getCalledFunction() &&
831 CS.getCalledFunction()->getName() == "memset_pattern16") {
832 const Function *MS = CS.getCalledFunction();
833 FunctionType *MemsetType = MS->getFunctionType();
834 if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
835 isa<PointerType>(MemsetType->getParamType(0)) &&
836 isa<PointerType>(MemsetType->getParamType(1)) &&
837 isa<IntegerType>(MemsetType->getParamType(2))) {
838 uint64_t Len = UnknownSize;
839 if (const ConstantInt *LenCI = dyn_cast<ConstantInt>(CS.getArgument(2)))
840 Len = LenCI->getZExtValue();
841 const Value *Dest = CS.getArgument(0);
842 const Value *Src = CS.getArgument(1);
843 // If it can't overlap the source dest, then it doesn't modref the loc.
844 if (isNoAlias(Location(Dest, Len), Loc)) {
Owen Andersonf4f09f82011-09-06 23:43:26 +0000845 // Always reads 16 bytes of the source.
846 if (isNoAlias(Location(Src, 16), Loc))
Owen Anderson653cb032011-09-06 23:33:25 +0000847 return NoModRef;
848 // If it can't overlap the dest, then worst case it reads the loc.
849 Min = Ref;
Owen Andersonf4f09f82011-09-06 23:43:26 +0000850 // Always reads 16 bytes of the source.
851 } else if (isNoAlias(Location(Src, 16), Loc)) {
Owen Anderson653cb032011-09-06 23:33:25 +0000852 // If it can't overlap the source, then worst case it mutates the loc.
853 Min = Mod;
854 }
855 }
856 }
857
Chris Lattner2d332972008-06-16 06:30:22 +0000858 // The AliasAnalysis base class has some smarts, lets use them.
Dan Gohman2694e142010-11-10 01:02:18 +0000859 return ModRefResult(AliasAnalysis::getModRefInfo(CS, Loc) & Min);
Dan Gohman64d842e2010-09-08 01:32:20 +0000860}
Chris Lattner2d332972008-06-16 06:30:22 +0000861
Craig Topperb94011f2013-07-14 04:42:23 +0000862static bool areVarIndicesEqual(SmallVectorImpl<VariableGEPIndex> &Indices1,
863 SmallVectorImpl<VariableGEPIndex> &Indices2) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000864 unsigned Size1 = Indices1.size();
865 unsigned Size2 = Indices2.size();
866
867 if (Size1 != Size2)
868 return false;
869
870 for (unsigned I = 0; I != Size1; ++I)
871 if (Indices1[I] != Indices2[I])
872 return false;
873
874 return true;
875}
876
Chris Lattnera99edbe2009-11-26 02:11:08 +0000877/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
878/// against another pointer. We know that V1 is a GEP, but we don't know
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000879/// anything about V2. UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
Chris Lattner5341c962009-11-26 02:14:59 +0000880/// UnderlyingV2 is the same for V2.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000881///
Chris Lattnerd6a2a992003-02-26 19:41:54 +0000882AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +0000883BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, uint64_t V1Size,
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000884 const MDNode *V1TBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000885 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +0000886 const MDNode *V2TBAAInfo,
Chris Lattner5341c962009-11-26 02:14:59 +0000887 const Value *UnderlyingV1,
888 const Value *UnderlyingV2) {
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000889 int64_t GEP1BaseOffset;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000890 SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000891
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000892 // If we have two gep instructions with must-alias or not-alias'ing base
893 // pointers, figure out if the indexes to the GEP tell us anything about the
894 // derived pointer.
Chris Lattnera99edbe2009-11-26 02:11:08 +0000895 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000896 // Do the base pointers alias?
897 AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, 0,
898 UnderlyingV2, UnknownSize, 0);
899
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000900 // Check for geps of non-aliasing underlying pointers where the offsets are
901 // identical.
Arnold Schwaighoferaadf1042013-03-26 18:07:53 +0000902 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000903 // Do the base pointers alias assuming type and size.
904 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size,
905 V1TBAAInfo, UnderlyingV2,
906 V2Size, V2TBAAInfo);
907 if (PreciseBaseAlias == NoAlias) {
908 // See if the computed offset from the common pointer tells us about the
909 // relation of the resulting pointer.
910 int64_t GEP2BaseOffset;
911 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
912 const Value *GEP2BasePtr =
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000913 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, DL);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000914 const Value *GEP1BasePtr =
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000915 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, DL);
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000916 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000917 // same result except when DecomposeGEPExpression has no DataLayout.
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000918 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000919 assert(DL == 0 &&
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000920 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
921 return MayAlias;
922 }
923 // Same offsets.
924 if (GEP1BaseOffset == GEP2BaseOffset &&
925 areVarIndicesEqual(GEP1VariableIndices, GEP2VariableIndices))
926 return NoAlias;
927 GEP1VariableIndices.clear();
928 }
929 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000930
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000931 // If we get a No or May, then return it immediately, no amount of analysis
932 // will improve this situation.
933 if (BaseAlias != MustAlias) return BaseAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +0000934
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000935 // Otherwise, we have a MustAlias. Since the base pointers alias each other
936 // exactly, see if the computed offset from the common pointer tells us
937 // about the relation of the resulting pointer.
938 const Value *GEP1BasePtr =
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000939 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000940
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000941 int64_t GEP2BaseOffset;
Chris Lattner1b9c3872010-08-18 22:47:56 +0000942 SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000943 const Value *GEP2BasePtr =
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000944 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000945
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000946 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000947 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000948 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000949 assert(DL == 0 &&
Dan Gohmana4fcd242010-12-15 20:02:24 +0000950 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000951 return MayAlias;
952 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000953
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000954 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
955 // symbolic difference.
956 GEP1BaseOffset -= GEP2BaseOffset;
Dan Gohmanad867b02010-08-03 20:23:52 +0000957 GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000958
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000959 } else {
960 // Check to see if these two pointers are related by the getelementptr
961 // instruction. If one pointer is a GEP with a non-zero index of the other
962 // pointer, we know they cannot alias.
Chris Lattner5c1cfc22009-11-26 16:52:32 +0000963
964 // If both accesses are unknown size, we can't do anything useful here.
Dan Gohman2a190082010-08-03 01:03:11 +0000965 if (V1Size == UnknownSize && V2Size == UnknownSize)
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000966 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000967
Dan Gohmanf3702452010-10-18 18:45:11 +0000968 AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, 0,
969 V2, V2Size, V2TBAAInfo);
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000970 if (R != MustAlias)
971 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
972 // If V2 is known not to alias GEP base pointer, then the two values
973 // cannot alias per GEP semantics: "A pointer value formed from a
974 // getelementptr instruction is associated with the addresses associated
975 // with the first operand of the getelementptr".
976 return R;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000977
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000978 const Value *GEP1BasePtr =
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000979 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, DL);
Jakub Staszak07f383f2013-08-24 14:16:00 +0000980
Arnold Schwaighofer76dca582012-09-06 14:31:51 +0000981 // DecomposeGEPExpression and GetUnderlyingObject should return the
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000982 // same result except when DecomposeGEPExpression has no DataLayout.
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000983 if (GEP1BasePtr != UnderlyingV1) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000984 assert(DL == 0 &&
Dan Gohmana4fcd242010-12-15 20:02:24 +0000985 "DecomposeGEPExpression and GetUnderlyingObject disagree!");
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000986 return MayAlias;
Chris Lattner6ea17f77f2003-12-11 22:44:13 +0000987 }
988 }
Jakub Staszak07f383f2013-08-24 14:16:00 +0000989
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000990 // In the two GEP Case, if there is no difference in the offsets of the
991 // computed pointers, the resultant pointers are a must alias. This
992 // hapens when we have two lexically identical GEP's (for example).
Chris Lattnerd6a2a992003-02-26 19:41:54 +0000993 //
Chris Lattner7a5b56a2009-11-26 02:17:34 +0000994 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
995 // must aliases the GEP, the end result is a must alias also.
996 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
Evan Chengc1eed9d2009-10-14 06:41:49 +0000997 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +0000998
Eli Friedman3d1b3072011-09-08 02:23:31 +0000999 // If there is a constant difference between the pointers, but the difference
1000 // is less than the size of the associated memory object, then we know
1001 // that the objects are partially overlapping. If the difference is
1002 // greater, we know they do not overlap.
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001003 if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001004 if (GEP1BaseOffset >= 0) {
1005 if (V2Size != UnknownSize) {
1006 if ((uint64_t)GEP1BaseOffset < V2Size)
1007 return PartialAlias;
1008 return NoAlias;
1009 }
1010 } else {
Arnold Schwaighofere3ac0992014-01-16 04:53:18 +00001011 // We have the situation where:
1012 // + +
1013 // | BaseOffset |
1014 // ---------------->|
1015 // |-->V1Size |-------> V2Size
1016 // GEP1 V2
1017 // We need to know that V2Size is not unknown, otherwise we might have
1018 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1019 if (V1Size != UnknownSize && V2Size != UnknownSize) {
Eli Friedman3d1b3072011-09-08 02:23:31 +00001020 if (-(uint64_t)GEP1BaseOffset < V1Size)
1021 return PartialAlias;
1022 return NoAlias;
1023 }
1024 }
Dan Gohmanc4bf5ca2010-12-13 22:50:24 +00001025 }
1026
Eli Friedman3d1b3072011-09-08 02:23:31 +00001027 // Try to distinguish something like &A[i][1] against &A[42][0].
1028 // Grab the least significant bit set in any of the scales.
Eli Friedmanb78ac542011-09-08 02:37:07 +00001029 if (!GEP1VariableIndices.empty()) {
1030 uint64_t Modulo = 0;
1031 for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i)
1032 Modulo |= (uint64_t)GEP1VariableIndices[i].Scale;
1033 Modulo = Modulo ^ (Modulo & (Modulo - 1));
Eli Friedman3d1b3072011-09-08 02:23:31 +00001034
Eli Friedmanb78ac542011-09-08 02:37:07 +00001035 // We can compute the difference between the two addresses
1036 // mod Modulo. Check whether that difference guarantees that the
1037 // two locations do not alias.
1038 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1039 if (V1Size != UnknownSize && V2Size != UnknownSize &&
1040 ModOffset >= V2Size && V1Size <= Modulo - ModOffset)
1041 return NoAlias;
1042 }
Eli Friedman3d1b3072011-09-08 02:23:31 +00001043
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001044 // Statically, we can see that the base objects are the same, but the
1045 // pointers have dynamic offsets which we can't resolve. And none of our
1046 // little tricks above worked.
1047 //
1048 // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1049 // practical effect of this is protecting TBAA in the case of dynamic
Dan Gohman9017b842012-02-17 18:33:38 +00001050 // indices into arrays of unions or malloc'd memory.
Dan Gohmanadf80ae2011-06-04 06:50:18 +00001051 return PartialAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001052}
1053
Dan Gohman4e7e7952011-06-03 20:17:36 +00001054static AliasAnalysis::AliasResult
1055MergeAliasResults(AliasAnalysis::AliasResult A, AliasAnalysis::AliasResult B) {
1056 // If the results agree, take it.
1057 if (A == B)
1058 return A;
1059 // A mix of PartialAlias and MustAlias is PartialAlias.
1060 if ((A == AliasAnalysis::PartialAlias && B == AliasAnalysis::MustAlias) ||
1061 (B == AliasAnalysis::PartialAlias && A == AliasAnalysis::MustAlias))
1062 return AliasAnalysis::PartialAlias;
1063 // Otherwise, we don't know anything.
1064 return AliasAnalysis::MayAlias;
1065}
1066
Chris Lattner98e253262009-11-23 16:45:27 +00001067/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1068/// instruction against another.
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001069AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001070BasicAliasAnalysis::aliasSelect(const SelectInst *SI, uint64_t SISize,
Dan Gohmanf3702452010-10-18 18:45:11 +00001071 const MDNode *SITBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001072 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +00001073 const MDNode *V2TBAAInfo) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001074 // If the values are Selects with the same condition, we can do a more precise
1075 // check: just check for aliases between the values on corresponding arms.
1076 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1077 if (SI->getCondition() == SI2->getCondition()) {
1078 AliasResult Alias =
Dan Gohmanf3702452010-10-18 18:45:11 +00001079 aliasCheck(SI->getTrueValue(), SISize, SITBAAInfo,
1080 SI2->getTrueValue(), V2Size, V2TBAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001081 if (Alias == MayAlias)
1082 return MayAlias;
1083 AliasResult ThisAlias =
Dan Gohmanf3702452010-10-18 18:45:11 +00001084 aliasCheck(SI->getFalseValue(), SISize, SITBAAInfo,
1085 SI2->getFalseValue(), V2Size, V2TBAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001086 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001087 }
1088
1089 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1090 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1091 AliasResult Alias =
Dan Gohmanf3702452010-10-18 18:45:11 +00001092 aliasCheck(V2, V2Size, V2TBAAInfo, SI->getTrueValue(), SISize, SITBAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001093 if (Alias == MayAlias)
1094 return MayAlias;
Dan Gohman7c34ece2010-06-28 21:16:52 +00001095
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001096 AliasResult ThisAlias =
Dan Gohmanf3702452010-10-18 18:45:11 +00001097 aliasCheck(V2, V2Size, V2TBAAInfo, SI->getFalseValue(), SISize, SITBAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001098 return MergeAliasResults(ThisAlias, Alias);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001099}
1100
Evan Chengf92f5552009-10-14 05:22:03 +00001101// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
Evan Cheng31565b32009-10-14 05:05:02 +00001102// against another.
Evan Chengc10e88d2009-10-13 22:02:20 +00001103AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001104BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
Dan Gohmanf3702452010-10-18 18:45:11 +00001105 const MDNode *PNTBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001106 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +00001107 const MDNode *V2TBAAInfo) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001108 // Track phi nodes we have visited. We use this information when we determine
1109 // value equivalence.
1110 VisitedPhiBBs.insert(PN->getParent());
1111
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001112 // If the values are PHIs in the same block, we can do a more precise
1113 // as well as efficient check: just check for aliases between the values
1114 // on corresponding edges.
1115 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1116 if (PN2->getParent() == PN->getParent()) {
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001117 LocPair Locs(Location(PN, PNSize, PNTBAAInfo),
1118 Location(V2, V2Size, V2TBAAInfo));
1119 if (PN > V2)
1120 std::swap(Locs.first, Locs.second);
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001121 // Analyse the PHIs' inputs under the assumption that the PHIs are
1122 // NoAlias.
1123 // If the PHIs are May/MustAlias there must be (recursively) an input
1124 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1125 // there must be an operation on the PHIs within the PHIs' value cycle
1126 // that causes a MayAlias.
1127 // Pretend the phis do not alias.
1128 AliasResult Alias = NoAlias;
1129 assert(AliasCache.count(Locs) &&
1130 "There must exist an entry for the phi node");
1131 AliasResult OrigAliasResult = AliasCache[Locs];
1132 AliasCache[Locs] = NoAlias;
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001133
Hal Finkela6f86fc2012-11-17 02:33:15 +00001134 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001135 AliasResult ThisAlias =
Dan Gohmanf3702452010-10-18 18:45:11 +00001136 aliasCheck(PN->getIncomingValue(i), PNSize, PNTBAAInfo,
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001137 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
Dan Gohmanf3702452010-10-18 18:45:11 +00001138 V2Size, V2TBAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001139 Alias = MergeAliasResults(ThisAlias, Alias);
1140 if (Alias == MayAlias)
1141 break;
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001142 }
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001143
1144 // Reset if speculation failed.
Arnold Schwaighoferedd62b12012-12-10 23:02:41 +00001145 if (Alias != NoAlias)
Arnold Schwaighofer8dc34cf2012-09-06 14:41:53 +00001146 AliasCache[Locs] = OrigAliasResult;
1147
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001148 return Alias;
1149 }
1150
Evan Cheng8ec25932009-10-16 00:33:09 +00001151 SmallPtrSet<Value*, 4> UniqueSrc;
Evan Chengc10e88d2009-10-13 22:02:20 +00001152 SmallVector<Value*, 4> V1Srcs;
Evan Chengc10e88d2009-10-13 22:02:20 +00001153 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1154 Value *PV1 = PN->getIncomingValue(i);
1155 if (isa<PHINode>(PV1))
1156 // If any of the source itself is a PHI, return MayAlias conservatively
Evan Chengc1eed9d2009-10-14 06:41:49 +00001157 // to avoid compile time explosion. The worst possible case is if both
1158 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1159 // and 'n' are the number of PHI sources.
Evan Chengc10e88d2009-10-13 22:02:20 +00001160 return MayAlias;
1161 if (UniqueSrc.insert(PV1))
1162 V1Srcs.push_back(PV1);
1163 }
1164
Dan Gohmanf3702452010-10-18 18:45:11 +00001165 AliasResult Alias = aliasCheck(V2, V2Size, V2TBAAInfo,
1166 V1Srcs[0], PNSize, PNTBAAInfo);
Evan Chengf92f5552009-10-14 05:22:03 +00001167 // Early exit if the check of the first PHI source against V2 is MayAlias.
1168 // Other results are not possible.
1169 if (Alias == MayAlias)
1170 return MayAlias;
1171
Evan Chengc10e88d2009-10-13 22:02:20 +00001172 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1173 // NoAlias / MustAlias. Otherwise, returns MayAlias.
Evan Chengc10e88d2009-10-13 22:02:20 +00001174 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1175 Value *V = V1Srcs[i];
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001176
Dan Gohmanf3702452010-10-18 18:45:11 +00001177 AliasResult ThisAlias = aliasCheck(V2, V2Size, V2TBAAInfo,
1178 V, PNSize, PNTBAAInfo);
Dan Gohman4e7e7952011-06-03 20:17:36 +00001179 Alias = MergeAliasResults(ThisAlias, Alias);
1180 if (Alias == MayAlias)
1181 break;
Evan Chengc10e88d2009-10-13 22:02:20 +00001182 }
1183
1184 return Alias;
1185}
1186
1187// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1188// such as array references.
Evan Chengf1f3dd32009-10-13 18:42:04 +00001189//
1190AliasAnalysis::AliasResult
Dan Gohmanf372cf82010-10-19 22:54:46 +00001191BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
Dan Gohmanf3702452010-10-18 18:45:11 +00001192 const MDNode *V1TBAAInfo,
Dan Gohmanf372cf82010-10-19 22:54:46 +00001193 const Value *V2, uint64_t V2Size,
Dan Gohmanf3702452010-10-18 18:45:11 +00001194 const MDNode *V2TBAAInfo) {
Dan Gohmancb45bd92010-04-08 18:11:50 +00001195 // If either of the memory references is empty, it doesn't matter what the
1196 // pointer values are.
1197 if (V1Size == 0 || V2Size == 0)
1198 return NoAlias;
1199
Evan Chengf1f3dd32009-10-13 18:42:04 +00001200 // Strip off any casts if they exist.
1201 V1 = V1->stripPointerCasts();
1202 V2 = V2->stripPointerCasts();
1203
1204 // Are we checking for alias of the same value?
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001205 // Because we look 'through' phi nodes we could look at "Value" pointers from
1206 // different iterations. We must therefore make sure that this is not the
1207 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1208 // happen by looking at the visited phi nodes and making sure they cannot
1209 // reach the value.
1210 if (isValueEqualInPotentialCycles(V1, V2))
1211 return MustAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001212
Duncan Sands19d0b472010-02-16 11:11:14 +00001213 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
Evan Chengf1f3dd32009-10-13 18:42:04 +00001214 return NoAlias; // Scalars cannot alias each other
1215
1216 // Figure out what objects these things are pointing to if we can.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001217 const Value *O1 = GetUnderlyingObject(V1, DL);
1218 const Value *O2 = GetUnderlyingObject(V2, DL);
Evan Chengf1f3dd32009-10-13 18:42:04 +00001219
Dan Gohmanccb45842009-11-09 19:29:11 +00001220 // Null values in the default address space don't point to any object, so they
1221 // don't alias any other pointer.
1222 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1223 if (CPN->getType()->getAddressSpace() == 0)
1224 return NoAlias;
1225 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1226 if (CPN->getType()->getAddressSpace() == 0)
1227 return NoAlias;
1228
Evan Chengf1f3dd32009-10-13 18:42:04 +00001229 if (O1 != O2) {
1230 // If V1/V2 point to two different objects we know that we have no alias.
Dan Gohman00ef9322010-07-07 14:27:09 +00001231 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001232 return NoAlias;
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001233
1234 // Constant pointers can't alias with non-const isIdentifiedObject objects.
Dan Gohman00ef9322010-07-07 14:27:09 +00001235 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1236 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
Nick Lewyckyc53e2ec2009-11-14 06:15:14 +00001237 return NoAlias;
1238
Michael Kupersteinf3e663a2013-05-28 08:17:48 +00001239 // Function arguments can't alias with things that are known to be
1240 // unambigously identified at the function level.
1241 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1242 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
Dan Gohman84f90a32010-07-01 20:08:40 +00001243 return NoAlias;
Evan Chengf1f3dd32009-10-13 18:42:04 +00001244
1245 // Most objects can't alias null.
Dan Gohman00ef9322010-07-07 14:27:09 +00001246 if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1247 (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001248 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001249
Dan Gohman5b0a8a82010-07-07 14:30:04 +00001250 // If one pointer is the result of a call/invoke or load and the other is a
1251 // non-escaping local object within the same function, then we know the
1252 // object couldn't escape to a point where the call could return it.
1253 //
1254 // Note that if the pointers are in different functions, there are a
1255 // variety of complications. A call with a nocapture argument may still
1256 // temporary store the nocapture argument's value in a temporary memory
1257 // location if that memory location doesn't escape. Or it may pass a
1258 // nocapture value to other functions as long as they don't capture it.
1259 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1260 return NoAlias;
1261 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1262 return NoAlias;
1263 }
1264
Evan Chengf1f3dd32009-10-13 18:42:04 +00001265 // If the size of one access is larger than the entire object on the other
1266 // side, then we know such behavior is undefined and can assume no alias.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001267 if (DL)
1268 if ((V1Size != UnknownSize && isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1269 (V2Size != UnknownSize && isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
Evan Chengf1f3dd32009-10-13 18:42:04 +00001270 return NoAlias;
Jakub Staszak07f383f2013-08-24 14:16:00 +00001271
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001272 // Check the cache before climbing up use-def chains. This also terminates
1273 // otherwise infinitely recursive queries.
1274 LocPair Locs(Location(V1, V1Size, V1TBAAInfo),
1275 Location(V2, V2Size, V2TBAAInfo));
1276 if (V1 > V2)
1277 std::swap(Locs.first, Locs.second);
1278 std::pair<AliasCacheTy::iterator, bool> Pair =
1279 AliasCache.insert(std::make_pair(Locs, MayAlias));
1280 if (!Pair.second)
1281 return Pair.first->second;
1282
Chris Lattner89288992009-11-26 02:13:03 +00001283 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1284 // GEP can't simplify, we don't even look at the PHI cases.
Chris Lattnerb2647b92009-10-17 23:48:54 +00001285 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001286 std::swap(V1, V2);
1287 std::swap(V1Size, V2Size);
Chris Lattner5341c962009-11-26 02:14:59 +00001288 std::swap(O1, O2);
Duncan Sands71c20702012-11-04 09:02:45 +00001289 std::swap(V1TBAAInfo, V2TBAAInfo);
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001290 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001291 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
Arnold Schwaighofer76dca582012-09-06 14:31:51 +00001292 AliasResult Result = aliasGEP(GV1, V1Size, V1TBAAInfo, V2, V2Size, V2TBAAInfo, O1, O2);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001293 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001294 }
Evan Chengc10e88d2009-10-13 22:02:20 +00001295
1296 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1297 std::swap(V1, V2);
1298 std::swap(V1Size, V2Size);
Duncan Sands71c20702012-11-04 09:02:45 +00001299 std::swap(V1TBAAInfo, V2TBAAInfo);
Evan Chengc10e88d2009-10-13 22:02:20 +00001300 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001301 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
Dan Gohmanf3702452010-10-18 18:45:11 +00001302 AliasResult Result = aliasPHI(PN, V1Size, V1TBAAInfo,
1303 V2, V2Size, V2TBAAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001304 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001305 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001306
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001307 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1308 std::swap(V1, V2);
1309 std::swap(V1Size, V2Size);
Duncan Sands71c20702012-11-04 09:02:45 +00001310 std::swap(V1TBAAInfo, V2TBAAInfo);
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001311 }
Dan Gohman02538ac2010-10-18 18:04:47 +00001312 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
Dan Gohmanf3702452010-10-18 18:45:11 +00001313 AliasResult Result = aliasSelect(S1, V1Size, V1TBAAInfo,
1314 V2, V2Size, V2TBAAInfo);
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001315 if (Result != MayAlias) return AliasCache[Locs] = Result;
Dan Gohman02538ac2010-10-18 18:04:47 +00001316 }
Dan Gohman3b7ba5f2009-10-26 21:55:43 +00001317
Dan Gohman44da55b2011-01-18 21:16:06 +00001318 // If both pointers are pointing into the same object and one of them
1319 // accesses is accessing the entire object, then the accesses must
1320 // overlap in some way.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001321 if (DL && O1 == O2)
1322 if ((V1Size != UnknownSize && isObjectSize(O1, V1Size, *DL, *TLI)) ||
1323 (V2Size != UnknownSize && isObjectSize(O2, V2Size, *DL, *TLI)))
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001324 return AliasCache[Locs] = PartialAlias;
Dan Gohman44da55b2011-01-18 21:16:06 +00001325
Dan Gohmanfb02cec2011-06-04 00:31:50 +00001326 AliasResult Result =
1327 AliasAnalysis::alias(Location(V1, V1Size, V1TBAAInfo),
1328 Location(V2, V2Size, V2TBAAInfo));
1329 return AliasCache[Locs] = Result;
Chris Lattnerd6a2a992003-02-26 19:41:54 +00001330}
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001331
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001332bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1333 const Value *V2) {
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001334 if (V != V2)
1335 return false;
1336
1337 const Instruction *Inst = dyn_cast<Instruction>(V);
1338 if (!Inst)
1339 return true;
1340
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001341 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1342 return false;
1343
1344 // Use dominance or loop info if available.
Chandler Carruth73523022014-01-13 13:07:17 +00001345 DominatorTreeWrapperPass *DTWP =
1346 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1347 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : 0;
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001348 LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>();
1349
1350 // Make sure that the visited phis cannot reach the Value. This ensures that
1351 // the Values cannot come from different iterations of a potential cycle the
1352 // phi nodes could be involved in.
1353 for (SmallPtrSet<const BasicBlock *, 8>::iterator PI = VisitedPhiBBs.begin(),
1354 PE = VisitedPhiBBs.end();
1355 PI != PE; ++PI)
1356 if (isPotentiallyReachable((*PI)->begin(), Inst, DT, LI))
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001357 return false;
1358
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001359 return true;
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001360}
1361
1362/// GetIndexDifference - Dest and Src are the variable indices from two
1363/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1364/// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
1365/// difference between the two pointers.
1366void BasicAliasAnalysis::GetIndexDifference(
1367 SmallVectorImpl<VariableGEPIndex> &Dest,
1368 const SmallVectorImpl<VariableGEPIndex> &Src) {
1369 if (Src.empty())
1370 return;
1371
1372 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1373 const Value *V = Src[i].V;
1374 ExtensionKind Extension = Src[i].Extension;
1375 int64_t Scale = Src[i].Scale;
1376
1377 // Find V in Dest. This is N^2, but pointer indices almost never have more
1378 // than a few variable indexes.
1379 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
Arnold Schwaighofer833a82e2014-01-03 05:47:03 +00001380 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1381 Dest[j].Extension != Extension)
Arnold Schwaighofer0d10a9d2014-01-02 03:31:36 +00001382 continue;
1383
1384 // If we found it, subtract off Scale V's from the entry in Dest. If it
1385 // goes to zero, remove the entry.
1386 if (Dest[j].Scale != Scale)
1387 Dest[j].Scale -= Scale;
1388 else
1389 Dest.erase(Dest.begin() + j);
1390 Scale = 0;
1391 break;
1392 }
1393
1394 // If we didn't consume this entry, add it to the end of the Dest list.
1395 if (Scale) {
1396 VariableGEPIndex Entry = { V, Extension, -Scale };
1397 Dest.push_back(Entry);
1398 }
1399 }
1400}