PromoteMemoryToRegister.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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 true. This is necessary in cases where, due to control flow, the
  370. /// alloca is potentially undefined on some control flow paths. e.g. code like
  371. /// this is potentially correct:
  372. ///
  373. /// for (...) { if (c) { A = undef; undef = B; } }
  374. ///
  375. /// ... so long as A is not used before undef is set.
  376. static void promoteSingleBlockAlloca(AllocaInst *AI, const AllocaInfo &Info,
  377. LargeBlockInfo &LBI,
  378. AliasSetTracker *AST) {
  379. // The trickiest case to handle is when we have large blocks. Because of this,
  380. // this code is optimized assuming that large blocks happen. This does not
  381. // significantly pessimize the small block case. This uses LargeBlockInfo to
  382. // make it efficient to get the index of various operations in the block.
  383. // Walk the use-def list of the alloca, getting the locations of all stores.
  384. typedef SmallVector<std::pair<unsigned, StoreInst *>, 64> StoresByIndexTy;
  385. StoresByIndexTy StoresByIndex;
  386. for (User *U : AI->users())
  387. if (StoreInst *SI = dyn_cast<StoreInst>(U))
  388. StoresByIndex.push_back(std::make_pair(LBI.getInstructionIndex(SI), SI));
  389. // Sort the stores by their index, making it efficient to do a lookup with a
  390. // binary search.
  391. std::sort(StoresByIndex.begin(), StoresByIndex.end(), less_first());
  392. // Walk all of the loads from this alloca, replacing them with the nearest
  393. // store above them, if any.
  394. for (auto UI = AI->user_begin(), E = AI->user_end(); UI != E;) {
  395. LoadInst *LI = dyn_cast<LoadInst>(*UI++);
  396. if (!LI)
  397. continue;
  398. unsigned LoadIdx = LBI.getInstructionIndex(LI);
  399. // Find the nearest store that has a lower index than this load.
  400. StoresByIndexTy::iterator I =
  401. std::lower_bound(StoresByIndex.begin(), StoresByIndex.end(),
  402. std::make_pair(LoadIdx,
  403. static_cast<StoreInst *>(nullptr)),
  404. less_first());
  405. if (I == StoresByIndex.begin())
  406. // If there is no store before this load, the load takes the undef value.
  407. LI->replaceAllUsesWith(UndefValue::get(LI->getType()));
  408. else
  409. // Otherwise, there was a store before this load, the load takes its value.
  410. LI->replaceAllUsesWith(std::prev(I)->second->getOperand(0));
  411. if (AST && LI->getType()->isPointerTy())
  412. AST->deleteValue(LI);
  413. LI->eraseFromParent();
  414. LBI.deleteValue(LI);
  415. }
  416. // Remove the (now dead) stores and alloca.
  417. while (!AI->use_empty()) {
  418. StoreInst *SI = cast<StoreInst>(AI->user_back());
  419. // Record debuginfo for the store before removing it.
  420. if (DbgDeclareInst *DDI = Info.DbgDeclare) {
  421. DIBuilder DIB(*AI->getParent()->getParent()->getParent(),
  422. /*AllowUnresolved*/ false);
  423. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  424. }
  425. SI->eraseFromParent();
  426. LBI.deleteValue(SI);
  427. }
  428. if (AST)
  429. AST->deleteValue(AI);
  430. AI->eraseFromParent();
  431. LBI.deleteValue(AI);
  432. // The alloca's debuginfo can be removed as well.
  433. if (DbgDeclareInst *DDI = Info.DbgDeclare) {
  434. DDI->eraseFromParent();
  435. LBI.deleteValue(DDI);
  436. }
  437. ++NumLocalPromoted;
  438. }
  439. void PromoteMem2Reg::run() {
  440. Function &F = *DT.getRoot()->getParent();
  441. if (AST)
  442. PointerAllocaValues.resize(Allocas.size());
  443. AllocaDbgDeclares.resize(Allocas.size());
  444. AllocaInfo Info;
  445. LargeBlockInfo LBI;
  446. IDFCalculator IDF(DT);
  447. for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
  448. AllocaInst *AI = Allocas[AllocaNum];
  449. assert(isAllocaPromotable(AI) && "Cannot promote non-promotable alloca!");
  450. assert(AI->getParent()->getParent() == &F &&
  451. "All allocas should be in the same function, which is same as DF!");
  452. removeLifetimeIntrinsicUsers(AI);
  453. if (AI->use_empty()) {
  454. // If there are no uses of the alloca, just delete it now.
  455. if (AST)
  456. AST->deleteValue(AI);
  457. AI->eraseFromParent();
  458. // Remove the alloca from the Allocas list, since it has been processed
  459. RemoveFromAllocasList(AllocaNum);
  460. ++NumDeadAlloca;
  461. continue;
  462. }
  463. // Calculate the set of read and write-locations for each alloca. This is
  464. // analogous to finding the 'uses' and 'definitions' of each variable.
  465. Info.AnalyzeAlloca(AI);
  466. // If there is only a single store to this value, replace any loads of
  467. // it that are directly dominated by the definition with the value stored.
  468. if (Info.DefiningBlocks.size() == 1) {
  469. if (rewriteSingleStoreAlloca(AI, Info, LBI, DT, AST)) {
  470. // The alloca has been processed, move on.
  471. RemoveFromAllocasList(AllocaNum);
  472. ++NumSingleStore;
  473. continue;
  474. }
  475. }
  476. // If the alloca is only read and written in one basic block, just perform a
  477. // linear sweep over the block to eliminate it.
  478. if (Info.OnlyUsedInOneBlock) {
  479. promoteSingleBlockAlloca(AI, Info, LBI, AST);
  480. // The alloca has been processed, move on.
  481. RemoveFromAllocasList(AllocaNum);
  482. continue;
  483. }
  484. // If we haven't computed a numbering for the BB's in the function, do so
  485. // now.
  486. if (BBNumbers.empty()) {
  487. unsigned ID = 0;
  488. for (auto &BB : F)
  489. BBNumbers[&BB] = ID++;
  490. }
  491. // If we have an AST to keep updated, remember some pointer value that is
  492. // stored into the alloca.
  493. if (AST)
  494. PointerAllocaValues[AllocaNum] = Info.AllocaPointerVal;
  495. // Remember the dbg.declare intrinsic describing this alloca, if any.
  496. if (Info.DbgDeclare)
  497. AllocaDbgDeclares[AllocaNum] = Info.DbgDeclare;
  498. // Keep the reverse mapping of the 'Allocas' array for the rename pass.
  499. AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
  500. // At this point, we're committed to promoting the alloca using IDF's, and
  501. // the standard SSA construction algorithm. Determine which blocks need PHI
  502. // nodes and see if we can optimize out some work by avoiding insertion of
  503. // dead phi nodes.
  504. // Unique the set of defining blocks for efficient lookup.
  505. SmallPtrSet<BasicBlock *, 32> DefBlocks;
  506. DefBlocks.insert(Info.DefiningBlocks.begin(), Info.DefiningBlocks.end());
  507. // Determine which blocks the value is live in. These are blocks which lead
  508. // to uses.
  509. SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
  510. ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks);
  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. IDF.setLiveInBlocks(LiveInBlocks);
  516. IDF.setDefiningBlocks(DefBlocks);
  517. SmallVector<BasicBlock *, 32> PHIBlocks;
  518. IDF.calculate(PHIBlocks);
  519. if (PHIBlocks.size() > 1)
  520. std::sort(PHIBlocks.begin(), PHIBlocks.end(),
  521. [this](BasicBlock *A, BasicBlock *B) {
  522. return BBNumbers.lookup(A) < BBNumbers.lookup(B);
  523. });
  524. unsigned CurrentVersion = 0;
  525. for (unsigned i = 0, e = PHIBlocks.size(); i != e; ++i)
  526. QueuePhiNode(PHIBlocks[i], AllocaNum, CurrentVersion);
  527. }
  528. if (Allocas.empty())
  529. return; // All of the allocas must have been trivial!
  530. LBI.clear();
  531. // Set the incoming values for the basic block to be null values for all of
  532. // the alloca's. We do this in case there is a load of a value that has not
  533. // been stored yet. In this case, it will get this null value.
  534. //
  535. RenamePassData::ValVector Values(Allocas.size());
  536. for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
  537. Values[i] = UndefValue::get(Allocas[i]->getAllocatedType());
  538. // Walks all basic blocks in the function performing the SSA rename algorithm
  539. // and inserting the phi nodes we marked as necessary
  540. //
  541. std::vector<RenamePassData> RenamePassWorkList;
  542. RenamePassWorkList.emplace_back(F.begin(), nullptr, std::move(Values));
  543. do {
  544. RenamePassData RPD;
  545. RPD.swap(RenamePassWorkList.back());
  546. RenamePassWorkList.pop_back();
  547. // RenamePass may add new worklist entries.
  548. RenamePass(RPD.BB, RPD.Pred, RPD.Values, RenamePassWorkList);
  549. } while (!RenamePassWorkList.empty());
  550. // The renamer uses the Visited set to avoid infinite loops. Clear it now.
  551. Visited.clear();
  552. // Remove the allocas themselves from the function.
  553. for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
  554. Instruction *A = Allocas[i];
  555. // If there are any uses of the alloca instructions left, they must be in
  556. // unreachable basic blocks that were not processed by walking the dominator
  557. // tree. Just delete the users now.
  558. if (!A->use_empty())
  559. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  560. if (AST)
  561. AST->deleteValue(A);
  562. A->eraseFromParent();
  563. }
  564. const DataLayout &DL = F.getParent()->getDataLayout();
  565. // Remove alloca's dbg.declare instrinsics from the function.
  566. for (unsigned i = 0, e = AllocaDbgDeclares.size(); i != e; ++i)
  567. if (DbgDeclareInst *DDI = AllocaDbgDeclares[i])
  568. DDI->eraseFromParent();
  569. // Loop over all of the PHI nodes and see if there are any that we can get
  570. // rid of because they merge all of the same incoming values. This can
  571. // happen due to undef values coming into the PHI nodes. This process is
  572. // iterative, because eliminating one PHI node can cause others to be removed.
  573. bool EliminatedAPHI = true;
  574. while (EliminatedAPHI) {
  575. EliminatedAPHI = false;
  576. // Iterating over NewPhiNodes is deterministic, so it is safe to try to
  577. // simplify and RAUW them as we go. If it was not, we could add uses to
  578. // the values we replace with in a non-deterministic order, thus creating
  579. // non-deterministic def->use chains.
  580. for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
  581. I = NewPhiNodes.begin(),
  582. E = NewPhiNodes.end();
  583. I != E;) {
  584. PHINode *PN = I->second;
  585. // If this PHI node merges one value and/or undefs, get the value.
  586. if (Value *V = SimplifyInstruction(PN, DL, nullptr, &DT, AC)) {
  587. if (AST && PN->getType()->isPointerTy())
  588. AST->deleteValue(PN);
  589. PN->replaceAllUsesWith(V);
  590. PN->eraseFromParent();
  591. NewPhiNodes.erase(I++);
  592. EliminatedAPHI = true;
  593. continue;
  594. }
  595. ++I;
  596. }
  597. }
  598. // At this point, the renamer has added entries to PHI nodes for all reachable
  599. // code. Unfortunately, there may be unreachable blocks which the renamer
  600. // hasn't traversed. If this is the case, the PHI nodes may not
  601. // have incoming values for all predecessors. Loop over all PHI nodes we have
  602. // created, inserting undef values if they are missing any incoming values.
  603. //
  604. for (DenseMap<std::pair<unsigned, unsigned>, PHINode *>::iterator
  605. I = NewPhiNodes.begin(),
  606. E = NewPhiNodes.end();
  607. I != E; ++I) {
  608. // We want to do this once per basic block. As such, only process a block
  609. // when we find the PHI that is the first entry in the block.
  610. PHINode *SomePHI = I->second;
  611. BasicBlock *BB = SomePHI->getParent();
  612. if (&BB->front() != SomePHI)
  613. continue;
  614. // Only do work here if there the PHI nodes are missing incoming values. We
  615. // know that all PHI nodes that were inserted in a block will have the same
  616. // number of incoming values, so we can just check any of them.
  617. if (SomePHI->getNumIncomingValues() == getNumPreds(BB))
  618. continue;
  619. // Get the preds for BB.
  620. SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
  621. // Ok, now we know that all of the PHI nodes are missing entries for some
  622. // basic blocks. Start by sorting the incoming predecessors for efficient
  623. // access.
  624. std::sort(Preds.begin(), Preds.end());
  625. // Now we loop through all BB's which have entries in SomePHI and remove
  626. // them from the Preds list.
  627. for (unsigned i = 0, e = SomePHI->getNumIncomingValues(); i != e; ++i) {
  628. // Do a log(n) search of the Preds list for the entry we want.
  629. SmallVectorImpl<BasicBlock *>::iterator EntIt = std::lower_bound(
  630. Preds.begin(), Preds.end(), SomePHI->getIncomingBlock(i));
  631. assert(EntIt != Preds.end() && *EntIt == SomePHI->getIncomingBlock(i) &&
  632. "PHI node has entry for a block which is not a predecessor!");
  633. // Remove the entry
  634. Preds.erase(EntIt);
  635. }
  636. // At this point, the blocks left in the preds list must have dummy
  637. // entries inserted into every PHI nodes for the block. Update all the phi
  638. // nodes in this block that we are inserting (there could be phis before
  639. // mem2reg runs).
  640. unsigned NumBadPreds = SomePHI->getNumIncomingValues();
  641. BasicBlock::iterator BBI = BB->begin();
  642. while ((SomePHI = dyn_cast<PHINode>(BBI++)) &&
  643. SomePHI->getNumIncomingValues() == NumBadPreds) {
  644. Value *UndefVal = UndefValue::get(SomePHI->getType());
  645. for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
  646. SomePHI->addIncoming(UndefVal, Preds[pred]);
  647. }
  648. }
  649. NewPhiNodes.clear();
  650. }
  651. /// \brief Determine which blocks the value is live in.
  652. ///
  653. /// These are blocks which lead to uses. Knowing this allows us to avoid
  654. /// inserting PHI nodes into blocks which don't lead to uses (thus, the
  655. /// inserted phi nodes would be dead).
  656. void PromoteMem2Reg::ComputeLiveInBlocks(
  657. AllocaInst *AI, AllocaInfo &Info,
  658. const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
  659. SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
  660. // To determine liveness, we must iterate through the predecessors of blocks
  661. // where the def is live. Blocks are added to the worklist if we need to
  662. // check their predecessors. Start with all the using blocks.
  663. SmallVector<BasicBlock *, 64> LiveInBlockWorklist(Info.UsingBlocks.begin(),
  664. Info.UsingBlocks.end());
  665. // If any of the using blocks is also a definition block, check to see if the
  666. // definition occurs before or after the use. If it happens before the use,
  667. // the value isn't really live-in.
  668. for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) {
  669. BasicBlock *BB = LiveInBlockWorklist[i];
  670. if (!DefBlocks.count(BB))
  671. continue;
  672. // Okay, this is a block that both uses and defines the value. If the first
  673. // reference to the alloca is a def (store), then we know it isn't live-in.
  674. for (BasicBlock::iterator I = BB->begin();; ++I) {
  675. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  676. if (SI->getOperand(1) != AI)
  677. continue;
  678. // We found a store to the alloca before a load. The alloca is not
  679. // actually live-in here.
  680. LiveInBlockWorklist[i] = LiveInBlockWorklist.back();
  681. LiveInBlockWorklist.pop_back();
  682. --i, --e;
  683. break;
  684. }
  685. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  686. if (LI->getOperand(0) != AI)
  687. continue;
  688. // Okay, we found a load before a store to the alloca. It is actually
  689. // live into this block.
  690. break;
  691. }
  692. }
  693. }
  694. // Now that we have a set of blocks where the phi is live-in, recursively add
  695. // their predecessors until we find the full region the value is live.
  696. while (!LiveInBlockWorklist.empty()) {
  697. BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
  698. // The block really is live in here, insert it into the set. If already in
  699. // the set, then it has already been processed.
  700. if (!LiveInBlocks.insert(BB).second)
  701. continue;
  702. // Since the value is live into BB, it is either defined in a predecessor or
  703. // live into it to. Add the preds to the worklist unless they are a
  704. // defining block.
  705. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  706. BasicBlock *P = *PI;
  707. // The value is not live into a predecessor if it defines the value.
  708. if (DefBlocks.count(P))
  709. continue;
  710. // Otherwise it is, add to the worklist.
  711. LiveInBlockWorklist.push_back(P);
  712. }
  713. }
  714. }
  715. /// \brief Queue a phi-node to be added to a basic-block for a specific Alloca.
  716. ///
  717. /// Returns true if there wasn't already a phi-node for that variable
  718. bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
  719. unsigned &Version) {
  720. // Look up the basic-block in question.
  721. PHINode *&PN = NewPhiNodes[std::make_pair(BBNumbers[BB], AllocaNo)];
  722. // If the BB already has a phi node added for the i'th alloca then we're done!
  723. if (PN)
  724. return false;
  725. // Create a PhiNode using the dereferenced type... and add the phi-node to the
  726. // BasicBlock.
  727. PN = PHINode::Create(Allocas[AllocaNo]->getAllocatedType(), getNumPreds(BB),
  728. Allocas[AllocaNo]->getName() + "." + Twine(Version++),
  729. BB->begin());
  730. ++NumPHIInsert;
  731. PhiToAllocaMap[PN] = AllocaNo;
  732. if (AST && PN->getType()->isPointerTy())
  733. AST->copyValue(PointerAllocaValues[AllocaNo], PN);
  734. return true;
  735. }
  736. /// \brief Recursively traverse the CFG of the function, renaming loads and
  737. /// stores to the allocas which we are promoting.
  738. ///
  739. /// IncomingVals indicates what value each Alloca contains on exit from the
  740. /// predecessor block Pred.
  741. void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
  742. RenamePassData::ValVector &IncomingVals,
  743. std::vector<RenamePassData> &Worklist) {
  744. NextIteration:
  745. // If we are inserting any phi nodes into this BB, they will already be in the
  746. // block.
  747. if (PHINode *APN = dyn_cast<PHINode>(BB->begin())) {
  748. // If we have PHI nodes to update, compute the number of edges from Pred to
  749. // BB.
  750. if (PhiToAllocaMap.count(APN)) {
  751. // We want to be able to distinguish between PHI nodes being inserted by
  752. // this invocation of mem2reg from those phi nodes that already existed in
  753. // the IR before mem2reg was run. We determine that APN is being inserted
  754. // because it is missing incoming edges. All other PHI nodes being
  755. // inserted by this pass of mem2reg will have the same number of incoming
  756. // operands so far. Remember this count.
  757. unsigned NewPHINumOperands = APN->getNumOperands();
  758. unsigned NumEdges = std::count(succ_begin(Pred), succ_end(Pred), BB);
  759. assert(NumEdges && "Must be at least one edge from Pred to BB!");
  760. // Add entries for all the phis.
  761. BasicBlock::iterator PNI = BB->begin();
  762. do {
  763. unsigned AllocaNo = PhiToAllocaMap[APN];
  764. // Add N incoming values to the PHI node.
  765. for (unsigned i = 0; i != NumEdges; ++i)
  766. APN->addIncoming(IncomingVals[AllocaNo], Pred);
  767. // The currently active variable for this block is now the PHI.
  768. IncomingVals[AllocaNo] = APN;
  769. // Get the next phi node.
  770. ++PNI;
  771. APN = dyn_cast<PHINode>(PNI);
  772. if (!APN)
  773. break;
  774. // Verify that it is missing entries. If not, it is not being inserted
  775. // by this mem2reg invocation so we want to ignore it.
  776. } while (APN->getNumOperands() == NewPHINumOperands);
  777. }
  778. }
  779. // Don't revisit blocks.
  780. if (!Visited.insert(BB).second)
  781. return;
  782. for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II);) {
  783. Instruction *I = II++; // get the instruction, increment iterator
  784. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  785. AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand());
  786. if (!Src)
  787. continue;
  788. DenseMap<AllocaInst *, unsigned>::iterator AI = AllocaLookup.find(Src);
  789. if (AI == AllocaLookup.end())
  790. continue;
  791. Value *V = IncomingVals[AI->second];
  792. // Anything using the load now uses the current value.
  793. LI->replaceAllUsesWith(V);
  794. if (AST && LI->getType()->isPointerTy())
  795. AST->deleteValue(LI);
  796. BB->getInstList().erase(LI);
  797. } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  798. // Delete this instruction and mark the name as the current holder of the
  799. // value
  800. AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand());
  801. if (!Dest)
  802. continue;
  803. DenseMap<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
  804. if (ai == AllocaLookup.end())
  805. continue;
  806. // what value were we writing?
  807. IncomingVals[ai->second] = SI->getOperand(0);
  808. // Record debuginfo for the store before removing it.
  809. if (DbgDeclareInst *DDI = AllocaDbgDeclares[ai->second])
  810. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  811. BB->getInstList().erase(SI);
  812. }
  813. }
  814. // 'Recurse' to our successors.
  815. succ_iterator I = succ_begin(BB), E = succ_end(BB);
  816. if (I == E)
  817. return;
  818. // Keep track of the successors so we don't visit the same successor twice
  819. SmallPtrSet<BasicBlock *, 8> VisitedSuccs;
  820. // Handle the first successor without using the worklist.
  821. VisitedSuccs.insert(*I);
  822. Pred = BB;
  823. BB = *I;
  824. ++I;
  825. for (; I != E; ++I)
  826. if (VisitedSuccs.insert(*I).second)
  827. Worklist.emplace_back(*I, Pred, IncomingVals);
  828. goto NextIteration;
  829. }
  830. void llvm::PromoteMemToReg(ArrayRef<AllocaInst *> Allocas, DominatorTree &DT,
  831. AliasSetTracker *AST, AssumptionCache *AC) {
  832. // If there is nothing to do, bail out...
  833. if (Allocas.empty())
  834. return;
  835. PromoteMem2Reg(Allocas, DT, AST, AC).run();
  836. }