GenericDomTreeConstruction.h 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- GenericDomTreeConstruction.h - Dominator Calculation ------*- 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. /// \file
  14. ///
  15. /// Generic dominator tree construction - this file provides routines to
  16. /// construct immediate dominator information for a flow-graph based on the
  17. /// Semi-NCA algorithm described in this dissertation:
  18. ///
  19. /// [1] Linear-Time Algorithms for Dominators and Related Problems
  20. /// Loukas Georgiadis, Princeton University, November 2005, pp. 21-23:
  21. /// ftp://ftp.cs.princeton.edu/reports/2005/737.pdf
  22. ///
  23. /// Semi-NCA algorithm runs in O(n^2) worst-case time but usually slightly
  24. /// faster than Simple Lengauer-Tarjan in practice.
  25. ///
  26. /// O(n^2) worst cases happen when the computation of nearest common ancestors
  27. /// requires O(n) average time, which is very unlikely in real world. If this
  28. /// ever turns out to be an issue, consider implementing a hybrid algorithm
  29. /// that uses SLT to perform full constructions and SemiNCA for incremental
  30. /// updates.
  31. ///
  32. /// The file uses the Depth Based Search algorithm to perform incremental
  33. /// updates (insertion and deletions). The implemented algorithm is based on
  34. /// this publication:
  35. ///
  36. /// [2] An Experimental Study of Dynamic Dominators
  37. /// Loukas Georgiadis, et al., April 12 2016, pp. 5-7, 9-10:
  38. /// https://arxiv.org/pdf/1604.02711.pdf
  39. ///
  40. //===----------------------------------------------------------------------===//
  41. #ifndef LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
  42. #define LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
  43. #include "llvm/ADT/ArrayRef.h"
  44. #include "llvm/ADT/DenseSet.h"
  45. #include "llvm/ADT/DepthFirstIterator.h"
  46. #include "llvm/ADT/PointerIntPair.h"
  47. #include "llvm/ADT/SmallPtrSet.h"
  48. #include "llvm/Support/Debug.h"
  49. #include "llvm/Support/GenericDomTree.h"
  50. #include <queue>
  51. #define DEBUG_TYPE "dom-tree-builder"
  52. namespace llvm {
  53. namespace DomTreeBuilder {
  54. template <typename DomTreeT>
  55. struct SemiNCAInfo {
  56. using NodePtr = typename DomTreeT::NodePtr;
  57. using NodeT = typename DomTreeT::NodeType;
  58. using TreeNodePtr = DomTreeNodeBase<NodeT> *;
  59. using RootsT = decltype(DomTreeT::Roots);
  60. static constexpr bool IsPostDom = DomTreeT::IsPostDominator;
  61. using GraphDiffT = GraphDiff<NodePtr, IsPostDom>;
  62. // Information record used by Semi-NCA during tree construction.
  63. struct InfoRec {
  64. unsigned DFSNum = 0;
  65. unsigned Parent = 0;
  66. unsigned Semi = 0;
  67. NodePtr Label = nullptr;
  68. NodePtr IDom = nullptr;
  69. SmallVector<NodePtr, 2> ReverseChildren;
  70. };
  71. // Number to node mapping is 1-based. Initialize the mapping to start with
  72. // a dummy element.
  73. std::vector<NodePtr> NumToNode = {nullptr};
  74. DenseMap<NodePtr, InfoRec> NodeToInfo;
  75. using UpdateT = typename DomTreeT::UpdateType;
  76. using UpdateKind = typename DomTreeT::UpdateKind;
  77. struct BatchUpdateInfo {
  78. // Note: Updates inside PreViewCFG are already legalized.
  79. BatchUpdateInfo(GraphDiffT &PreViewCFG, GraphDiffT *PostViewCFG = nullptr)
  80. : PreViewCFG(PreViewCFG), PostViewCFG(PostViewCFG),
  81. NumLegalized(PreViewCFG.getNumLegalizedUpdates()) {}
  82. // Remembers if the whole tree was recalculated at some point during the
  83. // current batch update.
  84. bool IsRecalculated = false;
  85. GraphDiffT &PreViewCFG;
  86. GraphDiffT *PostViewCFG;
  87. const size_t NumLegalized;
  88. };
  89. BatchUpdateInfo *BatchUpdates;
  90. using BatchUpdatePtr = BatchUpdateInfo *;
  91. // If BUI is a nullptr, then there's no batch update in progress.
  92. SemiNCAInfo(BatchUpdatePtr BUI) : BatchUpdates(BUI) {}
  93. void clear() {
  94. NumToNode = {nullptr}; // Restore to initial state with a dummy start node.
  95. NodeToInfo.clear();
  96. // Don't reset the pointer to BatchUpdateInfo here -- if there's an update
  97. // in progress, we need this information to continue it.
  98. }
  99. template <bool Inversed>
  100. static SmallVector<NodePtr, 8> getChildren(NodePtr N, BatchUpdatePtr BUI) {
  101. if (BUI)
  102. return BUI->PreViewCFG.template getChildren<Inversed>(N);
  103. return getChildren<Inversed>(N);
  104. }
  105. template <bool Inversed>
  106. static SmallVector<NodePtr, 8> getChildren(NodePtr N) {
  107. using DirectedNodeT =
  108. std::conditional_t<Inversed, Inverse<NodePtr>, NodePtr>;
  109. auto R = children<DirectedNodeT>(N);
  110. SmallVector<NodePtr, 8> Res(detail::reverse_if<!Inversed>(R));
  111. // Remove nullptr children for clang.
  112. llvm::erase_value(Res, nullptr);
  113. return Res;
  114. }
  115. NodePtr getIDom(NodePtr BB) const {
  116. auto InfoIt = NodeToInfo.find(BB);
  117. if (InfoIt == NodeToInfo.end()) return nullptr;
  118. return InfoIt->second.IDom;
  119. }
  120. TreeNodePtr getNodeForBlock(NodePtr BB, DomTreeT &DT) {
  121. if (TreeNodePtr Node = DT.getNode(BB)) return Node;
  122. // Haven't calculated this node yet? Get or calculate the node for the
  123. // immediate dominator.
  124. NodePtr IDom = getIDom(BB);
  125. assert(IDom || DT.DomTreeNodes[nullptr]);
  126. TreeNodePtr IDomNode = getNodeForBlock(IDom, DT);
  127. // Add a new tree node for this NodeT, and link it as a child of
  128. // IDomNode
  129. return DT.createChild(BB, IDomNode);
  130. }
  131. static bool AlwaysDescend(NodePtr, NodePtr) { return true; }
  132. struct BlockNamePrinter {
  133. NodePtr N;
  134. BlockNamePrinter(NodePtr Block) : N(Block) {}
  135. BlockNamePrinter(TreeNodePtr TN) : N(TN ? TN->getBlock() : nullptr) {}
  136. friend raw_ostream &operator<<(raw_ostream &O, const BlockNamePrinter &BP) {
  137. if (!BP.N)
  138. O << "nullptr";
  139. else
  140. BP.N->printAsOperand(O, false);
  141. return O;
  142. }
  143. };
  144. using NodeOrderMap = DenseMap<NodePtr, unsigned>;
  145. // Custom DFS implementation which can skip nodes based on a provided
  146. // predicate. It also collects ReverseChildren so that we don't have to spend
  147. // time getting predecessors in SemiNCA.
  148. //
  149. // If IsReverse is set to true, the DFS walk will be performed backwards
  150. // relative to IsPostDom -- using reverse edges for dominators and forward
  151. // edges for postdominators.
  152. //
  153. // If SuccOrder is specified then in this order the DFS traverses the children
  154. // otherwise the order is implied by the results of getChildren().
  155. template <bool IsReverse = false, typename DescendCondition>
  156. unsigned runDFS(NodePtr V, unsigned LastNum, DescendCondition Condition,
  157. unsigned AttachToNum,
  158. const NodeOrderMap *SuccOrder = nullptr) {
  159. assert(V);
  160. SmallVector<NodePtr, 64> WorkList = {V};
  161. if (NodeToInfo.count(V) != 0) NodeToInfo[V].Parent = AttachToNum;
  162. while (!WorkList.empty()) {
  163. const NodePtr BB = WorkList.pop_back_val();
  164. auto &BBInfo = NodeToInfo[BB];
  165. // Visited nodes always have positive DFS numbers.
  166. if (BBInfo.DFSNum != 0) continue;
  167. BBInfo.DFSNum = BBInfo.Semi = ++LastNum;
  168. BBInfo.Label = BB;
  169. NumToNode.push_back(BB);
  170. constexpr bool Direction = IsReverse != IsPostDom; // XOR.
  171. auto Successors = getChildren<Direction>(BB, BatchUpdates);
  172. if (SuccOrder && Successors.size() > 1)
  173. llvm::sort(
  174. Successors.begin(), Successors.end(), [=](NodePtr A, NodePtr B) {
  175. return SuccOrder->find(A)->second < SuccOrder->find(B)->second;
  176. });
  177. for (const NodePtr Succ : Successors) {
  178. const auto SIT = NodeToInfo.find(Succ);
  179. // Don't visit nodes more than once but remember to collect
  180. // ReverseChildren.
  181. if (SIT != NodeToInfo.end() && SIT->second.DFSNum != 0) {
  182. if (Succ != BB) SIT->second.ReverseChildren.push_back(BB);
  183. continue;
  184. }
  185. if (!Condition(BB, Succ)) continue;
  186. // It's fine to add Succ to the map, because we know that it will be
  187. // visited later.
  188. auto &SuccInfo = NodeToInfo[Succ];
  189. WorkList.push_back(Succ);
  190. SuccInfo.Parent = LastNum;
  191. SuccInfo.ReverseChildren.push_back(BB);
  192. }
  193. }
  194. return LastNum;
  195. }
  196. // V is a predecessor of W. eval() returns V if V < W, otherwise the minimum
  197. // of sdom(U), where U > W and there is a virtual forest path from U to V. The
  198. // virtual forest consists of linked edges of processed vertices.
  199. //
  200. // We can follow Parent pointers (virtual forest edges) to determine the
  201. // ancestor U with minimum sdom(U). But it is slow and thus we employ the path
  202. // compression technique to speed up to O(m*log(n)). Theoretically the virtual
  203. // forest can be organized as balanced trees to achieve almost linear
  204. // O(m*alpha(m,n)) running time. But it requires two auxiliary arrays (Size
  205. // and Child) and is unlikely to be faster than the simple implementation.
  206. //
  207. // For each vertex V, its Label points to the vertex with the minimal sdom(U)
  208. // (Semi) in its path from V (included) to NodeToInfo[V].Parent (excluded).
  209. NodePtr eval(NodePtr V, unsigned LastLinked,
  210. SmallVectorImpl<InfoRec *> &Stack) {
  211. InfoRec *VInfo = &NodeToInfo[V];
  212. if (VInfo->Parent < LastLinked)
  213. return VInfo->Label;
  214. // Store ancestors except the last (root of a virtual tree) into a stack.
  215. assert(Stack.empty());
  216. do {
  217. Stack.push_back(VInfo);
  218. VInfo = &NodeToInfo[NumToNode[VInfo->Parent]];
  219. } while (VInfo->Parent >= LastLinked);
  220. // Path compression. Point each vertex's Parent to the root and update its
  221. // Label if any of its ancestors (PInfo->Label) has a smaller Semi.
  222. const InfoRec *PInfo = VInfo;
  223. const InfoRec *PLabelInfo = &NodeToInfo[PInfo->Label];
  224. do {
  225. VInfo = Stack.pop_back_val();
  226. VInfo->Parent = PInfo->Parent;
  227. const InfoRec *VLabelInfo = &NodeToInfo[VInfo->Label];
  228. if (PLabelInfo->Semi < VLabelInfo->Semi)
  229. VInfo->Label = PInfo->Label;
  230. else
  231. PLabelInfo = VLabelInfo;
  232. PInfo = VInfo;
  233. } while (!Stack.empty());
  234. return VInfo->Label;
  235. }
  236. // This function requires DFS to be run before calling it.
  237. void runSemiNCA(DomTreeT &DT, const unsigned MinLevel = 0) {
  238. const unsigned NextDFSNum(NumToNode.size());
  239. // Initialize IDoms to spanning tree parents.
  240. for (unsigned i = 1; i < NextDFSNum; ++i) {
  241. const NodePtr V = NumToNode[i];
  242. auto &VInfo = NodeToInfo[V];
  243. VInfo.IDom = NumToNode[VInfo.Parent];
  244. }
  245. // Step #1: Calculate the semidominators of all vertices.
  246. SmallVector<InfoRec *, 32> EvalStack;
  247. for (unsigned i = NextDFSNum - 1; i >= 2; --i) {
  248. NodePtr W = NumToNode[i];
  249. auto &WInfo = NodeToInfo[W];
  250. // Initialize the semi dominator to point to the parent node.
  251. WInfo.Semi = WInfo.Parent;
  252. for (const auto &N : WInfo.ReverseChildren) {
  253. if (NodeToInfo.count(N) == 0) // Skip unreachable predecessors.
  254. continue;
  255. const TreeNodePtr TN = DT.getNode(N);
  256. // Skip predecessors whose level is above the subtree we are processing.
  257. if (TN && TN->getLevel() < MinLevel)
  258. continue;
  259. unsigned SemiU = NodeToInfo[eval(N, i + 1, EvalStack)].Semi;
  260. if (SemiU < WInfo.Semi) WInfo.Semi = SemiU;
  261. }
  262. }
  263. // Step #2: Explicitly define the immediate dominator of each vertex.
  264. // IDom[i] = NCA(SDom[i], SpanningTreeParent(i)).
  265. // Note that the parents were stored in IDoms and later got invalidated
  266. // during path compression in Eval.
  267. for (unsigned i = 2; i < NextDFSNum; ++i) {
  268. const NodePtr W = NumToNode[i];
  269. auto &WInfo = NodeToInfo[W];
  270. const unsigned SDomNum = NodeToInfo[NumToNode[WInfo.Semi]].DFSNum;
  271. NodePtr WIDomCandidate = WInfo.IDom;
  272. while (NodeToInfo[WIDomCandidate].DFSNum > SDomNum)
  273. WIDomCandidate = NodeToInfo[WIDomCandidate].IDom;
  274. WInfo.IDom = WIDomCandidate;
  275. }
  276. }
  277. // PostDominatorTree always has a virtual root that represents a virtual CFG
  278. // node that serves as a single exit from the function. All the other exits
  279. // (CFG nodes with terminators and nodes in infinite loops are logically
  280. // connected to this virtual CFG exit node).
  281. // This functions maps a nullptr CFG node to the virtual root tree node.
  282. void addVirtualRoot() {
  283. assert(IsPostDom && "Only postdominators have a virtual root");
  284. assert(NumToNode.size() == 1 && "SNCAInfo must be freshly constructed");
  285. auto &BBInfo = NodeToInfo[nullptr];
  286. BBInfo.DFSNum = BBInfo.Semi = 1;
  287. BBInfo.Label = nullptr;
  288. NumToNode.push_back(nullptr); // NumToNode[1] = nullptr;
  289. }
  290. // For postdominators, nodes with no forward successors are trivial roots that
  291. // are always selected as tree roots. Roots with forward successors correspond
  292. // to CFG nodes within infinite loops.
  293. static bool HasForwardSuccessors(const NodePtr N, BatchUpdatePtr BUI) {
  294. assert(N && "N must be a valid node");
  295. return !getChildren<false>(N, BUI).empty();
  296. }
  297. static NodePtr GetEntryNode(const DomTreeT &DT) {
  298. assert(DT.Parent && "Parent not set");
  299. return GraphTraits<typename DomTreeT::ParentPtr>::getEntryNode(DT.Parent);
  300. }
  301. // Finds all roots without relaying on the set of roots already stored in the
  302. // tree.
  303. // We define roots to be some non-redundant set of the CFG nodes
  304. static RootsT FindRoots(const DomTreeT &DT, BatchUpdatePtr BUI) {
  305. assert(DT.Parent && "Parent pointer is not set");
  306. RootsT Roots;
  307. // For dominators, function entry CFG node is always a tree root node.
  308. if (!IsPostDom) {
  309. Roots.push_back(GetEntryNode(DT));
  310. return Roots;
  311. }
  312. SemiNCAInfo SNCA(BUI);
  313. // PostDominatorTree always has a virtual root.
  314. SNCA.addVirtualRoot();
  315. unsigned Num = 1;
  316. LLVM_DEBUG(dbgs() << "\t\tLooking for trivial roots\n");
  317. // Step #1: Find all the trivial roots that are going to will definitely
  318. // remain tree roots.
  319. unsigned Total = 0;
  320. // It may happen that there are some new nodes in the CFG that are result of
  321. // the ongoing batch update, but we cannot really pretend that they don't
  322. // exist -- we won't see any outgoing or incoming edges to them, so it's
  323. // fine to discover them here, as they would end up appearing in the CFG at
  324. // some point anyway.
  325. for (const NodePtr N : nodes(DT.Parent)) {
  326. ++Total;
  327. // If it has no *successors*, it is definitely a root.
  328. if (!HasForwardSuccessors(N, BUI)) {
  329. Roots.push_back(N);
  330. // Run DFS not to walk this part of CFG later.
  331. Num = SNCA.runDFS(N, Num, AlwaysDescend, 1);
  332. LLVM_DEBUG(dbgs() << "Found a new trivial root: " << BlockNamePrinter(N)
  333. << "\n");
  334. LLVM_DEBUG(dbgs() << "Last visited node: "
  335. << BlockNamePrinter(SNCA.NumToNode[Num]) << "\n");
  336. }
  337. }
  338. LLVM_DEBUG(dbgs() << "\t\tLooking for non-trivial roots\n");
  339. // Step #2: Find all non-trivial root candidates. Those are CFG nodes that
  340. // are reverse-unreachable were not visited by previous DFS walks (i.e. CFG
  341. // nodes in infinite loops).
  342. bool HasNonTrivialRoots = false;
  343. // Accounting for the virtual exit, see if we had any reverse-unreachable
  344. // nodes.
  345. if (Total + 1 != Num) {
  346. HasNonTrivialRoots = true;
  347. // SuccOrder is the order of blocks in the function. It is needed to make
  348. // the calculation of the FurthestAway node and the whole PostDomTree
  349. // immune to swap successors transformation (e.g. canonicalizing branch
  350. // predicates). SuccOrder is initialized lazily only for successors of
  351. // reverse unreachable nodes.
  352. Optional<NodeOrderMap> SuccOrder;
  353. auto InitSuccOrderOnce = [&]() {
  354. SuccOrder = NodeOrderMap();
  355. for (const auto Node : nodes(DT.Parent))
  356. if (SNCA.NodeToInfo.count(Node) == 0)
  357. for (const auto Succ : getChildren<false>(Node, SNCA.BatchUpdates))
  358. SuccOrder->try_emplace(Succ, 0);
  359. // Add mapping for all entries of SuccOrder.
  360. unsigned NodeNum = 0;
  361. for (const auto Node : nodes(DT.Parent)) {
  362. ++NodeNum;
  363. auto Order = SuccOrder->find(Node);
  364. if (Order != SuccOrder->end()) {
  365. assert(Order->second == 0);
  366. Order->second = NodeNum;
  367. }
  368. }
  369. };
  370. // Make another DFS pass over all other nodes to find the
  371. // reverse-unreachable blocks, and find the furthest paths we'll be able
  372. // to make.
  373. // Note that this looks N^2, but it's really 2N worst case, if every node
  374. // is unreachable. This is because we are still going to only visit each
  375. // unreachable node once, we may just visit it in two directions,
  376. // depending on how lucky we get.
  377. for (const NodePtr I : nodes(DT.Parent)) {
  378. if (SNCA.NodeToInfo.count(I) == 0) {
  379. LLVM_DEBUG(dbgs()
  380. << "\t\t\tVisiting node " << BlockNamePrinter(I) << "\n");
  381. // Find the furthest away we can get by following successors, then
  382. // follow them in reverse. This gives us some reasonable answer about
  383. // the post-dom tree inside any infinite loop. In particular, it
  384. // guarantees we get to the farthest away point along *some*
  385. // path. This also matches the GCC's behavior.
  386. // If we really wanted a totally complete picture of dominance inside
  387. // this infinite loop, we could do it with SCC-like algorithms to find
  388. // the lowest and highest points in the infinite loop. In theory, it
  389. // would be nice to give the canonical backedge for the loop, but it's
  390. // expensive and does not always lead to a minimal set of roots.
  391. LLVM_DEBUG(dbgs() << "\t\t\tRunning forward DFS\n");
  392. if (!SuccOrder)
  393. InitSuccOrderOnce();
  394. assert(SuccOrder);
  395. const unsigned NewNum =
  396. SNCA.runDFS<true>(I, Num, AlwaysDescend, Num, &*SuccOrder);
  397. const NodePtr FurthestAway = SNCA.NumToNode[NewNum];
  398. LLVM_DEBUG(dbgs() << "\t\t\tFound a new furthest away node "
  399. << "(non-trivial root): "
  400. << BlockNamePrinter(FurthestAway) << "\n");
  401. Roots.push_back(FurthestAway);
  402. LLVM_DEBUG(dbgs() << "\t\t\tPrev DFSNum: " << Num << ", new DFSNum: "
  403. << NewNum << "\n\t\t\tRemoving DFS info\n");
  404. for (unsigned i = NewNum; i > Num; --i) {
  405. const NodePtr N = SNCA.NumToNode[i];
  406. LLVM_DEBUG(dbgs() << "\t\t\t\tRemoving DFS info for "
  407. << BlockNamePrinter(N) << "\n");
  408. SNCA.NodeToInfo.erase(N);
  409. SNCA.NumToNode.pop_back();
  410. }
  411. const unsigned PrevNum = Num;
  412. LLVM_DEBUG(dbgs() << "\t\t\tRunning reverse DFS\n");
  413. Num = SNCA.runDFS(FurthestAway, Num, AlwaysDescend, 1);
  414. for (unsigned i = PrevNum + 1; i <= Num; ++i)
  415. LLVM_DEBUG(dbgs() << "\t\t\t\tfound node "
  416. << BlockNamePrinter(SNCA.NumToNode[i]) << "\n");
  417. }
  418. }
  419. }
  420. LLVM_DEBUG(dbgs() << "Total: " << Total << ", Num: " << Num << "\n");
  421. LLVM_DEBUG(dbgs() << "Discovered CFG nodes:\n");
  422. LLVM_DEBUG(for (size_t i = 0; i <= Num; ++i) dbgs()
  423. << i << ": " << BlockNamePrinter(SNCA.NumToNode[i]) << "\n");
  424. assert((Total + 1 == Num) && "Everything should have been visited");
  425. // Step #3: If we found some non-trivial roots, make them non-redundant.
  426. if (HasNonTrivialRoots) RemoveRedundantRoots(DT, BUI, Roots);
  427. LLVM_DEBUG(dbgs() << "Found roots: ");
  428. LLVM_DEBUG(for (auto *Root
  429. : Roots) dbgs()
  430. << BlockNamePrinter(Root) << " ");
  431. LLVM_DEBUG(dbgs() << "\n");
  432. return Roots;
  433. }
  434. // This function only makes sense for postdominators.
  435. // We define roots to be some set of CFG nodes where (reverse) DFS walks have
  436. // to start in order to visit all the CFG nodes (including the
  437. // reverse-unreachable ones).
  438. // When the search for non-trivial roots is done it may happen that some of
  439. // the non-trivial roots are reverse-reachable from other non-trivial roots,
  440. // which makes them redundant. This function removes them from the set of
  441. // input roots.
  442. static void RemoveRedundantRoots(const DomTreeT &DT, BatchUpdatePtr BUI,
  443. RootsT &Roots) {
  444. assert(IsPostDom && "This function is for postdominators only");
  445. LLVM_DEBUG(dbgs() << "Removing redundant roots\n");
  446. SemiNCAInfo SNCA(BUI);
  447. for (unsigned i = 0; i < Roots.size(); ++i) {
  448. auto &Root = Roots[i];
  449. // Trivial roots are always non-redundant.
  450. if (!HasForwardSuccessors(Root, BUI)) continue;
  451. LLVM_DEBUG(dbgs() << "\tChecking if " << BlockNamePrinter(Root)
  452. << " remains a root\n");
  453. SNCA.clear();
  454. // Do a forward walk looking for the other roots.
  455. const unsigned Num = SNCA.runDFS<true>(Root, 0, AlwaysDescend, 0);
  456. // Skip the start node and begin from the second one (note that DFS uses
  457. // 1-based indexing).
  458. for (unsigned x = 2; x <= Num; ++x) {
  459. const NodePtr N = SNCA.NumToNode[x];
  460. // If we wound another root in a (forward) DFS walk, remove the current
  461. // root from the set of roots, as it is reverse-reachable from the other
  462. // one.
  463. if (llvm::is_contained(Roots, N)) {
  464. LLVM_DEBUG(dbgs() << "\tForward DFS walk found another root "
  465. << BlockNamePrinter(N) << "\n\tRemoving root "
  466. << BlockNamePrinter(Root) << "\n");
  467. std::swap(Root, Roots.back());
  468. Roots.pop_back();
  469. // Root at the back takes the current root's place.
  470. // Start the next loop iteration with the same index.
  471. --i;
  472. break;
  473. }
  474. }
  475. }
  476. }
  477. template <typename DescendCondition>
  478. void doFullDFSWalk(const DomTreeT &DT, DescendCondition DC) {
  479. if (!IsPostDom) {
  480. assert(DT.Roots.size() == 1 && "Dominators should have a singe root");
  481. runDFS(DT.Roots[0], 0, DC, 0);
  482. return;
  483. }
  484. addVirtualRoot();
  485. unsigned Num = 1;
  486. for (const NodePtr Root : DT.Roots) Num = runDFS(Root, Num, DC, 0);
  487. }
  488. static void CalculateFromScratch(DomTreeT &DT, BatchUpdatePtr BUI) {
  489. auto *Parent = DT.Parent;
  490. DT.reset();
  491. DT.Parent = Parent;
  492. // If the update is using the actual CFG, BUI is null. If it's using a view,
  493. // BUI is non-null and the PreCFGView is used. When calculating from
  494. // scratch, make the PreViewCFG equal to the PostCFGView, so Post is used.
  495. BatchUpdatePtr PostViewBUI = nullptr;
  496. if (BUI && BUI->PostViewCFG) {
  497. BUI->PreViewCFG = *BUI->PostViewCFG;
  498. PostViewBUI = BUI;
  499. }
  500. // This is rebuilding the whole tree, not incrementally, but PostViewBUI is
  501. // used in case the caller needs a DT update with a CFGView.
  502. SemiNCAInfo SNCA(PostViewBUI);
  503. // Step #0: Number blocks in depth-first order and initialize variables used
  504. // in later stages of the algorithm.
  505. DT.Roots = FindRoots(DT, PostViewBUI);
  506. SNCA.doFullDFSWalk(DT, AlwaysDescend);
  507. SNCA.runSemiNCA(DT);
  508. if (BUI) {
  509. BUI->IsRecalculated = true;
  510. LLVM_DEBUG(
  511. dbgs() << "DomTree recalculated, skipping future batch updates\n");
  512. }
  513. if (DT.Roots.empty()) return;
  514. // Add a node for the root. If the tree is a PostDominatorTree it will be
  515. // the virtual exit (denoted by (BasicBlock *) nullptr) which postdominates
  516. // all real exits (including multiple exit blocks, infinite loops).
  517. NodePtr Root = IsPostDom ? nullptr : DT.Roots[0];
  518. DT.RootNode = DT.createNode(Root);
  519. SNCA.attachNewSubtree(DT, DT.RootNode);
  520. }
  521. void attachNewSubtree(DomTreeT& DT, const TreeNodePtr AttachTo) {
  522. // Attach the first unreachable block to AttachTo.
  523. NodeToInfo[NumToNode[1]].IDom = AttachTo->getBlock();
  524. // Loop over all of the discovered blocks in the function...
  525. for (size_t i = 1, e = NumToNode.size(); i != e; ++i) {
  526. NodePtr W = NumToNode[i];
  527. // Don't replace this with 'count', the insertion side effect is important
  528. if (DT.DomTreeNodes[W]) continue; // Haven't calculated this node yet?
  529. NodePtr ImmDom = getIDom(W);
  530. // Get or calculate the node for the immediate dominator.
  531. TreeNodePtr IDomNode = getNodeForBlock(ImmDom, DT);
  532. // Add a new tree node for this BasicBlock, and link it as a child of
  533. // IDomNode.
  534. DT.createChild(W, IDomNode);
  535. }
  536. }
  537. void reattachExistingSubtree(DomTreeT &DT, const TreeNodePtr AttachTo) {
  538. NodeToInfo[NumToNode[1]].IDom = AttachTo->getBlock();
  539. for (size_t i = 1, e = NumToNode.size(); i != e; ++i) {
  540. const NodePtr N = NumToNode[i];
  541. const TreeNodePtr TN = DT.getNode(N);
  542. assert(TN);
  543. const TreeNodePtr NewIDom = DT.getNode(NodeToInfo[N].IDom);
  544. TN->setIDom(NewIDom);
  545. }
  546. }
  547. // Helper struct used during edge insertions.
  548. struct InsertionInfo {
  549. struct Compare {
  550. bool operator()(TreeNodePtr LHS, TreeNodePtr RHS) const {
  551. return LHS->getLevel() < RHS->getLevel();
  552. }
  553. };
  554. // Bucket queue of tree nodes ordered by descending level. For simplicity,
  555. // we use a priority_queue here.
  556. std::priority_queue<TreeNodePtr, SmallVector<TreeNodePtr, 8>,
  557. Compare>
  558. Bucket;
  559. SmallDenseSet<TreeNodePtr, 8> Visited;
  560. SmallVector<TreeNodePtr, 8> Affected;
  561. #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
  562. SmallVector<TreeNodePtr, 8> VisitedUnaffected;
  563. #endif
  564. };
  565. static void InsertEdge(DomTreeT &DT, const BatchUpdatePtr BUI,
  566. const NodePtr From, const NodePtr To) {
  567. assert((From || IsPostDom) &&
  568. "From has to be a valid CFG node or a virtual root");
  569. assert(To && "Cannot be a nullptr");
  570. LLVM_DEBUG(dbgs() << "Inserting edge " << BlockNamePrinter(From) << " -> "
  571. << BlockNamePrinter(To) << "\n");
  572. TreeNodePtr FromTN = DT.getNode(From);
  573. if (!FromTN) {
  574. // Ignore edges from unreachable nodes for (forward) dominators.
  575. if (!IsPostDom) return;
  576. // The unreachable node becomes a new root -- a tree node for it.
  577. TreeNodePtr VirtualRoot = DT.getNode(nullptr);
  578. FromTN = DT.createChild(From, VirtualRoot);
  579. DT.Roots.push_back(From);
  580. }
  581. DT.DFSInfoValid = false;
  582. const TreeNodePtr ToTN = DT.getNode(To);
  583. if (!ToTN)
  584. InsertUnreachable(DT, BUI, FromTN, To);
  585. else
  586. InsertReachable(DT, BUI, FromTN, ToTN);
  587. }
  588. // Determines if some existing root becomes reverse-reachable after the
  589. // insertion. Rebuilds the whole tree if that situation happens.
  590. static bool UpdateRootsBeforeInsertion(DomTreeT &DT, const BatchUpdatePtr BUI,
  591. const TreeNodePtr From,
  592. const TreeNodePtr To) {
  593. assert(IsPostDom && "This function is only for postdominators");
  594. // Destination node is not attached to the virtual root, so it cannot be a
  595. // root.
  596. if (!DT.isVirtualRoot(To->getIDom())) return false;
  597. if (!llvm::is_contained(DT.Roots, To->getBlock()))
  598. return false; // To is not a root, nothing to update.
  599. LLVM_DEBUG(dbgs() << "\t\tAfter the insertion, " << BlockNamePrinter(To)
  600. << " is no longer a root\n\t\tRebuilding the tree!!!\n");
  601. CalculateFromScratch(DT, BUI);
  602. return true;
  603. }
  604. static bool isPermutation(const SmallVectorImpl<NodePtr> &A,
  605. const SmallVectorImpl<NodePtr> &B) {
  606. if (A.size() != B.size())
  607. return false;
  608. SmallPtrSet<NodePtr, 4> Set(A.begin(), A.end());
  609. for (NodePtr N : B)
  610. if (Set.count(N) == 0)
  611. return false;
  612. return true;
  613. }
  614. // Updates the set of roots after insertion or deletion. This ensures that
  615. // roots are the same when after a series of updates and when the tree would
  616. // be built from scratch.
  617. static void UpdateRootsAfterUpdate(DomTreeT &DT, const BatchUpdatePtr BUI) {
  618. assert(IsPostDom && "This function is only for postdominators");
  619. // The tree has only trivial roots -- nothing to update.
  620. if (std::none_of(DT.Roots.begin(), DT.Roots.end(), [BUI](const NodePtr N) {
  621. return HasForwardSuccessors(N, BUI);
  622. }))
  623. return;
  624. // Recalculate the set of roots.
  625. RootsT Roots = FindRoots(DT, BUI);
  626. if (!isPermutation(DT.Roots, Roots)) {
  627. // The roots chosen in the CFG have changed. This is because the
  628. // incremental algorithm does not really know or use the set of roots and
  629. // can make a different (implicit) decision about which node within an
  630. // infinite loop becomes a root.
  631. LLVM_DEBUG(dbgs() << "Roots are different in updated trees\n"
  632. << "The entire tree needs to be rebuilt\n");
  633. // It may be possible to update the tree without recalculating it, but
  634. // we do not know yet how to do it, and it happens rarely in practice.
  635. CalculateFromScratch(DT, BUI);
  636. }
  637. }
  638. // Handles insertion to a node already in the dominator tree.
  639. static void InsertReachable(DomTreeT &DT, const BatchUpdatePtr BUI,
  640. const TreeNodePtr From, const TreeNodePtr To) {
  641. LLVM_DEBUG(dbgs() << "\tReachable " << BlockNamePrinter(From->getBlock())
  642. << " -> " << BlockNamePrinter(To->getBlock()) << "\n");
  643. if (IsPostDom && UpdateRootsBeforeInsertion(DT, BUI, From, To)) return;
  644. // DT.findNCD expects both pointers to be valid. When From is a virtual
  645. // root, then its CFG block pointer is a nullptr, so we have to 'compute'
  646. // the NCD manually.
  647. const NodePtr NCDBlock =
  648. (From->getBlock() && To->getBlock())
  649. ? DT.findNearestCommonDominator(From->getBlock(), To->getBlock())
  650. : nullptr;
  651. assert(NCDBlock || DT.isPostDominator());
  652. const TreeNodePtr NCD = DT.getNode(NCDBlock);
  653. assert(NCD);
  654. LLVM_DEBUG(dbgs() << "\t\tNCA == " << BlockNamePrinter(NCD) << "\n");
  655. const unsigned NCDLevel = NCD->getLevel();
  656. // Based on Lemma 2.5 from [2], after insertion of (From,To), v is affected
  657. // iff depth(NCD)+1 < depth(v) && a path P from To to v exists where every
  658. // w on P s.t. depth(v) <= depth(w)
  659. //
  660. // This reduces to a widest path problem (maximizing the depth of the
  661. // minimum vertex in the path) which can be solved by a modified version of
  662. // Dijkstra with a bucket queue (named depth-based search in [2]).
  663. // To is in the path, so depth(NCD)+1 < depth(v) <= depth(To). Nothing
  664. // affected if this does not hold.
  665. if (NCDLevel + 1 >= To->getLevel())
  666. return;
  667. InsertionInfo II;
  668. SmallVector<TreeNodePtr, 8> UnaffectedOnCurrentLevel;
  669. II.Bucket.push(To);
  670. II.Visited.insert(To);
  671. while (!II.Bucket.empty()) {
  672. TreeNodePtr TN = II.Bucket.top();
  673. II.Bucket.pop();
  674. II.Affected.push_back(TN);
  675. const unsigned CurrentLevel = TN->getLevel();
  676. LLVM_DEBUG(dbgs() << "Mark " << BlockNamePrinter(TN) <<
  677. "as affected, CurrentLevel " << CurrentLevel << "\n");
  678. assert(TN->getBlock() && II.Visited.count(TN) && "Preconditions!");
  679. while (true) {
  680. // Unlike regular Dijkstra, we have an inner loop to expand more
  681. // vertices. The first iteration is for the (affected) vertex popped
  682. // from II.Bucket and the rest are for vertices in
  683. // UnaffectedOnCurrentLevel, which may eventually expand to affected
  684. // vertices.
  685. //
  686. // Invariant: there is an optimal path from `To` to TN with the minimum
  687. // depth being CurrentLevel.
  688. for (const NodePtr Succ : getChildren<IsPostDom>(TN->getBlock(), BUI)) {
  689. const TreeNodePtr SuccTN = DT.getNode(Succ);
  690. assert(SuccTN &&
  691. "Unreachable successor found at reachable insertion");
  692. const unsigned SuccLevel = SuccTN->getLevel();
  693. LLVM_DEBUG(dbgs() << "\tSuccessor " << BlockNamePrinter(Succ)
  694. << ", level = " << SuccLevel << "\n");
  695. // There is an optimal path from `To` to Succ with the minimum depth
  696. // being min(CurrentLevel, SuccLevel).
  697. //
  698. // If depth(NCD)+1 < depth(Succ) is not satisfied, Succ is unaffected
  699. // and no affected vertex may be reached by a path passing through it.
  700. // Stop here. Also, Succ may be visited by other predecessors but the
  701. // first visit has the optimal path. Stop if Succ has been visited.
  702. if (SuccLevel <= NCDLevel + 1 || !II.Visited.insert(SuccTN).second)
  703. continue;
  704. if (SuccLevel > CurrentLevel) {
  705. // Succ is unaffected but it may (transitively) expand to affected
  706. // vertices. Store it in UnaffectedOnCurrentLevel.
  707. LLVM_DEBUG(dbgs() << "\t\tMarking visited not affected "
  708. << BlockNamePrinter(Succ) << "\n");
  709. UnaffectedOnCurrentLevel.push_back(SuccTN);
  710. #ifndef NDEBUG
  711. II.VisitedUnaffected.push_back(SuccTN);
  712. #endif
  713. } else {
  714. // The condition is satisfied (Succ is affected). Add Succ to the
  715. // bucket queue.
  716. LLVM_DEBUG(dbgs() << "\t\tAdd " << BlockNamePrinter(Succ)
  717. << " to a Bucket\n");
  718. II.Bucket.push(SuccTN);
  719. }
  720. }
  721. if (UnaffectedOnCurrentLevel.empty())
  722. break;
  723. TN = UnaffectedOnCurrentLevel.pop_back_val();
  724. LLVM_DEBUG(dbgs() << " Next: " << BlockNamePrinter(TN) << "\n");
  725. }
  726. }
  727. // Finish by updating immediate dominators and levels.
  728. UpdateInsertion(DT, BUI, NCD, II);
  729. }
  730. // Updates immediate dominators and levels after insertion.
  731. static void UpdateInsertion(DomTreeT &DT, const BatchUpdatePtr BUI,
  732. const TreeNodePtr NCD, InsertionInfo &II) {
  733. LLVM_DEBUG(dbgs() << "Updating NCD = " << BlockNamePrinter(NCD) << "\n");
  734. for (const TreeNodePtr TN : II.Affected) {
  735. LLVM_DEBUG(dbgs() << "\tIDom(" << BlockNamePrinter(TN)
  736. << ") = " << BlockNamePrinter(NCD) << "\n");
  737. TN->setIDom(NCD);
  738. }
  739. #if defined(LLVM_ENABLE_ABI_BREAKING_CHECKS) && !defined(NDEBUG)
  740. for (const TreeNodePtr TN : II.VisitedUnaffected)
  741. assert(TN->getLevel() == TN->getIDom()->getLevel() + 1 &&
  742. "TN should have been updated by an affected ancestor");
  743. #endif
  744. if (IsPostDom) UpdateRootsAfterUpdate(DT, BUI);
  745. }
  746. // Handles insertion to previously unreachable nodes.
  747. static void InsertUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI,
  748. const TreeNodePtr From, const NodePtr To) {
  749. LLVM_DEBUG(dbgs() << "Inserting " << BlockNamePrinter(From)
  750. << " -> (unreachable) " << BlockNamePrinter(To) << "\n");
  751. // Collect discovered edges to already reachable nodes.
  752. SmallVector<std::pair<NodePtr, TreeNodePtr>, 8> DiscoveredEdgesToReachable;
  753. // Discover and connect nodes that became reachable with the insertion.
  754. ComputeUnreachableDominators(DT, BUI, To, From, DiscoveredEdgesToReachable);
  755. LLVM_DEBUG(dbgs() << "Inserted " << BlockNamePrinter(From)
  756. << " -> (prev unreachable) " << BlockNamePrinter(To)
  757. << "\n");
  758. // Used the discovered edges and inset discovered connecting (incoming)
  759. // edges.
  760. for (const auto &Edge : DiscoveredEdgesToReachable) {
  761. LLVM_DEBUG(dbgs() << "\tInserting discovered connecting edge "
  762. << BlockNamePrinter(Edge.first) << " -> "
  763. << BlockNamePrinter(Edge.second) << "\n");
  764. InsertReachable(DT, BUI, DT.getNode(Edge.first), Edge.second);
  765. }
  766. }
  767. // Connects nodes that become reachable with an insertion.
  768. static void ComputeUnreachableDominators(
  769. DomTreeT &DT, const BatchUpdatePtr BUI, const NodePtr Root,
  770. const TreeNodePtr Incoming,
  771. SmallVectorImpl<std::pair<NodePtr, TreeNodePtr>>
  772. &DiscoveredConnectingEdges) {
  773. assert(!DT.getNode(Root) && "Root must not be reachable");
  774. // Visit only previously unreachable nodes.
  775. auto UnreachableDescender = [&DT, &DiscoveredConnectingEdges](NodePtr From,
  776. NodePtr To) {
  777. const TreeNodePtr ToTN = DT.getNode(To);
  778. if (!ToTN) return true;
  779. DiscoveredConnectingEdges.push_back({From, ToTN});
  780. return false;
  781. };
  782. SemiNCAInfo SNCA(BUI);
  783. SNCA.runDFS(Root, 0, UnreachableDescender, 0);
  784. SNCA.runSemiNCA(DT);
  785. SNCA.attachNewSubtree(DT, Incoming);
  786. LLVM_DEBUG(dbgs() << "After adding unreachable nodes\n");
  787. }
  788. static void DeleteEdge(DomTreeT &DT, const BatchUpdatePtr BUI,
  789. const NodePtr From, const NodePtr To) {
  790. assert(From && To && "Cannot disconnect nullptrs");
  791. LLVM_DEBUG(dbgs() << "Deleting edge " << BlockNamePrinter(From) << " -> "
  792. << BlockNamePrinter(To) << "\n");
  793. #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
  794. // Ensure that the edge was in fact deleted from the CFG before informing
  795. // the DomTree about it.
  796. // The check is O(N), so run it only in debug configuration.
  797. auto IsSuccessor = [BUI](const NodePtr SuccCandidate, const NodePtr Of) {
  798. auto Successors = getChildren<IsPostDom>(Of, BUI);
  799. return llvm::is_contained(Successors, SuccCandidate);
  800. };
  801. (void)IsSuccessor;
  802. assert(!IsSuccessor(To, From) && "Deleted edge still exists in the CFG!");
  803. #endif
  804. const TreeNodePtr FromTN = DT.getNode(From);
  805. // Deletion in an unreachable subtree -- nothing to do.
  806. if (!FromTN) return;
  807. const TreeNodePtr ToTN = DT.getNode(To);
  808. if (!ToTN) {
  809. LLVM_DEBUG(
  810. dbgs() << "\tTo (" << BlockNamePrinter(To)
  811. << ") already unreachable -- there is no edge to delete\n");
  812. return;
  813. }
  814. const NodePtr NCDBlock = DT.findNearestCommonDominator(From, To);
  815. const TreeNodePtr NCD = DT.getNode(NCDBlock);
  816. // If To dominates From -- nothing to do.
  817. if (ToTN != NCD) {
  818. DT.DFSInfoValid = false;
  819. const TreeNodePtr ToIDom = ToTN->getIDom();
  820. LLVM_DEBUG(dbgs() << "\tNCD " << BlockNamePrinter(NCD) << ", ToIDom "
  821. << BlockNamePrinter(ToIDom) << "\n");
  822. // To remains reachable after deletion.
  823. // (Based on the caption under Figure 4. from [2].)
  824. if (FromTN != ToIDom || HasProperSupport(DT, BUI, ToTN))
  825. DeleteReachable(DT, BUI, FromTN, ToTN);
  826. else
  827. DeleteUnreachable(DT, BUI, ToTN);
  828. }
  829. if (IsPostDom) UpdateRootsAfterUpdate(DT, BUI);
  830. }
  831. // Handles deletions that leave destination nodes reachable.
  832. static void DeleteReachable(DomTreeT &DT, const BatchUpdatePtr BUI,
  833. const TreeNodePtr FromTN,
  834. const TreeNodePtr ToTN) {
  835. LLVM_DEBUG(dbgs() << "Deleting reachable " << BlockNamePrinter(FromTN)
  836. << " -> " << BlockNamePrinter(ToTN) << "\n");
  837. LLVM_DEBUG(dbgs() << "\tRebuilding subtree\n");
  838. // Find the top of the subtree that needs to be rebuilt.
  839. // (Based on the lemma 2.6 from [2].)
  840. const NodePtr ToIDom =
  841. DT.findNearestCommonDominator(FromTN->getBlock(), ToTN->getBlock());
  842. assert(ToIDom || DT.isPostDominator());
  843. const TreeNodePtr ToIDomTN = DT.getNode(ToIDom);
  844. assert(ToIDomTN);
  845. const TreeNodePtr PrevIDomSubTree = ToIDomTN->getIDom();
  846. // Top of the subtree to rebuild is the root node. Rebuild the tree from
  847. // scratch.
  848. if (!PrevIDomSubTree) {
  849. LLVM_DEBUG(dbgs() << "The entire tree needs to be rebuilt\n");
  850. CalculateFromScratch(DT, BUI);
  851. return;
  852. }
  853. // Only visit nodes in the subtree starting at To.
  854. const unsigned Level = ToIDomTN->getLevel();
  855. auto DescendBelow = [Level, &DT](NodePtr, NodePtr To) {
  856. return DT.getNode(To)->getLevel() > Level;
  857. };
  858. LLVM_DEBUG(dbgs() << "\tTop of subtree: " << BlockNamePrinter(ToIDomTN)
  859. << "\n");
  860. SemiNCAInfo SNCA(BUI);
  861. SNCA.runDFS(ToIDom, 0, DescendBelow, 0);
  862. LLVM_DEBUG(dbgs() << "\tRunning Semi-NCA\n");
  863. SNCA.runSemiNCA(DT, Level);
  864. SNCA.reattachExistingSubtree(DT, PrevIDomSubTree);
  865. }
  866. // Checks if a node has proper support, as defined on the page 3 and later
  867. // explained on the page 7 of [2].
  868. static bool HasProperSupport(DomTreeT &DT, const BatchUpdatePtr BUI,
  869. const TreeNodePtr TN) {
  870. LLVM_DEBUG(dbgs() << "IsReachableFromIDom " << BlockNamePrinter(TN)
  871. << "\n");
  872. auto TNB = TN->getBlock();
  873. for (const NodePtr Pred : getChildren<!IsPostDom>(TNB, BUI)) {
  874. LLVM_DEBUG(dbgs() << "\tPred " << BlockNamePrinter(Pred) << "\n");
  875. if (!DT.getNode(Pred)) continue;
  876. const NodePtr Support = DT.findNearestCommonDominator(TNB, Pred);
  877. LLVM_DEBUG(dbgs() << "\tSupport " << BlockNamePrinter(Support) << "\n");
  878. if (Support != TNB) {
  879. LLVM_DEBUG(dbgs() << "\t" << BlockNamePrinter(TN)
  880. << " is reachable from support "
  881. << BlockNamePrinter(Support) << "\n");
  882. return true;
  883. }
  884. }
  885. return false;
  886. }
  887. // Handle deletions that make destination node unreachable.
  888. // (Based on the lemma 2.7 from the [2].)
  889. static void DeleteUnreachable(DomTreeT &DT, const BatchUpdatePtr BUI,
  890. const TreeNodePtr ToTN) {
  891. LLVM_DEBUG(dbgs() << "Deleting unreachable subtree "
  892. << BlockNamePrinter(ToTN) << "\n");
  893. assert(ToTN);
  894. assert(ToTN->getBlock());
  895. if (IsPostDom) {
  896. // Deletion makes a region reverse-unreachable and creates a new root.
  897. // Simulate that by inserting an edge from the virtual root to ToTN and
  898. // adding it as a new root.
  899. LLVM_DEBUG(dbgs() << "\tDeletion made a region reverse-unreachable\n");
  900. LLVM_DEBUG(dbgs() << "\tAdding new root " << BlockNamePrinter(ToTN)
  901. << "\n");
  902. DT.Roots.push_back(ToTN->getBlock());
  903. InsertReachable(DT, BUI, DT.getNode(nullptr), ToTN);
  904. return;
  905. }
  906. SmallVector<NodePtr, 16> AffectedQueue;
  907. const unsigned Level = ToTN->getLevel();
  908. // Traverse destination node's descendants with greater level in the tree
  909. // and collect visited nodes.
  910. auto DescendAndCollect = [Level, &AffectedQueue, &DT](NodePtr, NodePtr To) {
  911. const TreeNodePtr TN = DT.getNode(To);
  912. assert(TN);
  913. if (TN->getLevel() > Level) return true;
  914. if (!llvm::is_contained(AffectedQueue, To))
  915. AffectedQueue.push_back(To);
  916. return false;
  917. };
  918. SemiNCAInfo SNCA(BUI);
  919. unsigned LastDFSNum =
  920. SNCA.runDFS(ToTN->getBlock(), 0, DescendAndCollect, 0);
  921. TreeNodePtr MinNode = ToTN;
  922. // Identify the top of the subtree to rebuild by finding the NCD of all
  923. // the affected nodes.
  924. for (const NodePtr N : AffectedQueue) {
  925. const TreeNodePtr TN = DT.getNode(N);
  926. const NodePtr NCDBlock =
  927. DT.findNearestCommonDominator(TN->getBlock(), ToTN->getBlock());
  928. assert(NCDBlock || DT.isPostDominator());
  929. const TreeNodePtr NCD = DT.getNode(NCDBlock);
  930. assert(NCD);
  931. LLVM_DEBUG(dbgs() << "Processing affected node " << BlockNamePrinter(TN)
  932. << " with NCD = " << BlockNamePrinter(NCD)
  933. << ", MinNode =" << BlockNamePrinter(MinNode) << "\n");
  934. if (NCD != TN && NCD->getLevel() < MinNode->getLevel()) MinNode = NCD;
  935. }
  936. // Root reached, rebuild the whole tree from scratch.
  937. if (!MinNode->getIDom()) {
  938. LLVM_DEBUG(dbgs() << "The entire tree needs to be rebuilt\n");
  939. CalculateFromScratch(DT, BUI);
  940. return;
  941. }
  942. // Erase the unreachable subtree in reverse preorder to process all children
  943. // before deleting their parent.
  944. for (unsigned i = LastDFSNum; i > 0; --i) {
  945. const NodePtr N = SNCA.NumToNode[i];
  946. const TreeNodePtr TN = DT.getNode(N);
  947. LLVM_DEBUG(dbgs() << "Erasing node " << BlockNamePrinter(TN) << "\n");
  948. EraseNode(DT, TN);
  949. }
  950. // The affected subtree start at the To node -- there's no extra work to do.
  951. if (MinNode == ToTN) return;
  952. LLVM_DEBUG(dbgs() << "DeleteUnreachable: running DFS with MinNode = "
  953. << BlockNamePrinter(MinNode) << "\n");
  954. const unsigned MinLevel = MinNode->getLevel();
  955. const TreeNodePtr PrevIDom = MinNode->getIDom();
  956. assert(PrevIDom);
  957. SNCA.clear();
  958. // Identify nodes that remain in the affected subtree.
  959. auto DescendBelow = [MinLevel, &DT](NodePtr, NodePtr To) {
  960. const TreeNodePtr ToTN = DT.getNode(To);
  961. return ToTN && ToTN->getLevel() > MinLevel;
  962. };
  963. SNCA.runDFS(MinNode->getBlock(), 0, DescendBelow, 0);
  964. LLVM_DEBUG(dbgs() << "Previous IDom(MinNode) = "
  965. << BlockNamePrinter(PrevIDom) << "\nRunning Semi-NCA\n");
  966. // Rebuild the remaining part of affected subtree.
  967. SNCA.runSemiNCA(DT, MinLevel);
  968. SNCA.reattachExistingSubtree(DT, PrevIDom);
  969. }
  970. // Removes leaf tree nodes from the dominator tree.
  971. static void EraseNode(DomTreeT &DT, const TreeNodePtr TN) {
  972. assert(TN);
  973. assert(TN->getNumChildren() == 0 && "Not a tree leaf");
  974. const TreeNodePtr IDom = TN->getIDom();
  975. assert(IDom);
  976. auto ChIt = llvm::find(IDom->Children, TN);
  977. assert(ChIt != IDom->Children.end());
  978. std::swap(*ChIt, IDom->Children.back());
  979. IDom->Children.pop_back();
  980. DT.DomTreeNodes.erase(TN->getBlock());
  981. }
  982. //~~
  983. //===--------------------- DomTree Batch Updater --------------------------===
  984. //~~
  985. static void ApplyUpdates(DomTreeT &DT, GraphDiffT &PreViewCFG,
  986. GraphDiffT *PostViewCFG) {
  987. // Note: the PostViewCFG is only used when computing from scratch. It's data
  988. // should already included in the PreViewCFG for incremental updates.
  989. const size_t NumUpdates = PreViewCFG.getNumLegalizedUpdates();
  990. if (NumUpdates == 0)
  991. return;
  992. // Take the fast path for a single update and avoid running the batch update
  993. // machinery.
  994. if (NumUpdates == 1) {
  995. UpdateT Update = PreViewCFG.popUpdateForIncrementalUpdates();
  996. if (!PostViewCFG) {
  997. if (Update.getKind() == UpdateKind::Insert)
  998. InsertEdge(DT, /*BUI=*/nullptr, Update.getFrom(), Update.getTo());
  999. else
  1000. DeleteEdge(DT, /*BUI=*/nullptr, Update.getFrom(), Update.getTo());
  1001. } else {
  1002. BatchUpdateInfo BUI(*PostViewCFG, PostViewCFG);
  1003. if (Update.getKind() == UpdateKind::Insert)
  1004. InsertEdge(DT, &BUI, Update.getFrom(), Update.getTo());
  1005. else
  1006. DeleteEdge(DT, &BUI, Update.getFrom(), Update.getTo());
  1007. }
  1008. return;
  1009. }
  1010. BatchUpdateInfo BUI(PreViewCFG, PostViewCFG);
  1011. // Recalculate the DominatorTree when the number of updates
  1012. // exceeds a threshold, which usually makes direct updating slower than
  1013. // recalculation. We select this threshold proportional to the
  1014. // size of the DominatorTree. The constant is selected
  1015. // by choosing the one with an acceptable performance on some real-world
  1016. // inputs.
  1017. // Make unittests of the incremental algorithm work
  1018. if (DT.DomTreeNodes.size() <= 100) {
  1019. if (BUI.NumLegalized > DT.DomTreeNodes.size())
  1020. CalculateFromScratch(DT, &BUI);
  1021. } else if (BUI.NumLegalized > DT.DomTreeNodes.size() / 40)
  1022. CalculateFromScratch(DT, &BUI);
  1023. // If the DominatorTree was recalculated at some point, stop the batch
  1024. // updates. Full recalculations ignore batch updates and look at the actual
  1025. // CFG.
  1026. for (size_t i = 0; i < BUI.NumLegalized && !BUI.IsRecalculated; ++i)
  1027. ApplyNextUpdate(DT, BUI);
  1028. }
  1029. static void ApplyNextUpdate(DomTreeT &DT, BatchUpdateInfo &BUI) {
  1030. // Popping the next update, will move the PreViewCFG to the next snapshot.
  1031. UpdateT CurrentUpdate = BUI.PreViewCFG.popUpdateForIncrementalUpdates();
  1032. #if 0
  1033. // FIXME: The LLVM_DEBUG macro only plays well with a modular
  1034. // build of LLVM when the header is marked as textual, but doing
  1035. // so causes redefinition errors.
  1036. LLVM_DEBUG(dbgs() << "Applying update: ");
  1037. LLVM_DEBUG(CurrentUpdate.dump(); dbgs() << "\n");
  1038. #endif
  1039. if (CurrentUpdate.getKind() == UpdateKind::Insert)
  1040. InsertEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
  1041. else
  1042. DeleteEdge(DT, &BUI, CurrentUpdate.getFrom(), CurrentUpdate.getTo());
  1043. }
  1044. //~~
  1045. //===--------------- DomTree correctness verification ---------------------===
  1046. //~~
  1047. // Check if the tree has correct roots. A DominatorTree always has a single
  1048. // root which is the function's entry node. A PostDominatorTree can have
  1049. // multiple roots - one for each node with no successors and for infinite
  1050. // loops.
  1051. // Running time: O(N).
  1052. bool verifyRoots(const DomTreeT &DT) {
  1053. if (!DT.Parent && !DT.Roots.empty()) {
  1054. errs() << "Tree has no parent but has roots!\n";
  1055. errs().flush();
  1056. return false;
  1057. }
  1058. if (!IsPostDom) {
  1059. if (DT.Roots.empty()) {
  1060. errs() << "Tree doesn't have a root!\n";
  1061. errs().flush();
  1062. return false;
  1063. }
  1064. if (DT.getRoot() != GetEntryNode(DT)) {
  1065. errs() << "Tree's root is not its parent's entry node!\n";
  1066. errs().flush();
  1067. return false;
  1068. }
  1069. }
  1070. RootsT ComputedRoots = FindRoots(DT, nullptr);
  1071. if (!isPermutation(DT.Roots, ComputedRoots)) {
  1072. errs() << "Tree has different roots than freshly computed ones!\n";
  1073. errs() << "\tPDT roots: ";
  1074. for (const NodePtr N : DT.Roots) errs() << BlockNamePrinter(N) << ", ";
  1075. errs() << "\n\tComputed roots: ";
  1076. for (const NodePtr N : ComputedRoots)
  1077. errs() << BlockNamePrinter(N) << ", ";
  1078. errs() << "\n";
  1079. errs().flush();
  1080. return false;
  1081. }
  1082. return true;
  1083. }
  1084. // Checks if the tree contains all reachable nodes in the input graph.
  1085. // Running time: O(N).
  1086. bool verifyReachability(const DomTreeT &DT) {
  1087. clear();
  1088. doFullDFSWalk(DT, AlwaysDescend);
  1089. for (auto &NodeToTN : DT.DomTreeNodes) {
  1090. const TreeNodePtr TN = NodeToTN.second.get();
  1091. const NodePtr BB = TN->getBlock();
  1092. // Virtual root has a corresponding virtual CFG node.
  1093. if (DT.isVirtualRoot(TN)) continue;
  1094. if (NodeToInfo.count(BB) == 0) {
  1095. errs() << "DomTree node " << BlockNamePrinter(BB)
  1096. << " not found by DFS walk!\n";
  1097. errs().flush();
  1098. return false;
  1099. }
  1100. }
  1101. for (const NodePtr N : NumToNode) {
  1102. if (N && !DT.getNode(N)) {
  1103. errs() << "CFG node " << BlockNamePrinter(N)
  1104. << " not found in the DomTree!\n";
  1105. errs().flush();
  1106. return false;
  1107. }
  1108. }
  1109. return true;
  1110. }
  1111. // Check if for every parent with a level L in the tree all of its children
  1112. // have level L + 1.
  1113. // Running time: O(N).
  1114. static bool VerifyLevels(const DomTreeT &DT) {
  1115. for (auto &NodeToTN : DT.DomTreeNodes) {
  1116. const TreeNodePtr TN = NodeToTN.second.get();
  1117. const NodePtr BB = TN->getBlock();
  1118. if (!BB) continue;
  1119. const TreeNodePtr IDom = TN->getIDom();
  1120. if (!IDom && TN->getLevel() != 0) {
  1121. errs() << "Node without an IDom " << BlockNamePrinter(BB)
  1122. << " has a nonzero level " << TN->getLevel() << "!\n";
  1123. errs().flush();
  1124. return false;
  1125. }
  1126. if (IDom && TN->getLevel() != IDom->getLevel() + 1) {
  1127. errs() << "Node " << BlockNamePrinter(BB) << " has level "
  1128. << TN->getLevel() << " while its IDom "
  1129. << BlockNamePrinter(IDom->getBlock()) << " has level "
  1130. << IDom->getLevel() << "!\n";
  1131. errs().flush();
  1132. return false;
  1133. }
  1134. }
  1135. return true;
  1136. }
  1137. // Check if the computed DFS numbers are correct. Note that DFS info may not
  1138. // be valid, and when that is the case, we don't verify the numbers.
  1139. // Running time: O(N log(N)).
  1140. static bool VerifyDFSNumbers(const DomTreeT &DT) {
  1141. if (!DT.DFSInfoValid || !DT.Parent)
  1142. return true;
  1143. const NodePtr RootBB = IsPostDom ? nullptr : *DT.root_begin();
  1144. const TreeNodePtr Root = DT.getNode(RootBB);
  1145. auto PrintNodeAndDFSNums = [](const TreeNodePtr TN) {
  1146. errs() << BlockNamePrinter(TN) << " {" << TN->getDFSNumIn() << ", "
  1147. << TN->getDFSNumOut() << '}';
  1148. };
  1149. // Verify the root's DFS In number. Although DFS numbering would also work
  1150. // if we started from some other value, we assume 0-based numbering.
  1151. if (Root->getDFSNumIn() != 0) {
  1152. errs() << "DFSIn number for the tree root is not:\n\t";
  1153. PrintNodeAndDFSNums(Root);
  1154. errs() << '\n';
  1155. errs().flush();
  1156. return false;
  1157. }
  1158. // For each tree node verify if children's DFS numbers cover their parent's
  1159. // DFS numbers with no gaps.
  1160. for (const auto &NodeToTN : DT.DomTreeNodes) {
  1161. const TreeNodePtr Node = NodeToTN.second.get();
  1162. // Handle tree leaves.
  1163. if (Node->isLeaf()) {
  1164. if (Node->getDFSNumIn() + 1 != Node->getDFSNumOut()) {
  1165. errs() << "Tree leaf should have DFSOut = DFSIn + 1:\n\t";
  1166. PrintNodeAndDFSNums(Node);
  1167. errs() << '\n';
  1168. errs().flush();
  1169. return false;
  1170. }
  1171. continue;
  1172. }
  1173. // Make a copy and sort it such that it is possible to check if there are
  1174. // no gaps between DFS numbers of adjacent children.
  1175. SmallVector<TreeNodePtr, 8> Children(Node->begin(), Node->end());
  1176. llvm::sort(Children, [](const TreeNodePtr Ch1, const TreeNodePtr Ch2) {
  1177. return Ch1->getDFSNumIn() < Ch2->getDFSNumIn();
  1178. });
  1179. auto PrintChildrenError = [Node, &Children, PrintNodeAndDFSNums](
  1180. const TreeNodePtr FirstCh, const TreeNodePtr SecondCh) {
  1181. assert(FirstCh);
  1182. errs() << "Incorrect DFS numbers for:\n\tParent ";
  1183. PrintNodeAndDFSNums(Node);
  1184. errs() << "\n\tChild ";
  1185. PrintNodeAndDFSNums(FirstCh);
  1186. if (SecondCh) {
  1187. errs() << "\n\tSecond child ";
  1188. PrintNodeAndDFSNums(SecondCh);
  1189. }
  1190. errs() << "\nAll children: ";
  1191. for (const TreeNodePtr Ch : Children) {
  1192. PrintNodeAndDFSNums(Ch);
  1193. errs() << ", ";
  1194. }
  1195. errs() << '\n';
  1196. errs().flush();
  1197. };
  1198. if (Children.front()->getDFSNumIn() != Node->getDFSNumIn() + 1) {
  1199. PrintChildrenError(Children.front(), nullptr);
  1200. return false;
  1201. }
  1202. if (Children.back()->getDFSNumOut() + 1 != Node->getDFSNumOut()) {
  1203. PrintChildrenError(Children.back(), nullptr);
  1204. return false;
  1205. }
  1206. for (size_t i = 0, e = Children.size() - 1; i != e; ++i) {
  1207. if (Children[i]->getDFSNumOut() + 1 != Children[i + 1]->getDFSNumIn()) {
  1208. PrintChildrenError(Children[i], Children[i + 1]);
  1209. return false;
  1210. }
  1211. }
  1212. }
  1213. return true;
  1214. }
  1215. // The below routines verify the correctness of the dominator tree relative to
  1216. // the CFG it's coming from. A tree is a dominator tree iff it has two
  1217. // properties, called the parent property and the sibling property. Tarjan
  1218. // and Lengauer prove (but don't explicitly name) the properties as part of
  1219. // the proofs in their 1972 paper, but the proofs are mostly part of proving
  1220. // things about semidominators and idoms, and some of them are simply asserted
  1221. // based on even earlier papers (see, e.g., lemma 2). Some papers refer to
  1222. // these properties as "valid" and "co-valid". See, e.g., "Dominators,
  1223. // directed bipolar orders, and independent spanning trees" by Loukas
  1224. // Georgiadis and Robert E. Tarjan, as well as "Dominator Tree Verification
  1225. // and Vertex-Disjoint Paths " by the same authors.
  1226. // A very simple and direct explanation of these properties can be found in
  1227. // "An Experimental Study of Dynamic Dominators", found at
  1228. // https://arxiv.org/abs/1604.02711
  1229. // The easiest way to think of the parent property is that it's a requirement
  1230. // of being a dominator. Let's just take immediate dominators. For PARENT to
  1231. // be an immediate dominator of CHILD, all paths in the CFG must go through
  1232. // PARENT before they hit CHILD. This implies that if you were to cut PARENT
  1233. // out of the CFG, there should be no paths to CHILD that are reachable. If
  1234. // there are, then you now have a path from PARENT to CHILD that goes around
  1235. // PARENT and still reaches CHILD, which by definition, means PARENT can't be
  1236. // a dominator of CHILD (let alone an immediate one).
  1237. // The sibling property is similar. It says that for each pair of sibling
  1238. // nodes in the dominator tree (LEFT and RIGHT) , they must not dominate each
  1239. // other. If sibling LEFT dominated sibling RIGHT, it means there are no
  1240. // paths in the CFG from sibling LEFT to sibling RIGHT that do not go through
  1241. // LEFT, and thus, LEFT is really an ancestor (in the dominator tree) of
  1242. // RIGHT, not a sibling.
  1243. // It is possible to verify the parent and sibling properties in linear time,
  1244. // but the algorithms are complex. Instead, we do it in a straightforward
  1245. // N^2 and N^3 way below, using direct path reachability.
  1246. // Checks if the tree has the parent property: if for all edges from V to W in
  1247. // the input graph, such that V is reachable, the parent of W in the tree is
  1248. // an ancestor of V in the tree.
  1249. // Running time: O(N^2).
  1250. //
  1251. // This means that if a node gets disconnected from the graph, then all of
  1252. // the nodes it dominated previously will now become unreachable.
  1253. bool verifyParentProperty(const DomTreeT &DT) {
  1254. for (auto &NodeToTN : DT.DomTreeNodes) {
  1255. const TreeNodePtr TN = NodeToTN.second.get();
  1256. const NodePtr BB = TN->getBlock();
  1257. if (!BB || TN->isLeaf())
  1258. continue;
  1259. LLVM_DEBUG(dbgs() << "Verifying parent property of node "
  1260. << BlockNamePrinter(TN) << "\n");
  1261. clear();
  1262. doFullDFSWalk(DT, [BB](NodePtr From, NodePtr To) {
  1263. return From != BB && To != BB;
  1264. });
  1265. for (TreeNodePtr Child : TN->children())
  1266. if (NodeToInfo.count(Child->getBlock()) != 0) {
  1267. errs() << "Child " << BlockNamePrinter(Child)
  1268. << " reachable after its parent " << BlockNamePrinter(BB)
  1269. << " is removed!\n";
  1270. errs().flush();
  1271. return false;
  1272. }
  1273. }
  1274. return true;
  1275. }
  1276. // Check if the tree has sibling property: if a node V does not dominate a
  1277. // node W for all siblings V and W in the tree.
  1278. // Running time: O(N^3).
  1279. //
  1280. // This means that if a node gets disconnected from the graph, then all of its
  1281. // siblings will now still be reachable.
  1282. bool verifySiblingProperty(const DomTreeT &DT) {
  1283. for (auto &NodeToTN : DT.DomTreeNodes) {
  1284. const TreeNodePtr TN = NodeToTN.second.get();
  1285. const NodePtr BB = TN->getBlock();
  1286. if (!BB || TN->isLeaf())
  1287. continue;
  1288. for (const TreeNodePtr N : TN->children()) {
  1289. clear();
  1290. NodePtr BBN = N->getBlock();
  1291. doFullDFSWalk(DT, [BBN](NodePtr From, NodePtr To) {
  1292. return From != BBN && To != BBN;
  1293. });
  1294. for (const TreeNodePtr S : TN->children()) {
  1295. if (S == N) continue;
  1296. if (NodeToInfo.count(S->getBlock()) == 0) {
  1297. errs() << "Node " << BlockNamePrinter(S)
  1298. << " not reachable when its sibling " << BlockNamePrinter(N)
  1299. << " is removed!\n";
  1300. errs().flush();
  1301. return false;
  1302. }
  1303. }
  1304. }
  1305. }
  1306. return true;
  1307. }
  1308. // Check if the given tree is the same as a freshly computed one for the same
  1309. // Parent.
  1310. // Running time: O(N^2), but faster in practice (same as tree construction).
  1311. //
  1312. // Note that this does not check if that the tree construction algorithm is
  1313. // correct and should be only used for fast (but possibly unsound)
  1314. // verification.
  1315. static bool IsSameAsFreshTree(const DomTreeT &DT) {
  1316. DomTreeT FreshTree;
  1317. FreshTree.recalculate(*DT.Parent);
  1318. const bool Different = DT.compare(FreshTree);
  1319. if (Different) {
  1320. errs() << (DT.isPostDominator() ? "Post" : "")
  1321. << "DominatorTree is different than a freshly computed one!\n"
  1322. << "\tCurrent:\n";
  1323. DT.print(errs());
  1324. errs() << "\n\tFreshly computed tree:\n";
  1325. FreshTree.print(errs());
  1326. errs().flush();
  1327. }
  1328. return !Different;
  1329. }
  1330. };
  1331. template <class DomTreeT>
  1332. void Calculate(DomTreeT &DT) {
  1333. SemiNCAInfo<DomTreeT>::CalculateFromScratch(DT, nullptr);
  1334. }
  1335. template <typename DomTreeT>
  1336. void CalculateWithUpdates(DomTreeT &DT,
  1337. ArrayRef<typename DomTreeT::UpdateType> Updates) {
  1338. // FIXME: Updated to use the PreViewCFG and behave the same as until now.
  1339. // This behavior is however incorrect; this actually needs the PostViewCFG.
  1340. GraphDiff<typename DomTreeT::NodePtr, DomTreeT::IsPostDominator> PreViewCFG(
  1341. Updates, /*ReverseApplyUpdates=*/true);
  1342. typename SemiNCAInfo<DomTreeT>::BatchUpdateInfo BUI(PreViewCFG);
  1343. SemiNCAInfo<DomTreeT>::CalculateFromScratch(DT, &BUI);
  1344. }
  1345. template <class DomTreeT>
  1346. void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
  1347. typename DomTreeT::NodePtr To) {
  1348. if (DT.isPostDominator()) std::swap(From, To);
  1349. SemiNCAInfo<DomTreeT>::InsertEdge(DT, nullptr, From, To);
  1350. }
  1351. template <class DomTreeT>
  1352. void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From,
  1353. typename DomTreeT::NodePtr To) {
  1354. if (DT.isPostDominator()) std::swap(From, To);
  1355. SemiNCAInfo<DomTreeT>::DeleteEdge(DT, nullptr, From, To);
  1356. }
  1357. template <class DomTreeT>
  1358. void ApplyUpdates(DomTreeT &DT,
  1359. GraphDiff<typename DomTreeT::NodePtr,
  1360. DomTreeT::IsPostDominator> &PreViewCFG,
  1361. GraphDiff<typename DomTreeT::NodePtr,
  1362. DomTreeT::IsPostDominator> *PostViewCFG) {
  1363. SemiNCAInfo<DomTreeT>::ApplyUpdates(DT, PreViewCFG, PostViewCFG);
  1364. }
  1365. template <class DomTreeT>
  1366. bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL) {
  1367. SemiNCAInfo<DomTreeT> SNCA(nullptr);
  1368. // Simplist check is to compare against a new tree. This will also
  1369. // usefully print the old and new trees, if they are different.
  1370. if (!SNCA.IsSameAsFreshTree(DT))
  1371. return false;
  1372. // Common checks to verify the properties of the tree. O(N log N) at worst.
  1373. if (!SNCA.verifyRoots(DT) || !SNCA.verifyReachability(DT) ||
  1374. !SNCA.VerifyLevels(DT) || !SNCA.VerifyDFSNumbers(DT))
  1375. return false;
  1376. // Extra checks depending on VerificationLevel. Up to O(N^3).
  1377. if (VL == DomTreeT::VerificationLevel::Basic ||
  1378. VL == DomTreeT::VerificationLevel::Full)
  1379. if (!SNCA.verifyParentProperty(DT))
  1380. return false;
  1381. if (VL == DomTreeT::VerificationLevel::Full)
  1382. if (!SNCA.verifySiblingProperty(DT))
  1383. return false;
  1384. return true;
  1385. }
  1386. } // namespace DomTreeBuilder
  1387. } // namespace llvm
  1388. #undef DEBUG_TYPE
  1389. #endif
  1390. #ifdef __GNUC__
  1391. #pragma GCC diagnostic pop
  1392. #endif