BasicAliasAnalysis.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. //===- BasicAliasAnalysis.cpp - Local Alias Analysis Impl -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  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. #include "llvm/Analysis/AliasAnalysis.h"
  16. #include "llvm/Analysis/CaptureTracking.h"
  17. #include "llvm/Analysis/Passes.h"
  18. #include "llvm/Constants.h"
  19. #include "llvm/DerivedTypes.h"
  20. #include "llvm/Function.h"
  21. #include "llvm/GlobalVariable.h"
  22. #include "llvm/Instructions.h"
  23. #include "llvm/IntrinsicInst.h"
  24. #include "llvm/LLVMContext.h"
  25. #include "llvm/Pass.h"
  26. #include "llvm/Target/TargetData.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/STLExtras.h"
  29. #include "llvm/Support/Compiler.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include "llvm/Support/GetElementPtrTypeIterator.h"
  32. #include <algorithm>
  33. using namespace llvm;
  34. //===----------------------------------------------------------------------===//
  35. // Useful predicates
  36. //===----------------------------------------------------------------------===//
  37. static const User *isGEP(const Value *V) {
  38. if (isa<GetElementPtrInst>(V) ||
  39. (isa<ConstantExpr>(V) &&
  40. cast<ConstantExpr>(V)->getOpcode() == Instruction::GetElementPtr))
  41. return cast<User>(V);
  42. return 0;
  43. }
  44. static const Value *GetGEPOperands(const Value *V,
  45. SmallVector<Value*, 16> &GEPOps) {
  46. assert(GEPOps.empty() && "Expect empty list to populate!");
  47. GEPOps.insert(GEPOps.end(), cast<User>(V)->op_begin()+1,
  48. cast<User>(V)->op_end());
  49. // Accumulate all of the chained indexes into the operand array
  50. V = cast<User>(V)->getOperand(0);
  51. while (const User *G = isGEP(V)) {
  52. if (!isa<Constant>(GEPOps[0]) || isa<GlobalValue>(GEPOps[0]) ||
  53. !cast<Constant>(GEPOps[0])->isNullValue())
  54. break; // Don't handle folding arbitrary pointer offsets yet...
  55. GEPOps.erase(GEPOps.begin()); // Drop the zero index
  56. GEPOps.insert(GEPOps.begin(), G->op_begin()+1, G->op_end());
  57. V = G->getOperand(0);
  58. }
  59. return V;
  60. }
  61. /// isKnownNonNull - Return true if we know that the specified value is never
  62. /// null.
  63. static bool isKnownNonNull(const Value *V) {
  64. // Alloca never returns null, malloc might.
  65. if (isa<AllocaInst>(V)) return true;
  66. // A byval argument is never null.
  67. if (const Argument *A = dyn_cast<Argument>(V))
  68. return A->hasByValAttr();
  69. // Global values are not null unless extern weak.
  70. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
  71. return !GV->hasExternalWeakLinkage();
  72. return false;
  73. }
  74. /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
  75. /// object that never escapes from the function.
  76. static bool isNonEscapingLocalObject(const Value *V) {
  77. // If this is a local allocation, check to see if it escapes.
  78. if (isa<AllocationInst>(V) || isNoAliasCall(V))
  79. return !PointerMayBeCaptured(V, false);
  80. // If this is an argument that corresponds to a byval or noalias argument,
  81. // then it has not escaped before entering the function. Check if it escapes
  82. // inside the function.
  83. if (const Argument *A = dyn_cast<Argument>(V))
  84. if (A->hasByValAttr() || A->hasNoAliasAttr()) {
  85. // Don't bother analyzing arguments already known not to escape.
  86. if (A->hasNoCaptureAttr())
  87. return true;
  88. return !PointerMayBeCaptured(V, false);
  89. }
  90. return false;
  91. }
  92. /// isObjectSmallerThan - Return true if we can prove that the object specified
  93. /// by V is smaller than Size.
  94. static bool isObjectSmallerThan(const Value *V, unsigned Size,
  95. const TargetData &TD) {
  96. const Type *AccessTy;
  97. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
  98. AccessTy = GV->getType()->getElementType();
  99. } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
  100. if (!AI->isArrayAllocation())
  101. AccessTy = AI->getType()->getElementType();
  102. else
  103. return false;
  104. } else if (const Argument *A = dyn_cast<Argument>(V)) {
  105. if (A->hasByValAttr())
  106. AccessTy = cast<PointerType>(A->getType())->getElementType();
  107. else
  108. return false;
  109. } else {
  110. return false;
  111. }
  112. if (AccessTy->isSized())
  113. return TD.getTypeAllocSize(AccessTy) < Size;
  114. return false;
  115. }
  116. //===----------------------------------------------------------------------===//
  117. // NoAA Pass
  118. //===----------------------------------------------------------------------===//
  119. namespace {
  120. /// NoAA - This class implements the -no-aa pass, which always returns "I
  121. /// don't know" for alias queries. NoAA is unlike other alias analysis
  122. /// implementations, in that it does not chain to a previous analysis. As
  123. /// such it doesn't follow many of the rules that other alias analyses must.
  124. ///
  125. struct VISIBILITY_HIDDEN NoAA : public ImmutablePass, public AliasAnalysis {
  126. static char ID; // Class identification, replacement for typeinfo
  127. NoAA() : ImmutablePass(&ID) {}
  128. explicit NoAA(void *PID) : ImmutablePass(PID) { }
  129. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  130. AU.addRequired<TargetData>();
  131. }
  132. virtual void initializePass() {
  133. TD = &getAnalysis<TargetData>();
  134. }
  135. virtual AliasResult alias(const Value *V1, unsigned V1Size,
  136. const Value *V2, unsigned V2Size) {
  137. return MayAlias;
  138. }
  139. virtual void getArgumentAccesses(Function *F, CallSite CS,
  140. std::vector<PointerAccessInfo> &Info) {
  141. LLVM_UNREACHABLE("This method may not be called on this function!");
  142. }
  143. virtual void getMustAliases(Value *P, std::vector<Value*> &RetVals) { }
  144. virtual bool pointsToConstantMemory(const Value *P) { return false; }
  145. virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
  146. return ModRef;
  147. }
  148. virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
  149. return ModRef;
  150. }
  151. virtual bool hasNoModRefInfoForCalls() const { return true; }
  152. virtual void deleteValue(Value *V) {}
  153. virtual void copyValue(Value *From, Value *To) {}
  154. };
  155. } // End of anonymous namespace
  156. // Register this pass...
  157. char NoAA::ID = 0;
  158. static RegisterPass<NoAA>
  159. U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
  160. // Declare that we implement the AliasAnalysis interface
  161. static RegisterAnalysisGroup<AliasAnalysis> V(U);
  162. ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
  163. //===----------------------------------------------------------------------===//
  164. // BasicAA Pass
  165. //===----------------------------------------------------------------------===//
  166. namespace {
  167. /// BasicAliasAnalysis - This is the default alias analysis implementation.
  168. /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
  169. /// derives from the NoAA class.
  170. struct VISIBILITY_HIDDEN BasicAliasAnalysis : public NoAA {
  171. static char ID; // Class identification, replacement for typeinfo
  172. BasicAliasAnalysis() : NoAA(&ID) {}
  173. AliasResult alias(const Value *V1, unsigned V1Size,
  174. const Value *V2, unsigned V2Size);
  175. ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
  176. ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
  177. /// hasNoModRefInfoForCalls - We can provide mod/ref information against
  178. /// non-escaping allocations.
  179. virtual bool hasNoModRefInfoForCalls() const { return false; }
  180. /// pointsToConstantMemory - Chase pointers until we find a (constant
  181. /// global) or not.
  182. bool pointsToConstantMemory(const Value *P);
  183. private:
  184. // CheckGEPInstructions - Check two GEP instructions with known
  185. // must-aliasing base pointers. This checks to see if the index expressions
  186. // preclude the pointers from aliasing...
  187. AliasResult
  188. CheckGEPInstructions(const Type* BasePtr1Ty,
  189. Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size,
  190. const Type *BasePtr2Ty,
  191. Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size);
  192. };
  193. } // End of anonymous namespace
  194. // Register this pass...
  195. char BasicAliasAnalysis::ID = 0;
  196. static RegisterPass<BasicAliasAnalysis>
  197. X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
  198. // Declare that we implement the AliasAnalysis interface
  199. static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
  200. ImmutablePass *llvm::createBasicAliasAnalysisPass() {
  201. return new BasicAliasAnalysis();
  202. }
  203. /// pointsToConstantMemory - Chase pointers until we find a (constant
  204. /// global) or not.
  205. bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
  206. if (const GlobalVariable *GV =
  207. dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
  208. return GV->isConstant();
  209. return false;
  210. }
  211. // getModRefInfo - Check to see if the specified callsite can clobber the
  212. // specified memory object. Since we only look at local properties of this
  213. // function, we really can't say much about this query. We do, however, use
  214. // simple "address taken" analysis on local objects.
  215. //
  216. AliasAnalysis::ModRefResult
  217. BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
  218. if (!isa<Constant>(P)) {
  219. const Value *Object = P->getUnderlyingObject();
  220. // If this is a tail call and P points to a stack location, we know that
  221. // the tail call cannot access or modify the local stack.
  222. // We cannot exclude byval arguments here; these belong to the caller of
  223. // the current function not to the current function, and a tail callee
  224. // may reference them.
  225. if (isa<AllocaInst>(Object))
  226. if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
  227. if (CI->isTailCall())
  228. return NoModRef;
  229. // If the pointer is to a locally allocated object that does not escape,
  230. // then the call can not mod/ref the pointer unless the call takes the
  231. // argument without capturing it.
  232. if (isNonEscapingLocalObject(Object) && CS.getInstruction() != Object) {
  233. bool passedAsArg = false;
  234. // TODO: Eventually only check 'nocapture' arguments.
  235. for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
  236. CI != CE; ++CI)
  237. if (isa<PointerType>((*CI)->getType()) &&
  238. alias(cast<Value>(CI), ~0U, P, ~0U) != NoAlias)
  239. passedAsArg = true;
  240. if (!passedAsArg)
  241. return NoModRef;
  242. }
  243. }
  244. // The AliasAnalysis base class has some smarts, lets use them.
  245. return AliasAnalysis::getModRefInfo(CS, P, Size);
  246. }
  247. AliasAnalysis::ModRefResult
  248. BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
  249. // If CS1 or CS2 are readnone, they don't interact.
  250. ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
  251. if (CS1B == DoesNotAccessMemory) return NoModRef;
  252. ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
  253. if (CS2B == DoesNotAccessMemory) return NoModRef;
  254. // If they both only read from memory, just return ref.
  255. if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
  256. return Ref;
  257. // Otherwise, fall back to NoAA (mod+ref).
  258. return NoAA::getModRefInfo(CS1, CS2);
  259. }
  260. // alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such
  261. // as array references.
  262. //
  263. AliasAnalysis::AliasResult
  264. BasicAliasAnalysis::alias(const Value *V1, unsigned V1Size,
  265. const Value *V2, unsigned V2Size) {
  266. // Strip off any constant expression casts if they exist
  267. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V1))
  268. if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType()))
  269. V1 = CE->getOperand(0);
  270. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V2))
  271. if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType()))
  272. V2 = CE->getOperand(0);
  273. // Are we checking for alias of the same value?
  274. if (V1 == V2) return MustAlias;
  275. if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
  276. return NoAlias; // Scalars cannot alias each other
  277. // Strip off cast instructions. Since V1 and V2 are pointers, they must be
  278. // pointer<->pointer bitcasts.
  279. if (const BitCastInst *I = dyn_cast<BitCastInst>(V1))
  280. return alias(I->getOperand(0), V1Size, V2, V2Size);
  281. if (const BitCastInst *I = dyn_cast<BitCastInst>(V2))
  282. return alias(V1, V1Size, I->getOperand(0), V2Size);
  283. // Figure out what objects these things are pointing to if we can.
  284. const Value *O1 = V1->getUnderlyingObject();
  285. const Value *O2 = V2->getUnderlyingObject();
  286. if (O1 != O2) {
  287. // If V1/V2 point to two different objects we know that we have no alias.
  288. if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
  289. return NoAlias;
  290. // Arguments can't alias with local allocations or noalias calls.
  291. if ((isa<Argument>(O1) && (isa<AllocationInst>(O2) || isNoAliasCall(O2))) ||
  292. (isa<Argument>(O2) && (isa<AllocationInst>(O1) || isNoAliasCall(O1))))
  293. return NoAlias;
  294. // Most objects can't alias null.
  295. if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
  296. (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
  297. return NoAlias;
  298. }
  299. // If the size of one access is larger than the entire object on the other
  300. // side, then we know such behavior is undefined and can assume no alias.
  301. const TargetData &TD = getTargetData();
  302. if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, TD)) ||
  303. (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, TD)))
  304. return NoAlias;
  305. // If one pointer is the result of a call/invoke and the other is a
  306. // non-escaping local object, then we know the object couldn't escape to a
  307. // point where the call could return it.
  308. if ((isa<CallInst>(O1) || isa<InvokeInst>(O1)) &&
  309. isNonEscapingLocalObject(O2) && O1 != O2)
  310. return NoAlias;
  311. if ((isa<CallInst>(O2) || isa<InvokeInst>(O2)) &&
  312. isNonEscapingLocalObject(O1) && O1 != O2)
  313. return NoAlias;
  314. // If we have two gep instructions with must-alias'ing base pointers, figure
  315. // out if the indexes to the GEP tell us anything about the derived pointer.
  316. // Note that we also handle chains of getelementptr instructions as well as
  317. // constant expression getelementptrs here.
  318. //
  319. if (isGEP(V1) && isGEP(V2)) {
  320. const User *GEP1 = cast<User>(V1);
  321. const User *GEP2 = cast<User>(V2);
  322. // If V1 and V2 are identical GEPs, just recurse down on both of them.
  323. // This allows us to analyze things like:
  324. // P = gep A, 0, i, 1
  325. // Q = gep B, 0, i, 1
  326. // by just analyzing A and B. This is even safe for variable indices.
  327. if (GEP1->getType() == GEP2->getType() &&
  328. GEP1->getNumOperands() == GEP2->getNumOperands() &&
  329. GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() &&
  330. // All operands are the same, ignoring the base.
  331. std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
  332. return alias(GEP1->getOperand(0), V1Size, GEP2->getOperand(0), V2Size);
  333. // Drill down into the first non-gep value, to test for must-aliasing of
  334. // the base pointers.
  335. while (isGEP(GEP1->getOperand(0)) &&
  336. GEP1->getOperand(1) ==
  337. Context->getNullValue(GEP1->getOperand(1)->getType()))
  338. GEP1 = cast<User>(GEP1->getOperand(0));
  339. const Value *BasePtr1 = GEP1->getOperand(0);
  340. while (isGEP(GEP2->getOperand(0)) &&
  341. GEP2->getOperand(1) ==
  342. Context->getNullValue(GEP2->getOperand(1)->getType()))
  343. GEP2 = cast<User>(GEP2->getOperand(0));
  344. const Value *BasePtr2 = GEP2->getOperand(0);
  345. // Do the base pointers alias?
  346. AliasResult BaseAlias = alias(BasePtr1, ~0U, BasePtr2, ~0U);
  347. if (BaseAlias == NoAlias) return NoAlias;
  348. if (BaseAlias == MustAlias) {
  349. // If the base pointers alias each other exactly, check to see if we can
  350. // figure out anything about the resultant pointers, to try to prove
  351. // non-aliasing.
  352. // Collect all of the chained GEP operands together into one simple place
  353. SmallVector<Value*, 16> GEP1Ops, GEP2Ops;
  354. BasePtr1 = GetGEPOperands(V1, GEP1Ops);
  355. BasePtr2 = GetGEPOperands(V2, GEP2Ops);
  356. // If GetGEPOperands were able to fold to the same must-aliased pointer,
  357. // do the comparison.
  358. if (BasePtr1 == BasePtr2) {
  359. AliasResult GAlias =
  360. CheckGEPInstructions(BasePtr1->getType(),
  361. &GEP1Ops[0], GEP1Ops.size(), V1Size,
  362. BasePtr2->getType(),
  363. &GEP2Ops[0], GEP2Ops.size(), V2Size);
  364. if (GAlias != MayAlias)
  365. return GAlias;
  366. }
  367. }
  368. }
  369. // Check to see if these two pointers are related by a getelementptr
  370. // instruction. If one pointer is a GEP with a non-zero index of the other
  371. // pointer, we know they cannot alias.
  372. //
  373. if (isGEP(V2)) {
  374. std::swap(V1, V2);
  375. std::swap(V1Size, V2Size);
  376. }
  377. if (V1Size != ~0U && V2Size != ~0U)
  378. if (isGEP(V1)) {
  379. SmallVector<Value*, 16> GEPOperands;
  380. const Value *BasePtr = GetGEPOperands(V1, GEPOperands);
  381. AliasResult R = alias(BasePtr, V1Size, V2, V2Size);
  382. if (R == MustAlias) {
  383. // If there is at least one non-zero constant index, we know they cannot
  384. // alias.
  385. bool ConstantFound = false;
  386. bool AllZerosFound = true;
  387. for (unsigned i = 0, e = GEPOperands.size(); i != e; ++i)
  388. if (const Constant *C = dyn_cast<Constant>(GEPOperands[i])) {
  389. if (!C->isNullValue()) {
  390. ConstantFound = true;
  391. AllZerosFound = false;
  392. break;
  393. }
  394. } else {
  395. AllZerosFound = false;
  396. }
  397. // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
  398. // the ptr, the end result is a must alias also.
  399. if (AllZerosFound)
  400. return MustAlias;
  401. if (ConstantFound) {
  402. if (V2Size <= 1 && V1Size <= 1) // Just pointer check?
  403. return NoAlias;
  404. // Otherwise we have to check to see that the distance is more than
  405. // the size of the argument... build an index vector that is equal to
  406. // the arguments provided, except substitute 0's for any variable
  407. // indexes we find...
  408. if (cast<PointerType>(
  409. BasePtr->getType())->getElementType()->isSized()) {
  410. for (unsigned i = 0; i != GEPOperands.size(); ++i)
  411. if (!isa<ConstantInt>(GEPOperands[i]))
  412. GEPOperands[i] =
  413. Context->getNullValue(GEPOperands[i]->getType());
  414. int64_t Offset =
  415. getTargetData().getIndexedOffset(BasePtr->getType(),
  416. &GEPOperands[0],
  417. GEPOperands.size());
  418. if (Offset >= (int64_t)V2Size || Offset <= -(int64_t)V1Size)
  419. return NoAlias;
  420. }
  421. }
  422. }
  423. }
  424. return MayAlias;
  425. }
  426. // This function is used to determine if the indices of two GEP instructions are
  427. // equal. V1 and V2 are the indices.
  428. static bool IndexOperandsEqual(Value *V1, Value *V2, LLVMContext *Context) {
  429. if (V1->getType() == V2->getType())
  430. return V1 == V2;
  431. if (Constant *C1 = dyn_cast<Constant>(V1))
  432. if (Constant *C2 = dyn_cast<Constant>(V2)) {
  433. // Sign extend the constants to long types, if necessary
  434. if (C1->getType() != Type::Int64Ty)
  435. C1 = Context->getConstantExprSExt(C1, Type::Int64Ty);
  436. if (C2->getType() != Type::Int64Ty)
  437. C2 = Context->getConstantExprSExt(C2, Type::Int64Ty);
  438. return C1 == C2;
  439. }
  440. return false;
  441. }
  442. /// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
  443. /// base pointers. This checks to see if the index expressions preclude the
  444. /// pointers from aliasing...
  445. AliasAnalysis::AliasResult
  446. BasicAliasAnalysis::CheckGEPInstructions(
  447. const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S,
  448. const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) {
  449. // We currently can't handle the case when the base pointers have different
  450. // primitive types. Since this is uncommon anyway, we are happy being
  451. // extremely conservative.
  452. if (BasePtr1Ty != BasePtr2Ty)
  453. return MayAlias;
  454. const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty);
  455. // Find the (possibly empty) initial sequence of equal values... which are not
  456. // necessarily constants.
  457. unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops;
  458. unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
  459. unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
  460. unsigned UnequalOper = 0;
  461. while (UnequalOper != MinOperands &&
  462. IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper],
  463. Context)) {
  464. // Advance through the type as we go...
  465. ++UnequalOper;
  466. if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
  467. BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
  468. else {
  469. // If all operands equal each other, then the derived pointers must
  470. // alias each other...
  471. BasePtr1Ty = 0;
  472. assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
  473. "Ran out of type nesting, but not out of operands?");
  474. return MustAlias;
  475. }
  476. }
  477. // If we have seen all constant operands, and run out of indexes on one of the
  478. // getelementptrs, check to see if the tail of the leftover one is all zeros.
  479. // If so, return mustalias.
  480. if (UnequalOper == MinOperands) {
  481. if (NumGEP1Ops < NumGEP2Ops) {
  482. std::swap(GEP1Ops, GEP2Ops);
  483. std::swap(NumGEP1Ops, NumGEP2Ops);
  484. }
  485. bool AllAreZeros = true;
  486. for (unsigned i = UnequalOper; i != MaxOperands; ++i)
  487. if (!isa<Constant>(GEP1Ops[i]) ||
  488. !cast<Constant>(GEP1Ops[i])->isNullValue()) {
  489. AllAreZeros = false;
  490. break;
  491. }
  492. if (AllAreZeros) return MustAlias;
  493. }
  494. // So now we know that the indexes derived from the base pointers,
  495. // which are known to alias, are different. We can still determine a
  496. // no-alias result if there are differing constant pairs in the index
  497. // chain. For example:
  498. // A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
  499. //
  500. // We have to be careful here about array accesses. In particular, consider:
  501. // A[1][0] vs A[0][i]
  502. // In this case, we don't *know* that the array will be accessed in bounds:
  503. // the index could even be negative. Because of this, we have to
  504. // conservatively *give up* and return may alias. We disregard differing
  505. // array subscripts that are followed by a variable index without going
  506. // through a struct.
  507. //
  508. unsigned SizeMax = std::max(G1S, G2S);
  509. if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work.
  510. // Scan for the first operand that is constant and unequal in the
  511. // two getelementptrs...
  512. unsigned FirstConstantOper = UnequalOper;
  513. for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
  514. const Value *G1Oper = GEP1Ops[FirstConstantOper];
  515. const Value *G2Oper = GEP2Ops[FirstConstantOper];
  516. if (G1Oper != G2Oper) // Found non-equal constant indexes...
  517. if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper)))
  518. if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){
  519. if (G1OC->getType() != G2OC->getType()) {
  520. // Sign extend both operands to long.
  521. if (G1OC->getType() != Type::Int64Ty)
  522. G1OC = Context->getConstantExprSExt(G1OC, Type::Int64Ty);
  523. if (G2OC->getType() != Type::Int64Ty)
  524. G2OC = Context->getConstantExprSExt(G2OC, Type::Int64Ty);
  525. GEP1Ops[FirstConstantOper] = G1OC;
  526. GEP2Ops[FirstConstantOper] = G2OC;
  527. }
  528. if (G1OC != G2OC) {
  529. // Handle the "be careful" case above: if this is an array/vector
  530. // subscript, scan for a subsequent variable array index.
  531. if (const SequentialType *STy =
  532. dyn_cast<SequentialType>(BasePtr1Ty)) {
  533. const Type *NextTy = STy;
  534. bool isBadCase = false;
  535. for (unsigned Idx = FirstConstantOper;
  536. Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) {
  537. const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx];
  538. if (!isa<Constant>(V1) || !isa<Constant>(V2)) {
  539. isBadCase = true;
  540. break;
  541. }
  542. // If the array is indexed beyond the bounds of the static type
  543. // at this level, it will also fall into the "be careful" case.
  544. // It would theoretically be possible to analyze these cases,
  545. // but for now just be conservatively correct.
  546. if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
  547. if (cast<ConstantInt>(G1OC)->getZExtValue() >=
  548. ATy->getNumElements() ||
  549. cast<ConstantInt>(G2OC)->getZExtValue() >=
  550. ATy->getNumElements()) {
  551. isBadCase = true;
  552. break;
  553. }
  554. if (const VectorType *VTy = dyn_cast<VectorType>(STy))
  555. if (cast<ConstantInt>(G1OC)->getZExtValue() >=
  556. VTy->getNumElements() ||
  557. cast<ConstantInt>(G2OC)->getZExtValue() >=
  558. VTy->getNumElements()) {
  559. isBadCase = true;
  560. break;
  561. }
  562. STy = cast<SequentialType>(NextTy);
  563. NextTy = cast<SequentialType>(NextTy)->getElementType();
  564. }
  565. if (isBadCase) G1OC = 0;
  566. }
  567. // Make sure they are comparable (ie, not constant expressions), and
  568. // make sure the GEP with the smaller leading constant is GEP1.
  569. if (G1OC) {
  570. Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT,
  571. G1OC, G2OC);
  572. if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) {
  573. if (CV->getZExtValue()) { // If they are comparable and G2 > G1
  574. std::swap(GEP1Ops, GEP2Ops); // Make GEP1 < GEP2
  575. std::swap(NumGEP1Ops, NumGEP2Ops);
  576. }
  577. break;
  578. }
  579. }
  580. }
  581. }
  582. BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
  583. }
  584. // No shared constant operands, and we ran out of common operands. At this
  585. // point, the GEP instructions have run through all of their operands, and we
  586. // haven't found evidence that there are any deltas between the GEP's.
  587. // However, one GEP may have more operands than the other. If this is the
  588. // case, there may still be hope. Check this now.
  589. if (FirstConstantOper == MinOperands) {
  590. // Make GEP1Ops be the longer one if there is a longer one.
  591. if (NumGEP1Ops < NumGEP2Ops) {
  592. std::swap(GEP1Ops, GEP2Ops);
  593. std::swap(NumGEP1Ops, NumGEP2Ops);
  594. }
  595. // Is there anything to check?
  596. if (NumGEP1Ops > MinOperands) {
  597. for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
  598. if (isa<ConstantInt>(GEP1Ops[i]) &&
  599. !cast<ConstantInt>(GEP1Ops[i])->isZero()) {
  600. // Yup, there's a constant in the tail. Set all variables to
  601. // constants in the GEP instruction to make it suitable for
  602. // TargetData::getIndexedOffset.
  603. for (i = 0; i != MaxOperands; ++i)
  604. if (!isa<ConstantInt>(GEP1Ops[i]))
  605. GEP1Ops[i] = Context->getNullValue(GEP1Ops[i]->getType());
  606. // Okay, now get the offset. This is the relative offset for the full
  607. // instruction.
  608. const TargetData &TD = getTargetData();
  609. int64_t Offset1 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops,
  610. NumGEP1Ops);
  611. // Now check without any constants at the end.
  612. int64_t Offset2 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops,
  613. MinOperands);
  614. // Make sure we compare the absolute difference.
  615. if (Offset1 > Offset2)
  616. std::swap(Offset1, Offset2);
  617. // If the tail provided a bit enough offset, return noalias!
  618. if ((uint64_t)(Offset2-Offset1) >= SizeMax)
  619. return NoAlias;
  620. // Otherwise break - we don't look for another constant in the tail.
  621. break;
  622. }
  623. }
  624. // Couldn't find anything useful.
  625. return MayAlias;
  626. }
  627. // If there are non-equal constants arguments, then we can figure
  628. // out a minimum known delta between the two index expressions... at
  629. // this point we know that the first constant index of GEP1 is less
  630. // than the first constant index of GEP2.
  631. // Advance BasePtr[12]Ty over this first differing constant operand.
  632. BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->
  633. getTypeAtIndex(GEP2Ops[FirstConstantOper]);
  634. BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->
  635. getTypeAtIndex(GEP1Ops[FirstConstantOper]);
  636. // We are going to be using TargetData::getIndexedOffset to determine the
  637. // offset that each of the GEP's is reaching. To do this, we have to convert
  638. // all variable references to constant references. To do this, we convert the
  639. // initial sequence of array subscripts into constant zeros to start with.
  640. const Type *ZeroIdxTy = GEPPointerTy;
  641. for (unsigned i = 0; i != FirstConstantOper; ++i) {
  642. if (!isa<StructType>(ZeroIdxTy))
  643. GEP1Ops[i] = GEP2Ops[i] = Context->getNullValue(Type::Int32Ty);
  644. if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy))
  645. ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]);
  646. }
  647. // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
  648. // Loop over the rest of the operands...
  649. for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
  650. const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0;
  651. const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0;
  652. // If they are equal, use a zero index...
  653. if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
  654. if (!isa<ConstantInt>(Op1))
  655. GEP1Ops[i] = GEP2Ops[i] = Context->getNullValue(Op1->getType());
  656. // Otherwise, just keep the constants we have.
  657. } else {
  658. if (Op1) {
  659. if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
  660. // If this is an array index, make sure the array element is in range.
  661. if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) {
  662. if (Op1C->getZExtValue() >= AT->getNumElements())
  663. return MayAlias; // Be conservative with out-of-range accesses
  664. } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) {
  665. if (Op1C->getZExtValue() >= VT->getNumElements())
  666. return MayAlias; // Be conservative with out-of-range accesses
  667. }
  668. } else {
  669. // GEP1 is known to produce a value less than GEP2. To be
  670. // conservatively correct, we must assume the largest possible
  671. // constant is used in this position. This cannot be the initial
  672. // index to the GEP instructions (because we know we have at least one
  673. // element before this one with the different constant arguments), so
  674. // we know that the current index must be into either a struct or
  675. // array. Because we know it's not constant, this cannot be a
  676. // structure index. Because of this, we can calculate the maximum
  677. // value possible.
  678. //
  679. if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
  680. GEP1Ops[i] =
  681. Context->getConstantInt(Type::Int64Ty,AT->getNumElements()-1);
  682. else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty))
  683. GEP1Ops[i] =
  684. Context->getConstantInt(Type::Int64Ty,VT->getNumElements()-1);
  685. }
  686. }
  687. if (Op2) {
  688. if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
  689. // If this is an array index, make sure the array element is in range.
  690. if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) {
  691. if (Op2C->getZExtValue() >= AT->getNumElements())
  692. return MayAlias; // Be conservative with out-of-range accesses
  693. } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) {
  694. if (Op2C->getZExtValue() >= VT->getNumElements())
  695. return MayAlias; // Be conservative with out-of-range accesses
  696. }
  697. } else { // Conservatively assume the minimum value for this index
  698. GEP2Ops[i] = Context->getNullValue(Op2->getType());
  699. }
  700. }
  701. }
  702. if (BasePtr1Ty && Op1) {
  703. if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
  704. BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
  705. else
  706. BasePtr1Ty = 0;
  707. }
  708. if (BasePtr2Ty && Op2) {
  709. if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
  710. BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
  711. else
  712. BasePtr2Ty = 0;
  713. }
  714. }
  715. if (GEPPointerTy->getElementType()->isSized()) {
  716. int64_t Offset1 =
  717. getTargetData().getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops);
  718. int64_t Offset2 =
  719. getTargetData().getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops);
  720. assert(Offset1 != Offset2 &&
  721. "There is at least one different constant here!");
  722. // Make sure we compare the absolute difference.
  723. if (Offset1 > Offset2)
  724. std::swap(Offset1, Offset2);
  725. if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
  726. //cerr << "Determined that these two GEP's don't alias ["
  727. // << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
  728. return NoAlias;
  729. }
  730. }
  731. return MayAlias;
  732. }
  733. // Make sure that anything that uses AliasAnalysis pulls in this file...
  734. DEFINING_FILE_FOR(BasicAliasAnalysis)