blob: dcb5903a14e696c1ca02663bfaa81c57444dc200 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
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 Sandsb233fb52009-01-18 12:19:30 +000017#include "llvm/Analysis/CaptureTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018#include "llvm/Analysis/Passes.h"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
22#include "llvm/GlobalVariable.h"
23#include "llvm/Instructions.h"
Owen Anderson37f3ffb2008-02-17 21:29:08 +000024#include "llvm/IntrinsicInst.h"
Owen Andersond4d90a02009-07-06 18:42:36 +000025#include "llvm/LLVMContext.h"
Dan Gohmanb9010bc2009-07-17 22:25:10 +000026#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/Pass.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/ADT/SmallVector.h"
Owen Anderson1636de92007-09-07 04:06:50 +000030#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Support/Compiler.h"
Edwin Török675d5622009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include <algorithm>
35using namespace llvm;
36
Chris Lattner21c4fd12008-06-16 06:30:22 +000037//===----------------------------------------------------------------------===//
38// Useful predicates
39//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041static const User *isGEP(const Value *V) {
Dan Gohmanb9010bc2009-07-17 22:25:10 +000042 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
43 // For the purposes of BasicAliasAnalysis, if the GEP has overflow it
44 // could do crazy things.
45 if (GEP->hasNoPointerOverflow())
46 return GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047 return 0;
48}
49
50static const Value *GetGEPOperands(const Value *V,
Chris Lattner2d34c6c2008-12-10 01:04:47 +000051 SmallVector<Value*, 16> &GEPOps) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052 assert(GEPOps.empty() && "Expect empty list to populate!");
53 GEPOps.insert(GEPOps.end(), cast<User>(V)->op_begin()+1,
54 cast<User>(V)->op_end());
55
56 // Accumulate all of the chained indexes into the operand array
57 V = cast<User>(V)->getOperand(0);
58
59 while (const User *G = isGEP(V)) {
60 if (!isa<Constant>(GEPOps[0]) || isa<GlobalValue>(GEPOps[0]) ||
61 !cast<Constant>(GEPOps[0])->isNullValue())
62 break; // Don't handle folding arbitrary pointer offsets yet...
63 GEPOps.erase(GEPOps.begin()); // Drop the zero index
64 GEPOps.insert(GEPOps.begin(), G->op_begin()+1, G->op_end());
65 V = G->getOperand(0);
66 }
67 return V;
68}
69
Chris Lattnerfc2026e2008-06-16 06:10:11 +000070/// isKnownNonNull - Return true if we know that the specified value is never
71/// null.
72static bool isKnownNonNull(const Value *V) {
73 // Alloca never returns null, malloc might.
74 if (isa<AllocaInst>(V)) return true;
75
76 // A byval argument is never null.
77 if (const Argument *A = dyn_cast<Argument>(V))
78 return A->hasByValAttr();
79
80 // Global values are not null unless extern weak.
81 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
82 return !GV->hasExternalWeakLinkage();
83 return false;
84}
85
Chris Lattnerd26e5d82008-06-16 06:19:11 +000086/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
87/// object that never escapes from the function.
88static bool isNonEscapingLocalObject(const Value *V) {
Chris Lattner7ce67392008-06-16 06:28:01 +000089 // If this is a local allocation, check to see if it escapes.
Nick Lewyckyff384472008-11-24 03:41:24 +000090 if (isa<AllocationInst>(V) || isNoAliasCall(V))
Duncan Sandsb233fb52009-01-18 12:19:30 +000091 return !PointerMayBeCaptured(V, false);
Duncan Sands75378432009-01-05 21:19:53 +000092
Chris Lattner7ce67392008-06-16 06:28:01 +000093 // If this is an argument that corresponds to a byval or noalias argument,
Duncan Sands75378432009-01-05 21:19:53 +000094 // then it has not escaped before entering the function. Check if it escapes
95 // inside the function.
Chris Lattner7ce67392008-06-16 06:28:01 +000096 if (const Argument *A = dyn_cast<Argument>(V))
Duncan Sands75378432009-01-05 21:19:53 +000097 if (A->hasByValAttr() || A->hasNoAliasAttr()) {
98 // Don't bother analyzing arguments already known not to escape.
99 if (A->hasNoCaptureAttr())
100 return true;
Duncan Sandsb233fb52009-01-18 12:19:30 +0000101 return !PointerMayBeCaptured(V, false);
Duncan Sands75378432009-01-05 21:19:53 +0000102 }
Chris Lattnerd26e5d82008-06-16 06:19:11 +0000103 return false;
104}
105
106
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000107/// isObjectSmallerThan - Return true if we can prove that the object specified
108/// by V is smaller than Size.
109static bool isObjectSmallerThan(const Value *V, unsigned Size,
110 const TargetData &TD) {
Chris Lattner194ae9d2008-12-08 06:28:54 +0000111 const Type *AccessTy;
112 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000113 AccessTy = GV->getType()->getElementType();
Chris Lattner194ae9d2008-12-08 06:28:54 +0000114 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000115 if (!AI->isArrayAllocation())
116 AccessTy = AI->getType()->getElementType();
Chris Lattner194ae9d2008-12-08 06:28:54 +0000117 else
118 return false;
119 } else if (const Argument *A = dyn_cast<Argument>(V)) {
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000120 if (A->hasByValAttr())
121 AccessTy = cast<PointerType>(A->getType())->getElementType();
Chris Lattner194ae9d2008-12-08 06:28:54 +0000122 else
123 return false;
124 } else {
125 return false;
126 }
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000127
Chris Lattner194ae9d2008-12-08 06:28:54 +0000128 if (AccessTy->isSized())
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000129 return TD.getTypeAllocSize(AccessTy) < Size;
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000130 return false;
131}
132
Chris Lattner21c4fd12008-06-16 06:30:22 +0000133//===----------------------------------------------------------------------===//
134// NoAA Pass
135//===----------------------------------------------------------------------===//
136
137namespace {
138 /// NoAA - This class implements the -no-aa pass, which always returns "I
139 /// don't know" for alias queries. NoAA is unlike other alias analysis
140 /// implementations, in that it does not chain to a previous analysis. As
141 /// such it doesn't follow many of the rules that other alias analyses must.
142 ///
143 struct VISIBILITY_HIDDEN NoAA : public ImmutablePass, public AliasAnalysis {
144 static char ID; // Class identification, replacement for typeinfo
Dan Gohman26f8c272008-09-04 17:05:41 +0000145 NoAA() : ImmutablePass(&ID) {}
146 explicit NoAA(void *PID) : ImmutablePass(PID) { }
Chris Lattner21c4fd12008-06-16 06:30:22 +0000147
148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
149 AU.addRequired<TargetData>();
150 }
151
152 virtual void initializePass() {
153 TD = &getAnalysis<TargetData>();
154 }
155
156 virtual AliasResult alias(const Value *V1, unsigned V1Size,
157 const Value *V2, unsigned V2Size) {
158 return MayAlias;
159 }
160
Chris Lattner21c4fd12008-06-16 06:30:22 +0000161 virtual void getArgumentAccesses(Function *F, CallSite CS,
162 std::vector<PointerAccessInfo> &Info) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000163 llvm_unreachable("This method may not be called on this function!");
Chris Lattner21c4fd12008-06-16 06:30:22 +0000164 }
165
166 virtual void getMustAliases(Value *P, std::vector<Value*> &RetVals) { }
167 virtual bool pointsToConstantMemory(const Value *P) { return false; }
168 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
169 return ModRef;
170 }
171 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
172 return ModRef;
173 }
174 virtual bool hasNoModRefInfoForCalls() const { return true; }
175
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.
199 struct VISIBILITY_HIDDEN BasicAliasAnalysis : public NoAA {
200 static char ID; // Class identification, replacement for typeinfo
Dan Gohman26f8c272008-09-04 17:05:41 +0000201 BasicAliasAnalysis() : NoAA(&ID) {}
Chris Lattner21c4fd12008-06-16 06:30:22 +0000202 AliasResult alias(const Value *V1, unsigned V1Size,
203 const Value *V2, unsigned V2Size);
204
205 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
Chris Lattner7e0f4462008-12-09 21:19:42 +0000206 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
Owen Andersonab465642009-02-05 23:36:27 +0000207
Chris Lattner21c4fd12008-06-16 06:30:22 +0000208 /// hasNoModRefInfoForCalls - We can provide mod/ref information against
209 /// non-escaping allocations.
210 virtual bool hasNoModRefInfoForCalls() const { return false; }
211
212 /// pointsToConstantMemory - Chase pointers until we find a (constant
213 /// global) or not.
214 bool pointsToConstantMemory(const Value *P);
215
216 private:
217 // CheckGEPInstructions - Check two GEP instructions with known
218 // must-aliasing base pointers. This checks to see if the index expressions
219 // preclude the pointers from aliasing...
220 AliasResult
221 CheckGEPInstructions(const Type* BasePtr1Ty,
222 Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size,
223 const Type *BasePtr2Ty,
224 Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size);
225 };
226} // End of anonymous namespace
227
228// Register this pass...
229char BasicAliasAnalysis::ID = 0;
230static RegisterPass<BasicAliasAnalysis>
231X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
232
233// Declare that we implement the AliasAnalysis interface
234static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
235
236ImmutablePass *llvm::createBasicAliasAnalysisPass() {
237 return new BasicAliasAnalysis();
238}
239
240
241/// pointsToConstantMemory - Chase pointers until we find a (constant
242/// global) or not.
243bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
244 if (const GlobalVariable *GV =
Duncan Sands52fb8732008-10-01 15:25:41 +0000245 dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
Chris Lattner21c4fd12008-06-16 06:30:22 +0000246 return GV->isConstant();
247 return false;
248}
249
Owen Andersonab465642009-02-05 23:36:27 +0000250
Chris Lattner21c4fd12008-06-16 06:30:22 +0000251// getModRefInfo - Check to see if the specified callsite can clobber the
252// specified memory object. Since we only look at local properties of this
253// function, we really can't say much about this query. We do, however, use
254// simple "address taken" analysis on local objects.
255//
256AliasAnalysis::ModRefResult
257BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
258 if (!isa<Constant>(P)) {
Duncan Sands52fb8732008-10-01 15:25:41 +0000259 const Value *Object = P->getUnderlyingObject();
Chris Lattner21c4fd12008-06-16 06:30:22 +0000260
261 // If this is a tail call and P points to a stack location, we know that
262 // the tail call cannot access or modify the local stack.
263 // We cannot exclude byval arguments here; these belong to the caller of
264 // the current function not to the current function, and a tail callee
265 // may reference them.
266 if (isa<AllocaInst>(Object))
267 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
268 if (CI->isTailCall())
269 return NoModRef;
270
Chris Lattnerb46b9752008-06-16 06:38:26 +0000271 // If the pointer is to a locally allocated object that does not escape,
272 // then the call can not mod/ref the pointer unless the call takes the
273 // argument without capturing it.
Nick Lewyckydf872b82009-02-13 07:06:27 +0000274 if (isNonEscapingLocalObject(Object) && CS.getInstruction() != Object) {
Chris Lattnerb46b9752008-06-16 06:38:26 +0000275 bool passedAsArg = false;
276 // TODO: Eventually only check 'nocapture' arguments.
277 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
278 CI != CE; ++CI)
279 if (isa<PointerType>((*CI)->getType()) &&
280 alias(cast<Value>(CI), ~0U, P, ~0U) != NoAlias)
281 passedAsArg = true;
282
283 if (!passedAsArg)
284 return NoModRef;
Chris Lattner21c4fd12008-06-16 06:30:22 +0000285 }
286 }
287
288 // The AliasAnalysis base class has some smarts, lets use them.
289 return AliasAnalysis::getModRefInfo(CS, P, Size);
290}
291
292
Chris Lattner7e0f4462008-12-09 21:19:42 +0000293AliasAnalysis::ModRefResult
294BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
295 // If CS1 or CS2 are readnone, they don't interact.
296 ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
297 if (CS1B == DoesNotAccessMemory) return NoModRef;
298
299 ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
300 if (CS2B == DoesNotAccessMemory) return NoModRef;
301
302 // If they both only read from memory, just return ref.
303 if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
304 return Ref;
305
306 // Otherwise, fall back to NoAA (mod+ref).
307 return NoAA::getModRefInfo(CS1, CS2);
308}
309
310
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311// alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such
Chris Lattner2d34c6c2008-12-10 01:04:47 +0000312// as array references.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313//
314AliasAnalysis::AliasResult
315BasicAliasAnalysis::alias(const Value *V1, unsigned V1Size,
316 const Value *V2, unsigned V2Size) {
Owen Andersone1f1f822009-07-16 18:04:31 +0000317 Context = &V1->getType()->getContext();
318
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 // Strip off any constant expression casts if they exist
320 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V1))
321 if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType()))
322 V1 = CE->getOperand(0);
323 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V2))
324 if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType()))
325 V2 = CE->getOperand(0);
326
327 // Are we checking for alias of the same value?
328 if (V1 == V2) return MustAlias;
329
Nick Lewyckyff384472008-11-24 03:41:24 +0000330 if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 return NoAlias; // Scalars cannot alias each other
332
Chris Lattner2d34c6c2008-12-10 01:04:47 +0000333 // Strip off cast instructions. Since V1 and V2 are pointers, they must be
334 // pointer<->pointer bitcasts.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 if (const BitCastInst *I = dyn_cast<BitCastInst>(V1))
336 return alias(I->getOperand(0), V1Size, V2, V2Size);
337 if (const BitCastInst *I = dyn_cast<BitCastInst>(V2))
338 return alias(V1, V1Size, I->getOperand(0), V2Size);
339
Chris Lattner2d34c6c2008-12-10 01:04:47 +0000340 // Figure out what objects these things are pointing to if we can.
Duncan Sands52fb8732008-10-01 15:25:41 +0000341 const Value *O1 = V1->getUnderlyingObject();
342 const Value *O2 = V2->getUnderlyingObject();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000344 if (O1 != O2) {
345 // If V1/V2 point to two different objects we know that we have no alias.
346 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
347 return NoAlias;
348
Nick Lewyckya604a942008-11-24 05:00:44 +0000349 // Arguments can't alias with local allocations or noalias calls.
350 if ((isa<Argument>(O1) && (isa<AllocationInst>(O2) || isNoAliasCall(O2))) ||
351 (isa<Argument>(O2) && (isa<AllocationInst>(O1) || isNoAliasCall(O1))))
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000352 return NoAlias;
Nick Lewyckyff384472008-11-24 03:41:24 +0000353
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000354 // Most objects can't alias null.
355 if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
356 (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
357 return NoAlias;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358 }
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000359
360 // If the size of one access is larger than the entire object on the other
361 // side, then we know such behavior is undefined and can assume no alias.
362 const TargetData &TD = getTargetData();
363 if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, TD)) ||
364 (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, TD)))
365 return NoAlias;
366
Chris Lattnerd26e5d82008-06-16 06:19:11 +0000367 // If one pointer is the result of a call/invoke and the other is a
368 // non-escaping local object, then we know the object couldn't escape to a
369 // point where the call could return it.
370 if ((isa<CallInst>(O1) || isa<InvokeInst>(O1)) &&
Nick Lewyckydf872b82009-02-13 07:06:27 +0000371 isNonEscapingLocalObject(O2) && O1 != O2)
Chris Lattnerd26e5d82008-06-16 06:19:11 +0000372 return NoAlias;
373 if ((isa<CallInst>(O2) || isa<InvokeInst>(O2)) &&
Nick Lewyckydf872b82009-02-13 07:06:27 +0000374 isNonEscapingLocalObject(O1) && O1 != O2)
Chris Lattnerd26e5d82008-06-16 06:19:11 +0000375 return NoAlias;
Chris Lattnerfc2026e2008-06-16 06:10:11 +0000376
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 // If we have two gep instructions with must-alias'ing base pointers, figure
378 // out if the indexes to the GEP tell us anything about the derived pointer.
379 // Note that we also handle chains of getelementptr instructions as well as
380 // constant expression getelementptrs here.
381 //
382 if (isGEP(V1) && isGEP(V2)) {
Chris Lattner2d34c6c2008-12-10 01:04:47 +0000383 const User *GEP1 = cast<User>(V1);
384 const User *GEP2 = cast<User>(V2);
385
386 // If V1 and V2 are identical GEPs, just recurse down on both of them.
387 // This allows us to analyze things like:
388 // P = gep A, 0, i, 1
389 // Q = gep B, 0, i, 1
390 // by just analyzing A and B. This is even safe for variable indices.
391 if (GEP1->getType() == GEP2->getType() &&
392 GEP1->getNumOperands() == GEP2->getNumOperands() &&
393 GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() &&
394 // All operands are the same, ignoring the base.
395 std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
396 return alias(GEP1->getOperand(0), V1Size, GEP2->getOperand(0), V2Size);
397
398
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 // Drill down into the first non-gep value, to test for must-aliasing of
400 // the base pointers.
Chris Lattner2d34c6c2008-12-10 01:04:47 +0000401 while (isGEP(GEP1->getOperand(0)) &&
402 GEP1->getOperand(1) ==
Owen Andersond4d90a02009-07-06 18:42:36 +0000403 Context->getNullValue(GEP1->getOperand(1)->getType()))
Chris Lattner2d34c6c2008-12-10 01:04:47 +0000404 GEP1 = cast<User>(GEP1->getOperand(0));
405 const Value *BasePtr1 = GEP1->getOperand(0);
Wojciech Matyjewicz170707f2007-12-13 16:22:58 +0000406
Chris Lattner2d34c6c2008-12-10 01:04:47 +0000407 while (isGEP(GEP2->getOperand(0)) &&
408 GEP2->getOperand(1) ==
Owen Andersond4d90a02009-07-06 18:42:36 +0000409 Context->getNullValue(GEP2->getOperand(1)->getType()))
Chris Lattner2d34c6c2008-12-10 01:04:47 +0000410 GEP2 = cast<User>(GEP2->getOperand(0));
411 const Value *BasePtr2 = GEP2->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412
413 // Do the base pointers alias?
414 AliasResult BaseAlias = alias(BasePtr1, ~0U, BasePtr2, ~0U);
415 if (BaseAlias == NoAlias) return NoAlias;
416 if (BaseAlias == MustAlias) {
417 // If the base pointers alias each other exactly, check to see if we can
418 // figure out anything about the resultant pointers, to try to prove
419 // non-aliasing.
420
421 // Collect all of the chained GEP operands together into one simple place
422 SmallVector<Value*, 16> GEP1Ops, GEP2Ops;
423 BasePtr1 = GetGEPOperands(V1, GEP1Ops);
424 BasePtr2 = GetGEPOperands(V2, GEP2Ops);
425
426 // If GetGEPOperands were able to fold to the same must-aliased pointer,
427 // do the comparison.
428 if (BasePtr1 == BasePtr2) {
429 AliasResult GAlias =
430 CheckGEPInstructions(BasePtr1->getType(),
431 &GEP1Ops[0], GEP1Ops.size(), V1Size,
432 BasePtr2->getType(),
433 &GEP2Ops[0], GEP2Ops.size(), V2Size);
434 if (GAlias != MayAlias)
435 return GAlias;
436 }
437 }
438 }
439
440 // Check to see if these two pointers are related by a getelementptr
441 // instruction. If one pointer is a GEP with a non-zero index of the other
442 // pointer, we know they cannot alias.
443 //
444 if (isGEP(V2)) {
445 std::swap(V1, V2);
446 std::swap(V1Size, V2Size);
447 }
448
449 if (V1Size != ~0U && V2Size != ~0U)
450 if (isGEP(V1)) {
451 SmallVector<Value*, 16> GEPOperands;
452 const Value *BasePtr = GetGEPOperands(V1, GEPOperands);
453
454 AliasResult R = alias(BasePtr, V1Size, V2, V2Size);
455 if (R == MustAlias) {
456 // If there is at least one non-zero constant index, we know they cannot
457 // alias.
458 bool ConstantFound = false;
459 bool AllZerosFound = true;
460 for (unsigned i = 0, e = GEPOperands.size(); i != e; ++i)
461 if (const Constant *C = dyn_cast<Constant>(GEPOperands[i])) {
462 if (!C->isNullValue()) {
463 ConstantFound = true;
464 AllZerosFound = false;
465 break;
466 }
467 } else {
468 AllZerosFound = false;
469 }
470
471 // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
472 // the ptr, the end result is a must alias also.
473 if (AllZerosFound)
474 return MustAlias;
475
476 if (ConstantFound) {
477 if (V2Size <= 1 && V1Size <= 1) // Just pointer check?
478 return NoAlias;
479
480 // Otherwise we have to check to see that the distance is more than
481 // the size of the argument... build an index vector that is equal to
482 // the arguments provided, except substitute 0's for any variable
483 // indexes we find...
484 if (cast<PointerType>(
485 BasePtr->getType())->getElementType()->isSized()) {
486 for (unsigned i = 0; i != GEPOperands.size(); ++i)
487 if (!isa<ConstantInt>(GEPOperands[i]))
488 GEPOperands[i] =
Owen Andersond4d90a02009-07-06 18:42:36 +0000489 Context->getNullValue(GEPOperands[i]->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000490 int64_t Offset =
491 getTargetData().getIndexedOffset(BasePtr->getType(),
492 &GEPOperands[0],
493 GEPOperands.size());
494
495 if (Offset >= (int64_t)V2Size || Offset <= -(int64_t)V1Size)
496 return NoAlias;
497 }
498 }
499 }
500 }
501
502 return MayAlias;
503}
504
Duncan Sandsa52b7542008-12-08 14:01:59 +0000505// This function is used to determine if the indices of two GEP instructions are
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506// equal. V1 and V2 are the indices.
Owen Anderson5349f052009-07-06 23:00:19 +0000507static bool IndexOperandsEqual(Value *V1, Value *V2, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000508 if (V1->getType() == V2->getType())
509 return V1 == V2;
510 if (Constant *C1 = dyn_cast<Constant>(V1))
511 if (Constant *C2 = dyn_cast<Constant>(V2)) {
512 // Sign extend the constants to long types, if necessary
513 if (C1->getType() != Type::Int64Ty)
Owen Andersond4d90a02009-07-06 18:42:36 +0000514 C1 = Context->getConstantExprSExt(C1, Type::Int64Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000515 if (C2->getType() != Type::Int64Ty)
Owen Andersond4d90a02009-07-06 18:42:36 +0000516 C2 = Context->getConstantExprSExt(C2, Type::Int64Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 return C1 == C2;
518 }
519 return false;
520}
521
522/// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
523/// base pointers. This checks to see if the index expressions preclude the
524/// pointers from aliasing...
525AliasAnalysis::AliasResult
526BasicAliasAnalysis::CheckGEPInstructions(
527 const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S,
528 const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) {
529 // We currently can't handle the case when the base pointers have different
530 // primitive types. Since this is uncommon anyway, we are happy being
531 // extremely conservative.
532 if (BasePtr1Ty != BasePtr2Ty)
533 return MayAlias;
534
535 const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty);
536
Owen Andersone1f1f822009-07-16 18:04:31 +0000537 Context = &GEPPointerTy->getContext();
538
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539 // Find the (possibly empty) initial sequence of equal values... which are not
540 // necessarily constants.
541 unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops;
542 unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
543 unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
544 unsigned UnequalOper = 0;
545 while (UnequalOper != MinOperands &&
Owen Andersond4d90a02009-07-06 18:42:36 +0000546 IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper],
547 Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000548 // Advance through the type as we go...
549 ++UnequalOper;
550 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
551 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
552 else {
553 // If all operands equal each other, then the derived pointers must
554 // alias each other...
555 BasePtr1Ty = 0;
556 assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
557 "Ran out of type nesting, but not out of operands?");
558 return MustAlias;
559 }
560 }
561
562 // If we have seen all constant operands, and run out of indexes on one of the
563 // getelementptrs, check to see if the tail of the leftover one is all zeros.
564 // If so, return mustalias.
565 if (UnequalOper == MinOperands) {
566 if (NumGEP1Ops < NumGEP2Ops) {
567 std::swap(GEP1Ops, GEP2Ops);
568 std::swap(NumGEP1Ops, NumGEP2Ops);
569 }
570
571 bool AllAreZeros = true;
572 for (unsigned i = UnequalOper; i != MaxOperands; ++i)
573 if (!isa<Constant>(GEP1Ops[i]) ||
574 !cast<Constant>(GEP1Ops[i])->isNullValue()) {
575 AllAreZeros = false;
576 break;
577 }
578 if (AllAreZeros) return MustAlias;
579 }
580
581
582 // So now we know that the indexes derived from the base pointers,
583 // which are known to alias, are different. We can still determine a
584 // no-alias result if there are differing constant pairs in the index
585 // chain. For example:
586 // A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
587 //
588 // We have to be careful here about array accesses. In particular, consider:
589 // A[1][0] vs A[0][i]
590 // In this case, we don't *know* that the array will be accessed in bounds:
591 // the index could even be negative. Because of this, we have to
592 // conservatively *give up* and return may alias. We disregard differing
593 // array subscripts that are followed by a variable index without going
594 // through a struct.
595 //
596 unsigned SizeMax = std::max(G1S, G2S);
597 if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work.
598
599 // Scan for the first operand that is constant and unequal in the
600 // two getelementptrs...
601 unsigned FirstConstantOper = UnequalOper;
602 for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
603 const Value *G1Oper = GEP1Ops[FirstConstantOper];
604 const Value *G2Oper = GEP2Ops[FirstConstantOper];
605
606 if (G1Oper != G2Oper) // Found non-equal constant indexes...
607 if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper)))
608 if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){
609 if (G1OC->getType() != G2OC->getType()) {
610 // Sign extend both operands to long.
611 if (G1OC->getType() != Type::Int64Ty)
Owen Andersond4d90a02009-07-06 18:42:36 +0000612 G1OC = Context->getConstantExprSExt(G1OC, Type::Int64Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 if (G2OC->getType() != Type::Int64Ty)
Owen Andersond4d90a02009-07-06 18:42:36 +0000614 G2OC = Context->getConstantExprSExt(G2OC, Type::Int64Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615 GEP1Ops[FirstConstantOper] = G1OC;
616 GEP2Ops[FirstConstantOper] = G2OC;
617 }
618
619 if (G1OC != G2OC) {
620 // Handle the "be careful" case above: if this is an array/vector
621 // subscript, scan for a subsequent variable array index.
Dan Gohmanb86a18b2009-05-27 01:48:27 +0000622 if (const SequentialType *STy =
623 dyn_cast<SequentialType>(BasePtr1Ty)) {
624 const Type *NextTy = STy;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 bool isBadCase = false;
626
Dan Gohmanb86a18b2009-05-27 01:48:27 +0000627 for (unsigned Idx = FirstConstantOper;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) {
629 const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx];
630 if (!isa<Constant>(V1) || !isa<Constant>(V2)) {
631 isBadCase = true;
632 break;
633 }
Dan Gohmanb86a18b2009-05-27 01:48:27 +0000634 // If the array is indexed beyond the bounds of the static type
635 // at this level, it will also fall into the "be careful" case.
636 // It would theoretically be possible to analyze these cases,
637 // but for now just be conservatively correct.
638 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
639 if (cast<ConstantInt>(G1OC)->getZExtValue() >=
640 ATy->getNumElements() ||
641 cast<ConstantInt>(G2OC)->getZExtValue() >=
642 ATy->getNumElements()) {
643 isBadCase = true;
644 break;
645 }
646 if (const VectorType *VTy = dyn_cast<VectorType>(STy))
647 if (cast<ConstantInt>(G1OC)->getZExtValue() >=
648 VTy->getNumElements() ||
649 cast<ConstantInt>(G2OC)->getZExtValue() >=
650 VTy->getNumElements()) {
651 isBadCase = true;
652 break;
653 }
654 STy = cast<SequentialType>(NextTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 NextTy = cast<SequentialType>(NextTy)->getElementType();
656 }
657
658 if (isBadCase) G1OC = 0;
659 }
660
661 // Make sure they are comparable (ie, not constant expressions), and
662 // make sure the GEP with the smaller leading constant is GEP1.
663 if (G1OC) {
664 Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT,
665 G1OC, G2OC);
666 if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) {
667 if (CV->getZExtValue()) { // If they are comparable and G2 > G1
668 std::swap(GEP1Ops, GEP2Ops); // Make GEP1 < GEP2
669 std::swap(NumGEP1Ops, NumGEP2Ops);
670 }
671 break;
672 }
673 }
674 }
675 }
676 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
677 }
678
679 // No shared constant operands, and we ran out of common operands. At this
680 // point, the GEP instructions have run through all of their operands, and we
681 // haven't found evidence that there are any deltas between the GEP's.
682 // However, one GEP may have more operands than the other. If this is the
683 // case, there may still be hope. Check this now.
684 if (FirstConstantOper == MinOperands) {
685 // Make GEP1Ops be the longer one if there is a longer one.
686 if (NumGEP1Ops < NumGEP2Ops) {
687 std::swap(GEP1Ops, GEP2Ops);
688 std::swap(NumGEP1Ops, NumGEP2Ops);
689 }
690
691 // Is there anything to check?
692 if (NumGEP1Ops > MinOperands) {
693 for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
694 if (isa<ConstantInt>(GEP1Ops[i]) &&
695 !cast<ConstantInt>(GEP1Ops[i])->isZero()) {
696 // Yup, there's a constant in the tail. Set all variables to
Wojciech Matyjewicze1709452008-06-02 17:26:12 +0000697 // constants in the GEP instruction to make it suitable for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 // TargetData::getIndexedOffset.
699 for (i = 0; i != MaxOperands; ++i)
700 if (!isa<ConstantInt>(GEP1Ops[i]))
Owen Andersond4d90a02009-07-06 18:42:36 +0000701 GEP1Ops[i] = Context->getNullValue(GEP1Ops[i]->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702 // Okay, now get the offset. This is the relative offset for the full
703 // instruction.
704 const TargetData &TD = getTargetData();
705 int64_t Offset1 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops,
706 NumGEP1Ops);
707
708 // Now check without any constants at the end.
709 int64_t Offset2 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops,
710 MinOperands);
711
Wojciech Matyjewicze1709452008-06-02 17:26:12 +0000712 // Make sure we compare the absolute difference.
713 if (Offset1 > Offset2)
714 std::swap(Offset1, Offset2);
715
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716 // If the tail provided a bit enough offset, return noalias!
717 if ((uint64_t)(Offset2-Offset1) >= SizeMax)
718 return NoAlias;
Wojciech Matyjewicze1709452008-06-02 17:26:12 +0000719 // Otherwise break - we don't look for another constant in the tail.
720 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 }
722 }
723
724 // Couldn't find anything useful.
725 return MayAlias;
726 }
727
728 // If there are non-equal constants arguments, then we can figure
729 // out a minimum known delta between the two index expressions... at
730 // this point we know that the first constant index of GEP1 is less
731 // than the first constant index of GEP2.
732
733 // Advance BasePtr[12]Ty over this first differing constant operand.
734 BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->
735 getTypeAtIndex(GEP2Ops[FirstConstantOper]);
736 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->
737 getTypeAtIndex(GEP1Ops[FirstConstantOper]);
738
739 // We are going to be using TargetData::getIndexedOffset to determine the
740 // offset that each of the GEP's is reaching. To do this, we have to convert
741 // all variable references to constant references. To do this, we convert the
742 // initial sequence of array subscripts into constant zeros to start with.
743 const Type *ZeroIdxTy = GEPPointerTy;
744 for (unsigned i = 0; i != FirstConstantOper; ++i) {
745 if (!isa<StructType>(ZeroIdxTy))
Owen Andersond4d90a02009-07-06 18:42:36 +0000746 GEP1Ops[i] = GEP2Ops[i] = Context->getNullValue(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747
748 if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy))
749 ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]);
750 }
751
752 // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
753
754 // Loop over the rest of the operands...
755 for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
756 const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0;
757 const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0;
758 // If they are equal, use a zero index...
759 if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
760 if (!isa<ConstantInt>(Op1))
Owen Andersond4d90a02009-07-06 18:42:36 +0000761 GEP1Ops[i] = GEP2Ops[i] = Context->getNullValue(Op1->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762 // Otherwise, just keep the constants we have.
763 } else {
764 if (Op1) {
765 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
766 // If this is an array index, make sure the array element is in range.
767 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) {
768 if (Op1C->getZExtValue() >= AT->getNumElements())
769 return MayAlias; // Be conservative with out-of-range accesses
Chris Lattnereaf7b232007-12-09 07:35:13 +0000770 } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) {
771 if (Op1C->getZExtValue() >= VT->getNumElements())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 return MayAlias; // Be conservative with out-of-range accesses
773 }
774
775 } else {
776 // GEP1 is known to produce a value less than GEP2. To be
777 // conservatively correct, we must assume the largest possible
778 // constant is used in this position. This cannot be the initial
779 // index to the GEP instructions (because we know we have at least one
780 // element before this one with the different constant arguments), so
781 // we know that the current index must be into either a struct or
782 // array. Because we know it's not constant, this cannot be a
783 // structure index. Because of this, we can calculate the maximum
784 // value possible.
785 //
786 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
Owen Andersond4d90a02009-07-06 18:42:36 +0000787 GEP1Ops[i] =
788 Context->getConstantInt(Type::Int64Ty,AT->getNumElements()-1);
Chris Lattnerc0656ad2007-11-06 05:58:42 +0000789 else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty))
Owen Andersond4d90a02009-07-06 18:42:36 +0000790 GEP1Ops[i] =
791 Context->getConstantInt(Type::Int64Ty,VT->getNumElements()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000792 }
793 }
794
795 if (Op2) {
796 if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
797 // If this is an array index, make sure the array element is in range.
Chris Lattnereaf7b232007-12-09 07:35:13 +0000798 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799 if (Op2C->getZExtValue() >= AT->getNumElements())
800 return MayAlias; // Be conservative with out-of-range accesses
Chris Lattnereaf7b232007-12-09 07:35:13 +0000801 } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) {
Chris Lattnerc0656ad2007-11-06 05:58:42 +0000802 if (Op2C->getZExtValue() >= VT->getNumElements())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 return MayAlias; // Be conservative with out-of-range accesses
804 }
805 } else { // Conservatively assume the minimum value for this index
Owen Andersond4d90a02009-07-06 18:42:36 +0000806 GEP2Ops[i] = Context->getNullValue(Op2->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 }
808 }
809 }
810
811 if (BasePtr1Ty && Op1) {
812 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
813 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
814 else
815 BasePtr1Ty = 0;
816 }
817
818 if (BasePtr2Ty && Op2) {
819 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
820 BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
821 else
822 BasePtr2Ty = 0;
823 }
824 }
825
826 if (GEPPointerTy->getElementType()->isSized()) {
827 int64_t Offset1 =
828 getTargetData().getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops);
829 int64_t Offset2 =
830 getTargetData().getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops);
Chris Lattnerc0656ad2007-11-06 05:58:42 +0000831 assert(Offset1 != Offset2 &&
832 "There is at least one different constant here!");
833
834 // Make sure we compare the absolute difference.
835 if (Offset1 > Offset2)
836 std::swap(Offset1, Offset2);
837
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
839 //cerr << "Determined that these two GEP's don't alias ["
840 // << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
841 return NoAlias;
842 }
843 }
844 return MayAlias;
845}
846
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847// Make sure that anything that uses AliasAnalysis pulls in this file...
848DEFINING_FILE_FOR(BasicAliasAnalysis)