SSAUpdaterImpl.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. /// Check all predecessors and if all of them have the same AvailableVal use
  282. /// it as value for block represented by Info. Return true if singluar value
  283. /// is found.
  284. bool FindSingularVal(BBInfo *Info) {
  285. if (!Info->NumPreds)
  286. return false;
  287. ValT Singular = Info->Preds[0]->DefBB->AvailableVal;
  288. if (!Singular)
  289. return false;
  290. for (unsigned Idx = 1; Idx < Info->NumPreds; ++Idx) {
  291. ValT PredVal = Info->Preds[Idx]->DefBB->AvailableVal;
  292. if (!PredVal || Singular != PredVal)
  293. return false;
  294. }
  295. // Record Singular value.
  296. (*AvailableVals)[Info->BB] = Singular;
  297. assert(BBMap[Info->BB] == Info && "Info missed in BBMap?");
  298. Info->AvailableVal = Singular;
  299. Info->DefBB = Info->Preds[0]->DefBB;
  300. return true;
  301. }
  302. /// FindAvailableVal - If this block requires a PHI, first check if an
  303. /// existing PHI matches the PHI placement and reaching definitions computed
  304. /// earlier, and if not, create a new PHI. Visit all the block's
  305. /// predecessors to calculate the available value for each one and fill in
  306. /// the incoming values for a new PHI.
  307. void FindAvailableVals(BlockListTy *BlockList) {
  308. // Go through the worklist in forward order (i.e., backward through the CFG)
  309. // and check if existing PHIs can be used. If not, create empty PHIs where
  310. // they are needed.
  311. for (typename BlockListTy::iterator I = BlockList->begin(),
  312. E = BlockList->end(); I != E; ++I) {
  313. BBInfo *Info = *I;
  314. // Check if there needs to be a PHI in BB.
  315. if (Info->DefBB != Info)
  316. continue;
  317. // Look for singular value.
  318. if (FindSingularVal(Info))
  319. continue;
  320. // Look for an existing PHI.
  321. FindExistingPHI(Info->BB, BlockList);
  322. if (Info->AvailableVal)
  323. continue;
  324. ValT PHI = Traits::CreateEmptyPHI(Info->BB, Info->NumPreds, Updater);
  325. Info->AvailableVal = PHI;
  326. (*AvailableVals)[Info->BB] = PHI;
  327. }
  328. // Now go back through the worklist in reverse order to fill in the
  329. // arguments for any new PHIs added in the forward traversal.
  330. for (typename BlockListTy::reverse_iterator I = BlockList->rbegin(),
  331. E = BlockList->rend(); I != E; ++I) {
  332. BBInfo *Info = *I;
  333. if (Info->DefBB != Info) {
  334. // Record the available value to speed up subsequent uses of this
  335. // SSAUpdater for the same value.
  336. (*AvailableVals)[Info->BB] = Info->DefBB->AvailableVal;
  337. continue;
  338. }
  339. // Check if this block contains a newly added PHI.
  340. PhiT *PHI = Traits::ValueIsNewPHI(Info->AvailableVal, Updater);
  341. if (!PHI)
  342. continue;
  343. // Iterate through the block's predecessors.
  344. for (unsigned p = 0; p != Info->NumPreds; ++p) {
  345. BBInfo *PredInfo = Info->Preds[p];
  346. BlkT *Pred = PredInfo->BB;
  347. // Skip to the nearest preceding definition.
  348. if (PredInfo->DefBB != PredInfo)
  349. PredInfo = PredInfo->DefBB;
  350. Traits::AddPHIOperand(PHI, PredInfo->AvailableVal, Pred);
  351. }
  352. LLVM_DEBUG(dbgs() << " Inserted PHI: " << *PHI << "\n");
  353. // If the client wants to know about all new instructions, tell it.
  354. if (InsertedPHIs) InsertedPHIs->push_back(PHI);
  355. }
  356. }
  357. /// FindExistingPHI - Look through the PHI nodes in a block to see if any of
  358. /// them match what is needed.
  359. void FindExistingPHI(BlkT *BB, BlockListTy *BlockList) {
  360. for (auto &SomePHI : BB->phis()) {
  361. if (CheckIfPHIMatches(&SomePHI)) {
  362. RecordMatchingPHIs(BlockList);
  363. break;
  364. }
  365. // Match failed: clear all the PHITag values.
  366. for (typename BlockListTy::iterator I = BlockList->begin(),
  367. E = BlockList->end(); I != E; ++I)
  368. (*I)->PHITag = nullptr;
  369. }
  370. }
  371. /// CheckIfPHIMatches - Check if a PHI node matches the placement and values
  372. /// in the BBMap.
  373. bool CheckIfPHIMatches(PhiT *PHI) {
  374. SmallVector<PhiT *, 20> WorkList;
  375. WorkList.push_back(PHI);
  376. // Mark that the block containing this PHI has been visited.
  377. BBMap[PHI->getParent()]->PHITag = PHI;
  378. while (!WorkList.empty()) {
  379. PHI = WorkList.pop_back_val();
  380. // Iterate through the PHI's incoming values.
  381. for (typename Traits::PHI_iterator I = Traits::PHI_begin(PHI),
  382. E = Traits::PHI_end(PHI); I != E; ++I) {
  383. ValT IncomingVal = I.getIncomingValue();
  384. BBInfo *PredInfo = BBMap[I.getIncomingBlock()];
  385. // Skip to the nearest preceding definition.
  386. if (PredInfo->DefBB != PredInfo)
  387. PredInfo = PredInfo->DefBB;
  388. // Check if it matches the expected value.
  389. if (PredInfo->AvailableVal) {
  390. if (IncomingVal == PredInfo->AvailableVal)
  391. continue;
  392. return false;
  393. }
  394. // Check if the value is a PHI in the correct block.
  395. PhiT *IncomingPHIVal = Traits::ValueIsPHI(IncomingVal, Updater);
  396. if (!IncomingPHIVal || IncomingPHIVal->getParent() != PredInfo->BB)
  397. return false;
  398. // If this block has already been visited, check if this PHI matches.
  399. if (PredInfo->PHITag) {
  400. if (IncomingPHIVal == PredInfo->PHITag)
  401. continue;
  402. return false;
  403. }
  404. PredInfo->PHITag = IncomingPHIVal;
  405. WorkList.push_back(IncomingPHIVal);
  406. }
  407. }
  408. return true;
  409. }
  410. /// RecordMatchingPHIs - For each PHI node that matches, record it in both
  411. /// the BBMap and the AvailableVals mapping.
  412. void RecordMatchingPHIs(BlockListTy *BlockList) {
  413. for (typename BlockListTy::iterator I = BlockList->begin(),
  414. E = BlockList->end(); I != E; ++I)
  415. if (PhiT *PHI = (*I)->PHITag) {
  416. BlkT *BB = PHI->getParent();
  417. ValT PHIVal = Traits::GetPHIValue(PHI);
  418. (*AvailableVals)[BB] = PHIVal;
  419. BBMap[BB]->AvailableVal = PHIVal;
  420. }
  421. }
  422. };
  423. } // end namespace llvm
  424. #undef DEBUG_TYPE // "ssaupdater"
  425. #endif // LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
  426. #ifdef __GNUC__
  427. #pragma GCC diagnostic pop
  428. #endif