DomTreeUpdater.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. //===- DomTreeUpdater.h - DomTree/Post DomTree Updater ----------*- C++ -*-===//
  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 defines the DomTreeUpdater class, which provides a uniform way to
  10. // update dominator tree related data structures.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_ANALYSIS_DOMTREEUPDATER_H
  14. #define LLVM_ANALYSIS_DOMTREEUPDATER_H
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/IR/Dominators.h"
  17. #include "llvm/IR/ValueHandle.h"
  18. #include "llvm/Support/Compiler.h"
  19. #include <cstddef>
  20. #include <functional>
  21. #include <vector>
  22. namespace llvm {
  23. class PostDominatorTree;
  24. class DomTreeUpdater {
  25. public:
  26. enum class UpdateStrategy : unsigned char { Eager = 0, Lazy = 1 };
  27. explicit DomTreeUpdater(UpdateStrategy Strategy_) : Strategy(Strategy_) {}
  28. DomTreeUpdater(DominatorTree &DT_, UpdateStrategy Strategy_)
  29. : DT(&DT_), Strategy(Strategy_) {}
  30. DomTreeUpdater(DominatorTree *DT_, UpdateStrategy Strategy_)
  31. : DT(DT_), Strategy(Strategy_) {}
  32. DomTreeUpdater(PostDominatorTree &PDT_, UpdateStrategy Strategy_)
  33. : PDT(&PDT_), Strategy(Strategy_) {}
  34. DomTreeUpdater(PostDominatorTree *PDT_, UpdateStrategy Strategy_)
  35. : PDT(PDT_), Strategy(Strategy_) {}
  36. DomTreeUpdater(DominatorTree &DT_, PostDominatorTree &PDT_,
  37. UpdateStrategy Strategy_)
  38. : DT(&DT_), PDT(&PDT_), Strategy(Strategy_) {}
  39. DomTreeUpdater(DominatorTree *DT_, PostDominatorTree *PDT_,
  40. UpdateStrategy Strategy_)
  41. : DT(DT_), PDT(PDT_), Strategy(Strategy_) {}
  42. ~DomTreeUpdater() { flush(); }
  43. /// Returns true if the current strategy is Lazy.
  44. bool isLazy() const { return Strategy == UpdateStrategy::Lazy; };
  45. /// Returns true if the current strategy is Eager.
  46. bool isEager() const { return Strategy == UpdateStrategy::Eager; };
  47. /// Returns true if it holds a DominatorTree.
  48. bool hasDomTree() const { return DT != nullptr; }
  49. /// Returns true if it holds a PostDominatorTree.
  50. bool hasPostDomTree() const { return PDT != nullptr; }
  51. /// Returns true if there is BasicBlock awaiting deletion.
  52. /// The deletion will only happen until a flush event and
  53. /// all available trees are up-to-date.
  54. /// Returns false under Eager UpdateStrategy.
  55. bool hasPendingDeletedBB() const { return !DeletedBBs.empty(); }
  56. /// Returns true if DelBB is awaiting deletion.
  57. /// Returns false under Eager UpdateStrategy.
  58. bool isBBPendingDeletion(BasicBlock *DelBB) const;
  59. /// Returns true if either of DT or PDT is valid and the tree has at
  60. /// least one update pending. If DT or PDT is nullptr it is treated
  61. /// as having no pending updates. This function does not check
  62. /// whether there is BasicBlock awaiting deletion.
  63. /// Returns false under Eager UpdateStrategy.
  64. bool hasPendingUpdates() const;
  65. /// Returns true if there are DominatorTree updates queued.
  66. /// Returns false under Eager UpdateStrategy or DT is nullptr.
  67. bool hasPendingDomTreeUpdates() const;
  68. /// Returns true if there are PostDominatorTree updates queued.
  69. /// Returns false under Eager UpdateStrategy or PDT is nullptr.
  70. bool hasPendingPostDomTreeUpdates() const;
  71. ///@{
  72. /// \name Mutation APIs
  73. ///
  74. /// These methods provide APIs for submitting updates to the DominatorTree and
  75. /// the PostDominatorTree.
  76. ///
  77. /// Note: There are two strategies to update the DominatorTree and the
  78. /// PostDominatorTree:
  79. /// 1. Eager UpdateStrategy: Updates are submitted and then flushed
  80. /// immediately.
  81. /// 2. Lazy UpdateStrategy: Updates are submitted but only flushed when you
  82. /// explicitly call Flush APIs. It is recommended to use this update strategy
  83. /// when you submit a bunch of updates multiple times which can then
  84. /// add up to a large number of updates between two queries on the
  85. /// DominatorTree. The incremental updater can reschedule the updates or
  86. /// decide to recalculate the dominator tree in order to speedup the updating
  87. /// process depending on the number of updates.
  88. ///
  89. /// Although GenericDomTree provides several update primitives,
  90. /// it is not encouraged to use these APIs directly.
  91. /// Submit updates to all available trees.
  92. /// The Eager Strategy flushes updates immediately while the Lazy Strategy
  93. /// queues the updates.
  94. ///
  95. /// Note: The "existence" of an edge in a CFG refers to the CFG which DTU is
  96. /// in sync with + all updates before that single update.
  97. ///
  98. /// CAUTION!
  99. /// 1. It is required for the state of the LLVM IR to be updated
  100. /// *before* submitting the updates because the internal update routine will
  101. /// analyze the current state of the CFG to determine whether an update
  102. /// is valid.
  103. /// 2. It is illegal to submit any update that has already been submitted,
  104. /// i.e., you are supposed not to insert an existent edge or delete a
  105. /// nonexistent edge.
  106. void applyUpdates(ArrayRef<DominatorTree::UpdateType> Updates);
  107. /// Submit updates to all available trees. It will also
  108. /// 1. discard duplicated updates,
  109. /// 2. remove invalid updates. (Invalid updates means deletion of an edge that
  110. /// still exists or insertion of an edge that does not exist.)
  111. /// The Eager Strategy flushes updates immediately while the Lazy Strategy
  112. /// queues the updates.
  113. ///
  114. /// Note: The "existence" of an edge in a CFG refers to the CFG which DTU is
  115. /// in sync with + all updates before that single update.
  116. ///
  117. /// CAUTION!
  118. /// 1. It is required for the state of the LLVM IR to be updated
  119. /// *before* submitting the updates because the internal update routine will
  120. /// analyze the current state of the CFG to determine whether an update
  121. /// is valid.
  122. /// 2. It is illegal to submit any update that has already been submitted,
  123. /// i.e., you are supposed not to insert an existent edge or delete a
  124. /// nonexistent edge.
  125. /// 3. It is only legal to submit updates to an edge in the order CFG changes
  126. /// are made. The order you submit updates on different edges is not
  127. /// restricted.
  128. void applyUpdatesPermissive(ArrayRef<DominatorTree::UpdateType> Updates);
  129. /// Notify DTU that the entry block was replaced.
  130. /// Recalculate all available trees and flush all BasicBlocks
  131. /// awaiting deletion immediately.
  132. void recalculate(Function &F);
  133. /// \deprecated { Submit an edge insertion to all available trees. The Eager
  134. /// Strategy flushes this update immediately while the Lazy Strategy queues
  135. /// the update. An internal function checks if the edge exists in the CFG in
  136. /// DEBUG mode. CAUTION! This function has to be called *after* making the
  137. /// update on the actual CFG. It is illegal to submit any update that has
  138. /// already been applied. }
  139. LLVM_ATTRIBUTE_DEPRECATED(void insertEdge(BasicBlock *From, BasicBlock *To),
  140. "Use applyUpdates() instead.");
  141. /// \deprecated {Submit an edge insertion to all available trees.
  142. /// Under either Strategy, an invalid update will be discard silently.
  143. /// Invalid update means inserting an edge that does not exist in the CFG.
  144. /// The Eager Strategy flushes this update immediately while the Lazy Strategy
  145. /// queues the update. It is only recommended to use this method when you
  146. /// want to discard an invalid update.
  147. /// CAUTION! It is illegal to submit any update that has already been
  148. /// submitted. }
  149. LLVM_ATTRIBUTE_DEPRECATED(void insertEdgeRelaxed(BasicBlock *From,
  150. BasicBlock *To),
  151. "Use applyUpdatesPermissive() instead.");
  152. /// \deprecated { Submit an edge deletion to all available trees. The Eager
  153. /// Strategy flushes this update immediately while the Lazy Strategy queues
  154. /// the update. An internal function checks if the edge doesn't exist in the
  155. /// CFG in DEBUG mode.
  156. /// CAUTION! This function has to be called *after* making the update on the
  157. /// actual CFG. It is illegal to submit any update that has already been
  158. /// submitted. }
  159. LLVM_ATTRIBUTE_DEPRECATED(void deleteEdge(BasicBlock *From, BasicBlock *To),
  160. "Use applyUpdates() instead.");
  161. /// \deprecated { Submit an edge deletion to all available trees.
  162. /// Under either Strategy, an invalid update will be discard silently.
  163. /// Invalid update means deleting an edge that exists in the CFG.
  164. /// The Eager Strategy flushes this update immediately while the Lazy Strategy
  165. /// queues the update. It is only recommended to use this method when you
  166. /// want to discard an invalid update.
  167. /// CAUTION! It is illegal to submit any update that has already been
  168. /// submitted. }
  169. LLVM_ATTRIBUTE_DEPRECATED(void deleteEdgeRelaxed(BasicBlock *From,
  170. BasicBlock *To),
  171. "Use applyUpdatesPermissive() instead.");
  172. /// Delete DelBB. DelBB will be removed from its Parent and
  173. /// erased from available trees if it exists and finally get deleted.
  174. /// Under Eager UpdateStrategy, DelBB will be processed immediately.
  175. /// Under Lazy UpdateStrategy, DelBB will be queued until a flush event and
  176. /// all available trees are up-to-date. Assert if any instruction of DelBB is
  177. /// modified while awaiting deletion. When both DT and PDT are nullptrs, DelBB
  178. /// will be queued until flush() is called.
  179. void deleteBB(BasicBlock *DelBB);
  180. /// Delete DelBB. DelBB will be removed from its Parent and
  181. /// erased from available trees if it exists. Then the callback will
  182. /// be called. Finally, DelBB will be deleted.
  183. /// Under Eager UpdateStrategy, DelBB will be processed immediately.
  184. /// Under Lazy UpdateStrategy, DelBB will be queued until a flush event and
  185. /// all available trees are up-to-date. Assert if any instruction of DelBB is
  186. /// modified while awaiting deletion. Multiple callbacks can be queued for one
  187. /// DelBB under Lazy UpdateStrategy.
  188. void callbackDeleteBB(BasicBlock *DelBB,
  189. std::function<void(BasicBlock *)> Callback);
  190. ///@}
  191. ///@{
  192. /// \name Flush APIs
  193. ///
  194. /// CAUTION! By the moment these flush APIs are called, the current CFG needs
  195. /// to be the same as the CFG which DTU is in sync with + all updates
  196. /// submitted.
  197. /// Flush DomTree updates and return DomTree.
  198. /// It flushes Deleted BBs if both trees are up-to-date.
  199. /// It must only be called when it has a DomTree.
  200. DominatorTree &getDomTree();
  201. /// Flush PostDomTree updates and return PostDomTree.
  202. /// It flushes Deleted BBs if both trees are up-to-date.
  203. /// It must only be called when it has a PostDomTree.
  204. PostDominatorTree &getPostDomTree();
  205. /// Apply all pending updates to available trees and flush all BasicBlocks
  206. /// awaiting deletion.
  207. void flush();
  208. ///@}
  209. /// Debug method to help view the internal state of this class.
  210. LLVM_DUMP_METHOD void dump() const;
  211. private:
  212. class CallBackOnDeletion final : public CallbackVH {
  213. public:
  214. CallBackOnDeletion(BasicBlock *V,
  215. std::function<void(BasicBlock *)> Callback)
  216. : CallbackVH(V), DelBB(V), Callback_(Callback) {}
  217. private:
  218. BasicBlock *DelBB = nullptr;
  219. std::function<void(BasicBlock *)> Callback_;
  220. void deleted() override {
  221. Callback_(DelBB);
  222. CallbackVH::deleted();
  223. }
  224. };
  225. SmallVector<DominatorTree::UpdateType, 16> PendUpdates;
  226. size_t PendDTUpdateIndex = 0;
  227. size_t PendPDTUpdateIndex = 0;
  228. DominatorTree *DT = nullptr;
  229. PostDominatorTree *PDT = nullptr;
  230. const UpdateStrategy Strategy;
  231. SmallPtrSet<BasicBlock *, 8> DeletedBBs;
  232. std::vector<CallBackOnDeletion> Callbacks;
  233. bool IsRecalculatingDomTree = false;
  234. bool IsRecalculatingPostDomTree = false;
  235. /// First remove all the instructions of DelBB and then make sure DelBB has a
  236. /// valid terminator instruction which is necessary to have when DelBB still
  237. /// has to be inside of its parent Function while awaiting deletion under Lazy
  238. /// UpdateStrategy to prevent other routines from asserting the state of the
  239. /// IR is inconsistent. Assert if DelBB is nullptr or has predecessors.
  240. void validateDeleteBB(BasicBlock *DelBB);
  241. /// Returns true if at least one BasicBlock is deleted.
  242. bool forceFlushDeletedBB();
  243. /// Helper function to apply all pending DomTree updates.
  244. void applyDomTreeUpdates();
  245. /// Helper function to apply all pending PostDomTree updates.
  246. void applyPostDomTreeUpdates();
  247. /// Helper function to flush deleted BasicBlocks if all available
  248. /// trees are up-to-date.
  249. void tryFlushDeletedBB();
  250. /// Drop all updates applied by all available trees and delete BasicBlocks if
  251. /// all available trees are up-to-date.
  252. void dropOutOfDateUpdates();
  253. /// Erase Basic Block node that has been unlinked from Function
  254. /// in the DomTree and PostDomTree.
  255. void eraseDelBBNode(BasicBlock *DelBB);
  256. /// Returns true if the update appears in the LLVM IR.
  257. /// It is used to check whether an update is valid in
  258. /// insertEdge/deleteEdge or is unnecessary in the batch update.
  259. bool isUpdateValid(DominatorTree::UpdateType Update) const;
  260. /// Returns true if the update is self dominance.
  261. bool isSelfDominance(DominatorTree::UpdateType Update) const;
  262. };
  263. } // namespace llvm
  264. #endif // LLVM_ANALYSIS_DOMTREEUPDATER_H