DomTreeUpdater.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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/Instructions.h"
  17. #include "llvm/Support/GenericDomTree.h"
  18. #include <algorithm>
  19. #include <functional>
  20. #include <utility>
  21. namespace llvm {
  22. bool DomTreeUpdater::isUpdateValid(
  23. const DominatorTree::UpdateType Update) const {
  24. const auto *From = Update.getFrom();
  25. const auto *To = Update.getTo();
  26. const auto Kind = Update.getKind();
  27. // Discard updates by inspecting the current state of successors of From.
  28. // Since isUpdateValid() must be called *after* the Terminator of From is
  29. // altered we can determine if the update is unnecessary for batch updates
  30. // or invalid for a single update.
  31. const bool HasEdge = llvm::is_contained(successors(From), To);
  32. // If the IR does not match the update,
  33. // 1. In batch updates, this update is unnecessary.
  34. // 2. When called by insertEdge*()/deleteEdge*(), this update is invalid.
  35. // Edge does not exist in IR.
  36. if (Kind == DominatorTree::Insert && !HasEdge)
  37. return false;
  38. // Edge exists in IR.
  39. if (Kind == DominatorTree::Delete && HasEdge)
  40. return false;
  41. return true;
  42. }
  43. bool DomTreeUpdater::isSelfDominance(
  44. const DominatorTree::UpdateType Update) const {
  45. // Won't affect DomTree and PostDomTree.
  46. return Update.getFrom() == Update.getTo();
  47. }
  48. void DomTreeUpdater::applyDomTreeUpdates() {
  49. // No pending DomTreeUpdates.
  50. if (Strategy != UpdateStrategy::Lazy || !DT)
  51. return;
  52. // Only apply updates not are applied by DomTree.
  53. if (hasPendingDomTreeUpdates()) {
  54. const auto I = PendUpdates.begin() + PendDTUpdateIndex;
  55. const auto E = PendUpdates.end();
  56. assert(I < E && "Iterator range invalid; there should be DomTree updates.");
  57. DT->applyUpdates(ArrayRef<DominatorTree::UpdateType>(I, E));
  58. PendDTUpdateIndex = PendUpdates.size();
  59. }
  60. }
  61. void DomTreeUpdater::flush() {
  62. applyDomTreeUpdates();
  63. applyPostDomTreeUpdates();
  64. dropOutOfDateUpdates();
  65. }
  66. void DomTreeUpdater::applyPostDomTreeUpdates() {
  67. // No pending PostDomTreeUpdates.
  68. if (Strategy != UpdateStrategy::Lazy || !PDT)
  69. return;
  70. // Only apply updates not are applied by PostDomTree.
  71. if (hasPendingPostDomTreeUpdates()) {
  72. const auto I = PendUpdates.begin() + PendPDTUpdateIndex;
  73. const auto E = PendUpdates.end();
  74. assert(I < E &&
  75. "Iterator range invalid; there should be PostDomTree updates.");
  76. PDT->applyUpdates(ArrayRef<DominatorTree::UpdateType>(I, E));
  77. PendPDTUpdateIndex = PendUpdates.size();
  78. }
  79. }
  80. void DomTreeUpdater::tryFlushDeletedBB() {
  81. if (!hasPendingUpdates())
  82. forceFlushDeletedBB();
  83. }
  84. bool DomTreeUpdater::forceFlushDeletedBB() {
  85. if (DeletedBBs.empty())
  86. return false;
  87. for (auto *BB : DeletedBBs) {
  88. // After calling deleteBB or callbackDeleteBB under Lazy UpdateStrategy,
  89. // validateDeleteBB() removes all instructions of DelBB and adds an
  90. // UnreachableInst as its terminator. So we check whether the BasicBlock to
  91. // delete only has an UnreachableInst inside.
  92. assert(BB->getInstList().size() == 1 &&
  93. 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 (undef).
  188. if (!I.use_empty())
  189. I.replaceAllUsesWith(llvm::UndefValue::get(I.getType()));
  190. DelBB->getInstList().pop_back();
  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::insertEdge(BasicBlock *From, BasicBlock *To) {
  274. #ifndef NDEBUG
  275. assert(isUpdateValid({DominatorTree::Insert, From, To}) &&
  276. "Inserted edge does not appear in the CFG");
  277. #endif
  278. if (!DT && !PDT)
  279. return;
  280. // Won't affect DomTree and PostDomTree; discard update.
  281. if (From == To)
  282. return;
  283. if (Strategy == UpdateStrategy::Eager) {
  284. if (DT)
  285. DT->insertEdge(From, To);
  286. if (PDT)
  287. PDT->insertEdge(From, To);
  288. return;
  289. }
  290. PendUpdates.push_back({DominatorTree::Insert, From, To});
  291. }
  292. void DomTreeUpdater::insertEdgeRelaxed(BasicBlock *From, BasicBlock *To) {
  293. if (From == To)
  294. return;
  295. if (!DT && !PDT)
  296. return;
  297. if (!isUpdateValid({DominatorTree::Insert, From, To}))
  298. return;
  299. if (Strategy == UpdateStrategy::Eager) {
  300. if (DT)
  301. DT->insertEdge(From, To);
  302. if (PDT)
  303. PDT->insertEdge(From, To);
  304. return;
  305. }
  306. PendUpdates.push_back({DominatorTree::Insert, From, To});
  307. }
  308. void DomTreeUpdater::deleteEdge(BasicBlock *From, BasicBlock *To) {
  309. #ifndef NDEBUG
  310. assert(isUpdateValid({DominatorTree::Delete, From, To}) &&
  311. "Deleted edge still exists in the CFG!");
  312. #endif
  313. if (!DT && !PDT)
  314. return;
  315. // Won't affect DomTree and PostDomTree; discard update.
  316. if (From == To)
  317. return;
  318. if (Strategy == UpdateStrategy::Eager) {
  319. if (DT)
  320. DT->deleteEdge(From, To);
  321. if (PDT)
  322. PDT->deleteEdge(From, To);
  323. return;
  324. }
  325. PendUpdates.push_back({DominatorTree::Delete, From, To});
  326. }
  327. void DomTreeUpdater::deleteEdgeRelaxed(BasicBlock *From, BasicBlock *To) {
  328. if (From == To)
  329. return;
  330. if (!DT && !PDT)
  331. return;
  332. if (!isUpdateValid({DominatorTree::Delete, From, To}))
  333. return;
  334. if (Strategy == UpdateStrategy::Eager) {
  335. if (DT)
  336. DT->deleteEdge(From, To);
  337. if (PDT)
  338. PDT->deleteEdge(From, To);
  339. return;
  340. }
  341. PendUpdates.push_back({DominatorTree::Delete, From, To});
  342. }
  343. void DomTreeUpdater::dropOutOfDateUpdates() {
  344. if (Strategy == DomTreeUpdater::UpdateStrategy::Eager)
  345. return;
  346. tryFlushDeletedBB();
  347. // Drop all updates applied by both trees.
  348. if (!DT)
  349. PendDTUpdateIndex = PendUpdates.size();
  350. if (!PDT)
  351. PendPDTUpdateIndex = PendUpdates.size();
  352. const size_t dropIndex = std::min(PendDTUpdateIndex, PendPDTUpdateIndex);
  353. const auto B = PendUpdates.begin();
  354. const auto E = PendUpdates.begin() + dropIndex;
  355. assert(B <= E && "Iterator out of range.");
  356. PendUpdates.erase(B, E);
  357. // Calculate current index.
  358. PendDTUpdateIndex -= dropIndex;
  359. PendPDTUpdateIndex -= dropIndex;
  360. }
  361. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  362. LLVM_DUMP_METHOD void DomTreeUpdater::dump() const {
  363. raw_ostream &OS = llvm::dbgs();
  364. OS << "Available Trees: ";
  365. if (DT || PDT) {
  366. if (DT)
  367. OS << "DomTree ";
  368. if (PDT)
  369. OS << "PostDomTree ";
  370. OS << "\n";
  371. } else
  372. OS << "None\n";
  373. OS << "UpdateStrategy: ";
  374. if (Strategy == UpdateStrategy::Eager) {
  375. OS << "Eager\n";
  376. return;
  377. } else
  378. OS << "Lazy\n";
  379. int Index = 0;
  380. auto printUpdates =
  381. [&](ArrayRef<DominatorTree::UpdateType>::const_iterator begin,
  382. ArrayRef<DominatorTree::UpdateType>::const_iterator end) {
  383. if (begin == end)
  384. OS << " None\n";
  385. Index = 0;
  386. for (auto It = begin, ItEnd = end; It != ItEnd; ++It) {
  387. auto U = *It;
  388. OS << " " << Index << " : ";
  389. ++Index;
  390. if (U.getKind() == DominatorTree::Insert)
  391. OS << "Insert, ";
  392. else
  393. OS << "Delete, ";
  394. BasicBlock *From = U.getFrom();
  395. if (From) {
  396. auto S = From->getName();
  397. if (!From->hasName())
  398. S = "(no name)";
  399. OS << S << "(" << From << "), ";
  400. } else {
  401. OS << "(badref), ";
  402. }
  403. BasicBlock *To = U.getTo();
  404. if (To) {
  405. auto S = To->getName();
  406. if (!To->hasName())
  407. S = "(no_name)";
  408. OS << S << "(" << To << ")\n";
  409. } else {
  410. OS << "(badref)\n";
  411. }
  412. }
  413. };
  414. if (DT) {
  415. const auto I = PendUpdates.begin() + PendDTUpdateIndex;
  416. assert(PendUpdates.begin() <= I && I <= PendUpdates.end() &&
  417. "Iterator out of range.");
  418. OS << "Applied but not cleared DomTreeUpdates:\n";
  419. printUpdates(PendUpdates.begin(), I);
  420. OS << "Pending DomTreeUpdates:\n";
  421. printUpdates(I, PendUpdates.end());
  422. }
  423. if (PDT) {
  424. const auto I = PendUpdates.begin() + PendPDTUpdateIndex;
  425. assert(PendUpdates.begin() <= I && I <= PendUpdates.end() &&
  426. "Iterator out of range.");
  427. OS << "Applied but not cleared PostDomTreeUpdates:\n";
  428. printUpdates(PendUpdates.begin(), I);
  429. OS << "Pending PostDomTreeUpdates:\n";
  430. printUpdates(I, PendUpdates.end());
  431. }
  432. OS << "Pending DeletedBBs:\n";
  433. Index = 0;
  434. for (const auto *BB : DeletedBBs) {
  435. OS << " " << Index << " : ";
  436. ++Index;
  437. if (BB->hasName())
  438. OS << BB->getName() << "(";
  439. else
  440. OS << "(no_name)(";
  441. OS << BB << ")\n";
  442. }
  443. OS << "Pending Callbacks:\n";
  444. Index = 0;
  445. for (const auto &BB : Callbacks) {
  446. OS << " " << Index << " : ";
  447. ++Index;
  448. if (BB->hasName())
  449. OS << BB->getName() << "(";
  450. else
  451. OS << "(no_name)(";
  452. OS << BB << ")\n";
  453. }
  454. }
  455. #endif
  456. } // namespace llvm