blob: c82c802fcccfe65bbdfc7a75122ed0a82eb40201 [file] [log] [blame]
Chris Lattner9d7c9ea2003-11-25 20:11:47 +00001//===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukman2b37d7c2005-04-21 21:13:18 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerd501c132003-02-26 19:41:54 +00009//
10// This file defines the default implementation of the Alias Analysis interface
11// that simply implements a few identities (two different globals cannot alias,
12// etc), but otherwise does no analysis.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Analysis/AliasAnalysis.h"
Duncan Sands8556d2a2009-01-18 12:19:30 +000017#include "llvm/Analysis/CaptureTracking.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000018#include "llvm/Analysis/MemoryBuiltins.h"
Jeff Cohen534927d2005-01-08 22:01:16 +000019#include "llvm/Analysis/Passes.h"
Chris Lattner4244bb52004-03-15 03:36:49 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner23e2a5b2009-11-26 02:14:59 +000023#include "llvm/GlobalAlias.h"
Chris Lattner4244bb52004-03-15 03:36:49 +000024#include "llvm/GlobalVariable.h"
Alkis Evlogimenoseb62bc72004-07-29 12:17:34 +000025#include "llvm/Instructions.h"
Owen Anderson9b636cb2008-02-17 21:29:08 +000026#include "llvm/IntrinsicInst.h"
Dan Gohman3a7a68c2009-07-17 22:25:10 +000027#include "llvm/Operator.h"
Chris Lattner4244bb52004-03-15 03:36:49 +000028#include "llvm/Pass.h"
Chris Lattnerd501c132003-02-26 19:41:54 +000029#include "llvm/Target/TargetData.h"
Evan Cheng50a59142009-10-13 22:02:20 +000030#include "llvm/ADT/SmallSet.h"
Chris Lattnera77600e2007-02-10 22:15:31 +000031#include "llvm/ADT/SmallVector.h"
Owen Anderson718cb662007-09-07 04:06:50 +000032#include "llvm/ADT/STLExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner90aa8392006-10-04 21:52:35 +000034#include "llvm/Support/GetElementPtrTypeIterator.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Chris Lattnerec4e8082003-11-25 18:33:40 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Chris Lattnerdefa1c82008-06-16 06:30:22 +000038//===----------------------------------------------------------------------===//
39// Useful predicates
40//===----------------------------------------------------------------------===//
Devang Patel794fd752007-05-01 21:15:47 +000041
Chris Lattner539c9b92009-11-26 02:11:08 +000042static const Value *GetGEPOperands(const GEPOperator *V,
Chris Lattnerb957bda2008-12-10 01:04:47 +000043 SmallVector<Value*, 16> &GEPOps) {
Chris Lattner4a830882003-12-11 23:20:16 +000044 assert(GEPOps.empty() && "Expect empty list to populate!");
Chris Lattner539c9b92009-11-26 02:11:08 +000045 GEPOps.insert(GEPOps.end(), V->op_begin()+1, V->op_end());
Chris Lattner4a830882003-12-11 23:20:16 +000046
Chris Lattner539c9b92009-11-26 02:11:08 +000047 // Accumulate all of the chained indexes into the operand array.
48 Value *BasePtr = V->getOperand(0);
49 while (1) {
50 V = dyn_cast<GEPOperator>(BasePtr);
51 if (V == 0) return BasePtr;
52
53 // Don't handle folding arbitrary pointer offsets yet.
54 if (!isa<Constant>(GEPOps[0]) || !cast<Constant>(GEPOps[0])->isNullValue())
55 return BasePtr;
56
Chris Lattner4a830882003-12-11 23:20:16 +000057 GEPOps.erase(GEPOps.begin()); // Drop the zero index
Chris Lattner539c9b92009-11-26 02:11:08 +000058 GEPOps.insert(GEPOps.begin(), V->op_begin()+1, V->op_end());
Chris Lattner4a830882003-12-11 23:20:16 +000059 }
Chris Lattner4a830882003-12-11 23:20:16 +000060}
61
Chris Lattnera4139602008-06-16 06:10:11 +000062/// isKnownNonNull - Return true if we know that the specified value is never
63/// null.
64static bool isKnownNonNull(const Value *V) {
65 // Alloca never returns null, malloc might.
66 if (isa<AllocaInst>(V)) return true;
67
68 // A byval argument is never null.
69 if (const Argument *A = dyn_cast<Argument>(V))
70 return A->hasByValAttr();
71
72 // Global values are not null unless extern weak.
73 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
74 return !GV->hasExternalWeakLinkage();
75 return false;
76}
77
Chris Lattner845f0d22008-06-16 06:19:11 +000078/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
79/// object that never escapes from the function.
80static bool isNonEscapingLocalObject(const Value *V) {
Chris Lattnere7275792008-06-16 06:28:01 +000081 // If this is a local allocation, check to see if it escapes.
Victor Hernandez7b929da2009-10-23 21:09:37 +000082 if (isa<AllocaInst>(V) || isNoAliasCall(V))
Dan Gohmanf94b5ed2009-11-19 21:57:48 +000083 // Set StoreCaptures to True so that we can assume in our callers that the
84 // pointer is not the result of a load instruction. Currently
85 // PointerMayBeCaptured doesn't have any special analysis for the
86 // StoreCaptures=false case; if it did, our callers could be refined to be
87 // more precise.
88 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Duncan Sands91c9c3102009-01-05 21:19:53 +000089
Chris Lattnere7275792008-06-16 06:28:01 +000090 // If this is an argument that corresponds to a byval or noalias argument,
Duncan Sands91c9c3102009-01-05 21:19:53 +000091 // then it has not escaped before entering the function. Check if it escapes
92 // inside the function.
Chris Lattnere7275792008-06-16 06:28:01 +000093 if (const Argument *A = dyn_cast<Argument>(V))
Duncan Sands91c9c3102009-01-05 21:19:53 +000094 if (A->hasByValAttr() || A->hasNoAliasAttr()) {
95 // Don't bother analyzing arguments already known not to escape.
96 if (A->hasNoCaptureAttr())
97 return true;
Dan Gohmanf94b5ed2009-11-19 21:57:48 +000098 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Duncan Sands91c9c3102009-01-05 21:19:53 +000099 }
Chris Lattner845f0d22008-06-16 06:19:11 +0000100 return false;
101}
102
103
Chris Lattnera4139602008-06-16 06:10:11 +0000104/// isObjectSmallerThan - Return true if we can prove that the object specified
105/// by V is smaller than Size.
106static bool isObjectSmallerThan(const Value *V, unsigned Size,
Chris Lattner7b550cc2009-11-06 04:27:31 +0000107 const TargetData &TD) {
Chris Lattner295d4e92008-12-08 06:28:54 +0000108 const Type *AccessTy;
109 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
Chris Lattnera4139602008-06-16 06:10:11 +0000110 AccessTy = GV->getType()->getElementType();
Victor Hernandez7b929da2009-10-23 21:09:37 +0000111 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
Chris Lattnera4139602008-06-16 06:10:11 +0000112 if (!AI->isArrayAllocation())
113 AccessTy = AI->getType()->getElementType();
Chris Lattner295d4e92008-12-08 06:28:54 +0000114 else
115 return false;
Victor Hernandez46e83122009-09-18 21:34:51 +0000116 } else if (const CallInst* CI = extractMallocCall(V)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +0000117 if (!isArrayMalloc(V, &TD))
Victor Hernandez46e83122009-09-18 21:34:51 +0000118 // The size is the argument to the malloc call.
119 if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getOperand(1)))
120 return (C->getZExtValue() < Size);
121 return false;
Chris Lattner295d4e92008-12-08 06:28:54 +0000122 } else if (const Argument *A = dyn_cast<Argument>(V)) {
Chris Lattnera4139602008-06-16 06:10:11 +0000123 if (A->hasByValAttr())
124 AccessTy = cast<PointerType>(A->getType())->getElementType();
Chris Lattner295d4e92008-12-08 06:28:54 +0000125 else
126 return false;
127 } else {
128 return false;
129 }
Chris Lattnera4139602008-06-16 06:10:11 +0000130
Chris Lattner295d4e92008-12-08 06:28:54 +0000131 if (AccessTy->isSized())
Duncan Sands777d2302009-05-09 07:06:46 +0000132 return TD.getTypeAllocSize(AccessTy) < Size;
Chris Lattnera4139602008-06-16 06:10:11 +0000133 return false;
134}
135
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000136//===----------------------------------------------------------------------===//
137// NoAA Pass
138//===----------------------------------------------------------------------===//
139
140namespace {
141 /// NoAA - This class implements the -no-aa pass, which always returns "I
142 /// don't know" for alias queries. NoAA is unlike other alias analysis
143 /// implementations, in that it does not chain to a previous analysis. As
144 /// such it doesn't follow many of the rules that other alias analyses must.
145 ///
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000146 struct NoAA : public ImmutablePass, public AliasAnalysis {
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000147 static char ID; // Class identification, replacement for typeinfo
Dan Gohmanae73dc12008-09-04 17:05:41 +0000148 NoAA() : ImmutablePass(&ID) {}
149 explicit NoAA(void *PID) : ImmutablePass(PID) { }
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000150
151 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000152 }
153
154 virtual void initializePass() {
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000155 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000156 }
157
158 virtual AliasResult alias(const Value *V1, unsigned V1Size,
159 const Value *V2, unsigned V2Size) {
160 return MayAlias;
161 }
162
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000163 virtual void getArgumentAccesses(Function *F, CallSite CS,
164 std::vector<PointerAccessInfo> &Info) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000165 llvm_unreachable("This method may not be called on this function!");
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000166 }
167
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000168 virtual bool pointsToConstantMemory(const Value *P) { return false; }
169 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
170 return ModRef;
171 }
172 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
173 return ModRef;
174 }
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000175
176 virtual void deleteValue(Value *V) {}
177 virtual void copyValue(Value *From, Value *To) {}
178 };
179} // End of anonymous namespace
180
181// Register this pass...
182char NoAA::ID = 0;
183static RegisterPass<NoAA>
184U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
185
186// Declare that we implement the AliasAnalysis interface
187static RegisterAnalysisGroup<AliasAnalysis> V(U);
188
189ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
190
191//===----------------------------------------------------------------------===//
192// BasicAA Pass
193//===----------------------------------------------------------------------===//
194
195namespace {
196 /// BasicAliasAnalysis - This is the default alias analysis implementation.
197 /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
198 /// derives from the NoAA class.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000199 struct BasicAliasAnalysis : public NoAA {
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000200 static char ID; // Class identification, replacement for typeinfo
Dan Gohmanae73dc12008-09-04 17:05:41 +0000201 BasicAliasAnalysis() : NoAA(&ID) {}
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000202 AliasResult alias(const Value *V1, unsigned V1Size,
Evan Cheng50a59142009-10-13 22:02:20 +0000203 const Value *V2, unsigned V2Size) {
Evan Chengf0429fd2009-10-14 06:46:26 +0000204 assert(VisitedPHIs.empty() && "VisitedPHIs must be cleared after use!");
205 AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000206 VisitedPHIs.clear();
Evan Chengf0429fd2009-10-14 06:46:26 +0000207 return Alias;
Evan Cheng50a59142009-10-13 22:02:20 +0000208 }
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000209
210 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
Chris Lattner20d6f092008-12-09 21:19:42 +0000211 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Owen Andersone7942202009-02-05 23:36:27 +0000212
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000213 /// pointsToConstantMemory - Chase pointers until we find a (constant
214 /// global) or not.
215 bool pointsToConstantMemory(const Value *P);
216
217 private:
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000218 // VisitedPHIs - Track PHI nodes visited by a aliasCheck() call.
Dan Gohman6665b0e2009-10-26 21:55:43 +0000219 SmallPtrSet<const Value*, 16> VisitedPHIs;
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000220
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000221 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
222 // instruction against another.
Chris Lattner539c9b92009-11-26 02:11:08 +0000223 AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000224 const Value *V2, unsigned V2Size,
225 const Value *UnderlyingV1, const Value *UnderlyingV2);
Evan Cheng50a59142009-10-13 22:02:20 +0000226
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000227 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
228 // instruction against another.
Evan Chengd83c2ca2009-10-14 05:22:03 +0000229 AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000230 const Value *V2, unsigned V2Size);
Evan Cheng50a59142009-10-13 22:02:20 +0000231
Dan Gohman6665b0e2009-10-26 21:55:43 +0000232 /// aliasSelect - Disambiguate a Select instruction against another value.
233 AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
234 const Value *V2, unsigned V2Size);
235
Evan Cheng50a59142009-10-13 22:02:20 +0000236 AliasResult aliasCheck(const Value *V1, unsigned V1Size,
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000237 const Value *V2, unsigned V2Size);
Evan Cheng094f04b2009-10-13 18:42:04 +0000238
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000239 // CheckGEPInstructions - Check two GEP instructions with known
240 // must-aliasing base pointers. This checks to see if the index expressions
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000241 // preclude the pointers from aliasing.
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000242 AliasResult
243 CheckGEPInstructions(const Type* BasePtr1Ty,
244 Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size,
245 const Type *BasePtr2Ty,
246 Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size);
247 };
248} // End of anonymous namespace
249
250// Register this pass...
251char BasicAliasAnalysis::ID = 0;
252static RegisterPass<BasicAliasAnalysis>
253X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
254
255// Declare that we implement the AliasAnalysis interface
256static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
257
258ImmutablePass *llvm::createBasicAliasAnalysisPass() {
259 return new BasicAliasAnalysis();
260}
261
262
263/// pointsToConstantMemory - Chase pointers until we find a (constant
264/// global) or not.
265bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
266 if (const GlobalVariable *GV =
Duncan Sands5d0392c2008-10-01 15:25:41 +0000267 dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
Chris Lattnerb27db372009-11-23 17:07:35 +0000268 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
269 // global to be marked constant in some modules and non-constant in others.
270 // GV may even be a declaration, not a definition.
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000271 return GV->isConstant();
272 return false;
273}
274
Owen Andersone7942202009-02-05 23:36:27 +0000275
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000276/// getModRefInfo - Check to see if the specified callsite can clobber the
277/// specified memory object. Since we only look at local properties of this
278/// function, we really can't say much about this query. We do, however, use
279/// simple "address taken" analysis on local objects.
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000280AliasAnalysis::ModRefResult
281BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
Chris Lattner92e803c2009-11-22 16:05:05 +0000282 const Value *Object = P->getUnderlyingObject();
283
284 // If this is a tail call and P points to a stack location, we know that
285 // the tail call cannot access or modify the local stack.
286 // We cannot exclude byval arguments here; these belong to the caller of
287 // the current function not to the current function, and a tail callee
288 // may reference them.
289 if (isa<AllocaInst>(Object))
290 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
291 if (CI->isTailCall())
292 return NoModRef;
293
294 // If the pointer is to a locally allocated object that does not escape,
Chris Lattnerb34b82e2009-11-23 16:44:43 +0000295 // then the call can not mod/ref the pointer unless the call takes the pointer
296 // as an argument, and itself doesn't capture it.
Chris Lattner403ac2e2009-11-23 16:46:41 +0000297 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
298 isNonEscapingLocalObject(Object)) {
Chris Lattnerb34b82e2009-11-23 16:44:43 +0000299 bool PassedAsArg = false;
300 unsigned ArgNo = 0;
Chris Lattner92e803c2009-11-22 16:05:05 +0000301 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
Chris Lattnerb34b82e2009-11-23 16:44:43 +0000302 CI != CE; ++CI, ++ArgNo) {
303 // Only look at the no-capture pointer arguments.
304 if (!isa<PointerType>((*CI)->getType()) ||
305 !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
306 continue;
307
308 // If this is a no-capture pointer argument, see if we can tell that it
309 // is impossible to alias the pointer we're checking. If not, we have to
310 // assume that the call could touch the pointer, even though it doesn't
311 // escape.
Chris Lattner403ac2e2009-11-23 16:46:41 +0000312 if (!isNoAlias(cast<Value>(CI), ~0U, P, ~0U)) {
Chris Lattnerb34b82e2009-11-23 16:44:43 +0000313 PassedAsArg = true;
314 break;
315 }
316 }
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000317
Chris Lattnerb34b82e2009-11-23 16:44:43 +0000318 if (!PassedAsArg)
Chris Lattner92e803c2009-11-22 16:05:05 +0000319 return NoModRef;
320 }
321
322 // Finally, handle specific knowledge of intrinsics.
323 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
324 if (II == 0)
325 return AliasAnalysis::getModRefInfo(CS, P, Size);
326
327 switch (II->getIntrinsicID()) {
328 default: break;
329 case Intrinsic::memcpy:
330 case Intrinsic::memmove: {
331 unsigned Len = ~0U;
332 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3)))
333 Len = LenCI->getZExtValue();
334 Value *Dest = II->getOperand(1);
335 Value *Src = II->getOperand(2);
Chris Lattner403ac2e2009-11-23 16:46:41 +0000336 if (isNoAlias(Dest, Len, P, Size)) {
337 if (isNoAlias(Src, Len, P, Size))
Chris Lattner92e803c2009-11-22 16:05:05 +0000338 return NoModRef;
339 return Ref;
340 }
341 break;
342 }
343 case Intrinsic::memset:
Chris Lattner403ac2e2009-11-23 16:46:41 +0000344 // Since memset is 'accesses arguments' only, the AliasAnalysis base class
345 // will handle it for the variable length case.
Chris Lattner92e803c2009-11-22 16:05:05 +0000346 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3))) {
347 unsigned Len = LenCI->getZExtValue();
348 Value *Dest = II->getOperand(1);
Chris Lattner403ac2e2009-11-23 16:46:41 +0000349 if (isNoAlias(Dest, Len, P, Size))
Chris Lattner25df20f2008-06-16 06:38:26 +0000350 return NoModRef;
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000351 }
Chris Lattner92e803c2009-11-22 16:05:05 +0000352 break;
353 case Intrinsic::atomic_cmp_swap:
354 case Intrinsic::atomic_swap:
355 case Intrinsic::atomic_load_add:
356 case Intrinsic::atomic_load_sub:
357 case Intrinsic::atomic_load_and:
358 case Intrinsic::atomic_load_nand:
359 case Intrinsic::atomic_load_or:
360 case Intrinsic::atomic_load_xor:
361 case Intrinsic::atomic_load_max:
362 case Intrinsic::atomic_load_min:
363 case Intrinsic::atomic_load_umax:
364 case Intrinsic::atomic_load_umin:
365 if (TD) {
366 Value *Op1 = II->getOperand(1);
367 unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
Chris Lattner403ac2e2009-11-23 16:46:41 +0000368 if (isNoAlias(Op1, Op1Size, P, Size))
Chris Lattner92e803c2009-11-22 16:05:05 +0000369 return NoModRef;
Nick Lewycky5c9be672009-10-13 07:48:38 +0000370 }
Chris Lattner92e803c2009-11-22 16:05:05 +0000371 break;
372 case Intrinsic::lifetime_start:
373 case Intrinsic::lifetime_end:
374 case Intrinsic::invariant_start: {
375 unsigned PtrSize = cast<ConstantInt>(II->getOperand(1))->getZExtValue();
Chris Lattner403ac2e2009-11-23 16:46:41 +0000376 if (isNoAlias(II->getOperand(2), PtrSize, P, Size))
Chris Lattner92e803c2009-11-22 16:05:05 +0000377 return NoModRef;
378 break;
379 }
380 case Intrinsic::invariant_end: {
381 unsigned PtrSize = cast<ConstantInt>(II->getOperand(2))->getZExtValue();
Chris Lattner403ac2e2009-11-23 16:46:41 +0000382 if (isNoAlias(II->getOperand(3), PtrSize, P, Size))
Chris Lattner92e803c2009-11-22 16:05:05 +0000383 return NoModRef;
384 break;
385 }
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000386 }
387
388 // The AliasAnalysis base class has some smarts, lets use them.
389 return AliasAnalysis::getModRefInfo(CS, P, Size);
390}
391
392
Chris Lattner20d6f092008-12-09 21:19:42 +0000393AliasAnalysis::ModRefResult
394BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
395 // If CS1 or CS2 are readnone, they don't interact.
396 ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
397 if (CS1B == DoesNotAccessMemory) return NoModRef;
398
399 ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
400 if (CS2B == DoesNotAccessMemory) return NoModRef;
401
402 // If they both only read from memory, just return ref.
403 if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
404 return Ref;
405
406 // Otherwise, fall back to NoAA (mod+ref).
407 return NoAA::getModRefInfo(CS1, CS2);
408}
409
Chris Lattner4e91ee72009-11-26 02:13:03 +0000410/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
411/// into a base pointer with a constant offset and a number of scaled symbolic
412/// offsets.
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000413///
414/// When TargetData is around, this function is capable of analyzing everything
415/// that Value::getUnderlyingObject() can look through. When not, it just looks
416/// through pointer casts.
417///
418/// FIXME: Move this out to ValueTracking.cpp
419///
Chris Lattner4e91ee72009-11-26 02:13:03 +0000420static const Value *DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
421 SmallVectorImpl<std::pair<const Value*, uint64_t> > &VarIndices,
422 const TargetData *TD) {
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000423 // FIXME: Should limit depth like getUnderlyingObject?
Chris Lattner4e91ee72009-11-26 02:13:03 +0000424 BaseOffs = 0;
425 while (1) {
426 // See if this is a bitcast or GEP.
427 const Operator *Op = dyn_cast<Operator>(V);
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000428 if (Op == 0) {
429 // The only non-operator case we can handle are GlobalAliases.
430 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
431 if (!GA->mayBeOverridden()) {
432 V = GA->getAliasee();
433 continue;
434 }
435 }
436 return V;
437 }
Chris Lattner4e91ee72009-11-26 02:13:03 +0000438
439 if (Op->getOpcode() == Instruction::BitCast) {
440 V = Op->getOperand(0);
441 continue;
442 }
443
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000444 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
445 if (GEPOp == 0)
Chris Lattner4e91ee72009-11-26 02:13:03 +0000446 return V;
447
448 // Don't attempt to analyze GEPs over unsized objects.
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000449 if (!cast<PointerType>(GEPOp->getOperand(0)->getType())
Chris Lattner4e91ee72009-11-26 02:13:03 +0000450 ->getElementType()->isSized())
451 return V;
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000452
453 // If we are lacking TargetData information, we can't compute the offets of
454 // elements computed by GEPs. However, we can handle bitcast equivalent
455 // GEPs.
456 if (!TD) {
457 if (!GEPOp->hasAllZeroIndices())
458 return V;
459 V = GEPOp->getOperand(0);
460 continue;
461 }
Chris Lattner4e91ee72009-11-26 02:13:03 +0000462
463 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000464 gep_type_iterator GTI = gep_type_begin(GEPOp);
465 for (User::const_op_iterator I = next(GEPOp->op_begin()),
466 E = GEPOp->op_end(); I != E; ++I) {
Chris Lattner4e91ee72009-11-26 02:13:03 +0000467 Value *Index = *I;
468 // Compute the (potentially symbolic) offset in bytes for this index.
469 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
470 // For a struct, add the member offset.
471 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
472 if (FieldNo == 0) continue;
Chris Lattner4e91ee72009-11-26 02:13:03 +0000473
474 BaseOffs += TD->getStructLayout(STy)->getElementOffset(FieldNo);
475 continue;
476 }
477
478 // For an array/pointer, add the element offset, explicitly scaled.
479 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
480 if (CIdx->isZero()) continue;
Chris Lattner4e91ee72009-11-26 02:13:03 +0000481 BaseOffs += TD->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
482 continue;
483 }
484
Chris Lattner4e91ee72009-11-26 02:13:03 +0000485 // TODO: Could handle linear expressions here like A[X+1], also A[X*4|1].
486 uint64_t Scale = TD->getTypeAllocSize(*GTI);
487
488 // If we already had an occurrance of this index variable, merge this
489 // scale into it. For example, we want to handle:
490 // A[x][x] -> x*16 + x*4 -> x*20
491 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
492 if (VarIndices[i].first == Index) {
493 Scale += VarIndices[i].second;
494 VarIndices.erase(VarIndices.begin()+i);
495 break;
496 }
497 }
498
499 // Make sure that we have a scale that makes sense for this target's
500 // pointer size.
501 if (unsigned ShiftBits = 64-TD->getPointerSizeInBits()) {
502 Scale <<= ShiftBits;
503 Scale >>= ShiftBits;
504 }
505
506 if (Scale)
507 VarIndices.push_back(std::make_pair(Index, Scale));
508 }
509
510 // Analyze the base pointer next.
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000511 V = GEPOp->getOperand(0);
Chris Lattner4e91ee72009-11-26 02:13:03 +0000512 }
Chris Lattner4e91ee72009-11-26 02:13:03 +0000513}
514
515
Chris Lattner539c9b92009-11-26 02:11:08 +0000516/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
517/// against another pointer. We know that V1 is a GEP, but we don't know
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000518/// anything about V2. UnderlyingV1 is GEP1->getUnderlyingObject(),
519/// UnderlyingV2 is the same for V2.
Chris Lattner539c9b92009-11-26 02:11:08 +0000520///
Chris Lattnerd501c132003-02-26 19:41:54 +0000521AliasAnalysis::AliasResult
Chris Lattner539c9b92009-11-26 02:11:08 +0000522BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000523 const Value *V2, unsigned V2Size,
524 const Value *UnderlyingV1,
525 const Value *UnderlyingV2) {
Chris Lattnerb307c882003-12-11 22:44:13 +0000526 // If we have two gep instructions with must-alias'ing base pointers, figure
527 // out if the indexes to the GEP tell us anything about the derived pointer.
528 // Note that we also handle chains of getelementptr instructions as well as
529 // constant expression getelementptrs here.
Chris Lattnerd501c132003-02-26 19:41:54 +0000530 //
Chris Lattner539c9b92009-11-26 02:11:08 +0000531 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
Chris Lattnerb957bda2008-12-10 01:04:47 +0000532 // If V1 and V2 are identical GEPs, just recurse down on both of them.
533 // This allows us to analyze things like:
534 // P = gep A, 0, i, 1
535 // Q = gep B, 0, i, 1
536 // by just analyzing A and B. This is even safe for variable indices.
537 if (GEP1->getType() == GEP2->getType() &&
538 GEP1->getNumOperands() == GEP2->getNumOperands() &&
539 GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() &&
540 // All operands are the same, ignoring the base.
541 std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
Evan Cheng50a59142009-10-13 22:02:20 +0000542 return aliasCheck(GEP1->getOperand(0), V1Size,
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000543 GEP2->getOperand(0), V2Size);
Chris Lattnerb957bda2008-12-10 01:04:47 +0000544
Chris Lattnerb307c882003-12-11 22:44:13 +0000545 // Drill down into the first non-gep value, to test for must-aliasing of
546 // the base pointers.
Chris Lattner391d23b2009-10-17 23:48:54 +0000547 while (isa<GEPOperator>(GEP1->getOperand(0)) &&
Chris Lattnerb957bda2008-12-10 01:04:47 +0000548 GEP1->getOperand(1) ==
Owen Andersona7235ea2009-07-31 20:28:14 +0000549 Constant::getNullValue(GEP1->getOperand(1)->getType()))
Chris Lattner539c9b92009-11-26 02:11:08 +0000550 GEP1 = cast<GEPOperator>(GEP1->getOperand(0));
Chris Lattnerb957bda2008-12-10 01:04:47 +0000551 const Value *BasePtr1 = GEP1->getOperand(0);
Wojciech Matyjewicz4ba8cfc2007-12-13 16:22:58 +0000552
Chris Lattner391d23b2009-10-17 23:48:54 +0000553 while (isa<GEPOperator>(GEP2->getOperand(0)) &&
Chris Lattnerb957bda2008-12-10 01:04:47 +0000554 GEP2->getOperand(1) ==
Owen Andersona7235ea2009-07-31 20:28:14 +0000555 Constant::getNullValue(GEP2->getOperand(1)->getType()))
Chris Lattner539c9b92009-11-26 02:11:08 +0000556 GEP2 = cast<GEPOperator>(GEP2->getOperand(0));
Chris Lattnerb957bda2008-12-10 01:04:47 +0000557 const Value *BasePtr2 = GEP2->getOperand(0);
Chris Lattnerb307c882003-12-11 22:44:13 +0000558
559 // Do the base pointers alias?
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000560 AliasResult BaseAlias = aliasCheck(BasePtr1, ~0U, BasePtr2, ~0U);
Chris Lattnerb307c882003-12-11 22:44:13 +0000561 if (BaseAlias == NoAlias) return NoAlias;
562 if (BaseAlias == MustAlias) {
563 // If the base pointers alias each other exactly, check to see if we can
564 // figure out anything about the resultant pointers, to try to prove
565 // non-aliasing.
566
567 // Collect all of the chained GEP operands together into one simple place
Chris Lattnera77600e2007-02-10 22:15:31 +0000568 SmallVector<Value*, 16> GEP1Ops, GEP2Ops;
Chris Lattner539c9b92009-11-26 02:11:08 +0000569 BasePtr1 = GetGEPOperands(GEP1, GEP1Ops);
570 BasePtr2 = GetGEPOperands(GEP2, GEP2Ops);
Chris Lattnerb307c882003-12-11 22:44:13 +0000571
Chris Lattner730b1ad2004-07-29 07:56:39 +0000572 // If GetGEPOperands were able to fold to the same must-aliased pointer,
573 // do the comparison.
574 if (BasePtr1 == BasePtr2) {
575 AliasResult GAlias =
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +0000576 CheckGEPInstructions(BasePtr1->getType(),
577 &GEP1Ops[0], GEP1Ops.size(), V1Size,
578 BasePtr2->getType(),
579 &GEP2Ops[0], GEP2Ops.size(), V2Size);
Chris Lattner730b1ad2004-07-29 07:56:39 +0000580 if (GAlias != MayAlias)
581 return GAlias;
582 }
Chris Lattnerb307c882003-12-11 22:44:13 +0000583 }
584 }
Chris Lattnerd501c132003-02-26 19:41:54 +0000585
586 // Check to see if these two pointers are related by a getelementptr
587 // instruction. If one pointer is a GEP with a non-zero index of the other
588 // pointer, we know they cannot alias.
589 //
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000590 // FIXME: The check below only looks at the size of one of the pointers, not
591 // both, this may cause us to miss things.
Evan Cheng094f04b2009-10-13 18:42:04 +0000592 if (V1Size == ~0U || V2Size == ~0U)
593 return MayAlias;
594
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000595 AliasResult R = aliasCheck(UnderlyingV1, ~0U, V2, V2Size);
Evan Cheng681a33e2009-10-14 06:41:49 +0000596 if (R != MustAlias)
597 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
598 // If V2 is known not to alias GEP base pointer, then the two values
599 // cannot alias per GEP semantics: "A pointer value formed from a
600 // getelementptr instruction is associated with the addresses associated
601 // with the first operand of the getelementptr".
602 return R;
603
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000604 int64_t GEP1BaseOffset;
605 SmallVector<std::pair<const Value*, uint64_t>, 4> VariableIndices;
606 const Value *GEP1BasePtr =
607 DecomposeGEPExpression(GEP1, GEP1BaseOffset, VariableIndices, TD);
608
609 // If DecomposeGEPExpression isn't able to look all the way through the
610 // addressing operation, we must not have TD and this is too complex for us
611 // to handle without it.
612 if (GEP1BasePtr != UnderlyingV1) {
613 assert(TD == 0 &&
614 "DecomposeGEPExpression and getUnderlyingObject disagree!");
615 return MayAlias;
616 }
617
Evan Cheng681a33e2009-10-14 06:41:49 +0000618 // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
619 // the ptr, the end result is a must alias also.
Chris Lattner4e91ee72009-11-26 02:13:03 +0000620 if (GEP1BaseOffset == 0 && VariableIndices.empty())
Evan Cheng681a33e2009-10-14 06:41:49 +0000621 return MustAlias;
Evan Cheng094f04b2009-10-13 18:42:04 +0000622
Chris Lattner4e91ee72009-11-26 02:13:03 +0000623 // If we have a known constant offset, see if this offset is larger than the
624 // access size being queried. If so, and if no variable indices can remove
625 // pieces of this constant, then we know we have a no-alias. For example,
626 // &A[100] != &A.
627
628 // In order to handle cases like &A[100][i] where i is an out of range
629 // subscript, we have to ignore all constant offset pieces that are a multiple
630 // of a scaled index. Do this by removing constant offsets that are a
631 // multiple of any of our variable indices. This allows us to transform
632 // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
633 // provides an offset of 4 bytes (assuming a <= 4 byte access).
634 for (unsigned i = 0, e = VariableIndices.size(); i != e && GEP1BaseOffset;++i)
635 if (int64_t RemovedOffset = GEP1BaseOffset/VariableIndices[i].second)
636 GEP1BaseOffset -= RemovedOffset*VariableIndices[i].second;
637
638 // If our known offset is bigger than the access size, we know we don't have
639 // an alias.
640 if (GEP1BaseOffset) {
641 if (GEP1BaseOffset >= (int64_t)V2Size ||
642 GEP1BaseOffset <= -(int64_t)V1Size)
Evan Cheng681a33e2009-10-14 06:41:49 +0000643 return NoAlias;
Evan Cheng094f04b2009-10-13 18:42:04 +0000644 }
Chris Lattner4e91ee72009-11-26 02:13:03 +0000645
Evan Cheng094f04b2009-10-13 18:42:04 +0000646 return MayAlias;
647}
648
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000649/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
650/// instruction against another.
Dan Gohman6665b0e2009-10-26 21:55:43 +0000651AliasAnalysis::AliasResult
652BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
653 const Value *V2, unsigned V2Size) {
654 // If the values are Selects with the same condition, we can do a more precise
655 // check: just check for aliases between the values on corresponding arms.
656 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
657 if (SI->getCondition() == SI2->getCondition()) {
658 AliasResult Alias =
659 aliasCheck(SI->getTrueValue(), SISize,
660 SI2->getTrueValue(), V2Size);
661 if (Alias == MayAlias)
662 return MayAlias;
663 AliasResult ThisAlias =
664 aliasCheck(SI->getFalseValue(), SISize,
665 SI2->getFalseValue(), V2Size);
666 if (ThisAlias != Alias)
667 return MayAlias;
668 return Alias;
669 }
670
671 // If both arms of the Select node NoAlias or MustAlias V2, then returns
672 // NoAlias / MustAlias. Otherwise, returns MayAlias.
673 AliasResult Alias =
674 aliasCheck(SI->getTrueValue(), SISize, V2, V2Size);
675 if (Alias == MayAlias)
676 return MayAlias;
677 AliasResult ThisAlias =
678 aliasCheck(SI->getFalseValue(), SISize, V2, V2Size);
679 if (ThisAlias != Alias)
680 return MayAlias;
681 return Alias;
682}
683
Evan Chengd83c2ca2009-10-14 05:22:03 +0000684// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000685// against another.
Evan Cheng50a59142009-10-13 22:02:20 +0000686AliasAnalysis::AliasResult
Evan Chengd83c2ca2009-10-14 05:22:03 +0000687BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000688 const Value *V2, unsigned V2Size) {
Evan Cheng50a59142009-10-13 22:02:20 +0000689 // The PHI node has already been visited, avoid recursion any further.
Evan Chengd83c2ca2009-10-14 05:22:03 +0000690 if (!VisitedPHIs.insert(PN))
Evan Cheng50a59142009-10-13 22:02:20 +0000691 return MayAlias;
692
Dan Gohman6665b0e2009-10-26 21:55:43 +0000693 // If the values are PHIs in the same block, we can do a more precise
694 // as well as efficient check: just check for aliases between the values
695 // on corresponding edges.
696 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
697 if (PN2->getParent() == PN->getParent()) {
698 AliasResult Alias =
699 aliasCheck(PN->getIncomingValue(0), PNSize,
700 PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
701 V2Size);
702 if (Alias == MayAlias)
703 return MayAlias;
704 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
705 AliasResult ThisAlias =
706 aliasCheck(PN->getIncomingValue(i), PNSize,
707 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
708 V2Size);
709 if (ThisAlias != Alias)
710 return MayAlias;
711 }
712 return Alias;
713 }
714
Evan Chenga846a8a2009-10-16 00:33:09 +0000715 SmallPtrSet<Value*, 4> UniqueSrc;
Evan Cheng50a59142009-10-13 22:02:20 +0000716 SmallVector<Value*, 4> V1Srcs;
Evan Cheng50a59142009-10-13 22:02:20 +0000717 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
718 Value *PV1 = PN->getIncomingValue(i);
719 if (isa<PHINode>(PV1))
720 // If any of the source itself is a PHI, return MayAlias conservatively
Evan Cheng681a33e2009-10-14 06:41:49 +0000721 // to avoid compile time explosion. The worst possible case is if both
722 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
723 // and 'n' are the number of PHI sources.
Evan Cheng50a59142009-10-13 22:02:20 +0000724 return MayAlias;
725 if (UniqueSrc.insert(PV1))
726 V1Srcs.push_back(PV1);
727 }
728
Dan Gohman6665b0e2009-10-26 21:55:43 +0000729 AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
Evan Chengd83c2ca2009-10-14 05:22:03 +0000730 // Early exit if the check of the first PHI source against V2 is MayAlias.
731 // Other results are not possible.
732 if (Alias == MayAlias)
733 return MayAlias;
734
Evan Cheng50a59142009-10-13 22:02:20 +0000735 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
736 // NoAlias / MustAlias. Otherwise, returns MayAlias.
Evan Cheng50a59142009-10-13 22:02:20 +0000737 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
738 Value *V = V1Srcs[i];
Dan Gohman6665b0e2009-10-26 21:55:43 +0000739
740 // If V2 is a PHI, the recursive case will have been caught in the
741 // above aliasCheck call, so these subsequent calls to aliasCheck
742 // don't need to assume that V2 is being visited recursively.
743 VisitedPHIs.erase(V2);
744
Evan Chenga846a8a2009-10-16 00:33:09 +0000745 AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
Evan Chengd83c2ca2009-10-14 05:22:03 +0000746 if (ThisAlias != Alias || ThisAlias == MayAlias)
Evan Cheng50a59142009-10-13 22:02:20 +0000747 return MayAlias;
748 }
749
750 return Alias;
751}
752
753// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
754// such as array references.
Evan Cheng094f04b2009-10-13 18:42:04 +0000755//
756AliasAnalysis::AliasResult
Evan Cheng50a59142009-10-13 22:02:20 +0000757BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000758 const Value *V2, unsigned V2Size) {
Evan Cheng094f04b2009-10-13 18:42:04 +0000759 // Strip off any casts if they exist.
760 V1 = V1->stripPointerCasts();
761 V2 = V2->stripPointerCasts();
762
763 // Are we checking for alias of the same value?
764 if (V1 == V2) return MustAlias;
765
766 if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
767 return NoAlias; // Scalars cannot alias each other
768
769 // Figure out what objects these things are pointing to if we can.
770 const Value *O1 = V1->getUnderlyingObject();
771 const Value *O2 = V2->getUnderlyingObject();
772
Dan Gohmanf75ef662009-11-09 19:29:11 +0000773 // Null values in the default address space don't point to any object, so they
774 // don't alias any other pointer.
775 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
776 if (CPN->getType()->getAddressSpace() == 0)
777 return NoAlias;
778 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
779 if (CPN->getType()->getAddressSpace() == 0)
780 return NoAlias;
781
Evan Cheng094f04b2009-10-13 18:42:04 +0000782 if (O1 != O2) {
783 // If V1/V2 point to two different objects we know that we have no alias.
784 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
785 return NoAlias;
Nick Lewycky20162ac2009-11-14 06:15:14 +0000786
787 // Constant pointers can't alias with non-const isIdentifiedObject objects.
788 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
789 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
790 return NoAlias;
791
Evan Cheng094f04b2009-10-13 18:42:04 +0000792 // Arguments can't alias with local allocations or noalias calls.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000793 if ((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
794 (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1))))
Evan Cheng094f04b2009-10-13 18:42:04 +0000795 return NoAlias;
796
797 // Most objects can't alias null.
798 if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
799 (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
800 return NoAlias;
801 }
802
803 // If the size of one access is larger than the entire object on the other
804 // side, then we know such behavior is undefined and can assume no alias.
Evan Cheng094f04b2009-10-13 18:42:04 +0000805 if (TD)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000806 if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
807 (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
Evan Cheng094f04b2009-10-13 18:42:04 +0000808 return NoAlias;
809
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000810 // If one pointer is the result of a call/invoke or load and the other is a
Evan Cheng094f04b2009-10-13 18:42:04 +0000811 // non-escaping local object, then we know the object couldn't escape to a
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000812 // point where the call could return it. The load case works because
813 // isNonEscapingLocalObject considers all stores to be escapes (it
814 // passes true for the StoreCaptures argument to PointerMayBeCaptured).
815 if (O1 != O2) {
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000816 if ((isa<CallInst>(O1) || isa<InvokeInst>(O1) || isa<LoadInst>(O1) ||
Chris Lattner403ac2e2009-11-23 16:46:41 +0000817 isa<Argument>(O1)) &&
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000818 isNonEscapingLocalObject(O2))
819 return NoAlias;
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000820 if ((isa<CallInst>(O2) || isa<InvokeInst>(O2) || isa<LoadInst>(O2) ||
Chris Lattner403ac2e2009-11-23 16:46:41 +0000821 isa<Argument>(O2)) &&
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000822 isNonEscapingLocalObject(O1))
823 return NoAlias;
824 }
Evan Cheng094f04b2009-10-13 18:42:04 +0000825
Chris Lattner4e91ee72009-11-26 02:13:03 +0000826 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
827 // GEP can't simplify, we don't even look at the PHI cases.
Chris Lattner391d23b2009-10-17 23:48:54 +0000828 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
Chris Lattnerd501c132003-02-26 19:41:54 +0000829 std::swap(V1, V2);
830 std::swap(V1Size, V2Size);
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000831 std::swap(O1, O2);
Chris Lattnerd501c132003-02-26 19:41:54 +0000832 }
Chris Lattner539c9b92009-11-26 02:11:08 +0000833 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000834 return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
Evan Cheng50a59142009-10-13 22:02:20 +0000835
836 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
837 std::swap(V1, V2);
838 std::swap(V1Size, V2Size);
839 }
Evan Chengd83c2ca2009-10-14 05:22:03 +0000840 if (const PHINode *PN = dyn_cast<PHINode>(V1))
841 return aliasPHI(PN, V1Size, V2, V2Size);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000842
Dan Gohman6665b0e2009-10-26 21:55:43 +0000843 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
844 std::swap(V1, V2);
845 std::swap(V1Size, V2Size);
846 }
847 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
848 return aliasSelect(S1, V1Size, V2, V2Size);
849
Chris Lattnerd501c132003-02-26 19:41:54 +0000850 return MayAlias;
851}
852
Duncan Sands18327052008-12-08 14:01:59 +0000853// This function is used to determine if the indices of two GEP instructions are
Reid Spencer3da59db2006-11-27 01:05:10 +0000854// equal. V1 and V2 are the indices.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000855static bool IndexOperandsEqual(Value *V1, Value *V2) {
Chris Lattner28977af2004-04-05 01:30:19 +0000856 if (V1->getType() == V2->getType())
857 return V1 == V2;
858 if (Constant *C1 = dyn_cast<Constant>(V1))
859 if (Constant *C2 = dyn_cast<Constant>(V2)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000860 // Sign extend the constants to long types, if necessary
Chris Lattner7b550cc2009-11-06 04:27:31 +0000861 if (C1->getType() != Type::getInt64Ty(C1->getContext()))
862 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
863 if (C2->getType() != Type::getInt64Ty(C1->getContext()))
864 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
Chris Lattner28977af2004-04-05 01:30:19 +0000865 return C1 == C2;
866 }
867 return false;
868}
869
Chris Lattnerb307c882003-12-11 22:44:13 +0000870/// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
871/// base pointers. This checks to see if the index expressions preclude the
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000872/// pointers from aliasing.
Reid Spencerb83eb642006-10-20 07:07:24 +0000873AliasAnalysis::AliasResult
874BasicAliasAnalysis::CheckGEPInstructions(
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +0000875 const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S,
876 const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) {
Chris Lattnerb307c882003-12-11 22:44:13 +0000877 // We currently can't handle the case when the base pointers have different
878 // primitive types. Since this is uncommon anyway, we are happy being
879 // extremely conservative.
880 if (BasePtr1Ty != BasePtr2Ty)
881 return MayAlias;
882
Alkis Evlogimenosc49741d2004-12-08 23:56:15 +0000883 const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty);
Chris Lattnerb307c882003-12-11 22:44:13 +0000884
885 // Find the (possibly empty) initial sequence of equal values... which are not
886 // necessarily constants.
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +0000887 unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops;
Chris Lattnerb307c882003-12-11 22:44:13 +0000888 unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
889 unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
890 unsigned UnequalOper = 0;
891 while (UnequalOper != MinOperands &&
Chris Lattner7b550cc2009-11-06 04:27:31 +0000892 IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper])) {
Chris Lattnerb307c882003-12-11 22:44:13 +0000893 // Advance through the type as we go...
894 ++UnequalOper;
895 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
896 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
897 else {
898 // If all operands equal each other, then the derived pointers must
899 // alias each other...
900 BasePtr1Ty = 0;
901 assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
902 "Ran out of type nesting, but not out of operands?");
903 return MustAlias;
Chris Lattner920bd792003-06-02 05:42:39 +0000904 }
905 }
Chris Lattner920bd792003-06-02 05:42:39 +0000906
Chris Lattnerb307c882003-12-11 22:44:13 +0000907 // If we have seen all constant operands, and run out of indexes on one of the
908 // getelementptrs, check to see if the tail of the leftover one is all zeros.
909 // If so, return mustalias.
Chris Lattner4a830882003-12-11 23:20:16 +0000910 if (UnequalOper == MinOperands) {
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +0000911 if (NumGEP1Ops < NumGEP2Ops) {
912 std::swap(GEP1Ops, GEP2Ops);
913 std::swap(NumGEP1Ops, NumGEP2Ops);
914 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000915
Chris Lattnerb307c882003-12-11 22:44:13 +0000916 bool AllAreZeros = true;
917 for (unsigned i = UnequalOper; i != MaxOperands; ++i)
Chris Lattnera35339d2004-10-16 16:07:10 +0000918 if (!isa<Constant>(GEP1Ops[i]) ||
Chris Lattnerb307c882003-12-11 22:44:13 +0000919 !cast<Constant>(GEP1Ops[i])->isNullValue()) {
920 AllAreZeros = false;
921 break;
922 }
923 if (AllAreZeros) return MustAlias;
924 }
925
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000926
Chris Lattnerd501c132003-02-26 19:41:54 +0000927 // So now we know that the indexes derived from the base pointers,
928 // which are known to alias, are different. We can still determine a
929 // no-alias result if there are differing constant pairs in the index
930 // chain. For example:
931 // A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
932 //
Chris Lattner5a3cf8d2006-03-04 02:06:34 +0000933 // We have to be careful here about array accesses. In particular, consider:
934 // A[1][0] vs A[0][i]
935 // In this case, we don't *know* that the array will be accessed in bounds:
936 // the index could even be negative. Because of this, we have to
937 // conservatively *give up* and return may alias. We disregard differing
938 // array subscripts that are followed by a variable index without going
939 // through a struct.
940 //
Chris Lattnerd501c132003-02-26 19:41:54 +0000941 unsigned SizeMax = std::max(G1S, G2S);
Chris Lattnereaf8f9c2004-11-28 20:30:15 +0000942 if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work.
Chris Lattner920bd792003-06-02 05:42:39 +0000943
Chris Lattnerd501c132003-02-26 19:41:54 +0000944 // Scan for the first operand that is constant and unequal in the
Chris Lattner28977af2004-04-05 01:30:19 +0000945 // two getelementptrs...
Chris Lattnerd501c132003-02-26 19:41:54 +0000946 unsigned FirstConstantOper = UnequalOper;
Chris Lattnerb307c882003-12-11 22:44:13 +0000947 for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
948 const Value *G1Oper = GEP1Ops[FirstConstantOper];
949 const Value *G2Oper = GEP2Ops[FirstConstantOper];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000950
Chris Lattner6eb88d42004-01-12 17:57:32 +0000951 if (G1Oper != G2Oper) // Found non-equal constant indexes...
Chris Lattnera35339d2004-10-16 16:07:10 +0000952 if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper)))
953 if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){
Chris Lattner28977af2004-04-05 01:30:19 +0000954 if (G1OC->getType() != G2OC->getType()) {
955 // Sign extend both operands to long.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000956 const Type *Int64Ty = Type::getInt64Ty(G1OC->getContext());
957 if (G1OC->getType() != Int64Ty)
958 G1OC = ConstantExpr::getSExt(G1OC, Int64Ty);
959 if (G2OC->getType() != Int64Ty)
960 G2OC = ConstantExpr::getSExt(G2OC, Int64Ty);
Chris Lattner28977af2004-04-05 01:30:19 +0000961 GEP1Ops[FirstConstantOper] = G1OC;
962 GEP2Ops[FirstConstantOper] = G2OC;
963 }
Chris Lattner5a3cf8d2006-03-04 02:06:34 +0000964
Chris Lattner28977af2004-04-05 01:30:19 +0000965 if (G1OC != G2OC) {
Dan Gohman07a96762007-07-16 14:29:03 +0000966 // Handle the "be careful" case above: if this is an array/vector
Chris Lattner5a3cf8d2006-03-04 02:06:34 +0000967 // subscript, scan for a subsequent variable array index.
Dan Gohman72776d22009-05-27 01:48:27 +0000968 if (const SequentialType *STy =
969 dyn_cast<SequentialType>(BasePtr1Ty)) {
970 const Type *NextTy = STy;
Chris Lattner5a3cf8d2006-03-04 02:06:34 +0000971 bool isBadCase = false;
972
Dan Gohman72776d22009-05-27 01:48:27 +0000973 for (unsigned Idx = FirstConstantOper;
Chris Lattner7765d712006-11-03 21:58:48 +0000974 Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) {
Chris Lattner5a3cf8d2006-03-04 02:06:34 +0000975 const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx];
976 if (!isa<Constant>(V1) || !isa<Constant>(V2)) {
977 isBadCase = true;
978 break;
979 }
Dan Gohman72776d22009-05-27 01:48:27 +0000980 // If the array is indexed beyond the bounds of the static type
981 // at this level, it will also fall into the "be careful" case.
982 // It would theoretically be possible to analyze these cases,
983 // but for now just be conservatively correct.
984 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
985 if (cast<ConstantInt>(G1OC)->getZExtValue() >=
986 ATy->getNumElements() ||
987 cast<ConstantInt>(G2OC)->getZExtValue() >=
988 ATy->getNumElements()) {
989 isBadCase = true;
990 break;
991 }
992 if (const VectorType *VTy = dyn_cast<VectorType>(STy))
993 if (cast<ConstantInt>(G1OC)->getZExtValue() >=
994 VTy->getNumElements() ||
995 cast<ConstantInt>(G2OC)->getZExtValue() >=
996 VTy->getNumElements()) {
997 isBadCase = true;
998 break;
999 }
1000 STy = cast<SequentialType>(NextTy);
Chris Lattner7765d712006-11-03 21:58:48 +00001001 NextTy = cast<SequentialType>(NextTy)->getElementType();
Chris Lattner5a3cf8d2006-03-04 02:06:34 +00001002 }
1003
1004 if (isBadCase) G1OC = 0;
1005 }
1006
Chris Lattnera35339d2004-10-16 16:07:10 +00001007 // Make sure they are comparable (ie, not constant expressions), and
1008 // make sure the GEP with the smaller leading constant is GEP1.
Chris Lattner5a3cf8d2006-03-04 02:06:34 +00001009 if (G1OC) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001010 Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT,
1011 G1OC, G2OC);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001012 if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) {
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +00001013 if (CV->getZExtValue()) { // If they are comparable and G2 > G1
Chris Lattner5a3cf8d2006-03-04 02:06:34 +00001014 std::swap(GEP1Ops, GEP2Ops); // Make GEP1 < GEP2
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +00001015 std::swap(NumGEP1Ops, NumGEP2Ops);
1016 }
Chris Lattner5a3cf8d2006-03-04 02:06:34 +00001017 break;
1018 }
Chris Lattner28977af2004-04-05 01:30:19 +00001019 }
Chris Lattner6eb88d42004-01-12 17:57:32 +00001020 }
1021 }
Chris Lattnerb307c882003-12-11 22:44:13 +00001022 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
Chris Lattnerd501c132003-02-26 19:41:54 +00001023 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001024
Chris Lattnerb307c882003-12-11 22:44:13 +00001025 // No shared constant operands, and we ran out of common operands. At this
1026 // point, the GEP instructions have run through all of their operands, and we
1027 // haven't found evidence that there are any deltas between the GEP's.
1028 // However, one GEP may have more operands than the other. If this is the
Chris Lattner28977af2004-04-05 01:30:19 +00001029 // case, there may still be hope. Check this now.
Chris Lattnerb307c882003-12-11 22:44:13 +00001030 if (FirstConstantOper == MinOperands) {
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +00001031 // Without TargetData, we won't know what the offsets are.
1032 if (!TD)
1033 return MayAlias;
1034
Chris Lattnerb307c882003-12-11 22:44:13 +00001035 // Make GEP1Ops be the longer one if there is a longer one.
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +00001036 if (NumGEP1Ops < NumGEP2Ops) {
Chris Lattnerb307c882003-12-11 22:44:13 +00001037 std::swap(GEP1Ops, GEP2Ops);
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +00001038 std::swap(NumGEP1Ops, NumGEP2Ops);
1039 }
Chris Lattnerb307c882003-12-11 22:44:13 +00001040
1041 // Is there anything to check?
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +00001042 if (NumGEP1Ops > MinOperands) {
Chris Lattnerb307c882003-12-11 22:44:13 +00001043 for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001044 if (isa<ConstantInt>(GEP1Ops[i]) &&
Zhou Sheng843f07672007-04-19 05:39:12 +00001045 !cast<ConstantInt>(GEP1Ops[i])->isZero()) {
Chris Lattnerb307c882003-12-11 22:44:13 +00001046 // Yup, there's a constant in the tail. Set all variables to
Wojciech Matyjewicz98e3a682008-06-02 17:26:12 +00001047 // constants in the GEP instruction to make it suitable for
Chris Lattnerb307c882003-12-11 22:44:13 +00001048 // TargetData::getIndexedOffset.
1049 for (i = 0; i != MaxOperands; ++i)
Chris Lattner0bb38312007-01-12 18:20:48 +00001050 if (!isa<ConstantInt>(GEP1Ops[i]))
Owen Andersona7235ea2009-07-31 20:28:14 +00001051 GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
Chris Lattnerb307c882003-12-11 22:44:13 +00001052 // Okay, now get the offset. This is the relative offset for the full
1053 // instruction.
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +00001054 int64_t Offset1 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
1055 NumGEP1Ops);
Chris Lattnerb307c882003-12-11 22:44:13 +00001056
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +00001057 // Now check without any constants at the end.
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +00001058 int64_t Offset2 = TD->getIndexedOffset(GEPPointerTy, GEP1Ops,
1059 MinOperands);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001060
Wojciech Matyjewicz98e3a682008-06-02 17:26:12 +00001061 // Make sure we compare the absolute difference.
1062 if (Offset1 > Offset2)
1063 std::swap(Offset1, Offset2);
1064
Chris Lattnerb307c882003-12-11 22:44:13 +00001065 // If the tail provided a bit enough offset, return noalias!
1066 if ((uint64_t)(Offset2-Offset1) >= SizeMax)
1067 return NoAlias;
Wojciech Matyjewicz98e3a682008-06-02 17:26:12 +00001068 // Otherwise break - we don't look for another constant in the tail.
1069 break;
Chris Lattnerb307c882003-12-11 22:44:13 +00001070 }
1071 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001072
Chris Lattnerb307c882003-12-11 22:44:13 +00001073 // Couldn't find anything useful.
1074 return MayAlias;
1075 }
Chris Lattnerd501c132003-02-26 19:41:54 +00001076
1077 // If there are non-equal constants arguments, then we can figure
1078 // out a minimum known delta between the two index expressions... at
1079 // this point we know that the first constant index of GEP1 is less
1080 // than the first constant index of GEP2.
Chris Lattner1af55e12003-11-25 20:10:07 +00001081
Chris Lattnerb307c882003-12-11 22:44:13 +00001082 // Advance BasePtr[12]Ty over this first differing constant operand.
Chris Lattner2cfdd282006-03-04 21:48:01 +00001083 BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->
1084 getTypeAtIndex(GEP2Ops[FirstConstantOper]);
1085 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->
1086 getTypeAtIndex(GEP1Ops[FirstConstantOper]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001087
Chris Lattnerb307c882003-12-11 22:44:13 +00001088 // We are going to be using TargetData::getIndexedOffset to determine the
1089 // offset that each of the GEP's is reaching. To do this, we have to convert
1090 // all variable references to constant references. To do this, we convert the
Chris Lattner2cfdd282006-03-04 21:48:01 +00001091 // initial sequence of array subscripts into constant zeros to start with.
1092 const Type *ZeroIdxTy = GEPPointerTy;
1093 for (unsigned i = 0; i != FirstConstantOper; ++i) {
1094 if (!isa<StructType>(ZeroIdxTy))
Owen Anderson1d0be152009-08-13 21:58:54 +00001095 GEP1Ops[i] = GEP2Ops[i] =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001096 Constant::getNullValue(Type::getInt32Ty(ZeroIdxTy->getContext()));
Chris Lattnerb307c882003-12-11 22:44:13 +00001097
Chris Lattner2cfdd282006-03-04 21:48:01 +00001098 if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy))
1099 ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]);
1100 }
1101
Chris Lattnerb307c882003-12-11 22:44:13 +00001102 // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001103
Chris Lattnerd501c132003-02-26 19:41:54 +00001104 // Loop over the rest of the operands...
Chris Lattnerb307c882003-12-11 22:44:13 +00001105 for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
Chris Lattnerfd1ad3b2007-02-10 22:12:53 +00001106 const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0;
1107 const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0;
Chris Lattnerb307c882003-12-11 22:44:13 +00001108 // If they are equal, use a zero index...
1109 if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
Chris Lattner0bb38312007-01-12 18:20:48 +00001110 if (!isa<ConstantInt>(Op1))
Owen Andersona7235ea2009-07-31 20:28:14 +00001111 GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType());
Chris Lattnerb307c882003-12-11 22:44:13 +00001112 // Otherwise, just keep the constants we have.
Chris Lattnerd501c132003-02-26 19:41:54 +00001113 } else {
Chris Lattnerb307c882003-12-11 22:44:13 +00001114 if (Op1) {
1115 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1116 // If this is an array index, make sure the array element is in range.
Chris Lattner7765d712006-11-03 21:58:48 +00001117 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001118 if (Op1C->getZExtValue() >= AT->getNumElements())
Chris Lattnerb307c882003-12-11 22:44:13 +00001119 return MayAlias; // Be conservative with out-of-range accesses
Chris Lattnerf88380b2007-12-09 07:35:13 +00001120 } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) {
1121 if (Op1C->getZExtValue() >= VT->getNumElements())
Chris Lattner7765d712006-11-03 21:58:48 +00001122 return MayAlias; // Be conservative with out-of-range accesses
1123 }
1124
Chris Lattnerb307c882003-12-11 22:44:13 +00001125 } else {
1126 // GEP1 is known to produce a value less than GEP2. To be
1127 // conservatively correct, we must assume the largest possible
1128 // constant is used in this position. This cannot be the initial
1129 // index to the GEP instructions (because we know we have at least one
1130 // element before this one with the different constant arguments), so
1131 // we know that the current index must be into either a struct or
1132 // array. Because we know it's not constant, this cannot be a
1133 // structure index. Because of this, we can calculate the maximum
1134 // value possible.
1135 //
1136 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
Owen Anderson50895512009-07-06 18:42:36 +00001137 GEP1Ops[i] =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001138 ConstantInt::get(Type::getInt64Ty(AT->getContext()),
Owen Anderson1d0be152009-08-13 21:58:54 +00001139 AT->getNumElements()-1);
Chris Lattner9907cb12007-11-06 05:58:42 +00001140 else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty))
Owen Anderson50895512009-07-06 18:42:36 +00001141 GEP1Ops[i] =
Chris Lattner7b550cc2009-11-06 04:27:31 +00001142 ConstantInt::get(Type::getInt64Ty(VT->getContext()),
Owen Anderson1d0be152009-08-13 21:58:54 +00001143 VT->getNumElements()-1);
Chris Lattnerb307c882003-12-11 22:44:13 +00001144 }
Chris Lattnerd501c132003-02-26 19:41:54 +00001145 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001146
Chris Lattnerb307c882003-12-11 22:44:13 +00001147 if (Op2) {
1148 if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
1149 // If this is an array index, make sure the array element is in range.
Chris Lattnerf88380b2007-12-09 07:35:13 +00001150 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001151 if (Op2C->getZExtValue() >= AT->getNumElements())
Chris Lattnerb307c882003-12-11 22:44:13 +00001152 return MayAlias; // Be conservative with out-of-range accesses
Chris Lattnerf88380b2007-12-09 07:35:13 +00001153 } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) {
Chris Lattner9907cb12007-11-06 05:58:42 +00001154 if (Op2C->getZExtValue() >= VT->getNumElements())
Chris Lattner7765d712006-11-03 21:58:48 +00001155 return MayAlias; // Be conservative with out-of-range accesses
1156 }
Chris Lattnerb307c882003-12-11 22:44:13 +00001157 } else { // Conservatively assume the minimum value for this index
Owen Andersona7235ea2009-07-31 20:28:14 +00001158 GEP2Ops[i] = Constant::getNullValue(Op2->getType());
Chris Lattnerb307c882003-12-11 22:44:13 +00001159 }
Chris Lattner920bd792003-06-02 05:42:39 +00001160 }
Chris Lattnerb307c882003-12-11 22:44:13 +00001161 }
1162
1163 if (BasePtr1Ty && Op1) {
1164 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
1165 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
1166 else
1167 BasePtr1Ty = 0;
1168 }
1169
1170 if (BasePtr2Ty && Op2) {
1171 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
1172 BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
1173 else
1174 BasePtr2Ty = 0;
Chris Lattnerd501c132003-02-26 19:41:54 +00001175 }
1176 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001177
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +00001178 if (TD && GEPPointerTy->getElementType()->isSized()) {
Chris Lattner829621c2007-02-10 20:35:22 +00001179 int64_t Offset1 =
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +00001180 TD->getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops);
Chris Lattner829621c2007-02-10 20:35:22 +00001181 int64_t Offset2 =
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +00001182 TD->getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops);
Chris Lattner9907cb12007-11-06 05:58:42 +00001183 assert(Offset1 != Offset2 &&
1184 "There is at least one different constant here!");
1185
1186 // Make sure we compare the absolute difference.
1187 if (Offset1 > Offset2)
1188 std::swap(Offset1, Offset2);
1189
Alkis Evlogimenosc49741d2004-12-08 23:56:15 +00001190 if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
Bill Wendlinge8156192006-12-07 01:30:32 +00001191 //cerr << "Determined that these two GEP's don't alias ["
1192 // << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
Alkis Evlogimenosc49741d2004-12-08 23:56:15 +00001193 return NoAlias;
1194 }
Chris Lattnerd501c132003-02-26 19:41:54 +00001195 }
1196 return MayAlias;
1197}
1198
Chris Lattner5d56b2d2009-11-23 16:45:27 +00001199// Make sure that anything that uses AliasAnalysis pulls in this file.
Reid Spencer4f1bd9e2006-06-07 22:00:26 +00001200DEFINING_FILE_FOR(BasicAliasAnalysis)