blob: f8d8873c4f6392bca03d419477abe456d9209cbb [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"
Jeff Cohen534927d2005-01-08 22:01:16 +000017#include "llvm/Analysis/Passes.h"
Chris Lattner4244bb52004-03-15 03:36:49 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner23e2a5b2009-11-26 02:14:59 +000021#include "llvm/GlobalAlias.h"
Chris Lattner4244bb52004-03-15 03:36:49 +000022#include "llvm/GlobalVariable.h"
Alkis Evlogimenoseb62bc72004-07-29 12:17:34 +000023#include "llvm/Instructions.h"
Owen Anderson9b636cb2008-02-17 21:29:08 +000024#include "llvm/IntrinsicInst.h"
Dan Gohman3a7a68c2009-07-17 22:25:10 +000025#include "llvm/Operator.h"
Chris Lattner4244bb52004-03-15 03:36:49 +000026#include "llvm/Pass.h"
Chris Lattner5d5261c2009-11-26 16:26:43 +000027#include "llvm/Analysis/CaptureTracking.h"
28#include "llvm/Analysis/MemoryBuiltins.h"
29#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerd501c132003-02-26 19:41:54 +000030#include "llvm/Target/TargetData.h"
Evan Cheng50a59142009-10-13 22:02:20 +000031#include "llvm/ADT/SmallSet.h"
Chris Lattnera77600e2007-02-10 22:15:31 +000032#include "llvm/ADT/SmallVector.h"
Owen Anderson718cb662007-09-07 04:06:50 +000033#include "llvm/ADT/STLExtras.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000034#include "llvm/Support/ErrorHandling.h"
Chris Lattner90aa8392006-10-04 21:52:35 +000035#include "llvm/Support/GetElementPtrTypeIterator.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000036#include <algorithm>
Chris Lattnerec4e8082003-11-25 18:33:40 +000037using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000038
Chris Lattnerdefa1c82008-06-16 06:30:22 +000039//===----------------------------------------------------------------------===//
40// Useful predicates
41//===----------------------------------------------------------------------===//
Devang Patel794fd752007-05-01 21:15:47 +000042
Chris Lattnera4139602008-06-16 06:10:11 +000043/// isKnownNonNull - Return true if we know that the specified value is never
44/// null.
45static bool isKnownNonNull(const Value *V) {
46 // Alloca never returns null, malloc might.
47 if (isa<AllocaInst>(V)) return true;
48
49 // A byval argument is never null.
50 if (const Argument *A = dyn_cast<Argument>(V))
51 return A->hasByValAttr();
52
53 // Global values are not null unless extern weak.
54 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
55 return !GV->hasExternalWeakLinkage();
56 return false;
57}
58
Chris Lattner845f0d22008-06-16 06:19:11 +000059/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
60/// object that never escapes from the function.
61static bool isNonEscapingLocalObject(const Value *V) {
Chris Lattnere7275792008-06-16 06:28:01 +000062 // If this is a local allocation, check to see if it escapes.
Victor Hernandez7b929da2009-10-23 21:09:37 +000063 if (isa<AllocaInst>(V) || isNoAliasCall(V))
Dan Gohmanf94b5ed2009-11-19 21:57:48 +000064 // Set StoreCaptures to True so that we can assume in our callers that the
65 // pointer is not the result of a load instruction. Currently
66 // PointerMayBeCaptured doesn't have any special analysis for the
67 // StoreCaptures=false case; if it did, our callers could be refined to be
68 // more precise.
69 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Duncan Sands91c9c3102009-01-05 21:19:53 +000070
Chris Lattnere7275792008-06-16 06:28:01 +000071 // If this is an argument that corresponds to a byval or noalias argument,
Duncan Sands91c9c3102009-01-05 21:19:53 +000072 // then it has not escaped before entering the function. Check if it escapes
73 // inside the function.
Chris Lattnere7275792008-06-16 06:28:01 +000074 if (const Argument *A = dyn_cast<Argument>(V))
Duncan Sands91c9c3102009-01-05 21:19:53 +000075 if (A->hasByValAttr() || A->hasNoAliasAttr()) {
76 // Don't bother analyzing arguments already known not to escape.
77 if (A->hasNoCaptureAttr())
78 return true;
Dan Gohmanf94b5ed2009-11-19 21:57:48 +000079 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
Duncan Sands91c9c3102009-01-05 21:19:53 +000080 }
Chris Lattner845f0d22008-06-16 06:19:11 +000081 return false;
82}
83
84
Chris Lattnera4139602008-06-16 06:10:11 +000085/// isObjectSmallerThan - Return true if we can prove that the object specified
86/// by V is smaller than Size.
87static bool isObjectSmallerThan(const Value *V, unsigned Size,
Chris Lattner7b550cc2009-11-06 04:27:31 +000088 const TargetData &TD) {
Chris Lattner295d4e92008-12-08 06:28:54 +000089 const Type *AccessTy;
90 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
Chris Lattnera4139602008-06-16 06:10:11 +000091 AccessTy = GV->getType()->getElementType();
Victor Hernandez7b929da2009-10-23 21:09:37 +000092 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
Chris Lattnera4139602008-06-16 06:10:11 +000093 if (!AI->isArrayAllocation())
94 AccessTy = AI->getType()->getElementType();
Chris Lattner295d4e92008-12-08 06:28:54 +000095 else
96 return false;
Victor Hernandez46e83122009-09-18 21:34:51 +000097 } else if (const CallInst* CI = extractMallocCall(V)) {
Chris Lattner7b550cc2009-11-06 04:27:31 +000098 if (!isArrayMalloc(V, &TD))
Victor Hernandez46e83122009-09-18 21:34:51 +000099 // The size is the argument to the malloc call.
100 if (const ConstantInt* C = dyn_cast<ConstantInt>(CI->getOperand(1)))
101 return (C->getZExtValue() < Size);
102 return false;
Chris Lattner295d4e92008-12-08 06:28:54 +0000103 } else if (const Argument *A = dyn_cast<Argument>(V)) {
Chris Lattnera4139602008-06-16 06:10:11 +0000104 if (A->hasByValAttr())
105 AccessTy = cast<PointerType>(A->getType())->getElementType();
Chris Lattner295d4e92008-12-08 06:28:54 +0000106 else
107 return false;
108 } else {
109 return false;
110 }
Chris Lattnera4139602008-06-16 06:10:11 +0000111
Chris Lattner295d4e92008-12-08 06:28:54 +0000112 if (AccessTy->isSized())
Duncan Sands777d2302009-05-09 07:06:46 +0000113 return TD.getTypeAllocSize(AccessTy) < Size;
Chris Lattnera4139602008-06-16 06:10:11 +0000114 return false;
115}
116
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000117//===----------------------------------------------------------------------===//
118// NoAA Pass
119//===----------------------------------------------------------------------===//
120
121namespace {
122 /// NoAA - This class implements the -no-aa pass, which always returns "I
123 /// don't know" for alias queries. NoAA is unlike other alias analysis
124 /// implementations, in that it does not chain to a previous analysis. As
125 /// such it doesn't follow many of the rules that other alias analyses must.
126 ///
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000127 struct NoAA : public ImmutablePass, public AliasAnalysis {
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000128 static char ID; // Class identification, replacement for typeinfo
Dan Gohmanae73dc12008-09-04 17:05:41 +0000129 NoAA() : ImmutablePass(&ID) {}
130 explicit NoAA(void *PID) : ImmutablePass(PID) { }
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000131
132 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000133 }
134
135 virtual void initializePass() {
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000136 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000137 }
138
139 virtual AliasResult alias(const Value *V1, unsigned V1Size,
140 const Value *V2, unsigned V2Size) {
141 return MayAlias;
142 }
143
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000144 virtual void getArgumentAccesses(Function *F, CallSite CS,
145 std::vector<PointerAccessInfo> &Info) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000146 llvm_unreachable("This method may not be called on this function!");
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000147 }
148
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000149 virtual bool pointsToConstantMemory(const Value *P) { return false; }
150 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
151 return ModRef;
152 }
153 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
154 return ModRef;
155 }
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000156
157 virtual void deleteValue(Value *V) {}
158 virtual void copyValue(Value *From, Value *To) {}
159 };
160} // End of anonymous namespace
161
162// Register this pass...
163char NoAA::ID = 0;
164static RegisterPass<NoAA>
165U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
166
167// Declare that we implement the AliasAnalysis interface
168static RegisterAnalysisGroup<AliasAnalysis> V(U);
169
170ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
171
172//===----------------------------------------------------------------------===//
173// BasicAA Pass
174//===----------------------------------------------------------------------===//
175
176namespace {
177 /// BasicAliasAnalysis - This is the default alias analysis implementation.
178 /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
179 /// derives from the NoAA class.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000180 struct BasicAliasAnalysis : public NoAA {
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000181 static char ID; // Class identification, replacement for typeinfo
Dan Gohmanae73dc12008-09-04 17:05:41 +0000182 BasicAliasAnalysis() : NoAA(&ID) {}
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000183 AliasResult alias(const Value *V1, unsigned V1Size,
Evan Cheng50a59142009-10-13 22:02:20 +0000184 const Value *V2, unsigned V2Size) {
Evan Chengf0429fd2009-10-14 06:46:26 +0000185 assert(VisitedPHIs.empty() && "VisitedPHIs must be cleared after use!");
186 AliasResult Alias = aliasCheck(V1, V1Size, V2, V2Size);
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000187 VisitedPHIs.clear();
Evan Chengf0429fd2009-10-14 06:46:26 +0000188 return Alias;
Evan Cheng50a59142009-10-13 22:02:20 +0000189 }
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000190
191 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
Chris Lattner20d6f092008-12-09 21:19:42 +0000192 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Owen Andersone7942202009-02-05 23:36:27 +0000193
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000194 /// pointsToConstantMemory - Chase pointers until we find a (constant
195 /// global) or not.
196 bool pointsToConstantMemory(const Value *P);
197
198 private:
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000199 // VisitedPHIs - Track PHI nodes visited by a aliasCheck() call.
Dan Gohman6665b0e2009-10-26 21:55:43 +0000200 SmallPtrSet<const Value*, 16> VisitedPHIs;
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000201
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000202 // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
203 // instruction against another.
Chris Lattner539c9b92009-11-26 02:11:08 +0000204 AliasResult aliasGEP(const GEPOperator *V1, unsigned V1Size,
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000205 const Value *V2, unsigned V2Size,
206 const Value *UnderlyingV1, const Value *UnderlyingV2);
Evan Cheng50a59142009-10-13 22:02:20 +0000207
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000208 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
209 // instruction against another.
Evan Chengd83c2ca2009-10-14 05:22:03 +0000210 AliasResult aliasPHI(const PHINode *PN, unsigned PNSize,
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000211 const Value *V2, unsigned V2Size);
Evan Cheng50a59142009-10-13 22:02:20 +0000212
Dan Gohman6665b0e2009-10-26 21:55:43 +0000213 /// aliasSelect - Disambiguate a Select instruction against another value.
214 AliasResult aliasSelect(const SelectInst *SI, unsigned SISize,
215 const Value *V2, unsigned V2Size);
216
Evan Cheng50a59142009-10-13 22:02:20 +0000217 AliasResult aliasCheck(const Value *V1, unsigned V1Size,
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000218 const Value *V2, unsigned V2Size);
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000219 };
220} // End of anonymous namespace
221
222// Register this pass...
223char BasicAliasAnalysis::ID = 0;
224static RegisterPass<BasicAliasAnalysis>
225X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
226
227// Declare that we implement the AliasAnalysis interface
228static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
229
230ImmutablePass *llvm::createBasicAliasAnalysisPass() {
231 return new BasicAliasAnalysis();
232}
233
234
235/// pointsToConstantMemory - Chase pointers until we find a (constant
236/// global) or not.
237bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
238 if (const GlobalVariable *GV =
Duncan Sands5d0392c2008-10-01 15:25:41 +0000239 dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
Chris Lattnerb27db372009-11-23 17:07:35 +0000240 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
241 // global to be marked constant in some modules and non-constant in others.
242 // GV may even be a declaration, not a definition.
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000243 return GV->isConstant();
244 return false;
245}
246
Owen Andersone7942202009-02-05 23:36:27 +0000247
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000248/// getModRefInfo - Check to see if the specified callsite can clobber the
249/// specified memory object. Since we only look at local properties of this
250/// function, we really can't say much about this query. We do, however, use
251/// simple "address taken" analysis on local objects.
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000252AliasAnalysis::ModRefResult
253BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
Chris Lattner92e803c2009-11-22 16:05:05 +0000254 const Value *Object = P->getUnderlyingObject();
255
256 // If this is a tail call and P points to a stack location, we know that
257 // the tail call cannot access or modify the local stack.
258 // We cannot exclude byval arguments here; these belong to the caller of
259 // the current function not to the current function, and a tail callee
260 // may reference them.
261 if (isa<AllocaInst>(Object))
262 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
263 if (CI->isTailCall())
264 return NoModRef;
265
266 // If the pointer is to a locally allocated object that does not escape,
Chris Lattnerb34b82e2009-11-23 16:44:43 +0000267 // then the call can not mod/ref the pointer unless the call takes the pointer
268 // as an argument, and itself doesn't capture it.
Chris Lattner403ac2e2009-11-23 16:46:41 +0000269 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
270 isNonEscapingLocalObject(Object)) {
Chris Lattnerb34b82e2009-11-23 16:44:43 +0000271 bool PassedAsArg = false;
272 unsigned ArgNo = 0;
Chris Lattner92e803c2009-11-22 16:05:05 +0000273 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
Chris Lattnerb34b82e2009-11-23 16:44:43 +0000274 CI != CE; ++CI, ++ArgNo) {
275 // Only look at the no-capture pointer arguments.
276 if (!isa<PointerType>((*CI)->getType()) ||
277 !CS.paramHasAttr(ArgNo+1, Attribute::NoCapture))
278 continue;
279
280 // If this is a no-capture pointer argument, see if we can tell that it
281 // is impossible to alias the pointer we're checking. If not, we have to
282 // assume that the call could touch the pointer, even though it doesn't
283 // escape.
Chris Lattner403ac2e2009-11-23 16:46:41 +0000284 if (!isNoAlias(cast<Value>(CI), ~0U, P, ~0U)) {
Chris Lattnerb34b82e2009-11-23 16:44:43 +0000285 PassedAsArg = true;
286 break;
287 }
288 }
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000289
Chris Lattnerb34b82e2009-11-23 16:44:43 +0000290 if (!PassedAsArg)
Chris Lattner92e803c2009-11-22 16:05:05 +0000291 return NoModRef;
292 }
293
294 // Finally, handle specific knowledge of intrinsics.
295 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
296 if (II == 0)
297 return AliasAnalysis::getModRefInfo(CS, P, Size);
298
299 switch (II->getIntrinsicID()) {
300 default: break;
301 case Intrinsic::memcpy:
302 case Intrinsic::memmove: {
303 unsigned Len = ~0U;
304 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3)))
305 Len = LenCI->getZExtValue();
306 Value *Dest = II->getOperand(1);
307 Value *Src = II->getOperand(2);
Chris Lattner403ac2e2009-11-23 16:46:41 +0000308 if (isNoAlias(Dest, Len, P, Size)) {
309 if (isNoAlias(Src, Len, P, Size))
Chris Lattner92e803c2009-11-22 16:05:05 +0000310 return NoModRef;
311 return Ref;
312 }
313 break;
314 }
315 case Intrinsic::memset:
Chris Lattner403ac2e2009-11-23 16:46:41 +0000316 // Since memset is 'accesses arguments' only, the AliasAnalysis base class
317 // will handle it for the variable length case.
Chris Lattner92e803c2009-11-22 16:05:05 +0000318 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(II->getOperand(3))) {
319 unsigned Len = LenCI->getZExtValue();
320 Value *Dest = II->getOperand(1);
Chris Lattner403ac2e2009-11-23 16:46:41 +0000321 if (isNoAlias(Dest, Len, P, Size))
Chris Lattner25df20f2008-06-16 06:38:26 +0000322 return NoModRef;
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000323 }
Chris Lattner92e803c2009-11-22 16:05:05 +0000324 break;
325 case Intrinsic::atomic_cmp_swap:
326 case Intrinsic::atomic_swap:
327 case Intrinsic::atomic_load_add:
328 case Intrinsic::atomic_load_sub:
329 case Intrinsic::atomic_load_and:
330 case Intrinsic::atomic_load_nand:
331 case Intrinsic::atomic_load_or:
332 case Intrinsic::atomic_load_xor:
333 case Intrinsic::atomic_load_max:
334 case Intrinsic::atomic_load_min:
335 case Intrinsic::atomic_load_umax:
336 case Intrinsic::atomic_load_umin:
337 if (TD) {
338 Value *Op1 = II->getOperand(1);
339 unsigned Op1Size = TD->getTypeStoreSize(Op1->getType());
Chris Lattner403ac2e2009-11-23 16:46:41 +0000340 if (isNoAlias(Op1, Op1Size, P, Size))
Chris Lattner92e803c2009-11-22 16:05:05 +0000341 return NoModRef;
Nick Lewycky5c9be672009-10-13 07:48:38 +0000342 }
Chris Lattner92e803c2009-11-22 16:05:05 +0000343 break;
344 case Intrinsic::lifetime_start:
345 case Intrinsic::lifetime_end:
346 case Intrinsic::invariant_start: {
347 unsigned PtrSize = cast<ConstantInt>(II->getOperand(1))->getZExtValue();
Chris Lattner403ac2e2009-11-23 16:46:41 +0000348 if (isNoAlias(II->getOperand(2), PtrSize, P, Size))
Chris Lattner92e803c2009-11-22 16:05:05 +0000349 return NoModRef;
350 break;
351 }
352 case Intrinsic::invariant_end: {
353 unsigned PtrSize = cast<ConstantInt>(II->getOperand(2))->getZExtValue();
Chris Lattner403ac2e2009-11-23 16:46:41 +0000354 if (isNoAlias(II->getOperand(3), PtrSize, P, Size))
Chris Lattner92e803c2009-11-22 16:05:05 +0000355 return NoModRef;
356 break;
357 }
Chris Lattnerdefa1c82008-06-16 06:30:22 +0000358 }
359
360 // The AliasAnalysis base class has some smarts, lets use them.
361 return AliasAnalysis::getModRefInfo(CS, P, Size);
362}
363
364
Chris Lattner20d6f092008-12-09 21:19:42 +0000365AliasAnalysis::ModRefResult
366BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
367 // If CS1 or CS2 are readnone, they don't interact.
368 ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
369 if (CS1B == DoesNotAccessMemory) return NoModRef;
370
371 ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
372 if (CS2B == DoesNotAccessMemory) return NoModRef;
373
374 // If they both only read from memory, just return ref.
375 if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
376 return Ref;
377
378 // Otherwise, fall back to NoAA (mod+ref).
379 return NoAA::getModRefInfo(CS1, CS2);
380}
381
Chris Lattnerf6ac4d92009-11-26 16:18:10 +0000382/// GetLinearExpression - Analyze the specified value as a linear expression:
383/// "A*V + B". Return the scale and offset values as APInts and return V as a
384/// Value*. The incoming Value is known to be a scalar integer.
Chris Lattner5d5261c2009-11-26 16:26:43 +0000385static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
386 const TargetData *TD) {
Chris Lattnerf6ac4d92009-11-26 16:18:10 +0000387 assert(isa<IntegerType>(V->getType()) && "Not an integer value");
388
389 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
390 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
391 switch (BOp->getOpcode()) {
392 default: break;
Chris Lattner5d5261c2009-11-26 16:26:43 +0000393 case Instruction::Or:
394 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
395 // analyze it.
396 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), TD))
397 break;
398 // FALL THROUGH.
Chris Lattnerf6ac4d92009-11-26 16:18:10 +0000399 case Instruction::Add:
Chris Lattner5d5261c2009-11-26 16:26:43 +0000400 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, TD);
Chris Lattnerf6ac4d92009-11-26 16:18:10 +0000401 Offset += RHSC->getValue();
402 return V;
403 // TODO: SHL, MUL, OR.
404 }
405 }
406 }
407
408 Scale = 1;
409 Offset = 0;
410 return V;
411}
412
Chris Lattner4e91ee72009-11-26 02:13:03 +0000413/// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
414/// into a base pointer with a constant offset and a number of scaled symbolic
415/// offsets.
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000416///
417/// When TargetData is around, this function is capable of analyzing everything
418/// that Value::getUnderlyingObject() can look through. When not, it just looks
419/// through pointer casts.
420///
421/// FIXME: Move this out to ValueTracking.cpp
422///
Chris Lattner4e91ee72009-11-26 02:13:03 +0000423static const Value *DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
Chris Lattnerd84eb912009-11-26 02:17:34 +0000424 SmallVectorImpl<std::pair<const Value*, int64_t> > &VarIndices,
Chris Lattner4e91ee72009-11-26 02:13:03 +0000425 const TargetData *TD) {
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000426 // FIXME: Should limit depth like getUnderlyingObject?
Chris Lattner4e91ee72009-11-26 02:13:03 +0000427 BaseOffs = 0;
428 while (1) {
429 // See if this is a bitcast or GEP.
430 const Operator *Op = dyn_cast<Operator>(V);
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000431 if (Op == 0) {
432 // The only non-operator case we can handle are GlobalAliases.
433 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
434 if (!GA->mayBeOverridden()) {
435 V = GA->getAliasee();
436 continue;
437 }
438 }
439 return V;
440 }
Chris Lattner4e91ee72009-11-26 02:13:03 +0000441
442 if (Op->getOpcode() == Instruction::BitCast) {
443 V = Op->getOperand(0);
444 continue;
445 }
446
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000447 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
448 if (GEPOp == 0)
Chris Lattner4e91ee72009-11-26 02:13:03 +0000449 return V;
450
451 // Don't attempt to analyze GEPs over unsized objects.
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000452 if (!cast<PointerType>(GEPOp->getOperand(0)->getType())
Chris Lattner4e91ee72009-11-26 02:13:03 +0000453 ->getElementType()->isSized())
454 return V;
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000455
456 // If we are lacking TargetData information, we can't compute the offets of
457 // elements computed by GEPs. However, we can handle bitcast equivalent
458 // GEPs.
459 if (!TD) {
460 if (!GEPOp->hasAllZeroIndices())
461 return V;
462 V = GEPOp->getOperand(0);
463 continue;
464 }
Chris Lattner4e91ee72009-11-26 02:13:03 +0000465
466 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000467 gep_type_iterator GTI = gep_type_begin(GEPOp);
468 for (User::const_op_iterator I = next(GEPOp->op_begin()),
469 E = GEPOp->op_end(); I != E; ++I) {
Chris Lattner4e91ee72009-11-26 02:13:03 +0000470 Value *Index = *I;
471 // Compute the (potentially symbolic) offset in bytes for this index.
472 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
473 // For a struct, add the member offset.
474 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
475 if (FieldNo == 0) continue;
Chris Lattner4e91ee72009-11-26 02:13:03 +0000476
477 BaseOffs += TD->getStructLayout(STy)->getElementOffset(FieldNo);
478 continue;
479 }
480
481 // For an array/pointer, add the element offset, explicitly scaled.
482 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
483 if (CIdx->isZero()) continue;
Chris Lattner4e91ee72009-11-26 02:13:03 +0000484 BaseOffs += TD->getTypeAllocSize(*GTI)*CIdx->getSExtValue();
485 continue;
486 }
487
Chris Lattner4e91ee72009-11-26 02:13:03 +0000488 // TODO: Could handle linear expressions here like A[X+1], also A[X*4|1].
489 uint64_t Scale = TD->getTypeAllocSize(*GTI);
490
Chris Lattnerf6ac4d92009-11-26 16:18:10 +0000491 unsigned Width = cast<IntegerType>(Index->getType())->getBitWidth();
492 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
Chris Lattner5d5261c2009-11-26 16:26:43 +0000493 Index = GetLinearExpression(Index, IndexScale, IndexOffset, TD);
Chris Lattnerf6ac4d92009-11-26 16:18:10 +0000494
495 Scale *= IndexScale.getZExtValue();
496 BaseOffs += IndexOffset.getZExtValue()*Scale;
497
498
Chris Lattner4e91ee72009-11-26 02:13:03 +0000499 // If we already had an occurrance of this index variable, merge this
500 // scale into it. For example, we want to handle:
501 // A[x][x] -> x*16 + x*4 -> x*20
Chris Lattnerd84eb912009-11-26 02:17:34 +0000502 // This also ensures that 'x' only appears in the index list once.
Chris Lattner4e91ee72009-11-26 02:13:03 +0000503 for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
504 if (VarIndices[i].first == Index) {
505 Scale += VarIndices[i].second;
506 VarIndices.erase(VarIndices.begin()+i);
507 break;
508 }
509 }
510
511 // Make sure that we have a scale that makes sense for this target's
512 // pointer size.
513 if (unsigned ShiftBits = 64-TD->getPointerSizeInBits()) {
514 Scale <<= ShiftBits;
515 Scale >>= ShiftBits;
516 }
517
518 if (Scale)
519 VarIndices.push_back(std::make_pair(Index, Scale));
520 }
521
522 // Analyze the base pointer next.
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000523 V = GEPOp->getOperand(0);
Chris Lattner4e91ee72009-11-26 02:13:03 +0000524 }
Chris Lattner4e91ee72009-11-26 02:13:03 +0000525}
526
Chris Lattnerd84eb912009-11-26 02:17:34 +0000527/// GetIndiceDifference - Dest and Src are the variable indices from two
528/// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
529/// pointers. Subtract the GEP2 indices from GEP1 to find the symbolic
530/// difference between the two pointers.
531static void GetIndiceDifference(
532 SmallVectorImpl<std::pair<const Value*, int64_t> > &Dest,
533 const SmallVectorImpl<std::pair<const Value*, int64_t> > &Src) {
534 if (Src.empty()) return;
535
536 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
537 const Value *V = Src[i].first;
538 int64_t Scale = Src[i].second;
539
540 // Find V in Dest. This is N^2, but pointer indices almost never have more
541 // than a few variable indexes.
542 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
543 if (Dest[j].first != V) continue;
544
545 // If we found it, subtract off Scale V's from the entry in Dest. If it
546 // goes to zero, remove the entry.
547 if (Dest[j].second != Scale)
548 Dest[j].second -= Scale;
549 else
550 Dest.erase(Dest.begin()+j);
551 Scale = 0;
552 break;
553 }
554
555 // If we didn't consume this entry, add it to the end of the Dest list.
556 if (Scale)
557 Dest.push_back(std::make_pair(V, -Scale));
558 }
559}
Chris Lattner4e91ee72009-11-26 02:13:03 +0000560
Chris Lattner539c9b92009-11-26 02:11:08 +0000561/// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
562/// against another pointer. We know that V1 is a GEP, but we don't know
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000563/// anything about V2. UnderlyingV1 is GEP1->getUnderlyingObject(),
564/// UnderlyingV2 is the same for V2.
Chris Lattner539c9b92009-11-26 02:11:08 +0000565///
Chris Lattnerd501c132003-02-26 19:41:54 +0000566AliasAnalysis::AliasResult
Chris Lattner539c9b92009-11-26 02:11:08 +0000567BasicAliasAnalysis::aliasGEP(const GEPOperator *GEP1, unsigned V1Size,
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000568 const Value *V2, unsigned V2Size,
569 const Value *UnderlyingV1,
570 const Value *UnderlyingV2) {
Chris Lattnerd84eb912009-11-26 02:17:34 +0000571 int64_t GEP1BaseOffset;
572 SmallVector<std::pair<const Value*, int64_t>, 4> GEP1VariableIndices;
573
Chris Lattnerb307c882003-12-11 22:44:13 +0000574 // If we have two gep instructions with must-alias'ing base pointers, figure
575 // out if the indexes to the GEP tell us anything about the derived pointer.
Chris Lattner539c9b92009-11-26 02:11:08 +0000576 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
Chris Lattnerb307c882003-12-11 22:44:13 +0000577 // Do the base pointers alias?
Chris Lattnerd84eb912009-11-26 02:17:34 +0000578 AliasResult BaseAlias = aliasCheck(UnderlyingV1, ~0U, UnderlyingV2, ~0U);
579
580 // If we get a No or May, then return it immediately, no amount of analysis
581 // will improve this situation.
582 if (BaseAlias != MustAlias) return BaseAlias;
583
584 // Otherwise, we have a MustAlias. Since the base pointers alias each other
585 // exactly, see if the computed offset from the common pointer tells us
586 // about the relation of the resulting pointer.
587 const Value *GEP1BasePtr =
588 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
589
590 int64_t GEP2BaseOffset;
591 SmallVector<std::pair<const Value*, int64_t>, 4> GEP2VariableIndices;
592 const Value *GEP2BasePtr =
593 DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices, TD);
594
595 // If DecomposeGEPExpression isn't able to look all the way through the
596 // addressing operation, we must not have TD and this is too complex for us
597 // to handle without it.
598 if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
599 assert(TD == 0 &&
600 "DecomposeGEPExpression and getUnderlyingObject disagree!");
601 return MayAlias;
602 }
603
604 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
605 // symbolic difference.
606 GEP1BaseOffset -= GEP2BaseOffset;
607 GetIndiceDifference(GEP1VariableIndices, GEP2VariableIndices);
608
609 } else {
610 // Check to see if these two pointers are related by the getelementptr
611 // instruction. If one pointer is a GEP with a non-zero index of the other
612 // pointer, we know they cannot alias.
613 //
614 // FIXME: The check below only looks at the size of one of the pointers, not
615 // both, this may cause us to miss things.
616 if (V1Size == ~0U || V2Size == ~0U)
617 return MayAlias;
Chris Lattnerb307c882003-12-11 22:44:13 +0000618
Chris Lattnerd84eb912009-11-26 02:17:34 +0000619 AliasResult R = aliasCheck(UnderlyingV1, ~0U, V2, V2Size);
620 if (R != MustAlias)
621 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
622 // If V2 is known not to alias GEP base pointer, then the two values
623 // cannot alias per GEP semantics: "A pointer value formed from a
624 // getelementptr instruction is associated with the addresses associated
625 // with the first operand of the getelementptr".
626 return R;
Chris Lattnerb307c882003-12-11 22:44:13 +0000627
Chris Lattnerd84eb912009-11-26 02:17:34 +0000628 const Value *GEP1BasePtr =
629 DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices, TD);
630
631 // If DecomposeGEPExpression isn't able to look all the way through the
632 // addressing operation, we must not have TD and this is too complex for us
633 // to handle without it.
634 if (GEP1BasePtr != UnderlyingV1) {
635 assert(TD == 0 &&
636 "DecomposeGEPExpression and getUnderlyingObject disagree!");
637 return MayAlias;
Chris Lattnerb307c882003-12-11 22:44:13 +0000638 }
639 }
Chris Lattnerd84eb912009-11-26 02:17:34 +0000640
641 // In the two GEP Case, if there is no difference in the offsets of the
642 // computed pointers, the resultant pointers are a must alias. This
643 // hapens when we have two lexically identical GEP's (for example).
Chris Lattnerd501c132003-02-26 19:41:54 +0000644 //
Chris Lattnerd84eb912009-11-26 02:17:34 +0000645 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
646 // must aliases the GEP, the end result is a must alias also.
647 if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
Evan Cheng681a33e2009-10-14 06:41:49 +0000648 return MustAlias;
Evan Cheng094f04b2009-10-13 18:42:04 +0000649
Chris Lattner4e91ee72009-11-26 02:13:03 +0000650 // If we have a known constant offset, see if this offset is larger than the
651 // access size being queried. If so, and if no variable indices can remove
652 // pieces of this constant, then we know we have a no-alias. For example,
653 // &A[100] != &A.
654
655 // In order to handle cases like &A[100][i] where i is an out of range
656 // subscript, we have to ignore all constant offset pieces that are a multiple
657 // of a scaled index. Do this by removing constant offsets that are a
658 // multiple of any of our variable indices. This allows us to transform
659 // things like &A[i][1] because i has a stride of (e.g.) 8 bytes but the 1
660 // provides an offset of 4 bytes (assuming a <= 4 byte access).
Chris Lattnerd84eb912009-11-26 02:17:34 +0000661 for (unsigned i = 0, e = GEP1VariableIndices.size();
662 i != e && GEP1BaseOffset;++i)
663 if (int64_t RemovedOffset = GEP1BaseOffset/GEP1VariableIndices[i].second)
664 GEP1BaseOffset -= RemovedOffset*GEP1VariableIndices[i].second;
Chris Lattner4e91ee72009-11-26 02:13:03 +0000665
666 // If our known offset is bigger than the access size, we know we don't have
667 // an alias.
668 if (GEP1BaseOffset) {
669 if (GEP1BaseOffset >= (int64_t)V2Size ||
670 GEP1BaseOffset <= -(int64_t)V1Size)
Evan Cheng681a33e2009-10-14 06:41:49 +0000671 return NoAlias;
Evan Cheng094f04b2009-10-13 18:42:04 +0000672 }
Chris Lattner4e91ee72009-11-26 02:13:03 +0000673
Evan Cheng094f04b2009-10-13 18:42:04 +0000674 return MayAlias;
675}
676
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000677/// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
678/// instruction against another.
Dan Gohman6665b0e2009-10-26 21:55:43 +0000679AliasAnalysis::AliasResult
680BasicAliasAnalysis::aliasSelect(const SelectInst *SI, unsigned SISize,
681 const Value *V2, unsigned V2Size) {
682 // If the values are Selects with the same condition, we can do a more precise
683 // check: just check for aliases between the values on corresponding arms.
684 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
685 if (SI->getCondition() == SI2->getCondition()) {
686 AliasResult Alias =
687 aliasCheck(SI->getTrueValue(), SISize,
688 SI2->getTrueValue(), V2Size);
689 if (Alias == MayAlias)
690 return MayAlias;
691 AliasResult ThisAlias =
692 aliasCheck(SI->getFalseValue(), SISize,
693 SI2->getFalseValue(), V2Size);
694 if (ThisAlias != Alias)
695 return MayAlias;
696 return Alias;
697 }
698
699 // If both arms of the Select node NoAlias or MustAlias V2, then returns
700 // NoAlias / MustAlias. Otherwise, returns MayAlias.
701 AliasResult Alias =
702 aliasCheck(SI->getTrueValue(), SISize, V2, V2Size);
703 if (Alias == MayAlias)
704 return MayAlias;
705 AliasResult ThisAlias =
706 aliasCheck(SI->getFalseValue(), SISize, V2, V2Size);
707 if (ThisAlias != Alias)
708 return MayAlias;
709 return Alias;
710}
711
Evan Chengd83c2ca2009-10-14 05:22:03 +0000712// aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000713// against another.
Evan Cheng50a59142009-10-13 22:02:20 +0000714AliasAnalysis::AliasResult
Evan Chengd83c2ca2009-10-14 05:22:03 +0000715BasicAliasAnalysis::aliasPHI(const PHINode *PN, unsigned PNSize,
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000716 const Value *V2, unsigned V2Size) {
Evan Cheng50a59142009-10-13 22:02:20 +0000717 // The PHI node has already been visited, avoid recursion any further.
Evan Chengd83c2ca2009-10-14 05:22:03 +0000718 if (!VisitedPHIs.insert(PN))
Evan Cheng50a59142009-10-13 22:02:20 +0000719 return MayAlias;
720
Dan Gohman6665b0e2009-10-26 21:55:43 +0000721 // If the values are PHIs in the same block, we can do a more precise
722 // as well as efficient check: just check for aliases between the values
723 // on corresponding edges.
724 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
725 if (PN2->getParent() == PN->getParent()) {
726 AliasResult Alias =
727 aliasCheck(PN->getIncomingValue(0), PNSize,
728 PN2->getIncomingValueForBlock(PN->getIncomingBlock(0)),
729 V2Size);
730 if (Alias == MayAlias)
731 return MayAlias;
732 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
733 AliasResult ThisAlias =
734 aliasCheck(PN->getIncomingValue(i), PNSize,
735 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
736 V2Size);
737 if (ThisAlias != Alias)
738 return MayAlias;
739 }
740 return Alias;
741 }
742
Evan Chenga846a8a2009-10-16 00:33:09 +0000743 SmallPtrSet<Value*, 4> UniqueSrc;
Evan Cheng50a59142009-10-13 22:02:20 +0000744 SmallVector<Value*, 4> V1Srcs;
Evan Cheng50a59142009-10-13 22:02:20 +0000745 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
746 Value *PV1 = PN->getIncomingValue(i);
747 if (isa<PHINode>(PV1))
748 // If any of the source itself is a PHI, return MayAlias conservatively
Evan Cheng681a33e2009-10-14 06:41:49 +0000749 // to avoid compile time explosion. The worst possible case is if both
750 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
751 // and 'n' are the number of PHI sources.
Evan Cheng50a59142009-10-13 22:02:20 +0000752 return MayAlias;
753 if (UniqueSrc.insert(PV1))
754 V1Srcs.push_back(PV1);
755 }
756
Dan Gohman6665b0e2009-10-26 21:55:43 +0000757 AliasResult Alias = aliasCheck(V2, V2Size, V1Srcs[0], PNSize);
Evan Chengd83c2ca2009-10-14 05:22:03 +0000758 // Early exit if the check of the first PHI source against V2 is MayAlias.
759 // Other results are not possible.
760 if (Alias == MayAlias)
761 return MayAlias;
762
Evan Cheng50a59142009-10-13 22:02:20 +0000763 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
764 // NoAlias / MustAlias. Otherwise, returns MayAlias.
Evan Cheng50a59142009-10-13 22:02:20 +0000765 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
766 Value *V = V1Srcs[i];
Dan Gohman6665b0e2009-10-26 21:55:43 +0000767
768 // If V2 is a PHI, the recursive case will have been caught in the
769 // above aliasCheck call, so these subsequent calls to aliasCheck
770 // don't need to assume that V2 is being visited recursively.
771 VisitedPHIs.erase(V2);
772
Evan Chenga846a8a2009-10-16 00:33:09 +0000773 AliasResult ThisAlias = aliasCheck(V2, V2Size, V, PNSize);
Evan Chengd83c2ca2009-10-14 05:22:03 +0000774 if (ThisAlias != Alias || ThisAlias == MayAlias)
Evan Cheng50a59142009-10-13 22:02:20 +0000775 return MayAlias;
776 }
777
778 return Alias;
779}
780
781// aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
782// such as array references.
Evan Cheng094f04b2009-10-13 18:42:04 +0000783//
784AliasAnalysis::AliasResult
Evan Cheng50a59142009-10-13 22:02:20 +0000785BasicAliasAnalysis::aliasCheck(const Value *V1, unsigned V1Size,
Evan Cheng3dbe43b2009-10-14 05:05:02 +0000786 const Value *V2, unsigned V2Size) {
Evan Cheng094f04b2009-10-13 18:42:04 +0000787 // Strip off any casts if they exist.
788 V1 = V1->stripPointerCasts();
789 V2 = V2->stripPointerCasts();
790
791 // Are we checking for alias of the same value?
792 if (V1 == V2) return MustAlias;
793
794 if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
795 return NoAlias; // Scalars cannot alias each other
796
797 // Figure out what objects these things are pointing to if we can.
798 const Value *O1 = V1->getUnderlyingObject();
799 const Value *O2 = V2->getUnderlyingObject();
800
Dan Gohmanf75ef662009-11-09 19:29:11 +0000801 // Null values in the default address space don't point to any object, so they
802 // don't alias any other pointer.
803 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
804 if (CPN->getType()->getAddressSpace() == 0)
805 return NoAlias;
806 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
807 if (CPN->getType()->getAddressSpace() == 0)
808 return NoAlias;
809
Evan Cheng094f04b2009-10-13 18:42:04 +0000810 if (O1 != O2) {
811 // If V1/V2 point to two different objects we know that we have no alias.
812 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
813 return NoAlias;
Nick Lewycky20162ac2009-11-14 06:15:14 +0000814
815 // Constant pointers can't alias with non-const isIdentifiedObject objects.
816 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
817 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
818 return NoAlias;
819
Evan Cheng094f04b2009-10-13 18:42:04 +0000820 // Arguments can't alias with local allocations or noalias calls.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000821 if ((isa<Argument>(O1) && (isa<AllocaInst>(O2) || isNoAliasCall(O2))) ||
822 (isa<Argument>(O2) && (isa<AllocaInst>(O1) || isNoAliasCall(O1))))
Evan Cheng094f04b2009-10-13 18:42:04 +0000823 return NoAlias;
824
825 // Most objects can't alias null.
826 if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
827 (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
828 return NoAlias;
829 }
830
831 // If the size of one access is larger than the entire object on the other
832 // side, then we know such behavior is undefined and can assume no alias.
Evan Cheng094f04b2009-10-13 18:42:04 +0000833 if (TD)
Chris Lattner7b550cc2009-11-06 04:27:31 +0000834 if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, *TD)) ||
835 (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, *TD)))
Evan Cheng094f04b2009-10-13 18:42:04 +0000836 return NoAlias;
837
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000838 // If one pointer is the result of a call/invoke or load and the other is a
Evan Cheng094f04b2009-10-13 18:42:04 +0000839 // non-escaping local object, then we know the object couldn't escape to a
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000840 // point where the call could return it. The load case works because
841 // isNonEscapingLocalObject considers all stores to be escapes (it
842 // passes true for the StoreCaptures argument to PointerMayBeCaptured).
843 if (O1 != O2) {
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000844 if ((isa<CallInst>(O1) || isa<InvokeInst>(O1) || isa<LoadInst>(O1) ||
Chris Lattner403ac2e2009-11-23 16:46:41 +0000845 isa<Argument>(O1)) &&
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000846 isNonEscapingLocalObject(O2))
847 return NoAlias;
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000848 if ((isa<CallInst>(O2) || isa<InvokeInst>(O2) || isa<LoadInst>(O2) ||
Chris Lattner403ac2e2009-11-23 16:46:41 +0000849 isa<Argument>(O2)) &&
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000850 isNonEscapingLocalObject(O1))
851 return NoAlias;
852 }
Evan Cheng094f04b2009-10-13 18:42:04 +0000853
Chris Lattner4e91ee72009-11-26 02:13:03 +0000854 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
855 // GEP can't simplify, we don't even look at the PHI cases.
Chris Lattner391d23b2009-10-17 23:48:54 +0000856 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
Chris Lattnerd501c132003-02-26 19:41:54 +0000857 std::swap(V1, V2);
858 std::swap(V1Size, V2Size);
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000859 std::swap(O1, O2);
Chris Lattnerd501c132003-02-26 19:41:54 +0000860 }
Chris Lattner539c9b92009-11-26 02:11:08 +0000861 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1))
Chris Lattner23e2a5b2009-11-26 02:14:59 +0000862 return aliasGEP(GV1, V1Size, V2, V2Size, O1, O2);
Evan Cheng50a59142009-10-13 22:02:20 +0000863
864 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
865 std::swap(V1, V2);
866 std::swap(V1Size, V2Size);
867 }
Evan Chengd83c2ca2009-10-14 05:22:03 +0000868 if (const PHINode *PN = dyn_cast<PHINode>(V1))
869 return aliasPHI(PN, V1Size, V2, V2Size);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000870
Dan Gohman6665b0e2009-10-26 21:55:43 +0000871 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
872 std::swap(V1, V2);
873 std::swap(V1Size, V2Size);
874 }
875 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1))
876 return aliasSelect(S1, V1Size, V2, V2Size);
877
Chris Lattnerd501c132003-02-26 19:41:54 +0000878 return MayAlias;
879}
880
Chris Lattner5d56b2d2009-11-23 16:45:27 +0000881// Make sure that anything that uses AliasAnalysis pulls in this file.
Reid Spencer4f1bd9e2006-06-07 22:00:26 +0000882DEFINING_FILE_FOR(BasicAliasAnalysis)