MemoryDependenceAnalysis.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. //===- MemoryDependenceAnalysis.cpp - Mem Deps 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 an analysis that determines, for a given memory
  10. // operation, what preceding memory operations it depends on. It builds on
  11. // alias analysis information, and tries to provide a lazy, caching interface to
  12. // a common kind of alias information query.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/AliasAnalysis.h"
  22. #include "llvm/Analysis/AssumptionCache.h"
  23. #include "llvm/Analysis/MemoryBuiltins.h"
  24. #include "llvm/Analysis/MemoryLocation.h"
  25. #include "llvm/Analysis/PHITransAddr.h"
  26. #include "llvm/Analysis/TargetLibraryInfo.h"
  27. #include "llvm/Analysis/ValueTracking.h"
  28. #include "llvm/IR/BasicBlock.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/Function.h"
  31. #include "llvm/IR/InstrTypes.h"
  32. #include "llvm/IR/Instruction.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/IR/IntrinsicInst.h"
  35. #include "llvm/IR/LLVMContext.h"
  36. #include "llvm/IR/Metadata.h"
  37. #include "llvm/IR/Module.h"
  38. #include "llvm/IR/PredIteratorCache.h"
  39. #include "llvm/IR/Type.h"
  40. #include "llvm/IR/Use.h"
  41. #include "llvm/IR/Value.h"
  42. #include "llvm/InitializePasses.h"
  43. #include "llvm/Pass.h"
  44. #include "llvm/Support/AtomicOrdering.h"
  45. #include "llvm/Support/Casting.h"
  46. #include "llvm/Support/CommandLine.h"
  47. #include "llvm/Support/Compiler.h"
  48. #include "llvm/Support/Debug.h"
  49. #include <algorithm>
  50. #include <cassert>
  51. #include <iterator>
  52. #include <utility>
  53. using namespace llvm;
  54. #define DEBUG_TYPE "memdep"
  55. STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
  56. STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
  57. STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
  58. STATISTIC(NumCacheNonLocalPtr,
  59. "Number of fully cached non-local ptr responses");
  60. STATISTIC(NumCacheDirtyNonLocalPtr,
  61. "Number of cached, but dirty, non-local ptr responses");
  62. STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses");
  63. STATISTIC(NumCacheCompleteNonLocalPtr,
  64. "Number of block queries that were completely cached");
  65. // Limit for the number of instructions to scan in a block.
  66. static cl::opt<unsigned> BlockScanLimit(
  67. "memdep-block-scan-limit", cl::Hidden, cl::init(100),
  68. cl::desc("The number of instructions to scan in a block in memory "
  69. "dependency analysis (default = 100)"));
  70. static cl::opt<unsigned>
  71. BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(200),
  72. cl::desc("The number of blocks to scan during memory "
  73. "dependency analysis (default = 200)"));
  74. // Limit on the number of memdep results to process.
  75. static const unsigned int NumResultsLimit = 100;
  76. /// This is a helper function that removes Val from 'Inst's set in ReverseMap.
  77. ///
  78. /// If the set becomes empty, remove Inst's entry.
  79. template <typename KeyTy>
  80. static void
  81. RemoveFromReverseMap(DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>> &ReverseMap,
  82. Instruction *Inst, KeyTy Val) {
  83. typename DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>>::iterator InstIt =
  84. ReverseMap.find(Inst);
  85. assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
  86. bool Found = InstIt->second.erase(Val);
  87. assert(Found && "Invalid reverse map!");
  88. (void)Found;
  89. if (InstIt->second.empty())
  90. ReverseMap.erase(InstIt);
  91. }
  92. /// If the given instruction references a specific memory location, fill in Loc
  93. /// with the details, otherwise set Loc.Ptr to null.
  94. ///
  95. /// Returns a ModRefInfo value describing the general behavior of the
  96. /// instruction.
  97. static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc,
  98. const TargetLibraryInfo &TLI) {
  99. if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  100. if (LI->isUnordered()) {
  101. Loc = MemoryLocation::get(LI);
  102. return ModRefInfo::Ref;
  103. }
  104. if (LI->getOrdering() == AtomicOrdering::Monotonic) {
  105. Loc = MemoryLocation::get(LI);
  106. return ModRefInfo::ModRef;
  107. }
  108. Loc = MemoryLocation();
  109. return ModRefInfo::ModRef;
  110. }
  111. if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  112. if (SI->isUnordered()) {
  113. Loc = MemoryLocation::get(SI);
  114. return ModRefInfo::Mod;
  115. }
  116. if (SI->getOrdering() == AtomicOrdering::Monotonic) {
  117. Loc = MemoryLocation::get(SI);
  118. return ModRefInfo::ModRef;
  119. }
  120. Loc = MemoryLocation();
  121. return ModRefInfo::ModRef;
  122. }
  123. if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
  124. Loc = MemoryLocation::get(V);
  125. return ModRefInfo::ModRef;
  126. }
  127. if (const CallBase *CB = dyn_cast<CallBase>(Inst)) {
  128. if (Value *FreedOp = getFreedOperand(CB, &TLI)) {
  129. // calls to free() deallocate the entire structure
  130. Loc = MemoryLocation::getAfter(FreedOp);
  131. return ModRefInfo::Mod;
  132. }
  133. }
  134. if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  135. switch (II->getIntrinsicID()) {
  136. case Intrinsic::lifetime_start:
  137. case Intrinsic::lifetime_end:
  138. case Intrinsic::invariant_start:
  139. Loc = MemoryLocation::getForArgument(II, 1, TLI);
  140. // These intrinsics don't really modify the memory, but returning Mod
  141. // will allow them to be handled conservatively.
  142. return ModRefInfo::Mod;
  143. case Intrinsic::invariant_end:
  144. Loc = MemoryLocation::getForArgument(II, 2, TLI);
  145. // These intrinsics don't really modify the memory, but returning Mod
  146. // will allow them to be handled conservatively.
  147. return ModRefInfo::Mod;
  148. case Intrinsic::masked_load:
  149. Loc = MemoryLocation::getForArgument(II, 0, TLI);
  150. return ModRefInfo::Ref;
  151. case Intrinsic::masked_store:
  152. Loc = MemoryLocation::getForArgument(II, 1, TLI);
  153. return ModRefInfo::Mod;
  154. default:
  155. break;
  156. }
  157. }
  158. // Otherwise, just do the coarse-grained thing that always works.
  159. if (Inst->mayWriteToMemory())
  160. return ModRefInfo::ModRef;
  161. if (Inst->mayReadFromMemory())
  162. return ModRefInfo::Ref;
  163. return ModRefInfo::NoModRef;
  164. }
  165. /// Private helper for finding the local dependencies of a call site.
  166. MemDepResult MemoryDependenceResults::getCallDependencyFrom(
  167. CallBase *Call, bool isReadOnlyCall, BasicBlock::iterator ScanIt,
  168. BasicBlock *BB) {
  169. unsigned Limit = getDefaultBlockScanLimit();
  170. // Walk backwards through the block, looking for dependencies.
  171. while (ScanIt != BB->begin()) {
  172. Instruction *Inst = &*--ScanIt;
  173. // Debug intrinsics don't cause dependences and should not affect Limit
  174. if (isa<DbgInfoIntrinsic>(Inst))
  175. continue;
  176. // Limit the amount of scanning we do so we don't end up with quadratic
  177. // running time on extreme testcases.
  178. --Limit;
  179. if (!Limit)
  180. return MemDepResult::getUnknown();
  181. // If this inst is a memory op, get the pointer it accessed
  182. MemoryLocation Loc;
  183. ModRefInfo MR = GetLocation(Inst, Loc, TLI);
  184. if (Loc.Ptr) {
  185. // A simple instruction.
  186. if (isModOrRefSet(AA.getModRefInfo(Call, Loc)))
  187. return MemDepResult::getClobber(Inst);
  188. continue;
  189. }
  190. if (auto *CallB = dyn_cast<CallBase>(Inst)) {
  191. // If these two calls do not interfere, look past it.
  192. if (isNoModRef(AA.getModRefInfo(Call, CallB))) {
  193. // If the two calls are the same, return Inst as a Def, so that
  194. // Call can be found redundant and eliminated.
  195. if (isReadOnlyCall && !isModSet(MR) &&
  196. Call->isIdenticalToWhenDefined(CallB))
  197. return MemDepResult::getDef(Inst);
  198. // Otherwise if the two calls don't interact (e.g. CallB is readnone)
  199. // keep scanning.
  200. continue;
  201. } else
  202. return MemDepResult::getClobber(Inst);
  203. }
  204. // If we could not obtain a pointer for the instruction and the instruction
  205. // touches memory then assume that this is a dependency.
  206. if (isModOrRefSet(MR))
  207. return MemDepResult::getClobber(Inst);
  208. }
  209. // No dependence found. If this is the entry block of the function, it is
  210. // unknown, otherwise it is non-local.
  211. if (BB != &BB->getParent()->getEntryBlock())
  212. return MemDepResult::getNonLocal();
  213. return MemDepResult::getNonFuncLocal();
  214. }
  215. MemDepResult MemoryDependenceResults::getPointerDependencyFrom(
  216. const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
  217. BasicBlock *BB, Instruction *QueryInst, unsigned *Limit,
  218. BatchAAResults &BatchAA) {
  219. MemDepResult InvariantGroupDependency = MemDepResult::getUnknown();
  220. if (QueryInst != nullptr) {
  221. if (auto *LI = dyn_cast<LoadInst>(QueryInst)) {
  222. InvariantGroupDependency = getInvariantGroupPointerDependency(LI, BB);
  223. if (InvariantGroupDependency.isDef())
  224. return InvariantGroupDependency;
  225. }
  226. }
  227. MemDepResult SimpleDep = getSimplePointerDependencyFrom(
  228. MemLoc, isLoad, ScanIt, BB, QueryInst, Limit, BatchAA);
  229. if (SimpleDep.isDef())
  230. return SimpleDep;
  231. // Non-local invariant group dependency indicates there is non local Def
  232. // (it only returns nonLocal if it finds nonLocal def), which is better than
  233. // local clobber and everything else.
  234. if (InvariantGroupDependency.isNonLocal())
  235. return InvariantGroupDependency;
  236. assert(InvariantGroupDependency.isUnknown() &&
  237. "InvariantGroupDependency should be only unknown at this point");
  238. return SimpleDep;
  239. }
  240. MemDepResult MemoryDependenceResults::getPointerDependencyFrom(
  241. const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
  242. BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) {
  243. BatchAAResults BatchAA(AA);
  244. return getPointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst, Limit,
  245. BatchAA);
  246. }
  247. MemDepResult
  248. MemoryDependenceResults::getInvariantGroupPointerDependency(LoadInst *LI,
  249. BasicBlock *BB) {
  250. if (!LI->hasMetadata(LLVMContext::MD_invariant_group))
  251. return MemDepResult::getUnknown();
  252. // Take the ptr operand after all casts and geps 0. This way we can search
  253. // cast graph down only.
  254. Value *LoadOperand = LI->getPointerOperand()->stripPointerCasts();
  255. // It's is not safe to walk the use list of global value, because function
  256. // passes aren't allowed to look outside their functions.
  257. // FIXME: this could be fixed by filtering instructions from outside
  258. // of current function.
  259. if (isa<GlobalValue>(LoadOperand))
  260. return MemDepResult::getUnknown();
  261. // Queue to process all pointers that are equivalent to load operand.
  262. SmallVector<const Value *, 8> LoadOperandsQueue;
  263. LoadOperandsQueue.push_back(LoadOperand);
  264. Instruction *ClosestDependency = nullptr;
  265. // Order of instructions in uses list is unpredictible. In order to always
  266. // get the same result, we will look for the closest dominance.
  267. auto GetClosestDependency = [this](Instruction *Best, Instruction *Other) {
  268. assert(Other && "Must call it with not null instruction");
  269. if (Best == nullptr || DT.dominates(Best, Other))
  270. return Other;
  271. return Best;
  272. };
  273. // FIXME: This loop is O(N^2) because dominates can be O(n) and in worst case
  274. // we will see all the instructions. This should be fixed in MSSA.
  275. while (!LoadOperandsQueue.empty()) {
  276. const Value *Ptr = LoadOperandsQueue.pop_back_val();
  277. assert(Ptr && !isa<GlobalValue>(Ptr) &&
  278. "Null or GlobalValue should not be inserted");
  279. for (const Use &Us : Ptr->uses()) {
  280. auto *U = dyn_cast<Instruction>(Us.getUser());
  281. if (!U || U == LI || !DT.dominates(U, LI))
  282. continue;
  283. // Bitcast or gep with zeros are using Ptr. Add to queue to check it's
  284. // users. U = bitcast Ptr
  285. if (isa<BitCastInst>(U)) {
  286. LoadOperandsQueue.push_back(U);
  287. continue;
  288. }
  289. // Gep with zeros is equivalent to bitcast.
  290. // FIXME: we are not sure if some bitcast should be canonicalized to gep 0
  291. // or gep 0 to bitcast because of SROA, so there are 2 forms. When
  292. // typeless pointers will be ready then both cases will be gone
  293. // (and this BFS also won't be needed).
  294. if (auto *GEP = dyn_cast<GetElementPtrInst>(U))
  295. if (GEP->hasAllZeroIndices()) {
  296. LoadOperandsQueue.push_back(U);
  297. continue;
  298. }
  299. // If we hit load/store with the same invariant.group metadata (and the
  300. // same pointer operand) we can assume that value pointed by pointer
  301. // operand didn't change.
  302. if ((isa<LoadInst>(U) ||
  303. (isa<StoreInst>(U) &&
  304. cast<StoreInst>(U)->getPointerOperand() == Ptr)) &&
  305. U->hasMetadata(LLVMContext::MD_invariant_group))
  306. ClosestDependency = GetClosestDependency(ClosestDependency, U);
  307. }
  308. }
  309. if (!ClosestDependency)
  310. return MemDepResult::getUnknown();
  311. if (ClosestDependency->getParent() == BB)
  312. return MemDepResult::getDef(ClosestDependency);
  313. // Def(U) can't be returned here because it is non-local. If local
  314. // dependency won't be found then return nonLocal counting that the
  315. // user will call getNonLocalPointerDependency, which will return cached
  316. // result.
  317. NonLocalDefsCache.try_emplace(
  318. LI, NonLocalDepResult(ClosestDependency->getParent(),
  319. MemDepResult::getDef(ClosestDependency), nullptr));
  320. ReverseNonLocalDefsCache[ClosestDependency].insert(LI);
  321. return MemDepResult::getNonLocal();
  322. }
  323. MemDepResult MemoryDependenceResults::getSimplePointerDependencyFrom(
  324. const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
  325. BasicBlock *BB, Instruction *QueryInst, unsigned *Limit,
  326. BatchAAResults &BatchAA) {
  327. bool isInvariantLoad = false;
  328. unsigned DefaultLimit = getDefaultBlockScanLimit();
  329. if (!Limit)
  330. Limit = &DefaultLimit;
  331. // We must be careful with atomic accesses, as they may allow another thread
  332. // to touch this location, clobbering it. We are conservative: if the
  333. // QueryInst is not a simple (non-atomic) memory access, we automatically
  334. // return getClobber.
  335. // If it is simple, we know based on the results of
  336. // "Compiler testing via a theory of sound optimisations in the C11/C++11
  337. // memory model" in PLDI 2013, that a non-atomic location can only be
  338. // clobbered between a pair of a release and an acquire action, with no
  339. // access to the location in between.
  340. // Here is an example for giving the general intuition behind this rule.
  341. // In the following code:
  342. // store x 0;
  343. // release action; [1]
  344. // acquire action; [4]
  345. // %val = load x;
  346. // It is unsafe to replace %val by 0 because another thread may be running:
  347. // acquire action; [2]
  348. // store x 42;
  349. // release action; [3]
  350. // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
  351. // being 42. A key property of this program however is that if either
  352. // 1 or 4 were missing, there would be a race between the store of 42
  353. // either the store of 0 or the load (making the whole program racy).
  354. // The paper mentioned above shows that the same property is respected
  355. // by every program that can detect any optimization of that kind: either
  356. // it is racy (undefined) or there is a release followed by an acquire
  357. // between the pair of accesses under consideration.
  358. // If the load is invariant, we "know" that it doesn't alias *any* write. We
  359. // do want to respect mustalias results since defs are useful for value
  360. // forwarding, but any mayalias write can be assumed to be noalias.
  361. // Arguably, this logic should be pushed inside AliasAnalysis itself.
  362. if (isLoad && QueryInst) {
  363. LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
  364. if (LI && LI->hasMetadata(LLVMContext::MD_invariant_load))
  365. isInvariantLoad = true;
  366. }
  367. // True for volatile instruction.
  368. // For Load/Store return true if atomic ordering is stronger than AO,
  369. // for other instruction just true if it can read or write to memory.
  370. auto isComplexForReordering = [](Instruction * I, AtomicOrdering AO)->bool {
  371. if (I->isVolatile())
  372. return true;
  373. if (auto *LI = dyn_cast<LoadInst>(I))
  374. return isStrongerThan(LI->getOrdering(), AO);
  375. if (auto *SI = dyn_cast<StoreInst>(I))
  376. return isStrongerThan(SI->getOrdering(), AO);
  377. return I->mayReadOrWriteMemory();
  378. };
  379. // Walk backwards through the basic block, looking for dependencies.
  380. while (ScanIt != BB->begin()) {
  381. Instruction *Inst = &*--ScanIt;
  382. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
  383. // Debug intrinsics don't (and can't) cause dependencies.
  384. if (isa<DbgInfoIntrinsic>(II))
  385. continue;
  386. // Limit the amount of scanning we do so we don't end up with quadratic
  387. // running time on extreme testcases.
  388. --*Limit;
  389. if (!*Limit)
  390. return MemDepResult::getUnknown();
  391. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  392. // If we reach a lifetime begin or end marker, then the query ends here
  393. // because the value is undefined.
  394. Intrinsic::ID ID = II->getIntrinsicID();
  395. switch (ID) {
  396. case Intrinsic::lifetime_start: {
  397. // FIXME: This only considers queries directly on the invariant-tagged
  398. // pointer, not on query pointers that are indexed off of them. It'd
  399. // be nice to handle that at some point (the right approach is to use
  400. // GetPointerBaseWithConstantOffset).
  401. MemoryLocation ArgLoc = MemoryLocation::getAfter(II->getArgOperand(1));
  402. if (BatchAA.isMustAlias(ArgLoc, MemLoc))
  403. return MemDepResult::getDef(II);
  404. continue;
  405. }
  406. case Intrinsic::masked_load:
  407. case Intrinsic::masked_store: {
  408. MemoryLocation Loc;
  409. /*ModRefInfo MR =*/ GetLocation(II, Loc, TLI);
  410. AliasResult R = BatchAA.alias(Loc, MemLoc);
  411. if (R == AliasResult::NoAlias)
  412. continue;
  413. if (R == AliasResult::MustAlias)
  414. return MemDepResult::getDef(II);
  415. if (ID == Intrinsic::masked_load)
  416. continue;
  417. return MemDepResult::getClobber(II);
  418. }
  419. }
  420. }
  421. // Values depend on loads if the pointers are must aliased. This means
  422. // that a load depends on another must aliased load from the same value.
  423. // One exception is atomic loads: a value can depend on an atomic load that
  424. // it does not alias with when this atomic load indicates that another
  425. // thread may be accessing the location.
  426. if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  427. // While volatile access cannot be eliminated, they do not have to clobber
  428. // non-aliasing locations, as normal accesses, for example, can be safely
  429. // reordered with volatile accesses.
  430. if (LI->isVolatile()) {
  431. if (!QueryInst)
  432. // Original QueryInst *may* be volatile
  433. return MemDepResult::getClobber(LI);
  434. if (QueryInst->isVolatile())
  435. // Ordering required if QueryInst is itself volatile
  436. return MemDepResult::getClobber(LI);
  437. // Otherwise, volatile doesn't imply any special ordering
  438. }
  439. // Atomic loads have complications involved.
  440. // A Monotonic (or higher) load is OK if the query inst is itself not
  441. // atomic.
  442. // FIXME: This is overly conservative.
  443. if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) {
  444. if (!QueryInst ||
  445. isComplexForReordering(QueryInst, AtomicOrdering::NotAtomic))
  446. return MemDepResult::getClobber(LI);
  447. if (LI->getOrdering() != AtomicOrdering::Monotonic)
  448. return MemDepResult::getClobber(LI);
  449. }
  450. MemoryLocation LoadLoc = MemoryLocation::get(LI);
  451. // If we found a pointer, check if it could be the same as our pointer.
  452. AliasResult R = BatchAA.alias(LoadLoc, MemLoc);
  453. if (R == AliasResult::NoAlias)
  454. continue;
  455. if (isLoad) {
  456. // Must aliased loads are defs of each other.
  457. if (R == AliasResult::MustAlias)
  458. return MemDepResult::getDef(Inst);
  459. // If we have a partial alias, then return this as a clobber for the
  460. // client to handle.
  461. if (R == AliasResult::PartialAlias && R.hasOffset()) {
  462. ClobberOffsets[LI] = R.getOffset();
  463. return MemDepResult::getClobber(Inst);
  464. }
  465. // Random may-alias loads don't depend on each other without a
  466. // dependence.
  467. continue;
  468. }
  469. // Stores don't alias loads from read-only memory.
  470. if (!isModSet(BatchAA.getModRefInfoMask(LoadLoc)))
  471. continue;
  472. // Stores depend on may/must aliased loads.
  473. return MemDepResult::getDef(Inst);
  474. }
  475. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  476. // Atomic stores have complications involved.
  477. // A Monotonic store is OK if the query inst is itself not atomic.
  478. // FIXME: This is overly conservative.
  479. if (!SI->isUnordered() && SI->isAtomic()) {
  480. if (!QueryInst ||
  481. isComplexForReordering(QueryInst, AtomicOrdering::Unordered))
  482. return MemDepResult::getClobber(SI);
  483. // Ok, if we are here the guard above guarantee us that
  484. // QueryInst is a non-atomic or unordered load/store.
  485. // SI is atomic with monotonic or release semantic (seq_cst for store
  486. // is actually a release semantic plus total order over other seq_cst
  487. // instructions, as soon as QueryInst is not seq_cst we can consider it
  488. // as simple release semantic).
  489. // Monotonic and Release semantic allows re-ordering before store
  490. // so we are safe to go further and check the aliasing. It will prohibit
  491. // re-ordering in case locations are may or must alias.
  492. }
  493. // While volatile access cannot be eliminated, they do not have to clobber
  494. // non-aliasing locations, as normal accesses can for example be reordered
  495. // with volatile accesses.
  496. if (SI->isVolatile())
  497. if (!QueryInst || QueryInst->isVolatile())
  498. return MemDepResult::getClobber(SI);
  499. // If alias analysis can tell that this store is guaranteed to not modify
  500. // the query pointer, ignore it. Use getModRefInfo to handle cases where
  501. // the query pointer points to constant memory etc.
  502. if (!isModOrRefSet(BatchAA.getModRefInfo(SI, MemLoc)))
  503. continue;
  504. // Ok, this store might clobber the query pointer. Check to see if it is
  505. // a must alias: in this case, we want to return this as a def.
  506. // FIXME: Use ModRefInfo::Must bit from getModRefInfo call above.
  507. MemoryLocation StoreLoc = MemoryLocation::get(SI);
  508. // If we found a pointer, check if it could be the same as our pointer.
  509. AliasResult R = BatchAA.alias(StoreLoc, MemLoc);
  510. if (R == AliasResult::NoAlias)
  511. continue;
  512. if (R == AliasResult::MustAlias)
  513. return MemDepResult::getDef(Inst);
  514. if (isInvariantLoad)
  515. continue;
  516. return MemDepResult::getClobber(Inst);
  517. }
  518. // If this is an allocation, and if we know that the accessed pointer is to
  519. // the allocation, return Def. This means that there is no dependence and
  520. // the access can be optimized based on that. For example, a load could
  521. // turn into undef. Note that we can bypass the allocation itself when
  522. // looking for a clobber in many cases; that's an alias property and is
  523. // handled by BasicAA.
  524. if (isa<AllocaInst>(Inst) || isNoAliasCall(Inst)) {
  525. const Value *AccessPtr = getUnderlyingObject(MemLoc.Ptr);
  526. if (AccessPtr == Inst || BatchAA.isMustAlias(Inst, AccessPtr))
  527. return MemDepResult::getDef(Inst);
  528. }
  529. // If we found a select instruction for MemLoc pointer, return it as Def
  530. // dependency.
  531. if (isa<SelectInst>(Inst) && MemLoc.Ptr == Inst)
  532. return MemDepResult::getDef(Inst);
  533. if (isInvariantLoad)
  534. continue;
  535. // A release fence requires that all stores complete before it, but does
  536. // not prevent the reordering of following loads or stores 'before' the
  537. // fence. As a result, we look past it when finding a dependency for
  538. // loads. DSE uses this to find preceding stores to delete and thus we
  539. // can't bypass the fence if the query instruction is a store.
  540. if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
  541. if (isLoad && FI->getOrdering() == AtomicOrdering::Release)
  542. continue;
  543. // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
  544. ModRefInfo MR = BatchAA.getModRefInfo(Inst, MemLoc);
  545. // If necessary, perform additional analysis.
  546. if (isModAndRefSet(MR))
  547. MR = BatchAA.callCapturesBefore(Inst, MemLoc, &DT);
  548. switch (MR) {
  549. case ModRefInfo::NoModRef:
  550. // If the call has no effect on the queried pointer, just ignore it.
  551. continue;
  552. case ModRefInfo::Mod:
  553. return MemDepResult::getClobber(Inst);
  554. case ModRefInfo::Ref:
  555. // If the call is known to never store to the pointer, and if this is a
  556. // load query, we can safely ignore it (scan past it).
  557. if (isLoad)
  558. continue;
  559. [[fallthrough]];
  560. default:
  561. // Otherwise, there is a potential dependence. Return a clobber.
  562. return MemDepResult::getClobber(Inst);
  563. }
  564. }
  565. // No dependence found. If this is the entry block of the function, it is
  566. // unknown, otherwise it is non-local.
  567. if (BB != &BB->getParent()->getEntryBlock())
  568. return MemDepResult::getNonLocal();
  569. return MemDepResult::getNonFuncLocal();
  570. }
  571. MemDepResult MemoryDependenceResults::getDependency(Instruction *QueryInst) {
  572. ClobberOffsets.clear();
  573. Instruction *ScanPos = QueryInst;
  574. // Check for a cached result
  575. MemDepResult &LocalCache = LocalDeps[QueryInst];
  576. // If the cached entry is non-dirty, just return it. Note that this depends
  577. // on MemDepResult's default constructing to 'dirty'.
  578. if (!LocalCache.isDirty())
  579. return LocalCache;
  580. // Otherwise, if we have a dirty entry, we know we can start the scan at that
  581. // instruction, which may save us some work.
  582. if (Instruction *Inst = LocalCache.getInst()) {
  583. ScanPos = Inst;
  584. RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
  585. }
  586. BasicBlock *QueryParent = QueryInst->getParent();
  587. // Do the scan.
  588. if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
  589. // No dependence found. If this is the entry block of the function, it is
  590. // unknown, otherwise it is non-local.
  591. if (QueryParent != &QueryParent->getParent()->getEntryBlock())
  592. LocalCache = MemDepResult::getNonLocal();
  593. else
  594. LocalCache = MemDepResult::getNonFuncLocal();
  595. } else {
  596. MemoryLocation MemLoc;
  597. ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI);
  598. if (MemLoc.Ptr) {
  599. // If we can do a pointer scan, make it happen.
  600. bool isLoad = !isModSet(MR);
  601. if (auto *II = dyn_cast<IntrinsicInst>(QueryInst))
  602. isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
  603. LocalCache =
  604. getPointerDependencyFrom(MemLoc, isLoad, ScanPos->getIterator(),
  605. QueryParent, QueryInst, nullptr);
  606. } else if (auto *QueryCall = dyn_cast<CallBase>(QueryInst)) {
  607. bool isReadOnly = AA.onlyReadsMemory(QueryCall);
  608. LocalCache = getCallDependencyFrom(QueryCall, isReadOnly,
  609. ScanPos->getIterator(), QueryParent);
  610. } else
  611. // Non-memory instruction.
  612. LocalCache = MemDepResult::getUnknown();
  613. }
  614. // Remember the result!
  615. if (Instruction *I = LocalCache.getInst())
  616. ReverseLocalDeps[I].insert(QueryInst);
  617. return LocalCache;
  618. }
  619. #ifndef NDEBUG
  620. /// This method is used when -debug is specified to verify that cache arrays
  621. /// are properly kept sorted.
  622. static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache,
  623. int Count = -1) {
  624. if (Count == -1)
  625. Count = Cache.size();
  626. assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) &&
  627. "Cache isn't sorted!");
  628. }
  629. #endif
  630. const MemoryDependenceResults::NonLocalDepInfo &
  631. MemoryDependenceResults::getNonLocalCallDependency(CallBase *QueryCall) {
  632. assert(getDependency(QueryCall).isNonLocal() &&
  633. "getNonLocalCallDependency should only be used on calls with "
  634. "non-local deps!");
  635. PerInstNLInfo &CacheP = NonLocalDepsMap[QueryCall];
  636. NonLocalDepInfo &Cache = CacheP.first;
  637. // This is the set of blocks that need to be recomputed. In the cached case,
  638. // this can happen due to instructions being deleted etc. In the uncached
  639. // case, this starts out as the set of predecessors we care about.
  640. SmallVector<BasicBlock *, 32> DirtyBlocks;
  641. if (!Cache.empty()) {
  642. // Okay, we have a cache entry. If we know it is not dirty, just return it
  643. // with no computation.
  644. if (!CacheP.second) {
  645. ++NumCacheNonLocal;
  646. return Cache;
  647. }
  648. // If we already have a partially computed set of results, scan them to
  649. // determine what is dirty, seeding our initial DirtyBlocks worklist.
  650. for (auto &Entry : Cache)
  651. if (Entry.getResult().isDirty())
  652. DirtyBlocks.push_back(Entry.getBB());
  653. // Sort the cache so that we can do fast binary search lookups below.
  654. llvm::sort(Cache);
  655. ++NumCacheDirtyNonLocal;
  656. } else {
  657. // Seed DirtyBlocks with each of the preds of QueryInst's block.
  658. BasicBlock *QueryBB = QueryCall->getParent();
  659. append_range(DirtyBlocks, PredCache.get(QueryBB));
  660. ++NumUncacheNonLocal;
  661. }
  662. // isReadonlyCall - If this is a read-only call, we can be more aggressive.
  663. bool isReadonlyCall = AA.onlyReadsMemory(QueryCall);
  664. SmallPtrSet<BasicBlock *, 32> Visited;
  665. unsigned NumSortedEntries = Cache.size();
  666. LLVM_DEBUG(AssertSorted(Cache));
  667. // Iterate while we still have blocks to update.
  668. while (!DirtyBlocks.empty()) {
  669. BasicBlock *DirtyBB = DirtyBlocks.pop_back_val();
  670. // Already processed this block?
  671. if (!Visited.insert(DirtyBB).second)
  672. continue;
  673. // Do a binary search to see if we already have an entry for this block in
  674. // the cache set. If so, find it.
  675. LLVM_DEBUG(AssertSorted(Cache, NumSortedEntries));
  676. NonLocalDepInfo::iterator Entry =
  677. std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries,
  678. NonLocalDepEntry(DirtyBB));
  679. if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
  680. --Entry;
  681. NonLocalDepEntry *ExistingResult = nullptr;
  682. if (Entry != Cache.begin() + NumSortedEntries &&
  683. Entry->getBB() == DirtyBB) {
  684. // If we already have an entry, and if it isn't already dirty, the block
  685. // is done.
  686. if (!Entry->getResult().isDirty())
  687. continue;
  688. // Otherwise, remember this slot so we can update the value.
  689. ExistingResult = &*Entry;
  690. }
  691. // If the dirty entry has a pointer, start scanning from it so we don't have
  692. // to rescan the entire block.
  693. BasicBlock::iterator ScanPos = DirtyBB->end();
  694. if (ExistingResult) {
  695. if (Instruction *Inst = ExistingResult->getResult().getInst()) {
  696. ScanPos = Inst->getIterator();
  697. // We're removing QueryInst's use of Inst.
  698. RemoveFromReverseMap<Instruction *>(ReverseNonLocalDeps, Inst,
  699. QueryCall);
  700. }
  701. }
  702. // Find out if this block has a local dependency for QueryInst.
  703. MemDepResult Dep;
  704. if (ScanPos != DirtyBB->begin()) {
  705. Dep = getCallDependencyFrom(QueryCall, isReadonlyCall, ScanPos, DirtyBB);
  706. } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
  707. // No dependence found. If this is the entry block of the function, it is
  708. // a clobber, otherwise it is unknown.
  709. Dep = MemDepResult::getNonLocal();
  710. } else {
  711. Dep = MemDepResult::getNonFuncLocal();
  712. }
  713. // If we had a dirty entry for the block, update it. Otherwise, just add
  714. // a new entry.
  715. if (ExistingResult)
  716. ExistingResult->setResult(Dep);
  717. else
  718. Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
  719. // If the block has a dependency (i.e. it isn't completely transparent to
  720. // the value), remember the association!
  721. if (!Dep.isNonLocal()) {
  722. // Keep the ReverseNonLocalDeps map up to date so we can efficiently
  723. // update this when we remove instructions.
  724. if (Instruction *Inst = Dep.getInst())
  725. ReverseNonLocalDeps[Inst].insert(QueryCall);
  726. } else {
  727. // If the block *is* completely transparent to the load, we need to check
  728. // the predecessors of this block. Add them to our worklist.
  729. append_range(DirtyBlocks, PredCache.get(DirtyBB));
  730. }
  731. }
  732. return Cache;
  733. }
  734. void MemoryDependenceResults::getNonLocalPointerDependency(
  735. Instruction *QueryInst, SmallVectorImpl<NonLocalDepResult> &Result) {
  736. const MemoryLocation Loc = MemoryLocation::get(QueryInst);
  737. bool isLoad = isa<LoadInst>(QueryInst);
  738. BasicBlock *FromBB = QueryInst->getParent();
  739. assert(FromBB);
  740. assert(Loc.Ptr->getType()->isPointerTy() &&
  741. "Can't get pointer deps of a non-pointer!");
  742. Result.clear();
  743. {
  744. // Check if there is cached Def with invariant.group.
  745. auto NonLocalDefIt = NonLocalDefsCache.find(QueryInst);
  746. if (NonLocalDefIt != NonLocalDefsCache.end()) {
  747. Result.push_back(NonLocalDefIt->second);
  748. ReverseNonLocalDefsCache[NonLocalDefIt->second.getResult().getInst()]
  749. .erase(QueryInst);
  750. NonLocalDefsCache.erase(NonLocalDefIt);
  751. return;
  752. }
  753. }
  754. // This routine does not expect to deal with volatile instructions.
  755. // Doing so would require piping through the QueryInst all the way through.
  756. // TODO: volatiles can't be elided, but they can be reordered with other
  757. // non-volatile accesses.
  758. // We currently give up on any instruction which is ordered, but we do handle
  759. // atomic instructions which are unordered.
  760. // TODO: Handle ordered instructions
  761. auto isOrdered = [](Instruction *Inst) {
  762. if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  763. return !LI->isUnordered();
  764. } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  765. return !SI->isUnordered();
  766. }
  767. return false;
  768. };
  769. if (QueryInst->isVolatile() || isOrdered(QueryInst)) {
  770. Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
  771. const_cast<Value *>(Loc.Ptr)));
  772. return;
  773. }
  774. const DataLayout &DL = FromBB->getModule()->getDataLayout();
  775. PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC);
  776. // This is the set of blocks we've inspected, and the pointer we consider in
  777. // each block. Because of critical edges, we currently bail out if querying
  778. // a block with multiple different pointers. This can happen during PHI
  779. // translation.
  780. DenseMap<BasicBlock *, Value *> Visited;
  781. if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
  782. Result, Visited, true))
  783. return;
  784. Result.clear();
  785. Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
  786. const_cast<Value *>(Loc.Ptr)));
  787. }
  788. /// Compute the memdep value for BB with Pointer/PointeeSize using either
  789. /// cached information in Cache or by doing a lookup (which may use dirty cache
  790. /// info if available).
  791. ///
  792. /// If we do a lookup, add the result to the cache.
  793. MemDepResult MemoryDependenceResults::getNonLocalInfoForBlock(
  794. Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad,
  795. BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries,
  796. BatchAAResults &BatchAA) {
  797. bool isInvariantLoad = false;
  798. if (LoadInst *LI = dyn_cast_or_null<LoadInst>(QueryInst))
  799. isInvariantLoad = LI->getMetadata(LLVMContext::MD_invariant_load);
  800. // Do a binary search to see if we already have an entry for this block in
  801. // the cache set. If so, find it.
  802. NonLocalDepInfo::iterator Entry = std::upper_bound(
  803. Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB));
  804. if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB)
  805. --Entry;
  806. NonLocalDepEntry *ExistingResult = nullptr;
  807. if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB)
  808. ExistingResult = &*Entry;
  809. // Use cached result for invariant load only if there is no dependency for non
  810. // invariant load. In this case invariant load can not have any dependency as
  811. // well.
  812. if (ExistingResult && isInvariantLoad &&
  813. !ExistingResult->getResult().isNonFuncLocal())
  814. ExistingResult = nullptr;
  815. // If we have a cached entry, and it is non-dirty, use it as the value for
  816. // this dependency.
  817. if (ExistingResult && !ExistingResult->getResult().isDirty()) {
  818. ++NumCacheNonLocalPtr;
  819. return ExistingResult->getResult();
  820. }
  821. // Otherwise, we have to scan for the value. If we have a dirty cache
  822. // entry, start scanning from its position, otherwise we scan from the end
  823. // of the block.
  824. BasicBlock::iterator ScanPos = BB->end();
  825. if (ExistingResult && ExistingResult->getResult().getInst()) {
  826. assert(ExistingResult->getResult().getInst()->getParent() == BB &&
  827. "Instruction invalidated?");
  828. ++NumCacheDirtyNonLocalPtr;
  829. ScanPos = ExistingResult->getResult().getInst()->getIterator();
  830. // Eliminating the dirty entry from 'Cache', so update the reverse info.
  831. ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
  832. RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey);
  833. } else {
  834. ++NumUncacheNonLocalPtr;
  835. }
  836. // Scan the block for the dependency.
  837. MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB,
  838. QueryInst, nullptr, BatchAA);
  839. // Don't cache results for invariant load.
  840. if (isInvariantLoad)
  841. return Dep;
  842. // If we had a dirty entry for the block, update it. Otherwise, just add
  843. // a new entry.
  844. if (ExistingResult)
  845. ExistingResult->setResult(Dep);
  846. else
  847. Cache->push_back(NonLocalDepEntry(BB, Dep));
  848. // If the block has a dependency (i.e. it isn't completely transparent to
  849. // the value), remember the reverse association because we just added it
  850. // to Cache!
  851. if (!Dep.isLocal())
  852. return Dep;
  853. // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
  854. // update MemDep when we remove instructions.
  855. Instruction *Inst = Dep.getInst();
  856. assert(Inst && "Didn't depend on anything?");
  857. ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
  858. ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
  859. return Dep;
  860. }
  861. /// Sort the NonLocalDepInfo cache, given a certain number of elements in the
  862. /// array that are already properly ordered.
  863. ///
  864. /// This is optimized for the case when only a few entries are added.
  865. static void
  866. SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache,
  867. unsigned NumSortedEntries) {
  868. switch (Cache.size() - NumSortedEntries) {
  869. case 0:
  870. // done, no new entries.
  871. break;
  872. case 2: {
  873. // Two new entries, insert the last one into place.
  874. NonLocalDepEntry Val = Cache.back();
  875. Cache.pop_back();
  876. MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
  877. std::upper_bound(Cache.begin(), Cache.end() - 1, Val);
  878. Cache.insert(Entry, Val);
  879. [[fallthrough]];
  880. }
  881. case 1:
  882. // One new entry, Just insert the new value at the appropriate position.
  883. if (Cache.size() != 1) {
  884. NonLocalDepEntry Val = Cache.back();
  885. Cache.pop_back();
  886. MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
  887. llvm::upper_bound(Cache, Val);
  888. Cache.insert(Entry, Val);
  889. }
  890. break;
  891. default:
  892. // Added many values, do a full scale sort.
  893. llvm::sort(Cache);
  894. break;
  895. }
  896. }
  897. /// Perform a dependency query based on pointer/pointeesize starting at the end
  898. /// of StartBB.
  899. ///
  900. /// Add any clobber/def results to the results vector and keep track of which
  901. /// blocks are visited in 'Visited'.
  902. ///
  903. /// This has special behavior for the first block queries (when SkipFirstBlock
  904. /// is true). In this special case, it ignores the contents of the specified
  905. /// block and starts returning dependence info for its predecessors.
  906. ///
  907. /// This function returns true on success, or false to indicate that it could
  908. /// not compute dependence information for some reason. This should be treated
  909. /// as a clobber dependence on the first instruction in the predecessor block.
  910. bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
  911. Instruction *QueryInst, const PHITransAddr &Pointer,
  912. const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
  913. SmallVectorImpl<NonLocalDepResult> &Result,
  914. DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock,
  915. bool IsIncomplete) {
  916. // Look up the cached info for Pointer.
  917. ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
  918. // Set up a temporary NLPI value. If the map doesn't yet have an entry for
  919. // CacheKey, this value will be inserted as the associated value. Otherwise,
  920. // it'll be ignored, and we'll have to check to see if the cached size and
  921. // aa tags are consistent with the current query.
  922. NonLocalPointerInfo InitialNLPI;
  923. InitialNLPI.Size = Loc.Size;
  924. InitialNLPI.AATags = Loc.AATags;
  925. bool isInvariantLoad = false;
  926. if (LoadInst *LI = dyn_cast_or_null<LoadInst>(QueryInst))
  927. isInvariantLoad = LI->getMetadata(LLVMContext::MD_invariant_load);
  928. // Get the NLPI for CacheKey, inserting one into the map if it doesn't
  929. // already have one.
  930. std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
  931. NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
  932. NonLocalPointerInfo *CacheInfo = &Pair.first->second;
  933. // If we already have a cache entry for this CacheKey, we may need to do some
  934. // work to reconcile the cache entry and the current query.
  935. // Invariant loads don't participate in caching. Thus no need to reconcile.
  936. if (!isInvariantLoad && !Pair.second) {
  937. if (CacheInfo->Size != Loc.Size) {
  938. bool ThrowOutEverything;
  939. if (CacheInfo->Size.hasValue() && Loc.Size.hasValue()) {
  940. // FIXME: We may be able to do better in the face of results with mixed
  941. // precision. We don't appear to get them in practice, though, so just
  942. // be conservative.
  943. ThrowOutEverything =
  944. CacheInfo->Size.isPrecise() != Loc.Size.isPrecise() ||
  945. CacheInfo->Size.getValue() < Loc.Size.getValue();
  946. } else {
  947. // For our purposes, unknown size > all others.
  948. ThrowOutEverything = !Loc.Size.hasValue();
  949. }
  950. if (ThrowOutEverything) {
  951. // The query's Size is greater than the cached one. Throw out the
  952. // cached data and proceed with the query at the greater size.
  953. CacheInfo->Pair = BBSkipFirstBlockPair();
  954. CacheInfo->Size = Loc.Size;
  955. for (auto &Entry : CacheInfo->NonLocalDeps)
  956. if (Instruction *Inst = Entry.getResult().getInst())
  957. RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
  958. CacheInfo->NonLocalDeps.clear();
  959. // The cache is cleared (in the above line) so we will have lost
  960. // information about blocks we have already visited. We therefore must
  961. // assume that the cache information is incomplete.
  962. IsIncomplete = true;
  963. } else {
  964. // This query's Size is less than the cached one. Conservatively restart
  965. // the query using the greater size.
  966. return getNonLocalPointerDepFromBB(
  967. QueryInst, Pointer, Loc.getWithNewSize(CacheInfo->Size), isLoad,
  968. StartBB, Result, Visited, SkipFirstBlock, IsIncomplete);
  969. }
  970. }
  971. // If the query's AATags are inconsistent with the cached one,
  972. // conservatively throw out the cached data and restart the query with
  973. // no tag if needed.
  974. if (CacheInfo->AATags != Loc.AATags) {
  975. if (CacheInfo->AATags) {
  976. CacheInfo->Pair = BBSkipFirstBlockPair();
  977. CacheInfo->AATags = AAMDNodes();
  978. for (auto &Entry : CacheInfo->NonLocalDeps)
  979. if (Instruction *Inst = Entry.getResult().getInst())
  980. RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
  981. CacheInfo->NonLocalDeps.clear();
  982. // The cache is cleared (in the above line) so we will have lost
  983. // information about blocks we have already visited. We therefore must
  984. // assume that the cache information is incomplete.
  985. IsIncomplete = true;
  986. }
  987. if (Loc.AATags)
  988. return getNonLocalPointerDepFromBB(
  989. QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result,
  990. Visited, SkipFirstBlock, IsIncomplete);
  991. }
  992. }
  993. NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
  994. // If we have valid cached information for exactly the block we are
  995. // investigating, just return it with no recomputation.
  996. // Don't use cached information for invariant loads since it is valid for
  997. // non-invariant loads only.
  998. if (!IsIncomplete && !isInvariantLoad &&
  999. CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
  1000. // We have a fully cached result for this query then we can just return the
  1001. // cached results and populate the visited set. However, we have to verify
  1002. // that we don't already have conflicting results for these blocks. Check
  1003. // to ensure that if a block in the results set is in the visited set that
  1004. // it was for the same pointer query.
  1005. if (!Visited.empty()) {
  1006. for (auto &Entry : *Cache) {
  1007. DenseMap<BasicBlock *, Value *>::iterator VI =
  1008. Visited.find(Entry.getBB());
  1009. if (VI == Visited.end() || VI->second == Pointer.getAddr())
  1010. continue;
  1011. // We have a pointer mismatch in a block. Just return false, saying
  1012. // that something was clobbered in this result. We could also do a
  1013. // non-fully cached query, but there is little point in doing this.
  1014. return false;
  1015. }
  1016. }
  1017. Value *Addr = Pointer.getAddr();
  1018. for (auto &Entry : *Cache) {
  1019. Visited.insert(std::make_pair(Entry.getBB(), Addr));
  1020. if (Entry.getResult().isNonLocal()) {
  1021. continue;
  1022. }
  1023. if (DT.isReachableFromEntry(Entry.getBB())) {
  1024. Result.push_back(
  1025. NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr));
  1026. }
  1027. }
  1028. ++NumCacheCompleteNonLocalPtr;
  1029. return true;
  1030. }
  1031. // Otherwise, either this is a new block, a block with an invalid cache
  1032. // pointer or one that we're about to invalidate by putting more info into
  1033. // it than its valid cache info. If empty and not explicitly indicated as
  1034. // incomplete, the result will be valid cache info, otherwise it isn't.
  1035. //
  1036. // Invariant loads don't affect cache in any way thus no need to update
  1037. // CacheInfo as well.
  1038. if (!isInvariantLoad) {
  1039. if (!IsIncomplete && Cache->empty())
  1040. CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
  1041. else
  1042. CacheInfo->Pair = BBSkipFirstBlockPair();
  1043. }
  1044. SmallVector<BasicBlock *, 32> Worklist;
  1045. Worklist.push_back(StartBB);
  1046. // PredList used inside loop.
  1047. SmallVector<std::pair<BasicBlock *, PHITransAddr>, 16> PredList;
  1048. // Keep track of the entries that we know are sorted. Previously cached
  1049. // entries will all be sorted. The entries we add we only sort on demand (we
  1050. // don't insert every element into its sorted position). We know that we
  1051. // won't get any reuse from currently inserted values, because we don't
  1052. // revisit blocks after we insert info for them.
  1053. unsigned NumSortedEntries = Cache->size();
  1054. unsigned WorklistEntries = BlockNumberLimit;
  1055. bool GotWorklistLimit = false;
  1056. LLVM_DEBUG(AssertSorted(*Cache));
  1057. BatchAAResults BatchAA(AA);
  1058. while (!Worklist.empty()) {
  1059. BasicBlock *BB = Worklist.pop_back_val();
  1060. // If we do process a large number of blocks it becomes very expensive and
  1061. // likely it isn't worth worrying about
  1062. if (Result.size() > NumResultsLimit) {
  1063. // Sort it now (if needed) so that recursive invocations of
  1064. // getNonLocalPointerDepFromBB and other routines that could reuse the
  1065. // cache value will only see properly sorted cache arrays.
  1066. if (Cache && NumSortedEntries != Cache->size()) {
  1067. SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
  1068. }
  1069. // Since we bail out, the "Cache" set won't contain all of the
  1070. // results for the query. This is ok (we can still use it to accelerate
  1071. // specific block queries) but we can't do the fastpath "return all
  1072. // results from the set". Clear out the indicator for this.
  1073. CacheInfo->Pair = BBSkipFirstBlockPair();
  1074. return false;
  1075. }
  1076. // Skip the first block if we have it.
  1077. if (!SkipFirstBlock) {
  1078. // Analyze the dependency of *Pointer in FromBB. See if we already have
  1079. // been here.
  1080. assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
  1081. // Get the dependency info for Pointer in BB. If we have cached
  1082. // information, we will use it, otherwise we compute it.
  1083. LLVM_DEBUG(AssertSorted(*Cache, NumSortedEntries));
  1084. MemDepResult Dep = getNonLocalInfoForBlock(
  1085. QueryInst, Loc, isLoad, BB, Cache, NumSortedEntries, BatchAA);
  1086. // If we got a Def or Clobber, add this to the list of results.
  1087. if (!Dep.isNonLocal()) {
  1088. if (DT.isReachableFromEntry(BB)) {
  1089. Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
  1090. continue;
  1091. }
  1092. }
  1093. }
  1094. // If 'Pointer' is an instruction defined in this block, then we need to do
  1095. // phi translation to change it into a value live in the predecessor block.
  1096. // If not, we just add the predecessors to the worklist and scan them with
  1097. // the same Pointer.
  1098. if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
  1099. SkipFirstBlock = false;
  1100. SmallVector<BasicBlock *, 16> NewBlocks;
  1101. for (BasicBlock *Pred : PredCache.get(BB)) {
  1102. // Verify that we haven't looked at this block yet.
  1103. std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
  1104. Visited.insert(std::make_pair(Pred, Pointer.getAddr()));
  1105. if (InsertRes.second) {
  1106. // First time we've looked at *PI.
  1107. NewBlocks.push_back(Pred);
  1108. continue;
  1109. }
  1110. // If we have seen this block before, but it was with a different
  1111. // pointer then we have a phi translation failure and we have to treat
  1112. // this as a clobber.
  1113. if (InsertRes.first->second != Pointer.getAddr()) {
  1114. // Make sure to clean up the Visited map before continuing on to
  1115. // PredTranslationFailure.
  1116. for (unsigned i = 0; i < NewBlocks.size(); i++)
  1117. Visited.erase(NewBlocks[i]);
  1118. goto PredTranslationFailure;
  1119. }
  1120. }
  1121. if (NewBlocks.size() > WorklistEntries) {
  1122. // Make sure to clean up the Visited map before continuing on to
  1123. // PredTranslationFailure.
  1124. for (unsigned i = 0; i < NewBlocks.size(); i++)
  1125. Visited.erase(NewBlocks[i]);
  1126. GotWorklistLimit = true;
  1127. goto PredTranslationFailure;
  1128. }
  1129. WorklistEntries -= NewBlocks.size();
  1130. Worklist.append(NewBlocks.begin(), NewBlocks.end());
  1131. continue;
  1132. }
  1133. // We do need to do phi translation, if we know ahead of time we can't phi
  1134. // translate this value, don't even try.
  1135. if (!Pointer.IsPotentiallyPHITranslatable())
  1136. goto PredTranslationFailure;
  1137. // We may have added values to the cache list before this PHI translation.
  1138. // If so, we haven't done anything to ensure that the cache remains sorted.
  1139. // Sort it now (if needed) so that recursive invocations of
  1140. // getNonLocalPointerDepFromBB and other routines that could reuse the cache
  1141. // value will only see properly sorted cache arrays.
  1142. if (Cache && NumSortedEntries != Cache->size()) {
  1143. SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
  1144. NumSortedEntries = Cache->size();
  1145. }
  1146. Cache = nullptr;
  1147. PredList.clear();
  1148. for (BasicBlock *Pred : PredCache.get(BB)) {
  1149. PredList.push_back(std::make_pair(Pred, Pointer));
  1150. // Get the PHI translated pointer in this predecessor. This can fail if
  1151. // not translatable, in which case the getAddr() returns null.
  1152. PHITransAddr &PredPointer = PredList.back().second;
  1153. PredPointer.PHITranslateValue(BB, Pred, &DT, /*MustDominate=*/false);
  1154. Value *PredPtrVal = PredPointer.getAddr();
  1155. // Check to see if we have already visited this pred block with another
  1156. // pointer. If so, we can't do this lookup. This failure can occur
  1157. // with PHI translation when a critical edge exists and the PHI node in
  1158. // the successor translates to a pointer value different than the
  1159. // pointer the block was first analyzed with.
  1160. std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
  1161. Visited.insert(std::make_pair(Pred, PredPtrVal));
  1162. if (!InsertRes.second) {
  1163. // We found the pred; take it off the list of preds to visit.
  1164. PredList.pop_back();
  1165. // If the predecessor was visited with PredPtr, then we already did
  1166. // the analysis and can ignore it.
  1167. if (InsertRes.first->second == PredPtrVal)
  1168. continue;
  1169. // Otherwise, the block was previously analyzed with a different
  1170. // pointer. We can't represent the result of this case, so we just
  1171. // treat this as a phi translation failure.
  1172. // Make sure to clean up the Visited map before continuing on to
  1173. // PredTranslationFailure.
  1174. for (unsigned i = 0, n = PredList.size(); i < n; ++i)
  1175. Visited.erase(PredList[i].first);
  1176. goto PredTranslationFailure;
  1177. }
  1178. }
  1179. // Actually process results here; this need to be a separate loop to avoid
  1180. // calling getNonLocalPointerDepFromBB for blocks we don't want to return
  1181. // any results for. (getNonLocalPointerDepFromBB will modify our
  1182. // datastructures in ways the code after the PredTranslationFailure label
  1183. // doesn't expect.)
  1184. for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
  1185. BasicBlock *Pred = PredList[i].first;
  1186. PHITransAddr &PredPointer = PredList[i].second;
  1187. Value *PredPtrVal = PredPointer.getAddr();
  1188. bool CanTranslate = true;
  1189. // If PHI translation was unable to find an available pointer in this
  1190. // predecessor, then we have to assume that the pointer is clobbered in
  1191. // that predecessor. We can still do PRE of the load, which would insert
  1192. // a computation of the pointer in this predecessor.
  1193. if (!PredPtrVal)
  1194. CanTranslate = false;
  1195. // FIXME: it is entirely possible that PHI translating will end up with
  1196. // the same value. Consider PHI translating something like:
  1197. // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need*
  1198. // to recurse here, pedantically speaking.
  1199. // If getNonLocalPointerDepFromBB fails here, that means the cached
  1200. // result conflicted with the Visited list; we have to conservatively
  1201. // assume it is unknown, but this also does not block PRE of the load.
  1202. if (!CanTranslate ||
  1203. !getNonLocalPointerDepFromBB(QueryInst, PredPointer,
  1204. Loc.getWithNewPtr(PredPtrVal), isLoad,
  1205. Pred, Result, Visited)) {
  1206. // Add the entry to the Result list.
  1207. NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
  1208. Result.push_back(Entry);
  1209. // Since we had a phi translation failure, the cache for CacheKey won't
  1210. // include all of the entries that we need to immediately satisfy future
  1211. // queries. Mark this in NonLocalPointerDeps by setting the
  1212. // BBSkipFirstBlockPair pointer to null. This requires reuse of the
  1213. // cached value to do more work but not miss the phi trans failure.
  1214. NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
  1215. NLPI.Pair = BBSkipFirstBlockPair();
  1216. continue;
  1217. }
  1218. }
  1219. // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
  1220. CacheInfo = &NonLocalPointerDeps[CacheKey];
  1221. Cache = &CacheInfo->NonLocalDeps;
  1222. NumSortedEntries = Cache->size();
  1223. // Since we did phi translation, the "Cache" set won't contain all of the
  1224. // results for the query. This is ok (we can still use it to accelerate
  1225. // specific block queries) but we can't do the fastpath "return all
  1226. // results from the set" Clear out the indicator for this.
  1227. CacheInfo->Pair = BBSkipFirstBlockPair();
  1228. SkipFirstBlock = false;
  1229. continue;
  1230. PredTranslationFailure:
  1231. // The following code is "failure"; we can't produce a sane translation
  1232. // for the given block. It assumes that we haven't modified any of
  1233. // our datastructures while processing the current block.
  1234. if (!Cache) {
  1235. // Refresh the CacheInfo/Cache pointer if it got invalidated.
  1236. CacheInfo = &NonLocalPointerDeps[CacheKey];
  1237. Cache = &CacheInfo->NonLocalDeps;
  1238. NumSortedEntries = Cache->size();
  1239. }
  1240. // Since we failed phi translation, the "Cache" set won't contain all of the
  1241. // results for the query. This is ok (we can still use it to accelerate
  1242. // specific block queries) but we can't do the fastpath "return all
  1243. // results from the set". Clear out the indicator for this.
  1244. CacheInfo->Pair = BBSkipFirstBlockPair();
  1245. // If *nothing* works, mark the pointer as unknown.
  1246. //
  1247. // If this is the magic first block, return this as a clobber of the whole
  1248. // incoming value. Since we can't phi translate to one of the predecessors,
  1249. // we have to bail out.
  1250. if (SkipFirstBlock)
  1251. return false;
  1252. // Results of invariant loads are not cached thus no need to update cached
  1253. // information.
  1254. if (!isInvariantLoad) {
  1255. for (NonLocalDepEntry &I : llvm::reverse(*Cache)) {
  1256. if (I.getBB() != BB)
  1257. continue;
  1258. assert((GotWorklistLimit || I.getResult().isNonLocal() ||
  1259. !DT.isReachableFromEntry(BB)) &&
  1260. "Should only be here with transparent block");
  1261. I.setResult(MemDepResult::getUnknown());
  1262. break;
  1263. }
  1264. }
  1265. (void)GotWorklistLimit;
  1266. // Go ahead and report unknown dependence.
  1267. Result.push_back(
  1268. NonLocalDepResult(BB, MemDepResult::getUnknown(), Pointer.getAddr()));
  1269. }
  1270. // Okay, we're done now. If we added new values to the cache, re-sort it.
  1271. SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
  1272. LLVM_DEBUG(AssertSorted(*Cache));
  1273. return true;
  1274. }
  1275. /// If P exists in CachedNonLocalPointerInfo or NonLocalDefsCache, remove it.
  1276. void MemoryDependenceResults::removeCachedNonLocalPointerDependencies(
  1277. ValueIsLoadPair P) {
  1278. // Most of the time this cache is empty.
  1279. if (!NonLocalDefsCache.empty()) {
  1280. auto it = NonLocalDefsCache.find(P.getPointer());
  1281. if (it != NonLocalDefsCache.end()) {
  1282. RemoveFromReverseMap(ReverseNonLocalDefsCache,
  1283. it->second.getResult().getInst(), P.getPointer());
  1284. NonLocalDefsCache.erase(it);
  1285. }
  1286. if (auto *I = dyn_cast<Instruction>(P.getPointer())) {
  1287. auto toRemoveIt = ReverseNonLocalDefsCache.find(I);
  1288. if (toRemoveIt != ReverseNonLocalDefsCache.end()) {
  1289. for (const auto *entry : toRemoveIt->second)
  1290. NonLocalDefsCache.erase(entry);
  1291. ReverseNonLocalDefsCache.erase(toRemoveIt);
  1292. }
  1293. }
  1294. }
  1295. CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P);
  1296. if (It == NonLocalPointerDeps.end())
  1297. return;
  1298. // Remove all of the entries in the BB->val map. This involves removing
  1299. // instructions from the reverse map.
  1300. NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
  1301. for (const NonLocalDepEntry &DE : PInfo) {
  1302. Instruction *Target = DE.getResult().getInst();
  1303. if (!Target)
  1304. continue; // Ignore non-local dep results.
  1305. assert(Target->getParent() == DE.getBB());
  1306. // Eliminating the dirty entry from 'Cache', so update the reverse info.
  1307. RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
  1308. }
  1309. // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
  1310. NonLocalPointerDeps.erase(It);
  1311. }
  1312. void MemoryDependenceResults::invalidateCachedPointerInfo(Value *Ptr) {
  1313. // If Ptr isn't really a pointer, just ignore it.
  1314. if (!Ptr->getType()->isPointerTy())
  1315. return;
  1316. // Flush store info for the pointer.
  1317. removeCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
  1318. // Flush load info for the pointer.
  1319. removeCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
  1320. }
  1321. void MemoryDependenceResults::invalidateCachedPredecessors() {
  1322. PredCache.clear();
  1323. }
  1324. void MemoryDependenceResults::removeInstruction(Instruction *RemInst) {
  1325. // Walk through the Non-local dependencies, removing this one as the value
  1326. // for any cached queries.
  1327. NonLocalDepMapType::iterator NLDI = NonLocalDepsMap.find(RemInst);
  1328. if (NLDI != NonLocalDepsMap.end()) {
  1329. NonLocalDepInfo &BlockMap = NLDI->second.first;
  1330. for (auto &Entry : BlockMap)
  1331. if (Instruction *Inst = Entry.getResult().getInst())
  1332. RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
  1333. NonLocalDepsMap.erase(NLDI);
  1334. }
  1335. // If we have a cached local dependence query for this instruction, remove it.
  1336. LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
  1337. if (LocalDepEntry != LocalDeps.end()) {
  1338. // Remove us from DepInst's reverse set now that the local dep info is gone.
  1339. if (Instruction *Inst = LocalDepEntry->second.getInst())
  1340. RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
  1341. // Remove this local dependency info.
  1342. LocalDeps.erase(LocalDepEntry);
  1343. }
  1344. // If we have any cached dependencies on this instruction, remove
  1345. // them.
  1346. // If the instruction is a pointer, remove it from both the load info and the
  1347. // store info.
  1348. if (RemInst->getType()->isPointerTy()) {
  1349. removeCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
  1350. removeCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
  1351. } else {
  1352. // Otherwise, if the instructions is in the map directly, it must be a load.
  1353. // Remove it.
  1354. auto toRemoveIt = NonLocalDefsCache.find(RemInst);
  1355. if (toRemoveIt != NonLocalDefsCache.end()) {
  1356. assert(isa<LoadInst>(RemInst) &&
  1357. "only load instructions should be added directly");
  1358. const Instruction *DepV = toRemoveIt->second.getResult().getInst();
  1359. ReverseNonLocalDefsCache.find(DepV)->second.erase(RemInst);
  1360. NonLocalDefsCache.erase(toRemoveIt);
  1361. }
  1362. }
  1363. // Loop over all of the things that depend on the instruction we're removing.
  1364. SmallVector<std::pair<Instruction *, Instruction *>, 8> ReverseDepsToAdd;
  1365. // If we find RemInst as a clobber or Def in any of the maps for other values,
  1366. // we need to replace its entry with a dirty version of the instruction after
  1367. // it. If RemInst is a terminator, we use a null dirty value.
  1368. //
  1369. // Using a dirty version of the instruction after RemInst saves having to scan
  1370. // the entire block to get to this point.
  1371. MemDepResult NewDirtyVal;
  1372. if (!RemInst->isTerminator())
  1373. NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator());
  1374. ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
  1375. if (ReverseDepIt != ReverseLocalDeps.end()) {
  1376. // RemInst can't be the terminator if it has local stuff depending on it.
  1377. assert(!ReverseDepIt->second.empty() && !RemInst->isTerminator() &&
  1378. "Nothing can locally depend on a terminator");
  1379. for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
  1380. assert(InstDependingOnRemInst != RemInst &&
  1381. "Already removed our local dep info");
  1382. LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
  1383. // Make sure to remember that new things depend on NewDepInst.
  1384. assert(NewDirtyVal.getInst() &&
  1385. "There is no way something else can have "
  1386. "a local dep on this if it is a terminator!");
  1387. ReverseDepsToAdd.push_back(
  1388. std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst));
  1389. }
  1390. ReverseLocalDeps.erase(ReverseDepIt);
  1391. // Add new reverse deps after scanning the set, to avoid invalidating the
  1392. // 'ReverseDeps' reference.
  1393. while (!ReverseDepsToAdd.empty()) {
  1394. ReverseLocalDeps[ReverseDepsToAdd.back().first].insert(
  1395. ReverseDepsToAdd.back().second);
  1396. ReverseDepsToAdd.pop_back();
  1397. }
  1398. }
  1399. ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
  1400. if (ReverseDepIt != ReverseNonLocalDeps.end()) {
  1401. for (Instruction *I : ReverseDepIt->second) {
  1402. assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
  1403. PerInstNLInfo &INLD = NonLocalDepsMap[I];
  1404. // The information is now dirty!
  1405. INLD.second = true;
  1406. for (auto &Entry : INLD.first) {
  1407. if (Entry.getResult().getInst() != RemInst)
  1408. continue;
  1409. // Convert to a dirty entry for the subsequent instruction.
  1410. Entry.setResult(NewDirtyVal);
  1411. if (Instruction *NextI = NewDirtyVal.getInst())
  1412. ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
  1413. }
  1414. }
  1415. ReverseNonLocalDeps.erase(ReverseDepIt);
  1416. // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
  1417. while (!ReverseDepsToAdd.empty()) {
  1418. ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert(
  1419. ReverseDepsToAdd.back().second);
  1420. ReverseDepsToAdd.pop_back();
  1421. }
  1422. }
  1423. // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
  1424. // value in the NonLocalPointerDeps info.
  1425. ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
  1426. ReverseNonLocalPtrDeps.find(RemInst);
  1427. if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
  1428. SmallVector<std::pair<Instruction *, ValueIsLoadPair>, 8>
  1429. ReversePtrDepsToAdd;
  1430. for (ValueIsLoadPair P : ReversePtrDepIt->second) {
  1431. assert(P.getPointer() != RemInst &&
  1432. "Already removed NonLocalPointerDeps info for RemInst");
  1433. NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
  1434. // The cache is not valid for any specific block anymore.
  1435. NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
  1436. // Update any entries for RemInst to use the instruction after it.
  1437. for (auto &Entry : NLPDI) {
  1438. if (Entry.getResult().getInst() != RemInst)
  1439. continue;
  1440. // Convert to a dirty entry for the subsequent instruction.
  1441. Entry.setResult(NewDirtyVal);
  1442. if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
  1443. ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
  1444. }
  1445. // Re-sort the NonLocalDepInfo. Changing the dirty entry to its
  1446. // subsequent value may invalidate the sortedness.
  1447. llvm::sort(NLPDI);
  1448. }
  1449. ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
  1450. while (!ReversePtrDepsToAdd.empty()) {
  1451. ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert(
  1452. ReversePtrDepsToAdd.back().second);
  1453. ReversePtrDepsToAdd.pop_back();
  1454. }
  1455. }
  1456. assert(!NonLocalDepsMap.count(RemInst) && "RemInst got reinserted?");
  1457. LLVM_DEBUG(verifyRemoved(RemInst));
  1458. }
  1459. /// Verify that the specified instruction does not occur in our internal data
  1460. /// structures.
  1461. ///
  1462. /// This function verifies by asserting in debug builds.
  1463. void MemoryDependenceResults::verifyRemoved(Instruction *D) const {
  1464. #ifndef NDEBUG
  1465. for (const auto &DepKV : LocalDeps) {
  1466. assert(DepKV.first != D && "Inst occurs in data structures");
  1467. assert(DepKV.second.getInst() != D && "Inst occurs in data structures");
  1468. }
  1469. for (const auto &DepKV : NonLocalPointerDeps) {
  1470. assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key");
  1471. for (const auto &Entry : DepKV.second.NonLocalDeps)
  1472. assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value");
  1473. }
  1474. for (const auto &DepKV : NonLocalDepsMap) {
  1475. assert(DepKV.first != D && "Inst occurs in data structures");
  1476. const PerInstNLInfo &INLD = DepKV.second;
  1477. for (const auto &Entry : INLD.first)
  1478. assert(Entry.getResult().getInst() != D &&
  1479. "Inst occurs in data structures");
  1480. }
  1481. for (const auto &DepKV : ReverseLocalDeps) {
  1482. assert(DepKV.first != D && "Inst occurs in data structures");
  1483. for (Instruction *Inst : DepKV.second)
  1484. assert(Inst != D && "Inst occurs in data structures");
  1485. }
  1486. for (const auto &DepKV : ReverseNonLocalDeps) {
  1487. assert(DepKV.first != D && "Inst occurs in data structures");
  1488. for (Instruction *Inst : DepKV.second)
  1489. assert(Inst != D && "Inst occurs in data structures");
  1490. }
  1491. for (const auto &DepKV : ReverseNonLocalPtrDeps) {
  1492. assert(DepKV.first != D && "Inst occurs in rev NLPD map");
  1493. for (ValueIsLoadPair P : DepKV.second)
  1494. assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) &&
  1495. "Inst occurs in ReverseNonLocalPtrDeps map");
  1496. }
  1497. #endif
  1498. }
  1499. AnalysisKey MemoryDependenceAnalysis::Key;
  1500. MemoryDependenceAnalysis::MemoryDependenceAnalysis()
  1501. : DefaultBlockScanLimit(BlockScanLimit) {}
  1502. MemoryDependenceResults
  1503. MemoryDependenceAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
  1504. auto &AA = AM.getResult<AAManager>(F);
  1505. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  1506. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  1507. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  1508. return MemoryDependenceResults(AA, AC, TLI, DT, DefaultBlockScanLimit);
  1509. }
  1510. char MemoryDependenceWrapperPass::ID = 0;
  1511. INITIALIZE_PASS_BEGIN(MemoryDependenceWrapperPass, "memdep",
  1512. "Memory Dependence Analysis", false, true)
  1513. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1514. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  1515. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1516. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  1517. INITIALIZE_PASS_END(MemoryDependenceWrapperPass, "memdep",
  1518. "Memory Dependence Analysis", false, true)
  1519. MemoryDependenceWrapperPass::MemoryDependenceWrapperPass() : FunctionPass(ID) {
  1520. initializeMemoryDependenceWrapperPassPass(*PassRegistry::getPassRegistry());
  1521. }
  1522. MemoryDependenceWrapperPass::~MemoryDependenceWrapperPass() = default;
  1523. void MemoryDependenceWrapperPass::releaseMemory() {
  1524. MemDep.reset();
  1525. }
  1526. void MemoryDependenceWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  1527. AU.setPreservesAll();
  1528. AU.addRequired<AssumptionCacheTracker>();
  1529. AU.addRequired<DominatorTreeWrapperPass>();
  1530. AU.addRequiredTransitive<AAResultsWrapperPass>();
  1531. AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
  1532. }
  1533. bool MemoryDependenceResults::invalidate(Function &F, const PreservedAnalyses &PA,
  1534. FunctionAnalysisManager::Invalidator &Inv) {
  1535. // Check whether our analysis is preserved.
  1536. auto PAC = PA.getChecker<MemoryDependenceAnalysis>();
  1537. if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
  1538. // If not, give up now.
  1539. return true;
  1540. // Check whether the analyses we depend on became invalid for any reason.
  1541. if (Inv.invalidate<AAManager>(F, PA) ||
  1542. Inv.invalidate<AssumptionAnalysis>(F, PA) ||
  1543. Inv.invalidate<DominatorTreeAnalysis>(F, PA))
  1544. return true;
  1545. // Otherwise this analysis result remains valid.
  1546. return false;
  1547. }
  1548. unsigned MemoryDependenceResults::getDefaultBlockScanLimit() const {
  1549. return DefaultBlockScanLimit;
  1550. }
  1551. bool MemoryDependenceWrapperPass::runOnFunction(Function &F) {
  1552. auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
  1553. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1554. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  1555. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1556. MemDep.emplace(AA, AC, TLI, DT, BlockScanLimit);
  1557. return false;
  1558. }