DomTreeUpdater.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. //===- DomTreeUpdater.cpp - 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 implements the DomTreeUpdater class, which provides a uniform way
  10. // to update dominator tree related data structures.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/DomTreeUpdater.h"
  14. #include "llvm/ADT/SmallSet.h"
  15. #include "llvm/Analysis/PostDominators.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/Instructions.h"
  18. #include "llvm/Support/GenericDomTree.h"
  19. #include <algorithm>
  20. #include <functional>
  21. #include <utility>
  22. namespace llvm {
  23. bool DomTreeUpdater::isUpdateValid(
  24. const DominatorTree::UpdateType Update) const {
  25. const auto *From = Update.getFrom();
  26. const auto *To = Update.getTo();
  27. const auto Kind = Update.getKind();
  28. // Discard updates by inspecting the current state of successors of From.
  29. // Since isUpdateValid() must be called *after* the Terminator of From is
  30. // altered we can determine if the update is unnecessary for batch updates
  31. // or invalid for a single update.
  32. const bool HasEdge = llvm::is_contained(successors(From), To);
  33. // If the IR does not match the update,
  34. // 1. In batch updates, this update is unnecessary.
  35. // 2. When called by insertEdge*()/deleteEdge*(), this update is invalid.
  36. // Edge does not exist in IR.
  37. if (Kind == DominatorTree::Insert && !HasEdge)
  38. return false;
  39. // Edge exists in IR.
  40. if (Kind == DominatorTree::Delete && HasEdge)
  41. return false;
  42. return true;
  43. }
  44. bool DomTreeUpdater::isSelfDominance(
  45. const DominatorTree::UpdateType Update) const {
  46. // Won't affect DomTree and PostDomTree.
  47. return Update.getFrom() == Update.getTo();
  48. }
  49. void DomTreeUpdater::applyDomTreeUpdates() {
  50. // No pending DomTreeUpdates.
  51. if (Strategy != UpdateStrategy::Lazy || !DT)
  52. return;
  53. // Only apply updates not are applied by DomTree.
  54. if (hasPendingDomTreeUpdates()) {
  55. const auto I = PendUpdates.begin() + PendDTUpdateIndex;
  56. const auto E = PendUpdates.end();
  57. assert(I < E && "Iterator range invalid; there should be DomTree updates.");
  58. DT->applyUpdates(ArrayRef<DominatorTree::UpdateType>(I, E));
  59. PendDTUpdateIndex = PendUpdates.size();
  60. }
  61. }
  62. void DomTreeUpdater::flush() {
  63. applyDomTreeUpdates();
  64. applyPostDomTreeUpdates();
  65. dropOutOfDateUpdates();
  66. }
  67. void DomTreeUpdater::applyPostDomTreeUpdates() {
  68. // No pending PostDomTreeUpdates.
  69. if (Strategy != UpdateStrategy::Lazy || !PDT)
  70. return;
  71. // Only apply updates not are applied by PostDomTree.
  72. if (hasPendingPostDomTreeUpdates()) {
  73. const auto I = PendUpdates.begin() + PendPDTUpdateIndex;
  74. const auto E = PendUpdates.end();
  75. assert(I < E &&
  76. "Iterator range invalid; there should be PostDomTree updates.");
  77. PDT->applyUpdates(ArrayRef<DominatorTree::UpdateType>(I, E));
  78. PendPDTUpdateIndex = PendUpdates.size();
  79. }
  80. }
  81. void DomTreeUpdater::tryFlushDeletedBB() {
  82. if (!hasPendingUpdates())
  83. forceFlushDeletedBB();
  84. }
  85. bool DomTreeUpdater::forceFlushDeletedBB() {
  86. if (DeletedBBs.empty())
  87. return false;
  88. for (auto *BB : DeletedBBs) {
  89. // After calling deleteBB or callbackDeleteBB under Lazy UpdateStrategy,
  90. // validateDeleteBB() removes all instructions of DelBB and adds an
  91. // UnreachableInst as its terminator. So we check whether the BasicBlock to
  92. // delete only has an UnreachableInst inside.
  93. assert(BB->size() == 1 && isa<UnreachableInst>(BB->getTerminator()) &&
  94. "DelBB has been modified while awaiting deletion.");
  95. BB->removeFromParent();
  96. eraseDelBBNode(BB);
  97. delete BB;
  98. }
  99. DeletedBBs.clear();
  100. Callbacks.clear();
  101. return true;
  102. }
  103. void DomTreeUpdater::recalculate(Function &F) {
  104. if (Strategy == UpdateStrategy::Eager) {
  105. if (DT)
  106. DT->recalculate(F);
  107. if (PDT)
  108. PDT->recalculate(F);
  109. return;
  110. }
  111. // There is little performance gain if we pend the recalculation under
  112. // Lazy UpdateStrategy so we recalculate available trees immediately.
  113. // Prevent forceFlushDeletedBB() from erasing DomTree or PostDomTree nodes.
  114. IsRecalculatingDomTree = IsRecalculatingPostDomTree = true;
  115. // Because all trees are going to be up-to-date after recalculation,
  116. // flush awaiting deleted BasicBlocks.
  117. forceFlushDeletedBB();
  118. if (DT)
  119. DT->recalculate(F);
  120. if (PDT)
  121. PDT->recalculate(F);
  122. // Resume forceFlushDeletedBB() to erase DomTree or PostDomTree nodes.
  123. IsRecalculatingDomTree = IsRecalculatingPostDomTree = false;
  124. PendDTUpdateIndex = PendPDTUpdateIndex = PendUpdates.size();
  125. dropOutOfDateUpdates();
  126. }
  127. bool DomTreeUpdater::hasPendingUpdates() const {
  128. return hasPendingDomTreeUpdates() || hasPendingPostDomTreeUpdates();
  129. }
  130. bool DomTreeUpdater::hasPendingDomTreeUpdates() const {
  131. if (!DT)
  132. return false;
  133. return PendUpdates.size() != PendDTUpdateIndex;
  134. }
  135. bool DomTreeUpdater::hasPendingPostDomTreeUpdates() const {
  136. if (!PDT)
  137. return false;
  138. return PendUpdates.size() != PendPDTUpdateIndex;
  139. }
  140. bool DomTreeUpdater::isBBPendingDeletion(llvm::BasicBlock *DelBB) const {
  141. if (Strategy == UpdateStrategy::Eager || DeletedBBs.empty())
  142. return false;
  143. return DeletedBBs.contains(DelBB);
  144. }
  145. // The DT and PDT require the nodes related to updates
  146. // are not deleted when update functions are called.
  147. // So BasicBlock deletions must be pended when the
  148. // UpdateStrategy is Lazy. When the UpdateStrategy is
  149. // Eager, the BasicBlock will be deleted immediately.
  150. void DomTreeUpdater::deleteBB(BasicBlock *DelBB) {
  151. validateDeleteBB(DelBB);
  152. if (Strategy == UpdateStrategy::Lazy) {
  153. DeletedBBs.insert(DelBB);
  154. return;
  155. }
  156. DelBB->removeFromParent();
  157. eraseDelBBNode(DelBB);
  158. delete DelBB;
  159. }
  160. void DomTreeUpdater::callbackDeleteBB(
  161. BasicBlock *DelBB, std::function<void(BasicBlock *)> Callback) {
  162. validateDeleteBB(DelBB);
  163. if (Strategy == UpdateStrategy::Lazy) {
  164. Callbacks.push_back(CallBackOnDeletion(DelBB, Callback));
  165. DeletedBBs.insert(DelBB);
  166. return;
  167. }
  168. DelBB->removeFromParent();
  169. eraseDelBBNode(DelBB);
  170. Callback(DelBB);
  171. delete DelBB;
  172. }
  173. void DomTreeUpdater::eraseDelBBNode(BasicBlock *DelBB) {
  174. if (DT && !IsRecalculatingDomTree)
  175. if (DT->getNode(DelBB))
  176. DT->eraseNode(DelBB);
  177. if (PDT && !IsRecalculatingPostDomTree)
  178. if (PDT->getNode(DelBB))
  179. PDT->eraseNode(DelBB);
  180. }
  181. void DomTreeUpdater::validateDeleteBB(BasicBlock *DelBB) {
  182. assert(DelBB && "Invalid push_back of nullptr DelBB.");
  183. assert(pred_empty(DelBB) && "DelBB has one or more predecessors.");
  184. // DelBB is unreachable and all its instructions are dead.
  185. while (!DelBB->empty()) {
  186. Instruction &I = DelBB->back();
  187. // Replace used instructions with an arbitrary value (poison).
  188. if (!I.use_empty())
  189. I.replaceAllUsesWith(PoisonValue::get(I.getType()));
  190. DelBB->back().eraseFromParent();
  191. }
  192. // Make sure DelBB has a valid terminator instruction. As long as DelBB is a
  193. // Child of Function F it must contain valid IR.
  194. new UnreachableInst(DelBB->getContext(), DelBB);
  195. }
  196. void DomTreeUpdater::applyUpdates(ArrayRef<DominatorTree::UpdateType> Updates) {
  197. if (!DT && !PDT)
  198. return;
  199. if (Strategy == UpdateStrategy::Lazy) {
  200. PendUpdates.reserve(PendUpdates.size() + Updates.size());
  201. for (const auto &U : Updates)
  202. if (!isSelfDominance(U))
  203. PendUpdates.push_back(U);
  204. return;
  205. }
  206. if (DT)
  207. DT->applyUpdates(Updates);
  208. if (PDT)
  209. PDT->applyUpdates(Updates);
  210. }
  211. void DomTreeUpdater::applyUpdatesPermissive(
  212. ArrayRef<DominatorTree::UpdateType> Updates) {
  213. if (!DT && !PDT)
  214. return;
  215. SmallSet<std::pair<BasicBlock *, BasicBlock *>, 8> Seen;
  216. SmallVector<DominatorTree::UpdateType, 8> DeduplicatedUpdates;
  217. for (const auto &U : Updates) {
  218. auto Edge = std::make_pair(U.getFrom(), U.getTo());
  219. // Because it is illegal to submit updates that have already been applied
  220. // and updates to an edge need to be strictly ordered,
  221. // it is safe to infer the existence of an edge from the first update
  222. // to this edge.
  223. // If the first update to an edge is "Delete", it means that the edge
  224. // existed before. If the first update to an edge is "Insert", it means
  225. // that the edge didn't exist before.
  226. //
  227. // For example, if the user submits {{Delete, A, B}, {Insert, A, B}},
  228. // because
  229. // 1. it is illegal to submit updates that have already been applied,
  230. // i.e., user cannot delete an nonexistent edge,
  231. // 2. updates to an edge need to be strictly ordered,
  232. // So, initially edge A -> B existed.
  233. // We can then safely ignore future updates to this edge and directly
  234. // inspect the current CFG:
  235. // a. If the edge still exists, because the user cannot insert an existent
  236. // edge, so both {Delete, A, B}, {Insert, A, B} actually happened and
  237. // resulted in a no-op. DTU won't submit any update in this case.
  238. // b. If the edge doesn't exist, we can then infer that {Delete, A, B}
  239. // actually happened but {Insert, A, B} was an invalid update which never
  240. // happened. DTU will submit {Delete, A, B} in this case.
  241. if (!isSelfDominance(U) && Seen.count(Edge) == 0) {
  242. Seen.insert(Edge);
  243. // If the update doesn't appear in the CFG, it means that
  244. // either the change isn't made or relevant operations
  245. // result in a no-op.
  246. if (isUpdateValid(U)) {
  247. if (isLazy())
  248. PendUpdates.push_back(U);
  249. else
  250. DeduplicatedUpdates.push_back(U);
  251. }
  252. }
  253. }
  254. if (Strategy == UpdateStrategy::Lazy)
  255. return;
  256. if (DT)
  257. DT->applyUpdates(DeduplicatedUpdates);
  258. if (PDT)
  259. PDT->applyUpdates(DeduplicatedUpdates);
  260. }
  261. DominatorTree &DomTreeUpdater::getDomTree() {
  262. assert(DT && "Invalid acquisition of a null DomTree");
  263. applyDomTreeUpdates();
  264. dropOutOfDateUpdates();
  265. return *DT;
  266. }
  267. PostDominatorTree &DomTreeUpdater::getPostDomTree() {
  268. assert(PDT && "Invalid acquisition of a null PostDomTree");
  269. applyPostDomTreeUpdates();
  270. dropOutOfDateUpdates();
  271. return *PDT;
  272. }
  273. void DomTreeUpdater::dropOutOfDateUpdates() {
  274. if (Strategy == DomTreeUpdater::UpdateStrategy::Eager)
  275. return;
  276. tryFlushDeletedBB();
  277. // Drop all updates applied by both trees.
  278. if (!DT)
  279. PendDTUpdateIndex = PendUpdates.size();
  280. if (!PDT)
  281. PendPDTUpdateIndex = PendUpdates.size();
  282. const size_t dropIndex = std::min(PendDTUpdateIndex, PendPDTUpdateIndex);
  283. const auto B = PendUpdates.begin();
  284. const auto E = PendUpdates.begin() + dropIndex;
  285. assert(B <= E && "Iterator out of range.");
  286. PendUpdates.erase(B, E);
  287. // Calculate current index.
  288. PendDTUpdateIndex -= dropIndex;
  289. PendPDTUpdateIndex -= dropIndex;
  290. }
  291. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  292. LLVM_DUMP_METHOD void DomTreeUpdater::dump() const {
  293. raw_ostream &OS = llvm::dbgs();
  294. OS << "Available Trees: ";
  295. if (DT || PDT) {
  296. if (DT)
  297. OS << "DomTree ";
  298. if (PDT)
  299. OS << "PostDomTree ";
  300. OS << "\n";
  301. } else
  302. OS << "None\n";
  303. OS << "UpdateStrategy: ";
  304. if (Strategy == UpdateStrategy::Eager) {
  305. OS << "Eager\n";
  306. return;
  307. } else
  308. OS << "Lazy\n";
  309. int Index = 0;
  310. auto printUpdates =
  311. [&](ArrayRef<DominatorTree::UpdateType>::const_iterator begin,
  312. ArrayRef<DominatorTree::UpdateType>::const_iterator end) {
  313. if (begin == end)
  314. OS << " None\n";
  315. Index = 0;
  316. for (auto It = begin, ItEnd = end; It != ItEnd; ++It) {
  317. auto U = *It;
  318. OS << " " << Index << " : ";
  319. ++Index;
  320. if (U.getKind() == DominatorTree::Insert)
  321. OS << "Insert, ";
  322. else
  323. OS << "Delete, ";
  324. BasicBlock *From = U.getFrom();
  325. if (From) {
  326. auto S = From->getName();
  327. if (!From->hasName())
  328. S = "(no name)";
  329. OS << S << "(" << From << "), ";
  330. } else {
  331. OS << "(badref), ";
  332. }
  333. BasicBlock *To = U.getTo();
  334. if (To) {
  335. auto S = To->getName();
  336. if (!To->hasName())
  337. S = "(no_name)";
  338. OS << S << "(" << To << ")\n";
  339. } else {
  340. OS << "(badref)\n";
  341. }
  342. }
  343. };
  344. if (DT) {
  345. const auto I = PendUpdates.begin() + PendDTUpdateIndex;
  346. assert(PendUpdates.begin() <= I && I <= PendUpdates.end() &&
  347. "Iterator out of range.");
  348. OS << "Applied but not cleared DomTreeUpdates:\n";
  349. printUpdates(PendUpdates.begin(), I);
  350. OS << "Pending DomTreeUpdates:\n";
  351. printUpdates(I, PendUpdates.end());
  352. }
  353. if (PDT) {
  354. const auto I = PendUpdates.begin() + PendPDTUpdateIndex;
  355. assert(PendUpdates.begin() <= I && I <= PendUpdates.end() &&
  356. "Iterator out of range.");
  357. OS << "Applied but not cleared PostDomTreeUpdates:\n";
  358. printUpdates(PendUpdates.begin(), I);
  359. OS << "Pending PostDomTreeUpdates:\n";
  360. printUpdates(I, PendUpdates.end());
  361. }
  362. OS << "Pending DeletedBBs:\n";
  363. Index = 0;
  364. for (const auto *BB : DeletedBBs) {
  365. OS << " " << Index << " : ";
  366. ++Index;
  367. if (BB->hasName())
  368. OS << BB->getName() << "(";
  369. else
  370. OS << "(no_name)(";
  371. OS << BB << ")\n";
  372. }
  373. OS << "Pending Callbacks:\n";
  374. Index = 0;
  375. for (const auto &BB : Callbacks) {
  376. OS << " " << Index << " : ";
  377. ++Index;
  378. if (BB->hasName())
  379. OS << BB->getName() << "(";
  380. else
  381. OS << "(no_name)(";
  382. OS << BB << ")\n";
  383. }
  384. }
  385. #endif
  386. } // namespace llvm