/3rd_party/llvm/lib/Analysis/AliasAnalysis.cpp

https://code.google.com/p/softart/ · C++ · 556 lines · 342 code · 84 blank · 130 comment · 101 complexity · 1c83b975edafd8386967221d667f7b03 MD5 · raw file

  1. //===- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation -==//
  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 implements the generic AliasAnalysis interface which is used as the
  11. // common interface used by all clients and implementations of alias analysis.
  12. //
  13. // This file also implements the default version of the AliasAnalysis interface
  14. // that is to be used when no other implementation is specified. This does some
  15. // simple tests that detect obvious cases: two different global pointers cannot
  16. // alias, a global cannot alias a malloc, two different mallocs cannot alias,
  17. // etc.
  18. //
  19. // This alias analysis implementation really isn't very good for anything, but
  20. // it is very fast, and makes a nice clean default implementation. Because it
  21. // handles lots of little corner cases, other, more complex, alias analysis
  22. // implementations may choose to rely on this pass to resolve these simple and
  23. // easy cases.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "llvm/Analysis/AliasAnalysis.h"
  27. #include "llvm/Analysis/CaptureTracking.h"
  28. #include "llvm/Analysis/CFG.h"
  29. #include "llvm/Analysis/Dominators.h"
  30. #include "llvm/Analysis/ValueTracking.h"
  31. #include "llvm/IR/BasicBlock.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/Function.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/IntrinsicInst.h"
  36. #include "llvm/IR/LLVMContext.h"
  37. #include "llvm/IR/Type.h"
  38. #include "llvm/Pass.h"
  39. #include "llvm/Target/TargetLibraryInfo.h"
  40. using namespace llvm;
  41. // Register the AliasAnalysis interface, providing a nice name to refer to.
  42. INITIALIZE_ANALYSIS_GROUP(AliasAnalysis, "Alias Analysis", NoAA)
  43. char AliasAnalysis::ID = 0;
  44. //===----------------------------------------------------------------------===//
  45. // Default chaining methods
  46. //===----------------------------------------------------------------------===//
  47. AliasAnalysis::AliasResult
  48. AliasAnalysis::alias(const Location &LocA, const Location &LocB) {
  49. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  50. return AA->alias(LocA, LocB);
  51. }
  52. bool AliasAnalysis::pointsToConstantMemory(const Location &Loc,
  53. bool OrLocal) {
  54. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  55. return AA->pointsToConstantMemory(Loc, OrLocal);
  56. }
  57. void AliasAnalysis::deleteValue(Value *V) {
  58. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  59. AA->deleteValue(V);
  60. }
  61. void AliasAnalysis::copyValue(Value *From, Value *To) {
  62. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  63. AA->copyValue(From, To);
  64. }
  65. void AliasAnalysis::addEscapingUse(Use &U) {
  66. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  67. AA->addEscapingUse(U);
  68. }
  69. AliasAnalysis::ModRefResult
  70. AliasAnalysis::getModRefInfo(ImmutableCallSite CS,
  71. const Location &Loc) {
  72. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  73. ModRefBehavior MRB = getModRefBehavior(CS);
  74. if (MRB == DoesNotAccessMemory)
  75. return NoModRef;
  76. ModRefResult Mask = ModRef;
  77. if (onlyReadsMemory(MRB))
  78. Mask = Ref;
  79. if (onlyAccessesArgPointees(MRB)) {
  80. bool doesAlias = false;
  81. if (doesAccessArgPointees(MRB)) {
  82. MDNode *CSTag = CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa);
  83. for (ImmutableCallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
  84. AI != AE; ++AI) {
  85. const Value *Arg = *AI;
  86. if (!Arg->getType()->isPointerTy())
  87. continue;
  88. Location CSLoc(Arg, UnknownSize, CSTag);
  89. if (!isNoAlias(CSLoc, Loc)) {
  90. doesAlias = true;
  91. break;
  92. }
  93. }
  94. }
  95. if (!doesAlias)
  96. return NoModRef;
  97. }
  98. // If Loc is a constant memory location, the call definitely could not
  99. // modify the memory location.
  100. if ((Mask & Mod) && pointsToConstantMemory(Loc))
  101. Mask = ModRefResult(Mask & ~Mod);
  102. // If this is the end of the chain, don't forward.
  103. if (!AA) return Mask;
  104. // Otherwise, fall back to the next AA in the chain. But we can merge
  105. // in any mask we've managed to compute.
  106. return ModRefResult(AA->getModRefInfo(CS, Loc) & Mask);
  107. }
  108. AliasAnalysis::ModRefResult
  109. AliasAnalysis::getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2) {
  110. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  111. // If CS1 or CS2 are readnone, they don't interact.
  112. ModRefBehavior CS1B = getModRefBehavior(CS1);
  113. if (CS1B == DoesNotAccessMemory) return NoModRef;
  114. ModRefBehavior CS2B = getModRefBehavior(CS2);
  115. if (CS2B == DoesNotAccessMemory) return NoModRef;
  116. // If they both only read from memory, there is no dependence.
  117. if (onlyReadsMemory(CS1B) && onlyReadsMemory(CS2B))
  118. return NoModRef;
  119. AliasAnalysis::ModRefResult Mask = ModRef;
  120. // If CS1 only reads memory, the only dependence on CS2 can be
  121. // from CS1 reading memory written by CS2.
  122. if (onlyReadsMemory(CS1B))
  123. Mask = ModRefResult(Mask & Ref);
  124. // If CS2 only access memory through arguments, accumulate the mod/ref
  125. // information from CS1's references to the memory referenced by
  126. // CS2's arguments.
  127. if (onlyAccessesArgPointees(CS2B)) {
  128. AliasAnalysis::ModRefResult R = NoModRef;
  129. if (doesAccessArgPointees(CS2B)) {
  130. MDNode *CS2Tag = CS2.getInstruction()->getMetadata(LLVMContext::MD_tbaa);
  131. for (ImmutableCallSite::arg_iterator
  132. I = CS2.arg_begin(), E = CS2.arg_end(); I != E; ++I) {
  133. const Value *Arg = *I;
  134. if (!Arg->getType()->isPointerTy())
  135. continue;
  136. Location CS2Loc(Arg, UnknownSize, CS2Tag);
  137. R = ModRefResult((R | getModRefInfo(CS1, CS2Loc)) & Mask);
  138. if (R == Mask)
  139. break;
  140. }
  141. }
  142. return R;
  143. }
  144. // If CS1 only accesses memory through arguments, check if CS2 references
  145. // any of the memory referenced by CS1's arguments. If not, return NoModRef.
  146. if (onlyAccessesArgPointees(CS1B)) {
  147. AliasAnalysis::ModRefResult R = NoModRef;
  148. if (doesAccessArgPointees(CS1B)) {
  149. MDNode *CS1Tag = CS1.getInstruction()->getMetadata(LLVMContext::MD_tbaa);
  150. for (ImmutableCallSite::arg_iterator
  151. I = CS1.arg_begin(), E = CS1.arg_end(); I != E; ++I) {
  152. const Value *Arg = *I;
  153. if (!Arg->getType()->isPointerTy())
  154. continue;
  155. Location CS1Loc(Arg, UnknownSize, CS1Tag);
  156. if (getModRefInfo(CS2, CS1Loc) != NoModRef) {
  157. R = Mask;
  158. break;
  159. }
  160. }
  161. }
  162. if (R == NoModRef)
  163. return R;
  164. }
  165. // If this is the end of the chain, don't forward.
  166. if (!AA) return Mask;
  167. // Otherwise, fall back to the next AA in the chain. But we can merge
  168. // in any mask we've managed to compute.
  169. return ModRefResult(AA->getModRefInfo(CS1, CS2) & Mask);
  170. }
  171. AliasAnalysis::ModRefBehavior
  172. AliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
  173. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  174. ModRefBehavior Min = UnknownModRefBehavior;
  175. // Call back into the alias analysis with the other form of getModRefBehavior
  176. // to see if it can give a better response.
  177. if (const Function *F = CS.getCalledFunction())
  178. Min = getModRefBehavior(F);
  179. // If this is the end of the chain, don't forward.
  180. if (!AA) return Min;
  181. // Otherwise, fall back to the next AA in the chain. But we can merge
  182. // in any result we've managed to compute.
  183. return ModRefBehavior(AA->getModRefBehavior(CS) & Min);
  184. }
  185. AliasAnalysis::ModRefBehavior
  186. AliasAnalysis::getModRefBehavior(const Function *F) {
  187. assert(AA && "AA didn't call InitializeAliasAnalysis in its run method!");
  188. return AA->getModRefBehavior(F);
  189. }
  190. //===----------------------------------------------------------------------===//
  191. // AliasAnalysis non-virtual helper method implementation
  192. //===----------------------------------------------------------------------===//
  193. AliasAnalysis::Location AliasAnalysis::getLocation(const LoadInst *LI) {
  194. return Location(LI->getPointerOperand(),
  195. getTypeStoreSize(LI->getType()),
  196. LI->getMetadata(LLVMContext::MD_tbaa));
  197. }
  198. AliasAnalysis::Location AliasAnalysis::getLocation(const StoreInst *SI) {
  199. return Location(SI->getPointerOperand(),
  200. getTypeStoreSize(SI->getValueOperand()->getType()),
  201. SI->getMetadata(LLVMContext::MD_tbaa));
  202. }
  203. AliasAnalysis::Location AliasAnalysis::getLocation(const VAArgInst *VI) {
  204. return Location(VI->getPointerOperand(),
  205. UnknownSize,
  206. VI->getMetadata(LLVMContext::MD_tbaa));
  207. }
  208. AliasAnalysis::Location
  209. AliasAnalysis::getLocation(const AtomicCmpXchgInst *CXI) {
  210. return Location(CXI->getPointerOperand(),
  211. getTypeStoreSize(CXI->getCompareOperand()->getType()),
  212. CXI->getMetadata(LLVMContext::MD_tbaa));
  213. }
  214. AliasAnalysis::Location
  215. AliasAnalysis::getLocation(const AtomicRMWInst *RMWI) {
  216. return Location(RMWI->getPointerOperand(),
  217. getTypeStoreSize(RMWI->getValOperand()->getType()),
  218. RMWI->getMetadata(LLVMContext::MD_tbaa));
  219. }
  220. AliasAnalysis::Location
  221. AliasAnalysis::getLocationForSource(const MemTransferInst *MTI) {
  222. uint64_t Size = UnknownSize;
  223. if (ConstantInt *C = dyn_cast<ConstantInt>(MTI->getLength()))
  224. Size = C->getValue().getZExtValue();
  225. // memcpy/memmove can have TBAA tags. For memcpy, they apply
  226. // to both the source and the destination.
  227. MDNode *TBAATag = MTI->getMetadata(LLVMContext::MD_tbaa);
  228. return Location(MTI->getRawSource(), Size, TBAATag);
  229. }
  230. AliasAnalysis::Location
  231. AliasAnalysis::getLocationForDest(const MemIntrinsic *MTI) {
  232. uint64_t Size = UnknownSize;
  233. if (ConstantInt *C = dyn_cast<ConstantInt>(MTI->getLength()))
  234. Size = C->getValue().getZExtValue();
  235. // memcpy/memmove can have TBAA tags. For memcpy, they apply
  236. // to both the source and the destination.
  237. MDNode *TBAATag = MTI->getMetadata(LLVMContext::MD_tbaa);
  238. return Location(MTI->getRawDest(), Size, TBAATag);
  239. }
  240. AliasAnalysis::ModRefResult
  241. AliasAnalysis::getModRefInfo(const LoadInst *L, const Location &Loc) {
  242. // Be conservative in the face of volatile/atomic.
  243. if (!L->isUnordered())
  244. return ModRef;
  245. // If the load address doesn't alias the given address, it doesn't read
  246. // or write the specified memory.
  247. if (!alias(getLocation(L), Loc))
  248. return NoModRef;
  249. // Otherwise, a load just reads.
  250. return Ref;
  251. }
  252. AliasAnalysis::ModRefResult
  253. AliasAnalysis::getModRefInfo(const StoreInst *S, const Location &Loc) {
  254. // Be conservative in the face of volatile/atomic.
  255. if (!S->isUnordered())
  256. return ModRef;
  257. // If the store address cannot alias the pointer in question, then the
  258. // specified memory cannot be modified by the store.
  259. if (!alias(getLocation(S), Loc))
  260. return NoModRef;
  261. // If the pointer is a pointer to constant memory, then it could not have been
  262. // modified by this store.
  263. if (pointsToConstantMemory(Loc))
  264. return NoModRef;
  265. // Otherwise, a store just writes.
  266. return Mod;
  267. }
  268. AliasAnalysis::ModRefResult
  269. AliasAnalysis::getModRefInfo(const VAArgInst *V, const Location &Loc) {
  270. // If the va_arg address cannot alias the pointer in question, then the
  271. // specified memory cannot be accessed by the va_arg.
  272. if (!alias(getLocation(V), Loc))
  273. return NoModRef;
  274. // If the pointer is a pointer to constant memory, then it could not have been
  275. // modified by this va_arg.
  276. if (pointsToConstantMemory(Loc))
  277. return NoModRef;
  278. // Otherwise, a va_arg reads and writes.
  279. return ModRef;
  280. }
  281. AliasAnalysis::ModRefResult
  282. AliasAnalysis::getModRefInfo(const AtomicCmpXchgInst *CX, const Location &Loc) {
  283. // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
  284. if (CX->getOrdering() > Monotonic)
  285. return ModRef;
  286. // If the cmpxchg address does not alias the location, it does not access it.
  287. if (!alias(getLocation(CX), Loc))
  288. return NoModRef;
  289. return ModRef;
  290. }
  291. AliasAnalysis::ModRefResult
  292. AliasAnalysis::getModRefInfo(const AtomicRMWInst *RMW, const Location &Loc) {
  293. // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
  294. if (RMW->getOrdering() > Monotonic)
  295. return ModRef;
  296. // If the atomicrmw address does not alias the location, it does not access it.
  297. if (!alias(getLocation(RMW), Loc))
  298. return NoModRef;
  299. return ModRef;
  300. }
  301. namespace {
  302. /// Only find pointer captures which happen before the given instruction. Uses
  303. /// the dominator tree to determine whether one instruction is before another.
  304. /// Only support the case where the Value is defined in the same basic block
  305. /// as the given instruction and the use.
  306. struct CapturesBefore : public CaptureTracker {
  307. CapturesBefore(const Instruction *I, DominatorTree *DT)
  308. : BeforeHere(I), DT(DT), Captured(false) {}
  309. void tooManyUses() { Captured = true; }
  310. bool shouldExplore(Use *U) {
  311. Instruction *I = cast<Instruction>(U->getUser());
  312. BasicBlock *BB = I->getParent();
  313. // We explore this usage only if the usage can reach "BeforeHere".
  314. // If use is not reachable from entry, there is no need to explore.
  315. if (BeforeHere != I && !DT->isReachableFromEntry(BB))
  316. return false;
  317. // If the value is defined in the same basic block as use and BeforeHere,
  318. // there is no need to explore the use if BeforeHere dominates use.
  319. // Check whether there is a path from I to BeforeHere.
  320. if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
  321. !isPotentiallyReachable(I, BeforeHere, DT))
  322. return false;
  323. return true;
  324. }
  325. bool captured(Use *U) {
  326. Instruction *I = cast<Instruction>(U->getUser());
  327. BasicBlock *BB = I->getParent();
  328. // Same logic as in shouldExplore.
  329. if (BeforeHere != I && !DT->isReachableFromEntry(BB))
  330. return false;
  331. if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
  332. !isPotentiallyReachable(I, BeforeHere, DT))
  333. return false;
  334. Captured = true;
  335. return true;
  336. }
  337. const Instruction *BeforeHere;
  338. DominatorTree *DT;
  339. bool Captured;
  340. };
  341. }
  342. // FIXME: this is really just shoring-up a deficiency in alias analysis.
  343. // BasicAA isn't willing to spend linear time determining whether an alloca
  344. // was captured before or after this particular call, while we are. However,
  345. // with a smarter AA in place, this test is just wasting compile time.
  346. AliasAnalysis::ModRefResult
  347. AliasAnalysis::callCapturesBefore(const Instruction *I,
  348. const AliasAnalysis::Location &MemLoc,
  349. DominatorTree *DT) {
  350. if (!DT || !TD) return AliasAnalysis::ModRef;
  351. const Value *Object = GetUnderlyingObject(MemLoc.Ptr, TD);
  352. if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object) ||
  353. isa<Constant>(Object))
  354. return AliasAnalysis::ModRef;
  355. ImmutableCallSite CS(I);
  356. if (!CS.getInstruction() || CS.getInstruction() == Object)
  357. return AliasAnalysis::ModRef;
  358. CapturesBefore CB(I, DT);
  359. llvm::PointerMayBeCaptured(Object, &CB);
  360. if (CB.Captured)
  361. return AliasAnalysis::ModRef;
  362. unsigned ArgNo = 0;
  363. AliasAnalysis::ModRefResult R = AliasAnalysis::NoModRef;
  364. for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
  365. CI != CE; ++CI, ++ArgNo) {
  366. // Only look at the no-capture or byval pointer arguments. If this
  367. // pointer were passed to arguments that were neither of these, then it
  368. // couldn't be no-capture.
  369. if (!(*CI)->getType()->isPointerTy() ||
  370. (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
  371. continue;
  372. // If this is a no-capture pointer argument, see if we can tell that it
  373. // is impossible to alias the pointer we're checking. If not, we have to
  374. // assume that the call could touch the pointer, even though it doesn't
  375. // escape.
  376. if (isNoAlias(AliasAnalysis::Location(*CI),
  377. AliasAnalysis::Location(Object)))
  378. continue;
  379. if (CS.doesNotAccessMemory(ArgNo))
  380. continue;
  381. if (CS.onlyReadsMemory(ArgNo)) {
  382. R = AliasAnalysis::Ref;
  383. continue;
  384. }
  385. return AliasAnalysis::ModRef;
  386. }
  387. return R;
  388. }
  389. // AliasAnalysis destructor: DO NOT move this to the header file for
  390. // AliasAnalysis or else clients of the AliasAnalysis class may not depend on
  391. // the AliasAnalysis.o file in the current .a file, causing alias analysis
  392. // support to not be included in the tool correctly!
  393. //
  394. AliasAnalysis::~AliasAnalysis() {}
  395. /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
  396. /// AliasAnalysis interface before any other methods are called.
  397. ///
  398. void AliasAnalysis::InitializeAliasAnalysis(Pass *P) {
  399. TD = P->getAnalysisIfAvailable<DataLayout>();
  400. TLI = P->getAnalysisIfAvailable<TargetLibraryInfo>();
  401. AA = &P->getAnalysis<AliasAnalysis>();
  402. }
  403. // getAnalysisUsage - All alias analysis implementations should invoke this
  404. // directly (using AliasAnalysis::getAnalysisUsage(AU)).
  405. void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  406. AU.addRequired<AliasAnalysis>(); // All AA's chain
  407. }
  408. /// getTypeStoreSize - Return the DataLayout store size for the given type,
  409. /// if known, or a conservative value otherwise.
  410. ///
  411. uint64_t AliasAnalysis::getTypeStoreSize(Type *Ty) {
  412. return TD ? TD->getTypeStoreSize(Ty) : UnknownSize;
  413. }
  414. /// canBasicBlockModify - Return true if it is possible for execution of the
  415. /// specified basic block to modify the value pointed to by Ptr.
  416. ///
  417. bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
  418. const Location &Loc) {
  419. return canInstructionRangeModify(BB.front(), BB.back(), Loc);
  420. }
  421. /// canInstructionRangeModify - Return true if it is possible for the execution
  422. /// of the specified instructions to modify the value pointed to by Ptr. The
  423. /// instructions to consider are all of the instructions in the range of [I1,I2]
  424. /// INCLUSIVE. I1 and I2 must be in the same basic block.
  425. ///
  426. bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1,
  427. const Instruction &I2,
  428. const Location &Loc) {
  429. assert(I1.getParent() == I2.getParent() &&
  430. "Instructions not in same basic block!");
  431. BasicBlock::const_iterator I = &I1;
  432. BasicBlock::const_iterator E = &I2;
  433. ++E; // Convert from inclusive to exclusive range.
  434. for (; I != E; ++I) // Check every instruction in range
  435. if (getModRefInfo(I, Loc) & Mod)
  436. return true;
  437. return false;
  438. }
  439. /// isNoAliasCall - Return true if this pointer is returned by a noalias
  440. /// function.
  441. bool llvm::isNoAliasCall(const Value *V) {
  442. if (isa<CallInst>(V) || isa<InvokeInst>(V))
  443. return ImmutableCallSite(cast<Instruction>(V))
  444. .paramHasAttr(0, Attribute::NoAlias);
  445. return false;
  446. }
  447. /// isNoAliasArgument - Return true if this is an argument with the noalias
  448. /// attribute.
  449. bool llvm::isNoAliasArgument(const Value *V)
  450. {
  451. if (const Argument *A = dyn_cast<Argument>(V))
  452. return A->hasNoAliasAttr();
  453. return false;
  454. }
  455. /// isIdentifiedObject - Return true if this pointer refers to a distinct and
  456. /// identifiable object. This returns true for:
  457. /// Global Variables and Functions (but not Global Aliases)
  458. /// Allocas and Mallocs
  459. /// ByVal and NoAlias Arguments
  460. /// NoAlias returns
  461. ///
  462. bool llvm::isIdentifiedObject(const Value *V) {
  463. if (isa<AllocaInst>(V))
  464. return true;
  465. if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))
  466. return true;
  467. if (isNoAliasCall(V))
  468. return true;
  469. if (const Argument *A = dyn_cast<Argument>(V))
  470. return A->hasNoAliasAttr() || A->hasByValAttr();
  471. return false;
  472. }