LLVM API Documentation
00001 //===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the default implementation of the Alias Analysis interface 00011 // that simply implements a few identities (two different globals cannot alias, 00012 // etc), but otherwise does no analysis. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #include "llvm/Analysis/AliasAnalysis.h" 00017 #include "llvm/Analysis/Passes.h" 00018 #include "llvm/Constants.h" 00019 #include "llvm/DerivedTypes.h" 00020 #include "llvm/Function.h" 00021 #include "llvm/GlobalVariable.h" 00022 #include "llvm/Instructions.h" 00023 #include "llvm/IntrinsicInst.h" 00024 #include "llvm/Pass.h" 00025 #include "llvm/Target/TargetData.h" 00026 #include "llvm/ADT/SmallVector.h" 00027 #include "llvm/ADT/STLExtras.h" 00028 #include "llvm/Support/Compiler.h" 00029 #include "llvm/Support/GetElementPtrTypeIterator.h" 00030 #include "llvm/Support/ManagedStatic.h" 00031 #include <algorithm> 00032 using namespace llvm; 00033 00034 //===----------------------------------------------------------------------===// 00035 // Useful predicates 00036 //===----------------------------------------------------------------------===// 00037 00038 // Determine if an AllocationInst instruction escapes from the function it is 00039 // contained in. If it does not escape, there is no way for another function to 00040 // mod/ref it. We do this by looking at its uses and determining if the uses 00041 // can escape (recursively). 00042 static bool AddressMightEscape(const Value *V) { 00043 for (Value::use_const_iterator UI = V->use_begin(), E = V->use_end(); 00044 UI != E; ++UI) { 00045 const Instruction *I = cast<Instruction>(*UI); 00046 switch (I->getOpcode()) { 00047 case Instruction::Load: 00048 break; //next use. 00049 case Instruction::Store: 00050 if (I->getOperand(0) == V) 00051 return true; // Escapes if the pointer is stored. 00052 break; // next use. 00053 case Instruction::GetElementPtr: 00054 if (AddressMightEscape(I)) 00055 return true; 00056 break; // next use. 00057 case Instruction::BitCast: 00058 if (AddressMightEscape(I)) 00059 return true; 00060 break; // next use 00061 case Instruction::Ret: 00062 // If returned, the address will escape to calling functions, but no 00063 // callees could modify it. 00064 break; // next use 00065 case Instruction::Call: 00066 // If the call is to a few known safe intrinsics, we know that it does 00067 // not escape. 00068 // TODO: Eventually just check the 'nocapture' attribute. 00069 if (!isa<MemIntrinsic>(I)) 00070 return true; 00071 break; // next use 00072 default: 00073 return true; 00074 } 00075 } 00076 return false; 00077 } 00078 00079 static const User *isGEP(const Value *V) { 00080 if (isa<GetElementPtrInst>(V) || 00081 (isa<ConstantExpr>(V) && 00082 cast<ConstantExpr>(V)->getOpcode() == Instruction::GetElementPtr)) 00083 return cast<User>(V); 00084 return 0; 00085 } 00086 00087 static const Value *GetGEPOperands(const Value *V, 00088 SmallVector<Value*, 16> &GEPOps){ 00089 assert(GEPOps.empty() && "Expect empty list to populate!"); 00090 GEPOps.insert(GEPOps.end(), cast<User>(V)->op_begin()+1, 00091 cast<User>(V)->op_end()); 00092 00093 // Accumulate all of the chained indexes into the operand array 00094 V = cast<User>(V)->getOperand(0); 00095 00096 while (const User *G = isGEP(V)) { 00097 if (!isa<Constant>(GEPOps[0]) || isa<GlobalValue>(GEPOps[0]) || 00098 !cast<Constant>(GEPOps[0])->isNullValue()) 00099 break; // Don't handle folding arbitrary pointer offsets yet... 00100 GEPOps.erase(GEPOps.begin()); // Drop the zero index 00101 GEPOps.insert(GEPOps.begin(), G->op_begin()+1, G->op_end()); 00102 V = G->getOperand(0); 00103 } 00104 return V; 00105 } 00106 00107 /// isIdentifiedObject - Return true if this pointer refers to a distinct and 00108 /// identifiable object. This returns true for: 00109 /// Global Variables and Functions 00110 /// Allocas and Mallocs 00111 /// ByVal and NoAlias Arguments 00112 /// 00113 static bool isIdentifiedObject(const Value *V) { 00114 if (isa<GlobalValue>(V) || isa<AllocationInst>(V)) 00115 return true; 00116 if (const Argument *A = dyn_cast<Argument>(V)) 00117 return A->hasNoAliasAttr() || A->hasByValAttr(); 00118 return false; 00119 } 00120 00121 /// isKnownNonNull - Return true if we know that the specified value is never 00122 /// null. 00123 static bool isKnownNonNull(const Value *V) { 00124 // Alloca never returns null, malloc might. 00125 if (isa<AllocaInst>(V)) return true; 00126 00127 // A byval argument is never null. 00128 if (const Argument *A = dyn_cast<Argument>(V)) 00129 return A->hasByValAttr(); 00130 00131 // Global values are not null unless extern weak. 00132 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 00133 return !GV->hasExternalWeakLinkage(); 00134 return false; 00135 } 00136 00137 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local 00138 /// object that never escapes from the function. 00139 static bool isNonEscapingLocalObject(const Value *V) { 00140 // If this is a local allocation, check to see if it escapes. 00141 if (isa<AllocationInst>(V)) 00142 return !AddressMightEscape(V); 00143 00144 // If this is an argument that corresponds to a byval or noalias argument, 00145 // it can't escape either. 00146 if (const Argument *A = dyn_cast<Argument>(V)) 00147 if (A->hasByValAttr() || A->hasNoAliasAttr()) 00148 return !AddressMightEscape(V); 00149 return false; 00150 } 00151 00152 00153 /// isObjectSmallerThan - Return true if we can prove that the object specified 00154 /// by V is smaller than Size. 00155 static bool isObjectSmallerThan(const Value *V, unsigned Size, 00156 const TargetData &TD) { 00157 const Type *AccessTy = 0; 00158 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 00159 AccessTy = GV->getType()->getElementType(); 00160 00161 if (const AllocationInst *AI = dyn_cast<AllocationInst>(V)) 00162 if (!AI->isArrayAllocation()) 00163 AccessTy = AI->getType()->getElementType(); 00164 00165 if (const Argument *A = dyn_cast<Argument>(V)) 00166 if (A->hasByValAttr()) 00167 AccessTy = cast<PointerType>(A->getType())->getElementType(); 00168 00169 if (AccessTy && AccessTy->isSized()) 00170 return TD.getABITypeSize(AccessTy) < Size; 00171 return false; 00172 } 00173 00174 //===----------------------------------------------------------------------===// 00175 // NoAA Pass 00176 //===----------------------------------------------------------------------===// 00177 00178 namespace { 00179 /// NoAA - This class implements the -no-aa pass, which always returns "I 00180 /// don't know" for alias queries. NoAA is unlike other alias analysis 00181 /// implementations, in that it does not chain to a previous analysis. As 00182 /// such it doesn't follow many of the rules that other alias analyses must. 00183 /// 00184 struct VISIBILITY_HIDDEN NoAA : public ImmutablePass, public AliasAnalysis { 00185 static char ID; // Class identification, replacement for typeinfo 00186 NoAA() : ImmutablePass(&ID) {} 00187 explicit NoAA(void *PID) : ImmutablePass(PID) { } 00188 00189 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00190 AU.addRequired<TargetData>(); 00191 } 00192 00193 virtual void initializePass() { 00194 TD = &getAnalysis<TargetData>(); 00195 } 00196 00197 virtual AliasResult alias(const Value *V1, unsigned V1Size, 00198 const Value *V2, unsigned V2Size) { 00199 return MayAlias; 00200 } 00201 00202 virtual ModRefBehavior getModRefBehavior(Function *F, CallSite CS, 00203 std::vector<PointerAccessInfo> *Info) { 00204 return UnknownModRefBehavior; 00205 } 00206 00207 virtual void getArgumentAccesses(Function *F, CallSite CS, 00208 std::vector<PointerAccessInfo> &Info) { 00209 assert(0 && "This method may not be called on this function!"); 00210 } 00211 00212 virtual void getMustAliases(Value *P, std::vector<Value*> &RetVals) { } 00213 virtual bool pointsToConstantMemory(const Value *P) { return false; } 00214 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) { 00215 return ModRef; 00216 } 00217 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { 00218 return ModRef; 00219 } 00220 virtual bool hasNoModRefInfoForCalls() const { return true; } 00221 00222 virtual void deleteValue(Value *V) {} 00223 virtual void copyValue(Value *From, Value *To) {} 00224 }; 00225 } // End of anonymous namespace 00226 00227 // Register this pass... 00228 char NoAA::ID = 0; 00229 static RegisterPass<NoAA> 00230 U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true); 00231 00232 // Declare that we implement the AliasAnalysis interface 00233 static RegisterAnalysisGroup<AliasAnalysis> V(U); 00234 00235 ImmutablePass *llvm::createNoAAPass() { return new NoAA(); } 00236 00237 //===----------------------------------------------------------------------===// 00238 // BasicAA Pass 00239 //===----------------------------------------------------------------------===// 00240 00241 namespace { 00242 /// BasicAliasAnalysis - This is the default alias analysis implementation. 00243 /// Because it doesn't chain to a previous alias analysis (like -no-aa), it 00244 /// derives from the NoAA class. 00245 struct VISIBILITY_HIDDEN BasicAliasAnalysis : public NoAA { 00246 static char ID; // Class identification, replacement for typeinfo 00247 BasicAliasAnalysis() : NoAA(&ID) {} 00248 AliasResult alias(const Value *V1, unsigned V1Size, 00249 const Value *V2, unsigned V2Size); 00250 00251 ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size); 00252 ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) { 00253 return NoAA::getModRefInfo(CS1,CS2); 00254 } 00255 00256 /// hasNoModRefInfoForCalls - We can provide mod/ref information against 00257 /// non-escaping allocations. 00258 virtual bool hasNoModRefInfoForCalls() const { return false; } 00259 00260 /// pointsToConstantMemory - Chase pointers until we find a (constant 00261 /// global) or not. 00262 bool pointsToConstantMemory(const Value *P); 00263 00264 private: 00265 // CheckGEPInstructions - Check two GEP instructions with known 00266 // must-aliasing base pointers. This checks to see if the index expressions 00267 // preclude the pointers from aliasing... 00268 AliasResult 00269 CheckGEPInstructions(const Type* BasePtr1Ty, 00270 Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size, 00271 const Type *BasePtr2Ty, 00272 Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size); 00273 }; 00274 } // End of anonymous namespace 00275 00276 // Register this pass... 00277 char BasicAliasAnalysis::ID = 0; 00278 static RegisterPass<BasicAliasAnalysis> 00279 X("basicaa", "Basic Alias Analysis (default AA impl)", false, true); 00280 00281 // Declare that we implement the AliasAnalysis interface 00282 static RegisterAnalysisGroup<AliasAnalysis, true> Y(X); 00283 00284 ImmutablePass *llvm::createBasicAliasAnalysisPass() { 00285 return new BasicAliasAnalysis(); 00286 } 00287 00288 00289 /// pointsToConstantMemory - Chase pointers until we find a (constant 00290 /// global) or not. 00291 bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) { 00292 if (const GlobalVariable *GV = 00293 dyn_cast<GlobalVariable>(P->getUnderlyingObject())) 00294 return GV->isConstant(); 00295 return false; 00296 } 00297 00298 // getModRefInfo - Check to see if the specified callsite can clobber the 00299 // specified memory object. Since we only look at local properties of this 00300 // function, we really can't say much about this query. We do, however, use 00301 // simple "address taken" analysis on local objects. 00302 // 00303 AliasAnalysis::ModRefResult 00304 BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) { 00305 if (!isa<Constant>(P)) { 00306 const Value *Object = P->getUnderlyingObject(); 00307 00308 // If this is a tail call and P points to a stack location, we know that 00309 // the tail call cannot access or modify the local stack. 00310 // We cannot exclude byval arguments here; these belong to the caller of 00311 // the current function not to the current function, and a tail callee 00312 // may reference them. 00313 if (isa<AllocaInst>(Object)) 00314 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) 00315 if (CI->isTailCall()) 00316 return NoModRef; 00317 00318 // If the pointer is to a locally allocated object that does not escape, 00319 // then the call can not mod/ref the pointer unless the call takes the 00320 // argument without capturing it. 00321 if (isNonEscapingLocalObject(Object)) { 00322 bool passedAsArg = false; 00323 // TODO: Eventually only check 'nocapture' arguments. 00324 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end(); 00325 CI != CE; ++CI) 00326 if (isa<PointerType>((*CI)->getType()) && 00327 alias(cast<Value>(CI), ~0U, P, ~0U) != NoAlias) 00328 passedAsArg = true; 00329 00330 if (!passedAsArg) 00331 return NoModRef; 00332 } 00333 } 00334 00335 // The AliasAnalysis base class has some smarts, lets use them. 00336 return AliasAnalysis::getModRefInfo(CS, P, Size); 00337 } 00338 00339 00340 // alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such 00341 // as array references. Note that this function is heavily tail recursive. 00342 // Hopefully we have a smart C++ compiler. :) 00343 // 00344 AliasAnalysis::AliasResult 00345 BasicAliasAnalysis::alias(const Value *V1, unsigned V1Size, 00346 const Value *V2, unsigned V2Size) { 00347 // Strip off any constant expression casts if they exist 00348 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V1)) 00349 if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType())) 00350 V1 = CE->getOperand(0); 00351 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V2)) 00352 if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType())) 00353 V2 = CE->getOperand(0); 00354 00355 // Are we checking for alias of the same value? 00356 if (V1 == V2) return MustAlias; 00357 00358 if ((!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType())) && 00359 V1->getType() != Type::Int64Ty && V2->getType() != Type::Int64Ty) 00360 return NoAlias; // Scalars cannot alias each other 00361 00362 // Strip off cast instructions... 00363 if (const BitCastInst *I = dyn_cast<BitCastInst>(V1)) 00364 return alias(I->getOperand(0), V1Size, V2, V2Size); 00365 if (const BitCastInst *I = dyn_cast<BitCastInst>(V2)) 00366 return alias(V1, V1Size, I->getOperand(0), V2Size); 00367 00368 // Figure out what objects these things are pointing to if we can... 00369 const Value *O1 = V1->getUnderlyingObject(); 00370 const Value *O2 = V2->getUnderlyingObject(); 00371 00372 if (O1 != O2) { 00373 // If V1/V2 point to two different objects we know that we have no alias. 00374 if (isIdentifiedObject(O1) && isIdentifiedObject(O2)) 00375 return NoAlias; 00376 00377 // Incoming argument cannot alias locally allocated object! 00378 if ((isa<Argument>(O1) && isa<AllocationInst>(O2)) || 00379 (isa<Argument>(O2) && isa<AllocationInst>(O1))) 00380 return NoAlias; 00381 00382 // Most objects can't alias null. 00383 if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) || 00384 (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2))) 00385 return NoAlias; 00386 } 00387 00388 // If the size of one access is larger than the entire object on the other 00389 // side, then we know such behavior is undefined and can assume no alias. 00390 const TargetData &TD = getTargetData(); 00391 if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, TD)) || 00392 (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, TD))) 00393 return NoAlias; 00394 00395 // If one pointer is the result of a call/invoke and the other is a 00396 // non-escaping local object, then we know the object couldn't escape to a 00397 // point where the call could return it. 00398 if ((isa<CallInst>(O1) || isa<InvokeInst>(O1)) && 00399 isNonEscapingLocalObject(O2)) 00400 return NoAlias; 00401 if ((isa<CallInst>(O2) || isa<InvokeInst>(O2)) && 00402 isNonEscapingLocalObject(O1)) 00403 return NoAlias; 00404 00405 // If we have two gep instructions with must-alias'ing base pointers, figure 00406 // out if the indexes to the GEP tell us anything about the derived pointer. 00407 // Note that we also handle chains of getelementptr instructions as well as 00408 // constant expression getelementptrs here. 00409 // 00410 if (isGEP(V1) && isGEP(V2)) { 00411 // Drill down into the first non-gep value, to test for must-aliasing of 00412 // the base pointers. 00413 const User *G = cast<User>(V1); 00414 while (isGEP(G->getOperand(0)) && 00415 G->getOperand(1) == 00416 Constant::getNullValue(G->getOperand(1)->getType())) 00417 G = cast<User>(G->getOperand(0)); 00418 const Value *BasePtr1 = G->getOperand(0); 00419 00420 G = cast<User>(V2); 00421 while (isGEP(G->getOperand(0)) && 00422 G->getOperand(1) == 00423 Constant::getNullValue(G->getOperand(1)->getType())) 00424 G = cast<User>(G->getOperand(0)); 00425 const Value *BasePtr2 = G->getOperand(0); 00426 00427 // Do the base pointers alias? 00428 AliasResult BaseAlias = alias(BasePtr1, ~0U, BasePtr2, ~0U); 00429 if (BaseAlias == NoAlias) return NoAlias; 00430 if (BaseAlias == MustAlias) { 00431 // If the base pointers alias each other exactly, check to see if we can 00432 // figure out anything about the resultant pointers, to try to prove 00433 // non-aliasing. 00434 00435 // Collect all of the chained GEP operands together into one simple place 00436 SmallVector<Value*, 16> GEP1Ops, GEP2Ops; 00437 BasePtr1 = GetGEPOperands(V1, GEP1Ops); 00438 BasePtr2 = GetGEPOperands(V2, GEP2Ops); 00439 00440 // If GetGEPOperands were able to fold to the same must-aliased pointer, 00441 // do the comparison. 00442 if (BasePtr1 == BasePtr2) { 00443 AliasResult GAlias = 00444 CheckGEPInstructions(BasePtr1->getType(), 00445 &GEP1Ops[0], GEP1Ops.size(), V1Size, 00446 BasePtr2->getType(), 00447 &GEP2Ops[0], GEP2Ops.size(), V2Size); 00448 if (GAlias != MayAlias) 00449 return GAlias; 00450 } 00451 } 00452 } 00453 00454 // Check to see if these two pointers are related by a getelementptr 00455 // instruction. If one pointer is a GEP with a non-zero index of the other 00456 // pointer, we know they cannot alias. 00457 // 00458 if (isGEP(V2)) { 00459 std::swap(V1, V2); 00460 std::swap(V1Size, V2Size); 00461 } 00462 00463 if (V1Size != ~0U && V2Size != ~0U) 00464 if (isGEP(V1)) { 00465 SmallVector<Value*, 16> GEPOperands; 00466 const Value *BasePtr = GetGEPOperands(V1, GEPOperands); 00467 00468 AliasResult R = alias(BasePtr, V1Size, V2, V2Size); 00469 if (R == MustAlias) { 00470 // If there is at least one non-zero constant index, we know they cannot 00471 // alias. 00472 bool ConstantFound = false; 00473 bool AllZerosFound = true; 00474 for (unsigned i = 0, e = GEPOperands.size(); i != e; ++i) 00475 if (const Constant *C = dyn_cast<Constant>(GEPOperands[i])) { 00476 if (!C->isNullValue()) { 00477 ConstantFound = true; 00478 AllZerosFound = false; 00479 break; 00480 } 00481 } else { 00482 AllZerosFound = false; 00483 } 00484 00485 // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases 00486 // the ptr, the end result is a must alias also. 00487 if (AllZerosFound) 00488 return MustAlias; 00489 00490 if (ConstantFound) { 00491 if (V2Size <= 1 && V1Size <= 1) // Just pointer check? 00492 return NoAlias; 00493 00494 // Otherwise we have to check to see that the distance is more than 00495 // the size of the argument... build an index vector that is equal to 00496 // the arguments provided, except substitute 0's for any variable 00497 // indexes we find... 00498 if (cast<PointerType>( 00499 BasePtr->getType())->getElementType()->isSized()) { 00500 for (unsigned i = 0; i != GEPOperands.size(); ++i) 00501 if (!isa<ConstantInt>(GEPOperands[i])) 00502 GEPOperands[i] = 00503 Constant::getNullValue(GEPOperands[i]->getType()); 00504 int64_t Offset = 00505 getTargetData().getIndexedOffset(BasePtr->getType(), 00506 &GEPOperands[0], 00507 GEPOperands.size()); 00508 00509 if (Offset >= (int64_t)V2Size || Offset <= -(int64_t)V1Size) 00510 return NoAlias; 00511 } 00512 } 00513 } 00514 } 00515 00516 return MayAlias; 00517 } 00518 00519 // This function is used to determin if the indices of two GEP instructions are 00520 // equal. V1 and V2 are the indices. 00521 static bool IndexOperandsEqual(Value *V1, Value *V2) { 00522 if (V1->getType() == V2->getType()) 00523 return V1 == V2; 00524 if (Constant *C1 = dyn_cast<Constant>(V1)) 00525 if (Constant *C2 = dyn_cast<Constant>(V2)) { 00526 // Sign extend the constants to long types, if necessary 00527 if (C1->getType() != Type::Int64Ty) 00528 C1 = ConstantExpr::getSExt(C1, Type::Int64Ty); 00529 if (C2->getType() != Type::Int64Ty) 00530 C2 = ConstantExpr::getSExt(C2, Type::Int64Ty); 00531 return C1 == C2; 00532 } 00533 return false; 00534 } 00535 00536 /// CheckGEPInstructions - Check two GEP instructions with known must-aliasing 00537 /// base pointers. This checks to see if the index expressions preclude the 00538 /// pointers from aliasing... 00539 AliasAnalysis::AliasResult 00540 BasicAliasAnalysis::CheckGEPInstructions( 00541 const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S, 00542 const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) { 00543 // We currently can't handle the case when the base pointers have different 00544 // primitive types. Since this is uncommon anyway, we are happy being 00545 // extremely conservative. 00546 if (BasePtr1Ty != BasePtr2Ty) 00547 return MayAlias; 00548 00549 const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty); 00550 00551 // Find the (possibly empty) initial sequence of equal values... which are not 00552 // necessarily constants. 00553 unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops; 00554 unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands); 00555 unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands); 00556 unsigned UnequalOper = 0; 00557 while (UnequalOper != MinOperands && 00558 IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper])) { 00559 // Advance through the type as we go... 00560 ++UnequalOper; 00561 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty)) 00562 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]); 00563 else { 00564 // If all operands equal each other, then the derived pointers must 00565 // alias each other... 00566 BasePtr1Ty = 0; 00567 assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands && 00568 "Ran out of type nesting, but not out of operands?"); 00569 return MustAlias; 00570 } 00571 } 00572 00573 // If we have seen all constant operands, and run out of indexes on one of the 00574 // getelementptrs, check to see if the tail of the leftover one is all zeros. 00575 // If so, return mustalias. 00576 if (UnequalOper == MinOperands) { 00577 if (NumGEP1Ops < NumGEP2Ops) { 00578 std::swap(GEP1Ops, GEP2Ops); 00579 std::swap(NumGEP1Ops, NumGEP2Ops); 00580 } 00581 00582 bool AllAreZeros = true; 00583 for (unsigned i = UnequalOper; i != MaxOperands; ++i) 00584 if (!isa<Constant>(GEP1Ops[i]) || 00585 !cast<Constant>(GEP1Ops[i])->isNullValue()) { 00586 AllAreZeros = false; 00587 break; 00588 } 00589 if (AllAreZeros) return MustAlias; 00590 } 00591 00592 00593 // So now we know that the indexes derived from the base pointers, 00594 // which are known to alias, are different. We can still determine a 00595 // no-alias result if there are differing constant pairs in the index 00596 // chain. For example: 00597 // A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S)) 00598 // 00599 // We have to be careful here about array accesses. In particular, consider: 00600 // A[1][0] vs A[0][i] 00601 // In this case, we don't *know* that the array will be accessed in bounds: 00602 // the index could even be negative. Because of this, we have to 00603 // conservatively *give up* and return may alias. We disregard differing 00604 // array subscripts that are followed by a variable index without going 00605 // through a struct. 00606 // 00607 unsigned SizeMax = std::max(G1S, G2S); 00608 if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work. 00609 00610 // Scan for the first operand that is constant and unequal in the 00611 // two getelementptrs... 00612 unsigned FirstConstantOper = UnequalOper; 00613 for (; FirstConstantOper != MinOperands; ++FirstConstantOper) { 00614 const Value *G1Oper = GEP1Ops[FirstConstantOper]; 00615 const Value *G2Oper = GEP2Ops[FirstConstantOper]; 00616 00617 if (G1Oper != G2Oper) // Found non-equal constant indexes... 00618 if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper))) 00619 if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){ 00620 if (G1OC->getType() != G2OC->getType()) { 00621 // Sign extend both operands to long. 00622 if (G1OC->getType() != Type::Int64Ty) 00623 G1OC = ConstantExpr::getSExt(G1OC, Type::Int64Ty); 00624 if (G2OC->getType() != Type::Int64Ty) 00625 G2OC = ConstantExpr::getSExt(G2OC, Type::Int64Ty); 00626 GEP1Ops[FirstConstantOper] = G1OC; 00627 GEP2Ops[FirstConstantOper] = G2OC; 00628 } 00629 00630 if (G1OC != G2OC) { 00631 // Handle the "be careful" case above: if this is an array/vector 00632 // subscript, scan for a subsequent variable array index. 00633 if (isa<SequentialType>(BasePtr1Ty)) { 00634 const Type *NextTy = 00635 cast<SequentialType>(BasePtr1Ty)->getElementType(); 00636 bool isBadCase = false; 00637 00638 for (unsigned Idx = FirstConstantOper+1; 00639 Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) { 00640 const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx]; 00641 if (!isa<Constant>(V1) || !isa<Constant>(V2)) { 00642 isBadCase = true; 00643 break; 00644 } 00645 NextTy = cast<SequentialType>(NextTy)->getElementType(); 00646 } 00647 00648 if (isBadCase) G1OC = 0; 00649 } 00650 00651 // Make sure they are comparable (ie, not constant expressions), and 00652 // make sure the GEP with the smaller leading constant is GEP1. 00653 if (G1OC) { 00654 Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT, 00655 G1OC, G2OC); 00656 if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) { 00657 if (CV->getZExtValue()) { // If they are comparable and G2 > G1 00658 std::swap(GEP1Ops, GEP2Ops); // Make GEP1 < GEP2 00659 std::swap(NumGEP1Ops, NumGEP2Ops); 00660 } 00661 break; 00662 } 00663 } 00664 } 00665 } 00666 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper); 00667 } 00668 00669 // No shared constant operands, and we ran out of common operands. At this 00670 // point, the GEP instructions have run through all of their operands, and we 00671 // haven't found evidence that there are any deltas between the GEP's. 00672 // However, one GEP may have more operands than the other. If this is the 00673 // case, there may still be hope. Check this now. 00674 if (FirstConstantOper == MinOperands) { 00675 // Make GEP1Ops be the longer one if there is a longer one. 00676 if (NumGEP1Ops < NumGEP2Ops) { 00677 std::swap(GEP1Ops, GEP2Ops); 00678 std::swap(NumGEP1Ops, NumGEP2Ops); 00679 } 00680 00681 // Is there anything to check? 00682 if (NumGEP1Ops > MinOperands) { 00683 for (unsigned i = FirstConstantOper; i != MaxOperands; ++i) 00684 if (isa<ConstantInt>(GEP1Ops[i]) && 00685 !cast<ConstantInt>(GEP1Ops[i])->isZero()) { 00686 // Yup, there's a constant in the tail. Set all variables to 00687 // constants in the GEP instruction to make it suitable for 00688 // TargetData::getIndexedOffset. 00689 for (i = 0; i != MaxOperands; ++i) 00690 if (!isa<ConstantInt>(GEP1Ops[i])) 00691 GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType()); 00692 // Okay, now get the offset. This is the relative offset for the full 00693 // instruction. 00694 const TargetData &TD = getTargetData(); 00695 int64_t Offset1 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops, 00696 NumGEP1Ops); 00697 00698 // Now check without any constants at the end. 00699 int64_t Offset2 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops, 00700 MinOperands); 00701 00702 // Make sure we compare the absolute difference. 00703 if (Offset1 > Offset2) 00704 std::swap(Offset1, Offset2); 00705 00706 // If the tail provided a bit enough offset, return noalias! 00707 if ((uint64_t)(Offset2-Offset1) >= SizeMax) 00708 return NoAlias; 00709 // Otherwise break - we don't look for another constant in the tail. 00710 break; 00711 } 00712 } 00713 00714 // Couldn't find anything useful. 00715 return MayAlias; 00716 } 00717 00718 // If there are non-equal constants arguments, then we can figure 00719 // out a minimum known delta between the two index expressions... at 00720 // this point we know that the first constant index of GEP1 is less 00721 // than the first constant index of GEP2. 00722 00723 // Advance BasePtr[12]Ty over this first differing constant operand. 00724 BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)-> 00725 getTypeAtIndex(GEP2Ops[FirstConstantOper]); 00726 BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)-> 00727 getTypeAtIndex(GEP1Ops[FirstConstantOper]); 00728 00729 // We are going to be using TargetData::getIndexedOffset to determine the 00730 // offset that each of the GEP's is reaching. To do this, we have to convert 00731 // all variable references to constant references. To do this, we convert the 00732 // initial sequence of array subscripts into constant zeros to start with. 00733 const Type *ZeroIdxTy = GEPPointerTy; 00734 for (unsigned i = 0; i != FirstConstantOper; ++i) { 00735 if (!isa<StructType>(ZeroIdxTy)) 00736 GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Type::Int32Ty); 00737 00738 if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy)) 00739 ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]); 00740 } 00741 00742 // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok 00743 00744 // Loop over the rest of the operands... 00745 for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) { 00746 const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0; 00747 const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0; 00748 // If they are equal, use a zero index... 00749 if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) { 00750 if (!isa<ConstantInt>(Op1)) 00751 GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType()); 00752 // Otherwise, just keep the constants we have. 00753 } else { 00754 if (Op1) { 00755 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 00756 // If this is an array index, make sure the array element is in range. 00757 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) { 00758 if (Op1C->getZExtValue() >= AT->getNumElements()) 00759 return MayAlias; // Be conservative with out-of-range accesses 00760 } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) { 00761 if (Op1C->getZExtValue() >= VT->getNumElements()) 00762 return MayAlias; // Be conservative with out-of-range accesses 00763 } 00764 00765 } else { 00766 // GEP1 is known to produce a value less than GEP2. To be 00767 // conservatively correct, we must assume the largest possible 00768 // constant is used in this position. This cannot be the initial 00769 // index to the GEP instructions (because we know we have at least one 00770 // element before this one with the different constant arguments), so 00771 // we know that the current index must be into either a struct or 00772 // array. Because we know it's not constant, this cannot be a 00773 // structure index. Because of this, we can calculate the maximum 00774 // value possible. 00775 // 00776 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) 00777 GEP1Ops[i] = ConstantInt::get(Type::Int64Ty,AT->getNumElements()-1); 00778 else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) 00779 GEP1Ops[i] = ConstantInt::get(Type::Int64Ty,VT->getNumElements()-1); 00780 } 00781 } 00782 00783 if (Op2) { 00784 if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) { 00785 // If this is an array index, make sure the array element is in range. 00786 if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) { 00787 if (Op2C->getZExtValue() >= AT->getNumElements()) 00788 return MayAlias; // Be conservative with out-of-range accesses 00789 } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) { 00790 if (Op2C->getZExtValue() >= VT->getNumElements()) 00791 return MayAlias; // Be conservative with out-of-range accesses 00792 } 00793 } else { // Conservatively assume the minimum value for this index 00794 GEP2Ops[i] = Constant::getNullValue(Op2->getType()); 00795 } 00796 } 00797 } 00798 00799 if (BasePtr1Ty && Op1) { 00800 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty)) 00801 BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]); 00802 else 00803 BasePtr1Ty = 0; 00804 } 00805 00806 if (BasePtr2Ty && Op2) { 00807 if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty)) 00808 BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]); 00809 else 00810 BasePtr2Ty = 0; 00811 } 00812 } 00813 00814 if (GEPPointerTy->getElementType()->isSized()) { 00815 int64_t Offset1 = 00816 getTargetData().getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops); 00817 int64_t Offset2 = 00818 getTargetData().getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops); 00819 assert(Offset1 != Offset2 && 00820 "There is at least one different constant here!"); 00821 00822 // Make sure we compare the absolute difference. 00823 if (Offset1 > Offset2) 00824 std::swap(Offset1, Offset2); 00825 00826 if ((uint64_t)(Offset2-Offset1) >= SizeMax) { 00827 //cerr << "Determined that these two GEP's don't alias [" 00828 // << SizeMax << " bytes]: \n" << *GEP1 << *GEP2; 00829 return NoAlias; 00830 } 00831 } 00832 return MayAlias; 00833 } 00834 00835 // Make sure that anything that uses AliasAnalysis pulls in this file... 00836 DEFINING_FILE_FOR(BasicAliasAnalysis)