SSAUpdaterBulk.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. //===- SSAUpdaterBulk.cpp - Unstructured SSA Update Tool ------------------===//
  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 implements the SSAUpdaterBulk class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/Utils/SSAUpdaterBulk.h"
  13. #include "llvm/Analysis/IteratedDominanceFrontier.h"
  14. #include "llvm/IR/BasicBlock.h"
  15. #include "llvm/IR/Dominators.h"
  16. #include "llvm/IR/IRBuilder.h"
  17. #include "llvm/IR/Instructions.h"
  18. #include "llvm/IR/Use.h"
  19. #include "llvm/IR/Value.h"
  20. using namespace llvm;
  21. #define DEBUG_TYPE "ssaupdaterbulk"
  22. /// Helper function for finding a block which should have a value for the given
  23. /// user. For PHI-nodes this block is the corresponding predecessor, for other
  24. /// instructions it's their parent block.
  25. static BasicBlock *getUserBB(Use *U) {
  26. auto *User = cast<Instruction>(U->getUser());
  27. if (auto *UserPN = dyn_cast<PHINode>(User))
  28. return UserPN->getIncomingBlock(*U);
  29. else
  30. return User->getParent();
  31. }
  32. /// Add a new variable to the SSA rewriter. This needs to be called before
  33. /// AddAvailableValue or AddUse calls.
  34. unsigned SSAUpdaterBulk::AddVariable(StringRef Name, Type *Ty) {
  35. unsigned Var = Rewrites.size();
  36. LLVM_DEBUG(dbgs() << "SSAUpdater: Var=" << Var << ": initialized with Ty = "
  37. << *Ty << ", Name = " << Name << "\n");
  38. RewriteInfo RI(Name, Ty);
  39. Rewrites.push_back(RI);
  40. return Var;
  41. }
  42. /// Indicate that a rewritten value is available in the specified block with the
  43. /// specified value.
  44. void SSAUpdaterBulk::AddAvailableValue(unsigned Var, BasicBlock *BB, Value *V) {
  45. assert(Var < Rewrites.size() && "Variable not found!");
  46. LLVM_DEBUG(dbgs() << "SSAUpdater: Var=" << Var
  47. << ": added new available value" << *V << " in "
  48. << BB->getName() << "\n");
  49. Rewrites[Var].Defines[BB] = V;
  50. }
  51. /// Record a use of the symbolic value. This use will be updated with a
  52. /// rewritten value when RewriteAllUses is called.
  53. void SSAUpdaterBulk::AddUse(unsigned Var, Use *U) {
  54. assert(Var < Rewrites.size() && "Variable not found!");
  55. LLVM_DEBUG(dbgs() << "SSAUpdater: Var=" << Var << ": added a use" << *U->get()
  56. << " in " << getUserBB(U)->getName() << "\n");
  57. Rewrites[Var].Uses.push_back(U);
  58. }
  59. /// Return true if the SSAUpdater already has a value for the specified variable
  60. /// in the specified block.
  61. bool SSAUpdaterBulk::HasValueForBlock(unsigned Var, BasicBlock *BB) {
  62. return (Var < Rewrites.size()) ? Rewrites[Var].Defines.count(BB) : false;
  63. }
  64. // Compute value at the given block BB. We either should already know it, or we
  65. // should be able to recursively reach it going up dominator tree.
  66. Value *SSAUpdaterBulk::computeValueAt(BasicBlock *BB, RewriteInfo &R,
  67. DominatorTree *DT) {
  68. if (!R.Defines.count(BB)) {
  69. if (DT->isReachableFromEntry(BB) && PredCache.get(BB).size()) {
  70. BasicBlock *IDom = DT->getNode(BB)->getIDom()->getBlock();
  71. Value *V = computeValueAt(IDom, R, DT);
  72. R.Defines[BB] = V;
  73. } else
  74. R.Defines[BB] = UndefValue::get(R.Ty);
  75. }
  76. return R.Defines[BB];
  77. }
  78. /// Given sets of UsingBlocks and DefBlocks, compute the set of LiveInBlocks.
  79. /// This is basically a subgraph limited by DefBlocks and UsingBlocks.
  80. static void
  81. ComputeLiveInBlocks(const SmallPtrSetImpl<BasicBlock *> &UsingBlocks,
  82. const SmallPtrSetImpl<BasicBlock *> &DefBlocks,
  83. SmallPtrSetImpl<BasicBlock *> &LiveInBlocks,
  84. PredIteratorCache &PredCache) {
  85. // To determine liveness, we must iterate through the predecessors of blocks
  86. // where the def is live. Blocks are added to the worklist if we need to
  87. // check their predecessors. Start with all the using blocks.
  88. SmallVector<BasicBlock *, 64> LiveInBlockWorklist(UsingBlocks.begin(),
  89. UsingBlocks.end());
  90. // Now that we have a set of blocks where the phi is live-in, recursively add
  91. // their predecessors until we find the full region the value is live.
  92. while (!LiveInBlockWorklist.empty()) {
  93. BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
  94. // The block really is live in here, insert it into the set. If already in
  95. // the set, then it has already been processed.
  96. if (!LiveInBlocks.insert(BB).second)
  97. continue;
  98. // Since the value is live into BB, it is either defined in a predecessor or
  99. // live into it to. Add the preds to the worklist unless they are a
  100. // defining block.
  101. for (BasicBlock *P : PredCache.get(BB)) {
  102. // The value is not live into a predecessor if it defines the value.
  103. if (DefBlocks.count(P))
  104. continue;
  105. // Otherwise it is, add to the worklist.
  106. LiveInBlockWorklist.push_back(P);
  107. }
  108. }
  109. }
  110. /// Perform all the necessary updates, including new PHI-nodes insertion and the
  111. /// requested uses update.
  112. void SSAUpdaterBulk::RewriteAllUses(DominatorTree *DT,
  113. SmallVectorImpl<PHINode *> *InsertedPHIs) {
  114. for (auto &R : Rewrites) {
  115. // Compute locations for new phi-nodes.
  116. // For that we need to initialize DefBlocks from definitions in R.Defines,
  117. // UsingBlocks from uses in R.Uses, then compute LiveInBlocks, and then use
  118. // this set for computing iterated dominance frontier (IDF).
  119. // The IDF blocks are the blocks where we need to insert new phi-nodes.
  120. ForwardIDFCalculator IDF(*DT);
  121. LLVM_DEBUG(dbgs() << "SSAUpdater: rewriting " << R.Uses.size()
  122. << " use(s)\n");
  123. SmallPtrSet<BasicBlock *, 2> DefBlocks;
  124. for (auto &Def : R.Defines)
  125. DefBlocks.insert(Def.first);
  126. IDF.setDefiningBlocks(DefBlocks);
  127. SmallPtrSet<BasicBlock *, 2> UsingBlocks;
  128. for (Use *U : R.Uses)
  129. UsingBlocks.insert(getUserBB(U));
  130. SmallVector<BasicBlock *, 32> IDFBlocks;
  131. SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
  132. ComputeLiveInBlocks(UsingBlocks, DefBlocks, LiveInBlocks, PredCache);
  133. IDF.resetLiveInBlocks();
  134. IDF.setLiveInBlocks(LiveInBlocks);
  135. IDF.calculate(IDFBlocks);
  136. // We've computed IDF, now insert new phi-nodes there.
  137. SmallVector<PHINode *, 4> InsertedPHIsForVar;
  138. for (auto *FrontierBB : IDFBlocks) {
  139. IRBuilder<> B(FrontierBB, FrontierBB->begin());
  140. PHINode *PN = B.CreatePHI(R.Ty, 0, R.Name);
  141. R.Defines[FrontierBB] = PN;
  142. InsertedPHIsForVar.push_back(PN);
  143. if (InsertedPHIs)
  144. InsertedPHIs->push_back(PN);
  145. }
  146. // Fill in arguments of the inserted PHIs.
  147. for (auto *PN : InsertedPHIsForVar) {
  148. BasicBlock *PBB = PN->getParent();
  149. for (BasicBlock *Pred : PredCache.get(PBB))
  150. PN->addIncoming(computeValueAt(Pred, R, DT), Pred);
  151. }
  152. // Rewrite actual uses with the inserted definitions.
  153. SmallPtrSet<Use *, 4> ProcessedUses;
  154. for (Use *U : R.Uses) {
  155. if (!ProcessedUses.insert(U).second)
  156. continue;
  157. Value *V = computeValueAt(getUserBB(U), R, DT);
  158. Value *OldVal = U->get();
  159. assert(OldVal && "Invalid use!");
  160. // Notify that users of the existing value that it is being replaced.
  161. if (OldVal != V && OldVal->hasValueHandle())
  162. ValueHandleBase::ValueIsRAUWd(OldVal, V);
  163. LLVM_DEBUG(dbgs() << "SSAUpdater: replacing " << *OldVal << " with " << *V
  164. << "\n");
  165. U->set(V);
  166. }
  167. }
  168. }