PromoteMemoryToRegister.cpp 38 KB

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