AliasSetTracker.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. //===- AliasSetTracker.cpp - Alias Sets Tracker implementation-------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the AliasSetTracker and AliasSet classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/AliasSetTracker.h"
  13. #include "llvm/Analysis/AliasAnalysis.h"
  14. #include "llvm/Analysis/GuardUtils.h"
  15. #include "llvm/Analysis/LoopInfo.h"
  16. #include "llvm/Analysis/MemoryLocation.h"
  17. #include "llvm/Config/llvm-config.h"
  18. #include "llvm/IR/Constants.h"
  19. #include "llvm/IR/DataLayout.h"
  20. #include "llvm/IR/Function.h"
  21. #include "llvm/IR/InstIterator.h"
  22. #include "llvm/IR/Instructions.h"
  23. #include "llvm/IR/IntrinsicInst.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/IR/PassManager.h"
  26. #include "llvm/IR/PatternMatch.h"
  27. #include "llvm/IR/Value.h"
  28. #include "llvm/InitializePasses.h"
  29. #include "llvm/Pass.h"
  30. #include "llvm/Support/AtomicOrdering.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/Compiler.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. using namespace llvm;
  37. static cl::opt<unsigned>
  38. SaturationThreshold("alias-set-saturation-threshold", cl::Hidden,
  39. cl::init(250),
  40. cl::desc("The maximum number of pointers may-alias "
  41. "sets may contain before degradation"));
  42. /// mergeSetIn - Merge the specified alias set into this alias set.
  43. ///
  44. void AliasSet::mergeSetIn(AliasSet &AS, AliasSetTracker &AST) {
  45. assert(!AS.Forward && "Alias set is already forwarding!");
  46. assert(!Forward && "This set is a forwarding set!!");
  47. bool WasMustAlias = (Alias == SetMustAlias);
  48. // Update the alias and access types of this set...
  49. Access |= AS.Access;
  50. Alias |= AS.Alias;
  51. if (Alias == SetMustAlias) {
  52. // Check that these two merged sets really are must aliases. Since both
  53. // used to be must-alias sets, we can just check any pointer from each set
  54. // for aliasing.
  55. AliasAnalysis &AA = AST.getAliasAnalysis();
  56. PointerRec *L = getSomePointer();
  57. PointerRec *R = AS.getSomePointer();
  58. // If the pointers are not a must-alias pair, this set becomes a may alias.
  59. if (!AA.isMustAlias(
  60. MemoryLocation(L->getValue(), L->getSize(), L->getAAInfo()),
  61. MemoryLocation(R->getValue(), R->getSize(), R->getAAInfo())))
  62. Alias = SetMayAlias;
  63. }
  64. if (Alias == SetMayAlias) {
  65. if (WasMustAlias)
  66. AST.TotalMayAliasSetSize += size();
  67. if (AS.Alias == SetMustAlias)
  68. AST.TotalMayAliasSetSize += AS.size();
  69. }
  70. bool ASHadUnknownInsts = !AS.UnknownInsts.empty();
  71. if (UnknownInsts.empty()) { // Merge call sites...
  72. if (ASHadUnknownInsts) {
  73. std::swap(UnknownInsts, AS.UnknownInsts);
  74. addRef();
  75. }
  76. } else if (ASHadUnknownInsts) {
  77. llvm::append_range(UnknownInsts, AS.UnknownInsts);
  78. AS.UnknownInsts.clear();
  79. }
  80. AS.Forward = this; // Forward across AS now...
  81. addRef(); // AS is now pointing to us...
  82. // Merge the list of constituent pointers...
  83. if (AS.PtrList) {
  84. SetSize += AS.size();
  85. AS.SetSize = 0;
  86. *PtrListEnd = AS.PtrList;
  87. AS.PtrList->setPrevInList(PtrListEnd);
  88. PtrListEnd = AS.PtrListEnd;
  89. AS.PtrList = nullptr;
  90. AS.PtrListEnd = &AS.PtrList;
  91. assert(*AS.PtrListEnd == nullptr && "End of list is not null?");
  92. }
  93. if (ASHadUnknownInsts)
  94. AS.dropRef(AST);
  95. }
  96. void AliasSetTracker::removeAliasSet(AliasSet *AS) {
  97. if (AliasSet *Fwd = AS->Forward) {
  98. Fwd->dropRef(*this);
  99. AS->Forward = nullptr;
  100. } else // Update TotalMayAliasSetSize only if not forwarding.
  101. if (AS->Alias == AliasSet::SetMayAlias)
  102. TotalMayAliasSetSize -= AS->size();
  103. AliasSets.erase(AS);
  104. // If we've removed the saturated alias set, set saturated marker back to
  105. // nullptr and ensure this tracker is empty.
  106. if (AS == AliasAnyAS) {
  107. AliasAnyAS = nullptr;
  108. assert(AliasSets.empty() && "Tracker not empty");
  109. }
  110. }
  111. void AliasSet::removeFromTracker(AliasSetTracker &AST) {
  112. assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!");
  113. AST.removeAliasSet(this);
  114. }
  115. void AliasSet::addPointer(AliasSetTracker &AST, PointerRec &Entry,
  116. LocationSize Size, const AAMDNodes &AAInfo,
  117. bool KnownMustAlias, bool SkipSizeUpdate) {
  118. assert(!Entry.hasAliasSet() && "Entry already in set!");
  119. // Check to see if we have to downgrade to _may_ alias.
  120. if (isMustAlias())
  121. if (PointerRec *P = getSomePointer()) {
  122. if (!KnownMustAlias) {
  123. AliasAnalysis &AA = AST.getAliasAnalysis();
  124. AliasResult Result = AA.alias(
  125. MemoryLocation(P->getValue(), P->getSize(), P->getAAInfo()),
  126. MemoryLocation(Entry.getValue(), Size, AAInfo));
  127. if (Result != AliasResult::MustAlias) {
  128. Alias = SetMayAlias;
  129. AST.TotalMayAliasSetSize += size();
  130. }
  131. assert(Result != AliasResult::NoAlias && "Cannot be part of must set!");
  132. } else if (!SkipSizeUpdate)
  133. P->updateSizeAndAAInfo(Size, AAInfo);
  134. }
  135. Entry.setAliasSet(this);
  136. Entry.updateSizeAndAAInfo(Size, AAInfo);
  137. // Add it to the end of the list...
  138. ++SetSize;
  139. assert(*PtrListEnd == nullptr && "End of list is not null?");
  140. *PtrListEnd = &Entry;
  141. PtrListEnd = Entry.setPrevInList(PtrListEnd);
  142. assert(*PtrListEnd == nullptr && "End of list is not null?");
  143. // Entry points to alias set.
  144. addRef();
  145. if (Alias == SetMayAlias)
  146. AST.TotalMayAliasSetSize++;
  147. }
  148. void AliasSet::addUnknownInst(Instruction *I, AliasAnalysis &AA) {
  149. if (UnknownInsts.empty())
  150. addRef();
  151. UnknownInsts.emplace_back(I);
  152. // Guards are marked as modifying memory for control flow modelling purposes,
  153. // but don't actually modify any specific memory location.
  154. using namespace PatternMatch;
  155. bool MayWriteMemory = I->mayWriteToMemory() && !isGuard(I) &&
  156. !(I->use_empty() && match(I, m_Intrinsic<Intrinsic::invariant_start>()));
  157. if (!MayWriteMemory) {
  158. Alias = SetMayAlias;
  159. Access |= RefAccess;
  160. return;
  161. }
  162. // FIXME: This should use mod/ref information to make this not suck so bad
  163. Alias = SetMayAlias;
  164. Access = ModRefAccess;
  165. }
  166. /// aliasesPointer - If the specified pointer "may" (or must) alias one of the
  167. /// members in the set return the appropriate AliasResult. Otherwise return
  168. /// NoAlias.
  169. ///
  170. AliasResult AliasSet::aliasesPointer(const Value *Ptr, LocationSize Size,
  171. const AAMDNodes &AAInfo,
  172. AliasAnalysis &AA) const {
  173. if (AliasAny)
  174. return AliasResult::MayAlias;
  175. if (Alias == SetMustAlias) {
  176. assert(UnknownInsts.empty() && "Illegal must alias set!");
  177. // If this is a set of MustAliases, only check to see if the pointer aliases
  178. // SOME value in the set.
  179. PointerRec *SomePtr = getSomePointer();
  180. assert(SomePtr && "Empty must-alias set??");
  181. return AA.alias(MemoryLocation(SomePtr->getValue(), SomePtr->getSize(),
  182. SomePtr->getAAInfo()),
  183. MemoryLocation(Ptr, Size, AAInfo));
  184. }
  185. // If this is a may-alias set, we have to check all of the pointers in the set
  186. // to be sure it doesn't alias the set...
  187. for (iterator I = begin(), E = end(); I != E; ++I) {
  188. AliasResult AR =
  189. AA.alias(MemoryLocation(Ptr, Size, AAInfo),
  190. MemoryLocation(I.getPointer(), I.getSize(), I.getAAInfo()));
  191. if (AR != AliasResult::NoAlias)
  192. return AR;
  193. }
  194. // Check the unknown instructions...
  195. if (!UnknownInsts.empty()) {
  196. for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i)
  197. if (auto *Inst = getUnknownInst(i))
  198. if (isModOrRefSet(
  199. AA.getModRefInfo(Inst, MemoryLocation(Ptr, Size, AAInfo))))
  200. return AliasResult::MayAlias;
  201. }
  202. return AliasResult::NoAlias;
  203. }
  204. bool AliasSet::aliasesUnknownInst(const Instruction *Inst,
  205. AliasAnalysis &AA) const {
  206. if (AliasAny)
  207. return true;
  208. assert(Inst->mayReadOrWriteMemory() &&
  209. "Instruction must either read or write memory.");
  210. for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) {
  211. if (auto *UnknownInst = getUnknownInst(i)) {
  212. const auto *C1 = dyn_cast<CallBase>(UnknownInst);
  213. const auto *C2 = dyn_cast<CallBase>(Inst);
  214. if (!C1 || !C2 || isModOrRefSet(AA.getModRefInfo(C1, C2)) ||
  215. isModOrRefSet(AA.getModRefInfo(C2, C1)))
  216. return true;
  217. }
  218. }
  219. for (iterator I = begin(), E = end(); I != E; ++I)
  220. if (isModOrRefSet(AA.getModRefInfo(
  221. Inst, MemoryLocation(I.getPointer(), I.getSize(), I.getAAInfo()))))
  222. return true;
  223. return false;
  224. }
  225. Instruction* AliasSet::getUniqueInstruction() {
  226. if (AliasAny)
  227. // May have collapses alias set
  228. return nullptr;
  229. if (begin() != end()) {
  230. if (!UnknownInsts.empty())
  231. // Another instruction found
  232. return nullptr;
  233. if (std::next(begin()) != end())
  234. // Another instruction found
  235. return nullptr;
  236. Value *Addr = begin()->getValue();
  237. assert(!Addr->user_empty() &&
  238. "where's the instruction which added this pointer?");
  239. if (std::next(Addr->user_begin()) != Addr->user_end())
  240. // Another instruction found -- this is really restrictive
  241. // TODO: generalize!
  242. return nullptr;
  243. return cast<Instruction>(*(Addr->user_begin()));
  244. }
  245. if (1 != UnknownInsts.size())
  246. return nullptr;
  247. return cast<Instruction>(UnknownInsts[0]);
  248. }
  249. void AliasSetTracker::clear() {
  250. // Delete all the PointerRec entries.
  251. for (auto &I : PointerMap)
  252. I.second->eraseFromList();
  253. PointerMap.clear();
  254. // The alias sets should all be clear now.
  255. AliasSets.clear();
  256. }
  257. /// mergeAliasSetsForPointer - Given a pointer, merge all alias sets that may
  258. /// alias the pointer. Return the unified set, or nullptr if no set that aliases
  259. /// the pointer was found. MustAliasAll is updated to true/false if the pointer
  260. /// is found to MustAlias all the sets it merged.
  261. AliasSet *AliasSetTracker::mergeAliasSetsForPointer(const Value *Ptr,
  262. LocationSize Size,
  263. const AAMDNodes &AAInfo,
  264. bool &MustAliasAll) {
  265. AliasSet *FoundSet = nullptr;
  266. MustAliasAll = true;
  267. for (AliasSet &AS : llvm::make_early_inc_range(*this)) {
  268. if (AS.Forward)
  269. continue;
  270. AliasResult AR = AS.aliasesPointer(Ptr, Size, AAInfo, AA);
  271. if (AR == AliasResult::NoAlias)
  272. continue;
  273. if (AR != AliasResult::MustAlias)
  274. MustAliasAll = false;
  275. if (!FoundSet) {
  276. // If this is the first alias set ptr can go into, remember it.
  277. FoundSet = &AS;
  278. } else {
  279. // Otherwise, we must merge the sets.
  280. FoundSet->mergeSetIn(AS, *this);
  281. }
  282. }
  283. return FoundSet;
  284. }
  285. AliasSet *AliasSetTracker::findAliasSetForUnknownInst(Instruction *Inst) {
  286. AliasSet *FoundSet = nullptr;
  287. for (AliasSet &AS : llvm::make_early_inc_range(*this)) {
  288. if (AS.Forward || !AS.aliasesUnknownInst(Inst, AA))
  289. continue;
  290. if (!FoundSet) {
  291. // If this is the first alias set ptr can go into, remember it.
  292. FoundSet = &AS;
  293. } else {
  294. // Otherwise, we must merge the sets.
  295. FoundSet->mergeSetIn(AS, *this);
  296. }
  297. }
  298. return FoundSet;
  299. }
  300. AliasSet &AliasSetTracker::getAliasSetFor(const MemoryLocation &MemLoc) {
  301. Value * const Pointer = const_cast<Value*>(MemLoc.Ptr);
  302. const LocationSize Size = MemLoc.Size;
  303. const AAMDNodes &AAInfo = MemLoc.AATags;
  304. AliasSet::PointerRec &Entry = getEntryFor(Pointer);
  305. if (AliasAnyAS) {
  306. // At this point, the AST is saturated, so we only have one active alias
  307. // set. That means we already know which alias set we want to return, and
  308. // just need to add the pointer to that set to keep the data structure
  309. // consistent.
  310. // This, of course, means that we will never need a merge here.
  311. if (Entry.hasAliasSet()) {
  312. Entry.updateSizeAndAAInfo(Size, AAInfo);
  313. assert(Entry.getAliasSet(*this) == AliasAnyAS &&
  314. "Entry in saturated AST must belong to only alias set");
  315. } else {
  316. AliasAnyAS->addPointer(*this, Entry, Size, AAInfo);
  317. }
  318. return *AliasAnyAS;
  319. }
  320. bool MustAliasAll = false;
  321. // Check to see if the pointer is already known.
  322. if (Entry.hasAliasSet()) {
  323. // If the size changed, we may need to merge several alias sets.
  324. // Note that we can *not* return the result of mergeAliasSetsForPointer
  325. // due to a quirk of alias analysis behavior. Since alias(undef, undef)
  326. // is NoAlias, mergeAliasSetsForPointer(undef, ...) will not find the
  327. // the right set for undef, even if it exists.
  328. if (Entry.updateSizeAndAAInfo(Size, AAInfo))
  329. mergeAliasSetsForPointer(Pointer, Size, AAInfo, MustAliasAll);
  330. // Return the set!
  331. return *Entry.getAliasSet(*this)->getForwardedTarget(*this);
  332. }
  333. if (AliasSet *AS =
  334. mergeAliasSetsForPointer(Pointer, Size, AAInfo, MustAliasAll)) {
  335. // Add it to the alias set it aliases.
  336. AS->addPointer(*this, Entry, Size, AAInfo, MustAliasAll);
  337. return *AS;
  338. }
  339. // Otherwise create a new alias set to hold the loaded pointer.
  340. AliasSets.push_back(new AliasSet());
  341. AliasSets.back().addPointer(*this, Entry, Size, AAInfo, true);
  342. return AliasSets.back();
  343. }
  344. void AliasSetTracker::add(Value *Ptr, LocationSize Size,
  345. const AAMDNodes &AAInfo) {
  346. addPointer(MemoryLocation(Ptr, Size, AAInfo), AliasSet::NoAccess);
  347. }
  348. void AliasSetTracker::add(LoadInst *LI) {
  349. if (isStrongerThanMonotonic(LI->getOrdering()))
  350. return addUnknown(LI);
  351. addPointer(MemoryLocation::get(LI), AliasSet::RefAccess);
  352. }
  353. void AliasSetTracker::add(StoreInst *SI) {
  354. if (isStrongerThanMonotonic(SI->getOrdering()))
  355. return addUnknown(SI);
  356. addPointer(MemoryLocation::get(SI), AliasSet::ModAccess);
  357. }
  358. void AliasSetTracker::add(VAArgInst *VAAI) {
  359. addPointer(MemoryLocation::get(VAAI), AliasSet::ModRefAccess);
  360. }
  361. void AliasSetTracker::add(AnyMemSetInst *MSI) {
  362. addPointer(MemoryLocation::getForDest(MSI), AliasSet::ModAccess);
  363. }
  364. void AliasSetTracker::add(AnyMemTransferInst *MTI) {
  365. addPointer(MemoryLocation::getForDest(MTI), AliasSet::ModAccess);
  366. addPointer(MemoryLocation::getForSource(MTI), AliasSet::RefAccess);
  367. }
  368. void AliasSetTracker::addUnknown(Instruction *Inst) {
  369. if (isa<DbgInfoIntrinsic>(Inst))
  370. return; // Ignore DbgInfo Intrinsics.
  371. if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
  372. // These intrinsics will show up as affecting memory, but they are just
  373. // markers.
  374. switch (II->getIntrinsicID()) {
  375. default:
  376. break;
  377. // FIXME: Add lifetime/invariant intrinsics (See: PR30807).
  378. case Intrinsic::assume:
  379. case Intrinsic::experimental_noalias_scope_decl:
  380. case Intrinsic::sideeffect:
  381. case Intrinsic::pseudoprobe:
  382. return;
  383. }
  384. }
  385. if (!Inst->mayReadOrWriteMemory())
  386. return; // doesn't alias anything
  387. if (AliasSet *AS = findAliasSetForUnknownInst(Inst)) {
  388. AS->addUnknownInst(Inst, AA);
  389. return;
  390. }
  391. AliasSets.push_back(new AliasSet());
  392. AliasSets.back().addUnknownInst(Inst, AA);
  393. }
  394. void AliasSetTracker::add(Instruction *I) {
  395. // Dispatch to one of the other add methods.
  396. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  397. return add(LI);
  398. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  399. return add(SI);
  400. if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
  401. return add(VAAI);
  402. if (AnyMemSetInst *MSI = dyn_cast<AnyMemSetInst>(I))
  403. return add(MSI);
  404. if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(I))
  405. return add(MTI);
  406. // Handle all calls with known mod/ref sets genericall
  407. if (auto *Call = dyn_cast<CallBase>(I))
  408. if (Call->onlyAccessesArgMemory()) {
  409. auto getAccessFromModRef = [](ModRefInfo MRI) {
  410. if (isRefSet(MRI) && isModSet(MRI))
  411. return AliasSet::ModRefAccess;
  412. else if (isModSet(MRI))
  413. return AliasSet::ModAccess;
  414. else if (isRefSet(MRI))
  415. return AliasSet::RefAccess;
  416. else
  417. return AliasSet::NoAccess;
  418. };
  419. ModRefInfo CallMask = createModRefInfo(AA.getModRefBehavior(Call));
  420. // Some intrinsics are marked as modifying memory for control flow
  421. // modelling purposes, but don't actually modify any specific memory
  422. // location.
  423. using namespace PatternMatch;
  424. if (Call->use_empty() &&
  425. match(Call, m_Intrinsic<Intrinsic::invariant_start>()))
  426. CallMask = clearMod(CallMask);
  427. for (auto IdxArgPair : enumerate(Call->args())) {
  428. int ArgIdx = IdxArgPair.index();
  429. const Value *Arg = IdxArgPair.value();
  430. if (!Arg->getType()->isPointerTy())
  431. continue;
  432. MemoryLocation ArgLoc =
  433. MemoryLocation::getForArgument(Call, ArgIdx, nullptr);
  434. ModRefInfo ArgMask = AA.getArgModRefInfo(Call, ArgIdx);
  435. ArgMask = intersectModRef(CallMask, ArgMask);
  436. if (!isNoModRef(ArgMask))
  437. addPointer(ArgLoc, getAccessFromModRef(ArgMask));
  438. }
  439. return;
  440. }
  441. return addUnknown(I);
  442. }
  443. void AliasSetTracker::add(BasicBlock &BB) {
  444. for (auto &I : BB)
  445. add(&I);
  446. }
  447. void AliasSetTracker::add(const AliasSetTracker &AST) {
  448. assert(&AA == &AST.AA &&
  449. "Merging AliasSetTracker objects with different Alias Analyses!");
  450. // Loop over all of the alias sets in AST, adding the pointers contained
  451. // therein into the current alias sets. This can cause alias sets to be
  452. // merged together in the current AST.
  453. for (const AliasSet &AS : AST) {
  454. if (AS.Forward)
  455. continue; // Ignore forwarding alias sets
  456. // If there are any call sites in the alias set, add them to this AST.
  457. for (unsigned i = 0, e = AS.UnknownInsts.size(); i != e; ++i)
  458. if (auto *Inst = AS.getUnknownInst(i))
  459. add(Inst);
  460. // Loop over all of the pointers in this alias set.
  461. for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI)
  462. addPointer(
  463. MemoryLocation(ASI.getPointer(), ASI.getSize(), ASI.getAAInfo()),
  464. (AliasSet::AccessLattice)AS.Access);
  465. }
  466. }
  467. // deleteValue method - This method is used to remove a pointer value from the
  468. // AliasSetTracker entirely. It should be used when an instruction is deleted
  469. // from the program to update the AST. If you don't use this, you would have
  470. // dangling pointers to deleted instructions.
  471. //
  472. void AliasSetTracker::deleteValue(Value *PtrVal) {
  473. // First, look up the PointerRec for this pointer.
  474. PointerMapType::iterator I = PointerMap.find_as(PtrVal);
  475. if (I == PointerMap.end()) return; // Noop
  476. // If we found one, remove the pointer from the alias set it is in.
  477. AliasSet::PointerRec *PtrValEnt = I->second;
  478. AliasSet *AS = PtrValEnt->getAliasSet(*this);
  479. // Unlink and delete from the list of values.
  480. PtrValEnt->eraseFromList();
  481. if (AS->Alias == AliasSet::SetMayAlias) {
  482. AS->SetSize--;
  483. TotalMayAliasSetSize--;
  484. }
  485. // Stop using the alias set.
  486. AS->dropRef(*this);
  487. PointerMap.erase(I);
  488. }
  489. // copyValue - This method should be used whenever a preexisting value in the
  490. // program is copied or cloned, introducing a new value. Note that it is ok for
  491. // clients that use this method to introduce the same value multiple times: if
  492. // the tracker already knows about a value, it will ignore the request.
  493. //
  494. void AliasSetTracker::copyValue(Value *From, Value *To) {
  495. // First, look up the PointerRec for this pointer.
  496. PointerMapType::iterator I = PointerMap.find_as(From);
  497. if (I == PointerMap.end())
  498. return; // Noop
  499. assert(I->second->hasAliasSet() && "Dead entry?");
  500. AliasSet::PointerRec &Entry = getEntryFor(To);
  501. if (Entry.hasAliasSet()) return; // Already in the tracker!
  502. // getEntryFor above may invalidate iterator \c I, so reinitialize it.
  503. I = PointerMap.find_as(From);
  504. // Add it to the alias set it aliases...
  505. AliasSet *AS = I->second->getAliasSet(*this);
  506. AS->addPointer(*this, Entry, I->second->getSize(), I->second->getAAInfo(),
  507. true, true);
  508. }
  509. AliasSet &AliasSetTracker::mergeAllAliasSets() {
  510. assert(!AliasAnyAS && (TotalMayAliasSetSize > SaturationThreshold) &&
  511. "Full merge should happen once, when the saturation threshold is "
  512. "reached");
  513. // Collect all alias sets, so that we can drop references with impunity
  514. // without worrying about iterator invalidation.
  515. std::vector<AliasSet *> ASVector;
  516. ASVector.reserve(SaturationThreshold);
  517. for (AliasSet &AS : *this)
  518. ASVector.push_back(&AS);
  519. // Copy all instructions and pointers into a new set, and forward all other
  520. // sets to it.
  521. AliasSets.push_back(new AliasSet());
  522. AliasAnyAS = &AliasSets.back();
  523. AliasAnyAS->Alias = AliasSet::SetMayAlias;
  524. AliasAnyAS->Access = AliasSet::ModRefAccess;
  525. AliasAnyAS->AliasAny = true;
  526. for (auto Cur : ASVector) {
  527. // If Cur was already forwarding, just forward to the new AS instead.
  528. AliasSet *FwdTo = Cur->Forward;
  529. if (FwdTo) {
  530. Cur->Forward = AliasAnyAS;
  531. AliasAnyAS->addRef();
  532. FwdTo->dropRef(*this);
  533. continue;
  534. }
  535. // Otherwise, perform the actual merge.
  536. AliasAnyAS->mergeSetIn(*Cur, *this);
  537. }
  538. return *AliasAnyAS;
  539. }
  540. AliasSet &AliasSetTracker::addPointer(MemoryLocation Loc,
  541. AliasSet::AccessLattice E) {
  542. AliasSet &AS = getAliasSetFor(Loc);
  543. AS.Access |= E;
  544. if (!AliasAnyAS && (TotalMayAliasSetSize > SaturationThreshold)) {
  545. // The AST is now saturated. From here on, we conservatively consider all
  546. // pointers to alias each-other.
  547. return mergeAllAliasSets();
  548. }
  549. return AS;
  550. }
  551. //===----------------------------------------------------------------------===//
  552. // AliasSet/AliasSetTracker Printing Support
  553. //===----------------------------------------------------------------------===//
  554. void AliasSet::print(raw_ostream &OS) const {
  555. OS << " AliasSet[" << (const void*)this << ", " << RefCount << "] ";
  556. OS << (Alias == SetMustAlias ? "must" : "may") << " alias, ";
  557. switch (Access) {
  558. case NoAccess: OS << "No access "; break;
  559. case RefAccess: OS << "Ref "; break;
  560. case ModAccess: OS << "Mod "; break;
  561. case ModRefAccess: OS << "Mod/Ref "; break;
  562. default: llvm_unreachable("Bad value for Access!");
  563. }
  564. if (Forward)
  565. OS << " forwarding to " << (void*)Forward;
  566. if (!empty()) {
  567. OS << "Pointers: ";
  568. for (iterator I = begin(), E = end(); I != E; ++I) {
  569. if (I != begin()) OS << ", ";
  570. I.getPointer()->printAsOperand(OS << "(");
  571. if (I.getSize() == LocationSize::afterPointer())
  572. OS << ", unknown after)";
  573. else if (I.getSize() == LocationSize::beforeOrAfterPointer())
  574. OS << ", unknown before-or-after)";
  575. else
  576. OS << ", " << I.getSize() << ")";
  577. }
  578. }
  579. if (!UnknownInsts.empty()) {
  580. OS << "\n " << UnknownInsts.size() << " Unknown instructions: ";
  581. for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) {
  582. if (i) OS << ", ";
  583. if (auto *I = getUnknownInst(i)) {
  584. if (I->hasName())
  585. I->printAsOperand(OS);
  586. else
  587. I->print(OS);
  588. }
  589. }
  590. }
  591. OS << "\n";
  592. }
  593. void AliasSetTracker::print(raw_ostream &OS) const {
  594. OS << "Alias Set Tracker: " << AliasSets.size();
  595. if (AliasAnyAS)
  596. OS << " (Saturated)";
  597. OS << " alias sets for " << PointerMap.size() << " pointer values.\n";
  598. for (const AliasSet &AS : *this)
  599. AS.print(OS);
  600. OS << "\n";
  601. }
  602. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  603. LLVM_DUMP_METHOD void AliasSet::dump() const { print(dbgs()); }
  604. LLVM_DUMP_METHOD void AliasSetTracker::dump() const { print(dbgs()); }
  605. #endif
  606. //===----------------------------------------------------------------------===//
  607. // ASTCallbackVH Class Implementation
  608. //===----------------------------------------------------------------------===//
  609. void AliasSetTracker::ASTCallbackVH::deleted() {
  610. assert(AST && "ASTCallbackVH called with a null AliasSetTracker!");
  611. AST->deleteValue(getValPtr());
  612. // this now dangles!
  613. }
  614. void AliasSetTracker::ASTCallbackVH::allUsesReplacedWith(Value *V) {
  615. AST->copyValue(getValPtr(), V);
  616. }
  617. AliasSetTracker::ASTCallbackVH::ASTCallbackVH(Value *V, AliasSetTracker *ast)
  618. : CallbackVH(V), AST(ast) {}
  619. AliasSetTracker::ASTCallbackVH &
  620. AliasSetTracker::ASTCallbackVH::operator=(Value *V) {
  621. return *this = ASTCallbackVH(V, AST);
  622. }
  623. //===----------------------------------------------------------------------===//
  624. // AliasSetPrinter Pass
  625. //===----------------------------------------------------------------------===//
  626. namespace {
  627. class AliasSetPrinter : public FunctionPass {
  628. public:
  629. static char ID; // Pass identification, replacement for typeid
  630. AliasSetPrinter() : FunctionPass(ID) {
  631. initializeAliasSetPrinterPass(*PassRegistry::getPassRegistry());
  632. }
  633. void getAnalysisUsage(AnalysisUsage &AU) const override {
  634. AU.setPreservesAll();
  635. AU.addRequired<AAResultsWrapperPass>();
  636. }
  637. bool runOnFunction(Function &F) override {
  638. auto &AAWP = getAnalysis<AAResultsWrapperPass>();
  639. AliasSetTracker Tracker(AAWP.getAAResults());
  640. errs() << "Alias sets for function '" << F.getName() << "':\n";
  641. for (Instruction &I : instructions(F))
  642. Tracker.add(&I);
  643. Tracker.print(errs());
  644. return false;
  645. }
  646. };
  647. } // end anonymous namespace
  648. char AliasSetPrinter::ID = 0;
  649. INITIALIZE_PASS_BEGIN(AliasSetPrinter, "print-alias-sets",
  650. "Alias Set Printer", false, true)
  651. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  652. INITIALIZE_PASS_END(AliasSetPrinter, "print-alias-sets",
  653. "Alias Set Printer", false, true)
  654. AliasSetsPrinterPass::AliasSetsPrinterPass(raw_ostream &OS) : OS(OS) {}
  655. PreservedAnalyses AliasSetsPrinterPass::run(Function &F,
  656. FunctionAnalysisManager &AM) {
  657. auto &AA = AM.getResult<AAManager>(F);
  658. AliasSetTracker Tracker(AA);
  659. OS << "Alias sets for function '" << F.getName() << "':\n";
  660. for (Instruction &I : instructions(F))
  661. Tracker.add(&I);
  662. Tracker.print(OS);
  663. return PreservedAnalyses::all();
  664. }