PromoteMemoryToRegister.cpp 37 KB

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