SSAUpdaterImpl.h 16 KB

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