PromoteMemoryToRegister.cpp 38 KB

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