PromoteMemoryToRegister.cpp 41 KB

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