SSAUpdaterImpl.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. //===-- SSAUpdaterImpl.h - SSA Updater Implementation -----------*- C++ -*-===//
  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 provides a template that implements the core algorithm for the
  11. // SSAUpdater and MachineSSAUpdater.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
  15. #define LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/IR/ValueHandle.h"
  19. #include "llvm/Support/Allocator.h"
  20. #include "llvm/Support/Debug.h"
  21. namespace llvm {
  22. #define DEBUG_TYPE "ssaupdater"
  23. class CastInst;
  24. class PHINode;
  25. template<typename T> class SSAUpdaterTraits;
  26. template<typename UpdaterT>
  27. class SSAUpdaterImpl {
  28. private:
  29. UpdaterT *Updater;
  30. typedef SSAUpdaterTraits<UpdaterT> Traits;
  31. typedef typename Traits::BlkT BlkT;
  32. typedef typename Traits::ValT ValT;
  33. typedef typename Traits::PhiT PhiT;
  34. /// BBInfo - Per-basic block information used internally by SSAUpdaterImpl.
  35. /// The predecessors of each block are cached here since pred_iterator is
  36. /// slow and we need to iterate over the blocks at least a few times.
  37. class BBInfo {
  38. public:
  39. BlkT *BB; // Back-pointer to the corresponding block.
  40. ValT AvailableVal; // Value to use in this block.
  41. BBInfo *DefBB; // Block that defines the available value.
  42. int BlkNum; // Postorder number.
  43. BBInfo *IDom; // Immediate dominator.
  44. unsigned NumPreds; // Number of predecessor blocks.
  45. BBInfo **Preds; // Array[NumPreds] of predecessor blocks.
  46. PhiT *PHITag; // Marker for existing PHIs that match.
  47. BBInfo(BlkT *ThisBB, ValT V)
  48. : BB(ThisBB), AvailableVal(V), DefBB(V ? this : nullptr), BlkNum(0),
  49. IDom(nullptr), NumPreds(0), Preds(nullptr), PHITag(nullptr) {}
  50. };
  51. typedef DenseMap<BlkT*, ValT> AvailableValsTy;
  52. AvailableValsTy *AvailableVals;
  53. SmallVectorImpl<PhiT*> *InsertedPHIs;
  54. typedef SmallVectorImpl<BBInfo*> BlockListTy;
  55. typedef DenseMap<BlkT*, BBInfo*> BBMapTy;
  56. BBMapTy BBMap;
  57. BumpPtrAllocator Allocator;
  58. public:
  59. explicit SSAUpdaterImpl(UpdaterT *U, AvailableValsTy *A,
  60. SmallVectorImpl<PhiT*> *Ins) :
  61. Updater(U), AvailableVals(A), InsertedPHIs(Ins) { }
  62. /// GetValue - Check to see if AvailableVals has an entry for the specified
  63. /// BB and if so, return it. If not, construct SSA form by first
  64. /// calculating the required placement of PHIs and then inserting new PHIs
  65. /// where needed.
  66. ValT GetValue(BlkT *BB) {
  67. SmallVector<BBInfo*, 100> BlockList;
  68. BBInfo *PseudoEntry = BuildBlockList(BB, &BlockList);
  69. // Special case: bail out if BB is unreachable.
  70. if (BlockList.size() == 0) {
  71. ValT V = Traits::GetUndefVal(BB, Updater);
  72. (*AvailableVals)[BB] = V;
  73. return V;
  74. }
  75. FindDominators(&BlockList, PseudoEntry);
  76. FindPHIPlacement(&BlockList);
  77. FindAvailableVals(&BlockList);
  78. return BBMap[BB]->DefBB->AvailableVal;
  79. }
  80. /// BuildBlockList - Starting from the specified basic block, traverse back
  81. /// through its predecessors until reaching blocks with known values.
  82. /// Create BBInfo structures for the blocks and append them to the block
  83. /// list.
  84. BBInfo *BuildBlockList(BlkT *BB, BlockListTy *BlockList) {
  85. SmallVector<BBInfo*, 10> RootList;
  86. SmallVector<BBInfo*, 64> WorkList;
  87. BBInfo *Info = new (Allocator) BBInfo(BB, 0);
  88. BBMap[BB] = Info;
  89. WorkList.push_back(Info);
  90. // Search backward from BB, creating BBInfos along the way and stopping
  91. // when reaching blocks that define the value. Record those defining
  92. // blocks on the RootList.
  93. SmallVector<BlkT*, 10> Preds;
  94. while (!WorkList.empty()) {
  95. Info = WorkList.pop_back_val();
  96. Preds.clear();
  97. Traits::FindPredecessorBlocks(Info->BB, &Preds);
  98. Info->NumPreds = Preds.size();
  99. if (Info->NumPreds == 0)
  100. Info->Preds = nullptr;
  101. else
  102. Info->Preds = static_cast<BBInfo**>
  103. (Allocator.Allocate(Info->NumPreds * sizeof(BBInfo*),
  104. AlignOf<BBInfo*>::Alignment));
  105. for (unsigned p = 0; p != Info->NumPreds; ++p) {
  106. BlkT *Pred = Preds[p];
  107. // Check if BBMap already has a BBInfo for the predecessor block.
  108. typename BBMapTy::value_type &BBMapBucket =
  109. BBMap.FindAndConstruct(Pred);
  110. if (BBMapBucket.second) {
  111. Info->Preds[p] = BBMapBucket.second;
  112. continue;
  113. }
  114. // Create a new BBInfo for the predecessor.
  115. ValT PredVal = AvailableVals->lookup(Pred);
  116. BBInfo *PredInfo = new (Allocator) BBInfo(Pred, PredVal);
  117. BBMapBucket.second = PredInfo;
  118. Info->Preds[p] = PredInfo;
  119. if (PredInfo->AvailableVal) {
  120. RootList.push_back(PredInfo);
  121. continue;
  122. }
  123. WorkList.push_back(PredInfo);
  124. }
  125. }
  126. // Now that we know what blocks are backwards-reachable from the starting
  127. // block, do a forward depth-first traversal to assign postorder numbers
  128. // to those blocks.
  129. BBInfo *PseudoEntry = new (Allocator) BBInfo(nullptr, 0);
  130. unsigned BlkNum = 1;
  131. // Initialize the worklist with the roots from the backward traversal.
  132. while (!RootList.empty()) {
  133. Info = RootList.pop_back_val();
  134. Info->IDom = PseudoEntry;
  135. Info->BlkNum = -1;
  136. WorkList.push_back(Info);
  137. }
  138. while (!WorkList.empty()) {
  139. Info = WorkList.back();
  140. if (Info->BlkNum == -2) {
  141. // All the successors have been handled; assign the postorder number.
  142. Info->BlkNum = BlkNum++;
  143. // If not a root, put it on the BlockList.
  144. if (!Info->AvailableVal)
  145. BlockList->push_back(Info);
  146. WorkList.pop_back();
  147. continue;
  148. }
  149. // Leave this entry on the worklist, but set its BlkNum to mark that its
  150. // successors have been put on the worklist. When it returns to the top
  151. // the list, after handling its successors, it will be assigned a
  152. // number.
  153. Info->BlkNum = -2;
  154. // Add unvisited successors to the work list.
  155. for (typename Traits::BlkSucc_iterator SI =
  156. Traits::BlkSucc_begin(Info->BB),
  157. E = Traits::BlkSucc_end(Info->BB); SI != E; ++SI) {
  158. BBInfo *SuccInfo = BBMap[*SI];
  159. if (!SuccInfo || SuccInfo->BlkNum)
  160. continue;
  161. SuccInfo->BlkNum = -1;
  162. WorkList.push_back(SuccInfo);
  163. }
  164. }
  165. PseudoEntry->BlkNum = BlkNum;
  166. return PseudoEntry;
  167. }
  168. /// IntersectDominators - This is the dataflow lattice "meet" operation for
  169. /// finding dominators. Given two basic blocks, it walks up the dominator
  170. /// tree until it finds a common dominator of both. It uses the postorder
  171. /// number of the blocks to determine how to do that.
  172. BBInfo *IntersectDominators(BBInfo *Blk1, BBInfo *Blk2) {
  173. while (Blk1 != Blk2) {
  174. while (Blk1->BlkNum < Blk2->BlkNum) {
  175. Blk1 = Blk1->IDom;
  176. if (!Blk1)
  177. return Blk2;
  178. }
  179. while (Blk2->BlkNum < Blk1->BlkNum) {
  180. Blk2 = Blk2->IDom;
  181. if (!Blk2)
  182. return Blk1;
  183. }
  184. }
  185. return Blk1;
  186. }
  187. /// FindDominators - Calculate the dominator tree for the subset of the CFG
  188. /// corresponding to the basic blocks on the BlockList. This uses the
  189. /// algorithm from: "A Simple, Fast Dominance Algorithm" by Cooper, Harvey
  190. /// and Kennedy, published in Software--Practice and Experience, 2001,
  191. /// 4:1-10. Because the CFG subset does not include any edges leading into
  192. /// blocks that define the value, the results are not the usual dominator
  193. /// tree. The CFG subset has a single pseudo-entry node with edges to a set
  194. /// of root nodes for blocks that define the value. The dominators for this
  195. /// subset CFG are not the standard dominators but they are adequate for
  196. /// placing PHIs within the subset CFG.
  197. void FindDominators(BlockListTy *BlockList, BBInfo *PseudoEntry) {
  198. bool Changed;
  199. do {
  200. Changed = false;
  201. // Iterate over the list in reverse order, i.e., forward on CFG edges.
  202. for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
  203. E = BlockList->rend(); I != E; ++I) {
  204. BBInfo *Info = *I;
  205. BBInfo *NewIDom = nullptr;
  206. // Iterate through the block's predecessors.
  207. for (unsigned p = 0; p != Info->NumPreds; ++p) {
  208. BBInfo *Pred = Info->Preds[p];
  209. // Treat an unreachable predecessor as a definition with 'undef'.
  210. if (Pred->BlkNum == 0) {
  211. Pred->AvailableVal = Traits::GetUndefVal(Pred->BB, Updater);
  212. (*AvailableVals)[Pred->BB] = Pred->AvailableVal;
  213. Pred->DefBB = Pred;
  214. Pred->BlkNum = PseudoEntry->BlkNum;
  215. PseudoEntry->BlkNum++;
  216. }
  217. if (!NewIDom)
  218. NewIDom = Pred;
  219. else
  220. NewIDom = IntersectDominators(NewIDom, Pred);
  221. }
  222. // Check if the IDom value has changed.
  223. if (NewIDom && NewIDom != Info->IDom) {
  224. Info->IDom = NewIDom;
  225. Changed = true;
  226. }
  227. }
  228. } while (Changed);
  229. }
  230. /// IsDefInDomFrontier - Search up the dominator tree from Pred to IDom for
  231. /// any blocks containing definitions of the value. If one is found, then
  232. /// the successor of Pred is in the dominance frontier for the definition,
  233. /// and this function returns true.
  234. bool IsDefInDomFrontier(const BBInfo *Pred, const BBInfo *IDom) {
  235. for (; Pred != IDom; Pred = Pred->IDom) {
  236. if (Pred->DefBB == Pred)
  237. return true;
  238. }
  239. return false;
  240. }
  241. /// FindPHIPlacement - PHIs are needed in the iterated dominance frontiers
  242. /// of the known definitions. Iteratively add PHIs in the dom frontiers
  243. /// until nothing changes. Along the way, keep track of the nearest
  244. /// dominating definitions for non-PHI blocks.
  245. void FindPHIPlacement(BlockListTy *BlockList) {
  246. bool Changed;
  247. do {
  248. Changed = false;
  249. // Iterate over the list in reverse order, i.e., forward on CFG edges.
  250. for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
  251. E = BlockList->rend(); I != E; ++I) {
  252. BBInfo *Info = *I;
  253. // If this block already needs a PHI, there is nothing to do here.
  254. if (Info->DefBB == Info)
  255. continue;
  256. // Default to use the same def as the immediate dominator.
  257. BBInfo *NewDefBB = Info->IDom->DefBB;
  258. for (unsigned p = 0; p != Info->NumPreds; ++p) {
  259. if (IsDefInDomFrontier(Info->Preds[p], Info->IDom)) {
  260. // Need a PHI here.
  261. NewDefBB = Info;
  262. break;
  263. }
  264. }
  265. // Check if anything changed.
  266. if (NewDefBB != Info->DefBB) {
  267. Info->DefBB = NewDefBB;
  268. Changed = true;
  269. }
  270. }
  271. } while (Changed);
  272. }
  273. /// FindAvailableVal - If this block requires a PHI, first check if an
  274. /// existing PHI matches the PHI placement and reaching definitions computed
  275. /// earlier, and if not, create a new PHI. Visit all the block's
  276. /// predecessors to calculate the available value for each one and fill in
  277. /// the incoming values for a new PHI.
  278. void FindAvailableVals(BlockListTy *BlockList) {
  279. // Go through the worklist in forward order (i.e., backward through the CFG)
  280. // and check if existing PHIs can be used. If not, create empty PHIs where
  281. // they are needed.
  282. for (typename BlockListTy::iterator I = BlockList->begin(),
  283. E = BlockList->end(); I != E; ++I) {
  284. BBInfo *Info = *I;
  285. // Check if there needs to be a PHI in BB.
  286. if (Info->DefBB != Info)
  287. continue;
  288. // Look for an existing PHI.
  289. FindExistingPHI(Info->BB, BlockList);
  290. if (Info->AvailableVal)
  291. continue;
  292. ValT PHI = Traits::CreateEmptyPHI(Info->BB, Info->NumPreds, Updater);
  293. Info->AvailableVal = PHI;
  294. (*AvailableVals)[Info->BB] = PHI;
  295. }
  296. // Now go back through the worklist in reverse order to fill in the
  297. // arguments for any new PHIs added in the forward traversal.
  298. for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
  299. E = BlockList->rend(); I != E; ++I) {
  300. BBInfo *Info = *I;
  301. if (Info->DefBB != Info) {
  302. // Record the available value at join nodes to speed up subsequent
  303. // uses of this SSAUpdater for the same value.
  304. if (Info->NumPreds > 1)
  305. (*AvailableVals)[Info->BB] = Info->DefBB->AvailableVal;
  306. continue;
  307. }
  308. // Check if this block contains a newly added PHI.
  309. PhiT *PHI = Traits::ValueIsNewPHI(Info->AvailableVal, Updater);
  310. if (!PHI)
  311. continue;
  312. // Iterate through the block's predecessors.
  313. for (unsigned p = 0; p != Info->NumPreds; ++p) {
  314. BBInfo *PredInfo = Info->Preds[p];
  315. BlkT *Pred = PredInfo->BB;
  316. // Skip to the nearest preceding definition.
  317. if (PredInfo->DefBB != PredInfo)
  318. PredInfo = PredInfo->DefBB;
  319. Traits::AddPHIOperand(PHI, PredInfo->AvailableVal, Pred);
  320. }
  321. DEBUG(dbgs() << " Inserted PHI: " << *PHI << "\n");
  322. // If the client wants to know about all new instructions, tell it.
  323. if (InsertedPHIs) InsertedPHIs->push_back(PHI);
  324. }
  325. }
  326. /// FindExistingPHI - Look through the PHI nodes in a block to see if any of
  327. /// them match what is needed.
  328. void FindExistingPHI(BlkT *BB, BlockListTy *BlockList) {
  329. for (typename BlkT::iterator BBI = BB->begin(), BBE = BB->end();
  330. BBI != BBE; ++BBI) {
  331. PhiT *SomePHI = Traits::InstrIsPHI(BBI);
  332. if (!SomePHI)
  333. break;
  334. if (CheckIfPHIMatches(SomePHI)) {
  335. RecordMatchingPHIs(BlockList);
  336. break;
  337. }
  338. // Match failed: clear all the PHITag values.
  339. for (typename BlockListTy::iterator I = BlockList->begin(),
  340. E = BlockList->end(); I != E; ++I)
  341. (*I)->PHITag = nullptr;
  342. }
  343. }
  344. /// CheckIfPHIMatches - Check if a PHI node matches the placement and values
  345. /// in the BBMap.
  346. bool CheckIfPHIMatches(PhiT *PHI) {
  347. SmallVector<PhiT*, 20> WorkList;
  348. WorkList.push_back(PHI);
  349. // Mark that the block containing this PHI has been visited.
  350. BBMap[PHI->getParent()]->PHITag = PHI;
  351. while (!WorkList.empty()) {
  352. PHI = WorkList.pop_back_val();
  353. // Iterate through the PHI's incoming values.
  354. for (typename Traits::PHI_iterator I = Traits::PHI_begin(PHI),
  355. E = Traits::PHI_end(PHI); I != E; ++I) {
  356. ValT IncomingVal = I.getIncomingValue();
  357. BBInfo *PredInfo = BBMap[I.getIncomingBlock()];
  358. // Skip to the nearest preceding definition.
  359. if (PredInfo->DefBB != PredInfo)
  360. PredInfo = PredInfo->DefBB;
  361. // Check if it matches the expected value.
  362. if (PredInfo->AvailableVal) {
  363. if (IncomingVal == PredInfo->AvailableVal)
  364. continue;
  365. return false;
  366. }
  367. // Check if the value is a PHI in the correct block.
  368. PhiT *IncomingPHIVal = Traits::ValueIsPHI(IncomingVal, Updater);
  369. if (!IncomingPHIVal || IncomingPHIVal->getParent() != PredInfo->BB)
  370. return false;
  371. // If this block has already been visited, check if this PHI matches.
  372. if (PredInfo->PHITag) {
  373. if (IncomingPHIVal == PredInfo->PHITag)
  374. continue;
  375. return false;
  376. }
  377. PredInfo->PHITag = IncomingPHIVal;
  378. WorkList.push_back(IncomingPHIVal);
  379. }
  380. }
  381. return true;
  382. }
  383. /// RecordMatchingPHIs - For each PHI node that matches, record it in both
  384. /// the BBMap and the AvailableVals mapping.
  385. void RecordMatchingPHIs(BlockListTy *BlockList) {
  386. for (typename BlockListTy::iterator I = BlockList->begin(),
  387. E = BlockList->end(); I != E; ++I)
  388. if (PhiT *PHI = (*I)->PHITag) {
  389. BlkT *BB = PHI->getParent();
  390. ValT PHIVal = Traits::GetPHIValue(PHI);
  391. (*AvailableVals)[BB] = PHIVal;
  392. BBMap[BB]->AvailableVal = PHIVal;
  393. }
  394. }
  395. };
  396. #undef DEBUG_TYPE // "ssaupdater"
  397. } // End llvm namespace
  398. #endif