PromoteMemoryToRegister.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
  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 promotes memory references to be register references. It promotes
  10. // alloca instructions which only have loads and stores as uses. An alloca is
  11. // transformed by using iterated dominator frontiers to place PHI nodes, then
  12. // traversing the function in depth-first order to rewrite loads and stores as
  13. // appropriate.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/ADT/Twine.h"
  23. #include "llvm/Analysis/AssumptionCache.h"
  24. #include "llvm/Analysis/InstructionSimplify.h"
  25. #include "llvm/Analysis/IteratedDominanceFrontier.h"
  26. #include "llvm/Analysis/ValueTracking.h"
  27. #include "llvm/IR/BasicBlock.h"
  28. #include "llvm/IR/CFG.h"
  29. #include "llvm/IR/Constant.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/DIBuilder.h"
  32. #include "llvm/IR/DebugInfo.h"
  33. #include "llvm/IR/Dominators.h"
  34. #include "llvm/IR/Function.h"
  35. #include "llvm/IR/InstrTypes.h"
  36. #include "llvm/IR/Instruction.h"
  37. #include "llvm/IR/Instructions.h"
  38. #include "llvm/IR/IntrinsicInst.h"
  39. #include "llvm/IR/Intrinsics.h"
  40. #include "llvm/IR/LLVMContext.h"
  41. #include "llvm/IR/Module.h"
  42. #include "llvm/IR/Type.h"
  43. #include "llvm/IR/User.h"
  44. #include "llvm/Support/Casting.h"
  45. #include "llvm/Transforms/Utils/Local.h"
  46. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  47. #include <algorithm>
  48. #include <cassert>
  49. #include <iterator>
  50. #include <utility>
  51. #include <vector>
  52. using namespace llvm;
  53. #define DEBUG_TYPE "mem2reg"
  54. STATISTIC(NumLocalPromoted, "Number of alloca's promoted within one block");
  55. STATISTIC(NumSingleStore, "Number of alloca's promoted with a single store");
  56. STATISTIC(NumDeadAlloca, "Number of dead alloca's removed");
  57. STATISTIC(NumPHIInsert, "Number of PHI nodes inserted");
  58. bool llvm::isAllocaPromotable(const AllocaInst *AI) {
  59. // Only allow direct and non-volatile loads and stores...
  60. for (const User *U : AI->users()) {
  61. if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
  62. // Note that atomic loads can be transformed; atomic semantics do
  63. // not have any meaning for a local alloca.
  64. if (LI->isVolatile() || LI->getType() != AI->getAllocatedType())
  65. return false;
  66. } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
  67. if (SI->getValueOperand() == AI ||
  68. SI->getValueOperand()->getType() != AI->getAllocatedType())
  69. return false; // Don't allow a store OF the AI, only INTO the AI.
  70. // Note that atomic stores can be transformed; atomic semantics do
  71. // not have any meaning for a local alloca.
  72. if (SI->isVolatile())
  73. return false;
  74. } else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
  75. if (!II->isLifetimeStartOrEnd() && !II->isDroppable())
  76. return false;
  77. } else if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
  78. if (!onlyUsedByLifetimeMarkersOrDroppableInsts(BCI))
  79. return false;
  80. } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
  81. if (!GEPI->hasAllZeroIndices())
  82. return false;
  83. if (!onlyUsedByLifetimeMarkersOrDroppableInsts(GEPI))
  84. return false;
  85. } else if (const AddrSpaceCastInst *ASCI = dyn_cast<AddrSpaceCastInst>(U)) {
  86. if (!onlyUsedByLifetimeMarkers(ASCI))
  87. return false;
  88. } else {
  89. return false;
  90. }
  91. }
  92. return true;
  93. }
  94. namespace {
  95. /// Helper for updating assignment tracking debug info when promoting allocas.
  96. class AssignmentTrackingInfo {
  97. /// DbgAssignIntrinsics linked to the alloca with at most one per variable
  98. /// fragment. (i.e. not be a comprehensive set if there are multiple
  99. /// dbg.assigns for one variable fragment).
  100. SmallVector<DbgVariableIntrinsic *> DbgAssigns;
  101. public:
  102. void init(AllocaInst *AI) {
  103. SmallSet<DebugVariable, 2> Vars;
  104. for (DbgAssignIntrinsic *DAI : at::getAssignmentMarkers(AI)) {
  105. if (Vars.insert(DebugVariable(DAI)).second)
  106. DbgAssigns.push_back(DAI);
  107. }
  108. }
  109. /// Update assignment tracking debug info given for the to-be-deleted store
  110. /// \p ToDelete that stores to this alloca.
  111. void updateForDeletedStore(StoreInst *ToDelete, DIBuilder &DIB) const {
  112. // There's nothing to do if the alloca doesn't have any variables using
  113. // assignment tracking.
  114. if (DbgAssigns.empty()) {
  115. assert(at::getAssignmentMarkers(ToDelete).empty());
  116. return;
  117. }
  118. // Just leave dbg.assign intrinsics in place and remember that we've seen
  119. // one for each variable fragment.
  120. SmallSet<DebugVariable, 2> VarHasDbgAssignForStore;
  121. for (DbgAssignIntrinsic *DAI : at::getAssignmentMarkers(ToDelete))
  122. VarHasDbgAssignForStore.insert(DebugVariable(DAI));
  123. // It's possible for variables using assignment tracking to have no
  124. // dbg.assign linked to this store. These are variables in DbgAssigns that
  125. // are missing from VarHasDbgAssignForStore. Since there isn't a dbg.assign
  126. // to mark the assignment - and the store is going to be deleted - insert a
  127. // dbg.value to do that now. An untracked store may be either one that
  128. // cannot be represented using assignment tracking (non-const offset or
  129. // size) or one that is trackable but has had its DIAssignID attachment
  130. // dropped accidentally.
  131. for (auto *DAI : DbgAssigns) {
  132. if (VarHasDbgAssignForStore.contains(DebugVariable(DAI)))
  133. continue;
  134. ConvertDebugDeclareToDebugValue(DAI, ToDelete, DIB);
  135. }
  136. }
  137. /// Update assignment tracking debug info given for the newly inserted PHI \p
  138. /// NewPhi.
  139. void updateForNewPhi(PHINode *NewPhi, DIBuilder &DIB) const {
  140. // Regardless of the position of dbg.assigns relative to stores, the
  141. // incoming values into a new PHI should be the same for the (imaginary)
  142. // debug-phi.
  143. for (auto *DAI : DbgAssigns)
  144. ConvertDebugDeclareToDebugValue(DAI, NewPhi, DIB);
  145. }
  146. void clear() { DbgAssigns.clear(); }
  147. bool empty() { return DbgAssigns.empty(); }
  148. };
  149. struct AllocaInfo {
  150. using DbgUserVec = SmallVector<DbgVariableIntrinsic *, 1>;
  151. SmallVector<BasicBlock *, 32> DefiningBlocks;
  152. SmallVector<BasicBlock *, 32> UsingBlocks;
  153. StoreInst *OnlyStore;
  154. BasicBlock *OnlyBlock;
  155. bool OnlyUsedInOneBlock;
  156. /// Debug users of the alloca - does not include dbg.assign intrinsics.
  157. DbgUserVec DbgUsers;
  158. /// Helper to update assignment tracking debug info.
  159. AssignmentTrackingInfo AssignmentTracking;
  160. void clear() {
  161. DefiningBlocks.clear();
  162. UsingBlocks.clear();
  163. OnlyStore = nullptr;
  164. OnlyBlock = nullptr;
  165. OnlyUsedInOneBlock = true;
  166. DbgUsers.clear();
  167. AssignmentTracking.clear();
  168. }
  169. /// Scan the uses of the specified alloca, filling in the AllocaInfo used
  170. /// by the rest of the pass to reason about the uses of this alloca.
  171. void AnalyzeAlloca(AllocaInst *AI) {
  172. clear();
  173. // As we scan the uses of the alloca instruction, keep track of stores,
  174. // and decide whether all of the loads and stores to the alloca are within
  175. // the same basic block.
  176. for (User *U : AI->users()) {
  177. Instruction *User = cast<Instruction>(U);
  178. if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
  179. // Remember the basic blocks which define new values for the alloca
  180. DefiningBlocks.push_back(SI->getParent());
  181. OnlyStore = SI;
  182. } else {
  183. LoadInst *LI = cast<LoadInst>(User);
  184. // Otherwise it must be a load instruction, keep track of variable
  185. // reads.
  186. UsingBlocks.push_back(LI->getParent());
  187. }
  188. if (OnlyUsedInOneBlock) {
  189. if (!OnlyBlock)
  190. OnlyBlock = User->getParent();
  191. else if (OnlyBlock != User->getParent())
  192. OnlyUsedInOneBlock = false;
  193. }
  194. }
  195. DbgUserVec AllDbgUsers;
  196. findDbgUsers(AllDbgUsers, AI);
  197. std::copy_if(AllDbgUsers.begin(), AllDbgUsers.end(),
  198. std::back_inserter(DbgUsers), [](DbgVariableIntrinsic *DII) {
  199. return !isa<DbgAssignIntrinsic>(DII);
  200. });
  201. AssignmentTracking.init(AI);
  202. }
  203. };
  204. /// Data package used by RenamePass().
  205. struct RenamePassData {
  206. using ValVector = std::vector<Value *>;
  207. using LocationVector = std::vector<DebugLoc>;
  208. RenamePassData(BasicBlock *B, BasicBlock *P, ValVector V, LocationVector L)
  209. : BB(B), Pred(P), Values(std::move(V)), Locations(std::move(L)) {}
  210. BasicBlock *BB;
  211. BasicBlock *Pred;
  212. ValVector Values;
  213. LocationVector Locations;
  214. };
  215. /// This assigns and keeps a per-bb relative ordering of load/store
  216. /// instructions in the block that directly load or store an alloca.
  217. ///
  218. /// This functionality is important because it avoids scanning large basic
  219. /// blocks multiple times when promoting many allocas in the same block.
  220. class LargeBlockInfo {
  221. /// For each instruction that we track, keep the index of the
  222. /// instruction.
  223. ///
  224. /// The index starts out as the number of the instruction from the start of
  225. /// the block.
  226. DenseMap<const Instruction *, unsigned> InstNumbers;
  227. public:
  228. /// This code only looks at accesses to allocas.
  229. static bool isInterestingInstruction(const Instruction *I) {
  230. return (isa<LoadInst>(I) && isa<AllocaInst>(I->getOperand(0))) ||
  231. (isa<StoreInst>(I) && isa<AllocaInst>(I->getOperand(1)));
  232. }
  233. /// Get or calculate the index of the specified instruction.
  234. unsigned getInstructionIndex(const Instruction *I) {
  235. assert(isInterestingInstruction(I) &&
  236. "Not a load/store to/from an alloca?");
  237. // If we already have this instruction number, return it.
  238. DenseMap<const Instruction *, unsigned>::iterator It = InstNumbers.find(I);
  239. if (It != InstNumbers.end())
  240. return It->second;
  241. // Scan the whole block to get the instruction. This accumulates
  242. // information for every interesting instruction in the block, in order to
  243. // avoid gratuitus rescans.
  244. const BasicBlock *BB = I->getParent();
  245. unsigned InstNo = 0;
  246. for (const Instruction &BBI : *BB)
  247. if (isInterestingInstruction(&BBI))
  248. InstNumbers[&BBI] = InstNo++;
  249. It = InstNumbers.find(I);
  250. assert(It != InstNumbers.end() && "Didn't insert instruction?");
  251. return It->second;
  252. }
  253. void deleteValue(const Instruction *I) { InstNumbers.erase(I); }
  254. void clear() { InstNumbers.clear(); }
  255. };
  256. struct PromoteMem2Reg {
  257. /// The alloca instructions being promoted.
  258. std::vector<AllocaInst *> Allocas;
  259. DominatorTree &DT;
  260. DIBuilder DIB;
  261. /// A cache of @llvm.assume intrinsics used by SimplifyInstruction.
  262. AssumptionCache *AC;
  263. const SimplifyQuery SQ;
  264. /// Reverse mapping of Allocas.
  265. DenseMap<AllocaInst *, unsigned> AllocaLookup;
  266. /// The PhiNodes we're adding.
  267. ///
  268. /// That map is used to simplify some Phi nodes as we iterate over it, so
  269. /// it should have deterministic iterators. We could use a MapVector, but
  270. /// since we already maintain a map from BasicBlock* to a stable numbering
  271. /// (BBNumbers), the DenseMap is more efficient (also supports removal).
  272. DenseMap<std::pair<unsigned, unsigned>, PHINode *> NewPhiNodes;
  273. /// For each PHI node, keep track of which entry in Allocas it corresponds
  274. /// to.
  275. DenseMap<PHINode *, unsigned> PhiToAllocaMap;
  276. /// For each alloca, we keep track of the dbg.declare intrinsic that
  277. /// describes it, if any, so that we can convert it to a dbg.value
  278. /// intrinsic if the alloca gets promoted.
  279. SmallVector<AllocaInfo::DbgUserVec, 8> AllocaDbgUsers;
  280. /// For each alloca, keep an instance of a helper class that gives us an easy
  281. /// way to update assignment tracking debug info if the alloca is promoted.
  282. SmallVector<AssignmentTrackingInfo, 8> AllocaATInfo;
  283. /// The set of basic blocks the renamer has already visited.
  284. SmallPtrSet<BasicBlock *, 16> Visited;
  285. /// Contains a stable numbering of basic blocks to avoid non-determinstic
  286. /// behavior.
  287. DenseMap<BasicBlock *, unsigned> BBNumbers;
  288. /// Lazily compute the number of predecessors a block has.
  289. DenseMap<const BasicBlock *, unsigned> BBNumPreds;
  290. public:
  291. PromoteMem2Reg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
  292. AssumptionCache *AC)
  293. : Allocas(Allocas.begin(), Allocas.end()), DT(DT),
  294. DIB(*DT.getRoot()->getParent()->getParent(), /*AllowUnresolved*/ false),
  295. AC(AC), SQ(DT.getRoot()->getParent()->getParent()->getDataLayout(),
  296. nullptr, &DT, AC) {}
  297. void run();
  298. private:
  299. void RemoveFromAllocasList(unsigned &AllocaIdx) {
  300. Allocas[AllocaIdx] = Allocas.back();
  301. Allocas.pop_back();
  302. --AllocaIdx;
  303. }
  304. unsigned getNumPreds(const BasicBlock *BB) {
  305. unsigned &NP = BBNumPreds[BB];
  306. if (NP == 0)
  307. NP = pred_size(BB) + 1;
  308. return NP - 1;
  309. }
  310. void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info,
  311. const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
  312. SmallPtrSetImpl<BasicBlock *> &LiveInBlocks);
  313. void RenamePass(BasicBlock *BB, BasicBlock *Pred,
  314. RenamePassData::ValVector &IncVals,
  315. RenamePassData::LocationVector &IncLocs,
  316. std::vector<RenamePassData> &Worklist);
  317. bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
  318. };
  319. } // end anonymous namespace
  320. /// Given a LoadInst LI this adds assume(LI != null) after it.
  321. static void addAssumeNonNull(AssumptionCache *AC, LoadInst *LI) {
  322. Function *AssumeIntrinsic =
  323. Intrinsic::getDeclaration(LI->getModule(), Intrinsic::assume);
  324. ICmpInst *LoadNotNull = new ICmpInst(ICmpInst::ICMP_NE, LI,
  325. Constant::getNullValue(LI->getType()));
  326. LoadNotNull->insertAfter(LI);
  327. CallInst *CI = CallInst::Create(AssumeIntrinsic, {LoadNotNull});
  328. CI->insertAfter(LoadNotNull);
  329. AC->registerAssumption(cast<AssumeInst>(CI));
  330. }
  331. static void convertMetadataToAssumes(LoadInst *LI, Value *Val,
  332. const DataLayout &DL, AssumptionCache *AC,
  333. const DominatorTree *DT) {
  334. // If the load was marked as nonnull we don't want to lose that information
  335. // when we erase this Load. So we preserve it with an assume. As !nonnull
  336. // returns poison while assume violations are immediate undefined behavior,
  337. // we can only do this if the value is known non-poison.
  338. if (AC && LI->getMetadata(LLVMContext::MD_nonnull) &&
  339. LI->getMetadata(LLVMContext::MD_noundef) &&
  340. !isKnownNonZero(Val, DL, 0, AC, LI, DT))
  341. addAssumeNonNull(AC, LI);
  342. }
  343. static void removeIntrinsicUsers(AllocaInst *AI) {
  344. // Knowing that this alloca is promotable, we know that it's safe to kill all
  345. // instructions except for load and store.
  346. for (Use &U : llvm::make_early_inc_range(AI->uses())) {
  347. Instruction *I = cast<Instruction>(U.getUser());
  348. if (isa<LoadInst>(I) || isa<StoreInst>(I))
  349. continue;
  350. // Drop the use of AI in droppable instructions.
  351. if (I->isDroppable()) {
  352. I->dropDroppableUse(U);
  353. continue;
  354. }
  355. if (!I->getType()->isVoidTy()) {
  356. // The only users of this bitcast/GEP instruction are lifetime intrinsics.
  357. // Follow the use/def chain to erase them now instead of leaving it for
  358. // dead code elimination later.
  359. for (Use &UU : llvm::make_early_inc_range(I->uses())) {
  360. Instruction *Inst = cast<Instruction>(UU.getUser());
  361. // Drop the use of I in droppable instructions.
  362. if (Inst->isDroppable()) {
  363. Inst->dropDroppableUse(UU);
  364. continue;
  365. }
  366. Inst->eraseFromParent();
  367. }
  368. }
  369. I->eraseFromParent();
  370. }
  371. }
  372. /// Rewrite as many loads as possible given a single store.
  373. ///
  374. /// When there is only a single store, we can use the domtree to trivially
  375. /// replace all of the dominated loads with the stored value. Do so, and return
  376. /// true if this has successfully promoted the alloca entirely. If this returns
  377. /// false there were some loads which were not dominated by the single store
  378. /// and thus must be phi-ed with undef. We fall back to the standard alloca
  379. /// promotion algorithm in that case.
  380. static bool rewriteSingleStoreAlloca(AllocaInst *AI, AllocaInfo &Info,
  381. LargeBlockInfo &LBI, const DataLayout &DL,
  382. DominatorTree &DT, AssumptionCache *AC) {
  383. StoreInst *OnlyStore = Info.OnlyStore;
  384. bool StoringGlobalVal = !isa<Instruction>(OnlyStore->getOperand(0));
  385. BasicBlock *StoreBB = OnlyStore->getParent();
  386. int StoreIndex = -1;
  387. // Clear out UsingBlocks. We will reconstruct it here if needed.
  388. Info.UsingBlocks.clear();
  389. for (User *U : make_early_inc_range(AI->users())) {
  390. Instruction *UserInst = cast<Instruction>(U);
  391. if (UserInst == OnlyStore)
  392. continue;
  393. LoadInst *LI = cast<LoadInst>(UserInst);
  394. // Okay, if we have a load from the alloca, we want to replace it with the
  395. // only value stored to the alloca. We can do this if the value is
  396. // dominated by the store. If not, we use the rest of the mem2reg machinery
  397. // to insert the phi nodes as needed.
  398. if (!StoringGlobalVal) { // Non-instructions are always dominated.
  399. if (LI->getParent() == StoreBB) {
  400. // If we have a use that is in the same block as the store, compare the
  401. // indices of the two instructions to see which one came first. If the
  402. // load came before the store, we can't handle it.
  403. if (StoreIndex == -1)
  404. StoreIndex = LBI.getInstructionIndex(OnlyStore);
  405. if (unsigned(StoreIndex) > LBI.getInstructionIndex(LI)) {
  406. // Can't handle this load, bail out.
  407. Info.UsingBlocks.push_back(StoreBB);
  408. continue;
  409. }
  410. } else if (!DT.dominates(StoreBB, LI->getParent())) {
  411. // If the load and store are in different blocks, use BB dominance to
  412. // check their relationships. If the store doesn't dom the use, bail
  413. // out.
  414. Info.UsingBlocks.push_back(LI->getParent());
  415. continue;
  416. }
  417. }
  418. // Otherwise, we *can* safely rewrite this load.
  419. Value *ReplVal = OnlyStore->getOperand(0);
  420. // If the replacement value is the load, this must occur in unreachable
  421. // code.
  422. if (ReplVal == LI)
  423. ReplVal = PoisonValue::get(LI->getType());
  424. convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
  425. LI->replaceAllUsesWith(ReplVal);
  426. LI->eraseFromParent();
  427. LBI.deleteValue(LI);
  428. }
  429. // Finally, after the scan, check to see if the store is all that is left.
  430. if (!Info.UsingBlocks.empty())
  431. return false; // If not, we'll have to fall back for the remainder.
  432. DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
  433. // Update assignment tracking info for the store we're going to delete.
  434. Info.AssignmentTracking.updateForDeletedStore(Info.OnlyStore, DIB);
  435. // Record debuginfo for the store and remove the declaration's
  436. // debuginfo.
  437. for (DbgVariableIntrinsic *DII : Info.DbgUsers) {
  438. if (DII->isAddressOfVariable()) {
  439. ConvertDebugDeclareToDebugValue(DII, Info.OnlyStore, DIB);
  440. DII->eraseFromParent();
  441. } else if (DII->getExpression()->startsWithDeref()) {
  442. DII->eraseFromParent();
  443. }
  444. }
  445. // Remove dbg.assigns linked to the alloca as these are now redundant.
  446. at::deleteAssignmentMarkers(AI);
  447. // Remove the (now dead) store and alloca.
  448. Info.OnlyStore->eraseFromParent();
  449. LBI.deleteValue(Info.OnlyStore);
  450. AI->eraseFromParent();
  451. return true;
  452. }
  453. /// Many allocas are only used within a single basic block. If this is the
  454. /// case, avoid traversing the CFG and inserting a lot of potentially useless
  455. /// PHI nodes by just performing a single linear pass over the basic block
  456. /// using the Alloca.
  457. ///
  458. /// If we cannot promote this alloca (because it is read before it is written),
  459. /// return false. This is necessary in cases where, due to control flow, the
  460. /// alloca is undefined only on some control flow paths. e.g. code like
  461. /// this is correct in LLVM IR:
  462. /// // A is an alloca with no stores so far
  463. /// for (...) {
  464. /// int t = *A;
  465. /// if (!first_iteration)
  466. /// use(t);
  467. /// *A = 42;
  468. /// }
  469. static bool promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
  470. LargeBlockInfo &LBI,
  471. const DataLayout &DL,
  472. DominatorTree &DT,
  473. AssumptionCache *AC) {
  474. // The trickiest case to handle is when we have large blocks. Because of this,
  475. // this code is optimized assuming that large blocks happen. This does not
  476. // significantly pessimize the small block case. This uses LargeBlockInfo to
  477. // make it efficient to get the index of various operations in the block.
  478. // Walk the use-def list of the alloca, getting the locations of all stores.
  479. using StoresByIndexTy = SmallVector<std::pair<unsigned, StoreInst *>, 64>;
  480. StoresByIndexTy StoresByIndex;
  481. for (User *U : AI->users())
  482. if (StoreInst *SI = dyn_cast<StoreInst>(U))
  483. StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
  484. // Sort the stores by their index, making it efficient to do a lookup with a
  485. // binary search.
  486. llvm::sort(StoresByIndex, less_first());
  487. // Walk all of the loads from this alloca, replacing them with the nearest
  488. // store above them, if any.
  489. for (User *U : make_early_inc_range(AI->users())) {
  490. LoadInst *LI = dyn_cast<LoadInst>(U);
  491. if (!LI)
  492. continue;
  493. unsigned LoadIdx = LBI.getInstructionIndex(LI);
  494. // Find the nearest store that has a lower index than this load.
  495. StoresByIndexTy::iterator I = llvm::lower_bound(
  496. StoresByIndex,
  497. std::make_pair(LoadIdx, static_cast<StoreInst *>(nullptr)),
  498. less_first());
  499. Value *ReplVal;
  500. if (I == StoresByIndex.begin()) {
  501. if (StoresByIndex.empty())
  502. // If there are no stores, the load takes the undef value.
  503. ReplVal = UndefValue::get(LI->getType());
  504. else
  505. // There is no store before this load, bail out (load may be affected
  506. // by the following stores - see main comment).
  507. return false;
  508. } else {
  509. // Otherwise, there was a store before this load, the load takes its
  510. // value.
  511. ReplVal = std::prev(I)->second->getOperand(0);
  512. }
  513. convertMetadataToAssumes(LI, ReplVal, DL, AC, &DT);
  514. // If the replacement value is the load, this must occur in unreachable
  515. // code.
  516. if (ReplVal == LI)
  517. ReplVal = PoisonValue::get(LI->getType());
  518. LI->replaceAllUsesWith(ReplVal);
  519. LI->eraseFromParent();
  520. LBI.deleteValue(LI);
  521. }
  522. // Remove the (now dead) stores and alloca.
  523. DIBuilder DIB(*AI->getModule(), /*AllowUnresolved*/ false);
  524. while (!AI->use_empty()) {
  525. StoreInst *SI = cast<StoreInst>(AI->user_back());
  526. // Update assignment tracking info for the store we're going to delete.
  527. Info.AssignmentTracking.updateForDeletedStore(SI, DIB);
  528. // Record debuginfo for the store before removing it.
  529. for (DbgVariableIntrinsic *DII : Info.DbgUsers) {
  530. if (DII->isAddressOfVariable()) {
  531. ConvertDebugDeclareToDebugValue(DII, SI, DIB);
  532. }
  533. }
  534. SI->eraseFromParent();
  535. LBI.deleteValue(SI);
  536. }
  537. // Remove dbg.assigns linked to the alloca as these are now redundant.
  538. at::deleteAssignmentMarkers(AI);
  539. AI->eraseFromParent();
  540. // The alloca's debuginfo can be removed as well.
  541. for (DbgVariableIntrinsic *DII : Info.DbgUsers)
  542. if (DII->isAddressOfVariable() || DII->getExpression()->startsWithDeref())
  543. DII->eraseFromParent();
  544. ++NumLocalPromoted;
  545. return true;
  546. }
  547. void PromoteMem2Reg::run() {
  548. Function &F = *DT.getRoot()->getParent();
  549. AllocaDbgUsers.resize(Allocas.size());
  550. AllocaATInfo.resize(Allocas.size());
  551. AllocaInfo Info;
  552. LargeBlockInfo LBI;
  553. ForwardIDFCalculator IDF(DT);
  554. for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
  555. AllocaInst *AI = Allocas[AllocaNum];
  556. assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
  557. assert(AI->getParent()->getParent() == &F &&
  558. "All allocas should be in the same function, which is same as DF!");
  559. removeIntrinsicUsers(AI);
  560. if (AI->use_empty()) {
  561. // If there are no uses of the alloca, just delete it now.
  562. AI->eraseFromParent();
  563. // Remove the alloca from the Allocas list, since it has been processed
  564. RemoveFromAllocasList(AllocaNum);
  565. ++NumDeadAlloca;
  566. continue;
  567. }
  568. // Calculate the set of read and write-locations for each alloca. This is
  569. // analogous to finding the 'uses' and 'definitions' of each variable.
  570. Info.AnalyzeAlloca(AI);
  571. // If there is only a single store to this value, replace any loads of
  572. // it that are directly dominated by the definition with the value stored.
  573. if (Info.DefiningBlocks.size() == 1) {
  574. if (rewriteSingleStoreAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
  575. // The alloca has been processed, move on.
  576. RemoveFromAllocasList(AllocaNum);
  577. ++NumSingleStore;
  578. continue;
  579. }
  580. }
  581. // If the alloca is only read and written in one basic block, just perform a
  582. // linear sweep over the block to eliminate it.
  583. if (Info.OnlyUsedInOneBlock &&
  584. promoteSingleBlockAlloca(AI, Info, LBI, SQ.DL, DT, AC)) {
  585. // The alloca has been processed, move on.
  586. RemoveFromAllocasList(AllocaNum);
  587. continue;
  588. }
  589. // If we haven't computed a numbering for the BB's in the function, do so
  590. // now.
  591. if (BBNumbers.empty()) {
  592. unsigned ID = 0;
  593. for (auto &BB : F)
  594. BBNumbers[&BB] = ID++;
  595. }
  596. // Remember the dbg.declare intrinsic describing this alloca, if any.
  597. if (!Info.DbgUsers.empty())
  598. AllocaDbgUsers[AllocaNum] = Info.DbgUsers;
  599. if (!Info.AssignmentTracking.empty())
  600. AllocaATInfo[AllocaNum] = Info.AssignmentTracking;
  601. // Keep the reverse mapping of the 'Allocas' array for the rename pass.
  602. AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
  603. // Unique the set of defining blocks for efficient lookup.
  604. SmallPtrSet<BasicBlock *, 32> DefBlocks(Info.DefiningBlocks.begin(),
  605. Info.DefiningBlocks.end());
  606. // Determine which blocks the value is live in. These are blocks which lead
  607. // to uses.
  608. SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
  609. ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
  610. // At this point, we're committed to promoting the alloca using IDF's, and
  611. // the standard SSA construction algorithm. Determine which blocks need phi
  612. // nodes and see if we can optimize out some work by avoiding insertion of
  613. // dead phi nodes.
  614. IDF.setLiveInBlocks(LiveInBlocks);
  615. IDF.setDefiningBlocks(DefBlocks);
  616. SmallVector<BasicBlock *, 32> PHIBlocks;
  617. IDF.calculate(PHIBlocks);
  618. llvm::sort(PHIBlocks, [this](BasicBlock *A, BasicBlock *B) {
  619. return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
  620. });
  621. unsigned CurrentVersion = 0;
  622. for (BasicBlock *BB : PHIBlocks)
  623. QueuePhiNode(BB, AllocaNum, CurrentVersion);
  624. }
  625. if (Allocas.empty())
  626. return; // All of the allocas must have been trivial!
  627. LBI.clear();
  628. // Set the incoming values for the basic block to be null values for all of
  629. // the alloca's. We do this in case there is a load of a value that has not
  630. // been stored yet. In this case, it will get this null value.
  631. RenamePassData::ValVector Values(Allocas.size());
  632. for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
  633. Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
  634. // When handling debug info, treat all incoming values as if they have unknown
  635. // locations until proven otherwise.
  636. RenamePassData::LocationVector Locations(Allocas.size());
  637. // Walks all basic blocks in the function performing the SSA rename algorithm
  638. // and inserting the phi nodes we marked as necessary
  639. std::vector<RenamePassData> RenamePassWorkList;
  640. RenamePassWorkList.emplace_back(&F.front(), nullptr, std::move(Values),
  641. std::move(Locations));
  642. do {
  643. RenamePassData RPD = std::move(RenamePassWorkList.back());
  644. RenamePassWorkList.pop_back();
  645. // RenamePass may add new worklist entries.
  646. RenamePass(RPD.BB, RPD.Pred, RPD.Values, RPD.Locations, RenamePassWorkList);
  647. } while (!RenamePassWorkList.empty());
  648. // The renamer uses the Visited set to avoid infinite loops. Clear it now.
  649. Visited.clear();
  650. // Remove the allocas themselves from the function.
  651. for (Instruction *A : Allocas) {
  652. // Remove dbg.assigns linked to the alloca as these are now redundant.
  653. at::deleteAssignmentMarkers(A);
  654. // If there are any uses of the alloca instructions left, they must be in
  655. // unreachable basic blocks that were not processed by walking the dominator
  656. // tree. Just delete the users now.
  657. if (!A->use_empty())
  658. A->replaceAllUsesWith(PoisonValue::get(A->getType()));
  659. A->eraseFromParent();
  660. }
  661. // Remove alloca's dbg.declare intrinsics from the function.
  662. for (auto &DbgUsers : AllocaDbgUsers) {
  663. for (auto *DII : DbgUsers)
  664. if (DII->isAddressOfVariable() || DII->getExpression()->startsWithDeref())
  665. DII->eraseFromParent();
  666. }
  667. // Loop over all of the PHI nodes and see if there are any that we can get
  668. // rid of because they merge all of the same incoming values. This can
  669. // happen due to undef values coming into the PHI nodes. This process is
  670. // iterative, because eliminating one PHI node can cause others to be removed.
  671. bool EliminatedAPHI = true;
  672. while (EliminatedAPHI) {
  673. EliminatedAPHI = false;
  674. // Iterating over NewPhiNodes is deterministic, so it is safe to try to
  675. // simplify and RAUW them as we go. If it was not, we could add uses to
  676. // the values we replace with in a non-deterministic order, thus creating
  677. // non-deterministic def->use chains.
  678. for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
  679. I = NewPhiNodes.begin(),
  680. E = NewPhiNodes.end();
  681. I != E;) {
  682. PHINode *PN = I->second;
  683. // If this PHI node merges one value and/or undefs, get the value.
  684. if (Value *V = simplifyInstruction(PN, SQ)) {
  685. PN->replaceAllUsesWith(V);
  686. PN->eraseFromParent();
  687. NewPhiNodes.erase(I++);
  688. EliminatedAPHI = true;
  689. continue;
  690. }
  691. ++I;
  692. }
  693. }
  694. // At this point, the renamer has added entries to PHI nodes for all reachable
  695. // code. Unfortunately, there may be unreachable blocks which the renamer
  696. // hasn't traversed. If this is the case, the PHI nodes may not
  697. // have incoming values for all predecessors. Loop over all PHI nodes we have
  698. // created, inserting undef values if they are missing any incoming values.
  699. for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
  700. I = NewPhiNodes.begin(),
  701. E = NewPhiNodes.end();
  702. I != E; ++I) {
  703. // We want to do this once per basic block. As such, only process a block
  704. // when we find the PHI that is the first entry in the block.
  705. PHINode *SomePHI = I->second;
  706. BasicBlock *BB = SomePHI->getParent();
  707. if (&BB->front() != SomePHI)
  708. continue;
  709. // Only do work here if there the PHI nodes are missing incoming values. We
  710. // know that all PHI nodes that were inserted in a block will have the same
  711. // number of incoming values, so we can just check any of them.
  712. if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
  713. continue;
  714. // Get the preds for BB.
  715. SmallVector<BasicBlock *, 16> Preds(predecessors(BB));
  716. // Ok, now we know that all of the PHI nodes are missing entries for some
  717. // basic blocks. Start by sorting the incoming predecessors for efficient
  718. // access.
  719. auto CompareBBNumbers = [this](BasicBlock *A, BasicBlock *B) {
  720. return BBNumbers.find(A)->second < BBNumbers.find(B)->second;
  721. };
  722. llvm::sort(Preds, CompareBBNumbers);
  723. // Now we loop through all BB's which have entries in SomePHI and remove
  724. // them from the Preds list.
  725. for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
  726. // Do a log(n) search of the Preds list for the entry we want.
  727. SmallVectorImpl<BasicBlock *>::iterator EntIt = llvm::lower_bound(
  728. Preds, SomePHI->getIncomingBlock(i), CompareBBNumbers);
  729. assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
  730. "PHI node has entry for a block which is not a predecessor!");
  731. // Remove the entry
  732. Preds.erase(EntIt);
  733. }
  734. // At this point, the blocks left in the preds list must have dummy
  735. // entries inserted into every PHI nodes for the block. Update all the phi
  736. // nodes in this block that we are inserting (there could be phis before
  737. // mem2reg runs).
  738. unsigned NumBadPreds = SomePHI->getNumIncomingValues();
  739. BasicBlock::iterator BBI = BB->begin();
  740. while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
  741. SomePHI->getNumIncomingValues() == NumBadPreds) {
  742. Value *UndefVal = UndefValue::get(SomePHI->getType());
  743. for (BasicBlock *Pred : Preds)
  744. SomePHI->addIncoming(UndefVal, Pred);
  745. }
  746. }
  747. NewPhiNodes.clear();
  748. }
  749. /// Determine which blocks the value is live in.
  750. ///
  751. /// These are blocks which lead to uses. Knowing this allows us to avoid
  752. /// inserting PHI nodes into blocks which don't lead to uses (thus, the
  753. /// inserted phi nodes would be dead).
  754. void PromoteMem2Reg::ComputeLiveInBlocks(
  755. AllocaInst *AI, AllocaInfo &Info,
  756. const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
  757. SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
  758. // To determine liveness, we must iterate through the predecessors of blocks
  759. // where the def is live. Blocks are added to the worklist if we need to
  760. // check their predecessors. Start with all the using blocks.
  761. SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
  762. Info.UsingBlocks.end());
  763. // If any of the using blocks is also a definition block, check to see if the
  764. // definition occurs before or after the use. If it happens before the use,
  765. // the value isn't really live-in.
  766. for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
  767. BasicBlock *BB = LiveInBlockWorklist[i];
  768. if (!DefBlocks.count(BB))
  769. continue;
  770. // Okay, this is a block that both uses and defines the value. If the first
  771. // reference to the alloca is a def (store), then we know it isn't live-in.
  772. for (BasicBlock::iterator I = BB->begin();; ++I) {
  773. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  774. if (SI->getOperand(1) != AI)
  775. continue;
  776. // We found a store to the alloca before a load. The alloca is not
  777. // actually live-in here.
  778. LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
  779. LiveInBlockWorklist.pop_back();
  780. --i;
  781. --e;
  782. break;
  783. }
  784. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  785. // Okay, we found a load before a store to the alloca. It is actually
  786. // live into this block.
  787. if (LI->getOperand(0) == AI)
  788. break;
  789. }
  790. }
  791. // Now that we have a set of blocks where the phi is live-in, recursively add
  792. // their predecessors until we find the full region the value is live.
  793. while (!LiveInBlockWorklist.empty()) {
  794. BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
  795. // The block really is live in here, insert it into the set. If already in
  796. // the set, then it has already been processed.
  797. if (!LiveInBlocks.insert(BB).second)
  798. continue;
  799. // Since the value is live into BB, it is either defined in a predecessor or
  800. // live into it to. Add the preds to the worklist unless they are a
  801. // defining block.
  802. for (BasicBlock *P : predecessors(BB)) {
  803. // The value is not live into a predecessor if it defines the value.
  804. if (DefBlocks.count(P))
  805. continue;
  806. // Otherwise it is, add to the worklist.
  807. LiveInBlockWorklist.push_back(P);
  808. }
  809. }
  810. }
  811. /// Queue a phi-node to be added to a basic-block for a specific Alloca.
  812. ///
  813. /// Returns true if there wasn't already a phi-node for that variable
  814. bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
  815. unsigned &Version) {
  816. // Look up the basic-block in question.
  817. PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
  818. // If the BB already has a phi node added for the i'th alloca then we're done!
  819. if (PN)
  820. return false;
  821. // Create a PhiNode using the dereferenced type... and add the phi-node to the
  822. // BasicBlock.
  823. PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
  824. Allocas[AllocaNo]->getName() + "." + Twine(Version++),
  825. &BB->front());
  826. ++NumPHIInsert;
  827. PhiToAllocaMap[PN] = AllocaNo;
  828. return true;
  829. }
  830. /// Update the debug location of a phi. \p ApplyMergedLoc indicates whether to
  831. /// create a merged location incorporating \p DL, or to set \p DL directly.
  832. static void updateForIncomingValueLocation(PHINode *PN, DebugLoc DL,
  833. bool ApplyMergedLoc) {
  834. if (ApplyMergedLoc)
  835. PN->applyMergedLocation(PN->getDebugLoc(), DL);
  836. else
  837. PN->setDebugLoc(DL);
  838. }
  839. /// Recursively traverse the CFG of the function, renaming loads and
  840. /// stores to the allocas which we are promoting.
  841. ///
  842. /// IncomingVals indicates what value each Alloca contains on exit from the
  843. /// predecessor block Pred.
  844. void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
  845. RenamePassData::ValVector &IncomingVals,
  846. RenamePassData::LocationVector &IncomingLocs,
  847. std::vector<RenamePassData> &Worklist) {
  848. NextIteration:
  849. // If we are inserting any phi nodes into this BB, they will already be in the
  850. // block.
  851. if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
  852. // If we have PHI nodes to update, compute the number of edges from Pred to
  853. // BB.
  854. if (PhiToAllocaMap.count(APN)) {
  855. // We want to be able to distinguish between PHI nodes being inserted by
  856. // this invocation of mem2reg from those phi nodes that already existed in
  857. // the IR before mem2reg was run. We determine that APN is being inserted
  858. // because it is missing incoming edges. All other PHI nodes being
  859. // inserted by this pass of mem2reg will have the same number of incoming
  860. // operands so far. Remember this count.
  861. unsigned NewPHINumOperands = APN->getNumOperands();
  862. unsigned NumEdges = llvm::count(successors(Pred), BB);
  863. assert(NumEdges && "Must be at least one edge from Pred to BB!");
  864. // Add entries for all the phis.
  865. BasicBlock::iterator PNI = BB->begin();
  866. do {
  867. unsigned AllocaNo = PhiToAllocaMap[APN];
  868. // Update the location of the phi node.
  869. updateForIncomingValueLocation(APN, IncomingLocs[AllocaNo],
  870. APN->getNumIncomingValues() > 0);
  871. // Add N incoming values to the PHI node.
  872. for (unsigned i = 0; i != NumEdges; ++i)
  873. APN->addIncoming(IncomingVals[AllocaNo], Pred);
  874. // The currently active variable for this block is now the PHI.
  875. IncomingVals[AllocaNo] = APN;
  876. AllocaATInfo[AllocaNo].updateForNewPhi(APN, DIB);
  877. for (DbgVariableIntrinsic *DII : AllocaDbgUsers[AllocaNo])
  878. if (DII->isAddressOfVariable())
  879. ConvertDebugDeclareToDebugValue(DII, APN, DIB);
  880. // Get the next phi node.
  881. ++PNI;
  882. APN = dyn_cast<PHINode>(PNI);
  883. if (!APN)
  884. break;
  885. // Verify that it is missing entries. If not, it is not being inserted
  886. // by this mem2reg invocation so we want to ignore it.
  887. } while (APN->getNumOperands() == NewPHINumOperands);
  888. }
  889. }
  890. // Don't revisit blocks.
  891. if (!Visited.insert(BB).second)
  892. return;
  893. for (BasicBlock::iterator II = BB->begin(); !II->isTerminator();) {
  894. Instruction *I = &*II++; // get the instruction, increment iterator
  895. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  896. AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
  897. if (!Src)
  898. continue;
  899. DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
  900. if (AI == AllocaLookup.end())
  901. continue;
  902. Value *V = IncomingVals[AI->second];
  903. convertMetadataToAssumes(LI, V, SQ.DL, AC, &DT);
  904. // Anything using the load now uses the current value.
  905. LI->replaceAllUsesWith(V);
  906. LI->eraseFromParent();
  907. } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  908. // Delete this instruction and mark the name as the current holder of the
  909. // value
  910. AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
  911. if (!Dest)
  912. continue;
  913. DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
  914. if (ai == AllocaLookup.end())
  915. continue;
  916. // what value were we writing?
  917. unsigned AllocaNo = ai->second;
  918. IncomingVals[AllocaNo] = SI->getOperand(0);
  919. // Record debuginfo for the store before removing it.
  920. IncomingLocs[AllocaNo] = SI->getDebugLoc();
  921. AllocaATInfo[AllocaNo].updateForDeletedStore(SI, DIB);
  922. for (DbgVariableIntrinsic *DII : AllocaDbgUsers[ai->second])
  923. if (DII->isAddressOfVariable())
  924. ConvertDebugDeclareToDebugValue(DII, SI, DIB);
  925. SI->eraseFromParent();
  926. }
  927. }
  928. // 'Recurse' to our successors.
  929. succ_iterator I = succ_begin(BB), E = succ_end(BB);
  930. if (I == E)
  931. return;
  932. // Keep track of the successors so we don't visit the same successor twice
  933. SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
  934. // Handle the first successor without using the worklist.
  935. VisitedSuccs.insert(*I);
  936. Pred = BB;
  937. BB = *I;
  938. ++I;
  939. for (; I != E; ++I)
  940. if (VisitedSuccs.insert(*I).second)
  941. Worklist.emplace_back(*I, Pred, IncomingVals, IncomingLocs);
  942. goto NextIteration;
  943. }
  944. void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
  945. AssumptionCache *AC) {
  946. // If there is nothing to do, bail out...
  947. if (Allocas.empty())
  948. return;
  949. PromoteMem2Reg(Allocas, DT, AC).run();
  950. }