GenericDomTree.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. //===- GenericDomTree.h - Generic dominator trees for graphs ----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. ///
  11. /// This file defines a set of templates that efficiently compute a dominator
  12. /// tree over a generic graph. This is used typically in LLVM for fast
  13. /// dominance queries on the CFG, but is fully generic w.r.t. the underlying
  14. /// graph types.
  15. ///
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_SUPPORT_GENERICDOMTREE_H
  18. #define LLVM_SUPPORT_GENERICDOMTREE_H
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/DepthFirstIterator.h"
  21. #include "llvm/ADT/GraphTraits.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/Support/Compiler.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm>
  28. namespace llvm {
  29. /// \brief Base class that other, more interesting dominator analyses
  30. /// inherit from.
  31. template <class NodeT> class DominatorBase {
  32. protected:
  33. std::vector<NodeT *> Roots;
  34. bool IsPostDominators;
  35. explicit DominatorBase(bool isPostDom)
  36. : Roots(), IsPostDominators(isPostDom) {}
  37. DominatorBase(DominatorBase &&Arg)
  38. : Roots(std::move(Arg.Roots)),
  39. IsPostDominators(std::move(Arg.IsPostDominators)) {
  40. Arg.Roots.clear();
  41. }
  42. DominatorBase &operator=(DominatorBase &&RHS) {
  43. Roots = std::move(RHS.Roots);
  44. IsPostDominators = std::move(RHS.IsPostDominators);
  45. RHS.Roots.clear();
  46. return *this;
  47. }
  48. public:
  49. /// getRoots - Return the root blocks of the current CFG. This may include
  50. /// multiple blocks if we are computing post dominators. For forward
  51. /// dominators, this will always be a single block (the entry node).
  52. ///
  53. const std::vector<NodeT *> &getRoots() const { return Roots; }
  54. /// isPostDominator - Returns true if analysis based of postdoms
  55. ///
  56. bool isPostDominator() const { return IsPostDominators; }
  57. };
  58. template <class NodeT> class DominatorTreeBase;
  59. struct PostDominatorTree;
  60. /// \brief Base class for the actual dominator tree node.
  61. template <class NodeT> class DomTreeNodeBase {
  62. NodeT *TheBB;
  63. DomTreeNodeBase<NodeT> *IDom;
  64. std::vector<DomTreeNodeBase<NodeT> *> Children;
  65. mutable int DFSNumIn, DFSNumOut;
  66. template <class N> friend class DominatorTreeBase;
  67. friend struct PostDominatorTree;
  68. public:
  69. typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
  70. typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
  71. const_iterator;
  72. iterator begin() { return Children.begin(); }
  73. iterator end() { return Children.end(); }
  74. const_iterator begin() const { return Children.begin(); }
  75. const_iterator end() const { return Children.end(); }
  76. NodeT *getBlock() const { return TheBB; }
  77. DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
  78. const std::vector<DomTreeNodeBase<NodeT> *> &getChildren() const {
  79. return Children;
  80. }
  81. DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
  82. : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) {}
  83. std::unique_ptr<DomTreeNodeBase<NodeT>>
  84. addChild(std::unique_ptr<DomTreeNodeBase<NodeT>> C) {
  85. Children.push_back(C.get());
  86. return C;
  87. }
  88. size_t getNumChildren() const { return Children.size(); }
  89. void clearAllChildren() { Children.clear(); }
  90. bool compare(const DomTreeNodeBase<NodeT> *Other) const {
  91. if (getNumChildren() != Other->getNumChildren())
  92. return true;
  93. SmallPtrSet<const NodeT *, 4> OtherChildren;
  94. for (const_iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
  95. const NodeT *Nd = (*I)->getBlock();
  96. OtherChildren.insert(Nd);
  97. }
  98. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  99. const NodeT *N = (*I)->getBlock();
  100. if (OtherChildren.count(N) == 0)
  101. return true;
  102. }
  103. return false;
  104. }
  105. void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
  106. assert(IDom && "No immediate dominator?");
  107. if (IDom != NewIDom) {
  108. typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
  109. std::find(IDom->Children.begin(), IDom->Children.end(), this);
  110. assert(I != IDom->Children.end() &&
  111. "Not in immediate dominator children set!");
  112. // I am no longer your child...
  113. IDom->Children.erase(I);
  114. // Switch to new dominator
  115. IDom = NewIDom;
  116. IDom->Children.push_back(this);
  117. }
  118. }
  119. /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
  120. /// not call them.
  121. unsigned getDFSNumIn() const { return DFSNumIn; }
  122. unsigned getDFSNumOut() const { return DFSNumOut; }
  123. private:
  124. // Return true if this node is dominated by other. Use this only if DFS info
  125. // is valid.
  126. bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
  127. return this->DFSNumIn >= other->DFSNumIn &&
  128. this->DFSNumOut <= other->DFSNumOut;
  129. }
  130. };
  131. template <class NodeT>
  132. raw_ostream &operator<<(raw_ostream &o, const DomTreeNodeBase<NodeT> *Node) {
  133. if (Node->getBlock())
  134. Node->getBlock()->printAsOperand(o, false);
  135. else
  136. o << " <<exit node>>";
  137. o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
  138. return o << "\n";
  139. }
  140. template <class NodeT>
  141. void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
  142. unsigned Lev) {
  143. o.indent(2 * Lev) << "[" << Lev << "] " << N;
  144. for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
  145. E = N->end();
  146. I != E; ++I)
  147. PrintDomTree<NodeT>(*I, o, Lev + 1);
  148. }
  149. // The calculate routine is provided in a separate header but referenced here.
  150. template <class FuncT, class N>
  151. void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType> &DT,
  152. FuncT &F);
  153. /// \brief Core dominator tree base class.
  154. ///
  155. /// This class is a generic template over graph nodes. It is instantiated for
  156. /// various graphs in the LLVM IR or in the code generator.
  157. template <class NodeT> class DominatorTreeBase : public DominatorBase<NodeT> {
  158. DominatorTreeBase(const DominatorTreeBase &) = delete;
  159. DominatorTreeBase &operator=(const DominatorTreeBase &) = delete;
  160. bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
  161. const DomTreeNodeBase<NodeT> *B) const {
  162. assert(A != B);
  163. assert(isReachableFromEntry(B));
  164. assert(isReachableFromEntry(A));
  165. const DomTreeNodeBase<NodeT> *IDom;
  166. while ((IDom = B->getIDom()) != nullptr && IDom != A && IDom != B)
  167. B = IDom; // Walk up the tree
  168. return IDom != nullptr;
  169. }
  170. /// \brief Wipe this tree's state without releasing any resources.
  171. ///
  172. /// This is essentially a post-move helper only. It leaves the object in an
  173. /// assignable and destroyable state, but otherwise invalid.
  174. void wipe() {
  175. DomTreeNodes.clear();
  176. IDoms.clear();
  177. Vertex.clear();
  178. Info.clear();
  179. RootNode = nullptr;
  180. }
  181. protected:
  182. typedef DenseMap<NodeT *, std::unique_ptr<DomTreeNodeBase<NodeT>>>
  183. DomTreeNodeMapType;
  184. DomTreeNodeMapType DomTreeNodes;
  185. DomTreeNodeBase<NodeT> *RootNode;
  186. mutable bool DFSInfoValid;
  187. mutable unsigned int SlowQueries;
  188. // Information record used during immediate dominators computation.
  189. struct InfoRec {
  190. unsigned DFSNum;
  191. unsigned Parent;
  192. unsigned Semi;
  193. NodeT *Label;
  194. InfoRec() : DFSNum(0), Parent(0), Semi(0), Label(nullptr) {}
  195. };
  196. DenseMap<NodeT *, NodeT *> IDoms;
  197. // Vertex - Map the DFS number to the NodeT*
  198. std::vector<NodeT *> Vertex;
  199. // Info - Collection of information used during the computation of idoms.
  200. DenseMap<NodeT *, InfoRec> Info;
  201. void reset() {
  202. DomTreeNodes.clear();
  203. IDoms.clear();
  204. this->Roots.clear();
  205. Vertex.clear();
  206. RootNode = nullptr;
  207. DFSInfoValid = false;
  208. SlowQueries = 0;
  209. }
  210. // NewBB is split and now it has one successor. Update dominator tree to
  211. // reflect this change.
  212. template <class N, class GraphT>
  213. void Split(DominatorTreeBase<typename GraphT::NodeType> &DT,
  214. typename GraphT::NodeType *NewBB) {
  215. assert(std::distance(GraphT::child_begin(NewBB),
  216. GraphT::child_end(NewBB)) == 1 &&
  217. "NewBB should have a single successor!");
  218. typename GraphT::NodeType *NewBBSucc = *GraphT::child_begin(NewBB);
  219. std::vector<typename GraphT::NodeType *> PredBlocks;
  220. typedef GraphTraits<Inverse<N>> InvTraits;
  221. for (typename InvTraits::ChildIteratorType
  222. PI = InvTraits::child_begin(NewBB),
  223. PE = InvTraits::child_end(NewBB);
  224. PI != PE; ++PI)
  225. PredBlocks.push_back(*PI);
  226. assert(!PredBlocks.empty() && "No predblocks?");
  227. bool NewBBDominatesNewBBSucc = true;
  228. for (typename InvTraits::ChildIteratorType
  229. PI = InvTraits::child_begin(NewBBSucc),
  230. E = InvTraits::child_end(NewBBSucc);
  231. PI != E; ++PI) {
  232. typename InvTraits::NodeType *ND = *PI;
  233. if (ND != NewBB && !DT.dominates(NewBBSucc, ND) &&
  234. DT.isReachableFromEntry(ND)) {
  235. NewBBDominatesNewBBSucc = false;
  236. break;
  237. }
  238. }
  239. // Find NewBB's immediate dominator and create new dominator tree node for
  240. // NewBB.
  241. NodeT *NewBBIDom = nullptr;
  242. unsigned i = 0;
  243. for (i = 0; i < PredBlocks.size(); ++i)
  244. if (DT.isReachableFromEntry(PredBlocks[i])) {
  245. NewBBIDom = PredBlocks[i];
  246. break;
  247. }
  248. // It's possible that none of the predecessors of NewBB are reachable;
  249. // in that case, NewBB itself is unreachable, so nothing needs to be
  250. // changed.
  251. if (!NewBBIDom)
  252. return;
  253. for (i = i + 1; i < PredBlocks.size(); ++i) {
  254. if (DT.isReachableFromEntry(PredBlocks[i]))
  255. NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
  256. }
  257. // Create the new dominator tree node... and set the idom of NewBB.
  258. DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
  259. // If NewBB strictly dominates other blocks, then it is now the immediate
  260. // dominator of NewBBSucc. Update the dominator tree as appropriate.
  261. if (NewBBDominatesNewBBSucc) {
  262. DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
  263. DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
  264. }
  265. }
  266. public:
  267. explicit DominatorTreeBase(bool isPostDom)
  268. : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
  269. DominatorTreeBase(DominatorTreeBase &&Arg)
  270. : DominatorBase<NodeT>(
  271. std::move(static_cast<DominatorBase<NodeT> &>(Arg))),
  272. DomTreeNodes(std::move(Arg.DomTreeNodes)),
  273. RootNode(std::move(Arg.RootNode)),
  274. DFSInfoValid(std::move(Arg.DFSInfoValid)),
  275. SlowQueries(std::move(Arg.SlowQueries)), IDoms(std::move(Arg.IDoms)),
  276. Vertex(std::move(Arg.Vertex)), Info(std::move(Arg.Info)) {
  277. Arg.wipe();
  278. }
  279. DominatorTreeBase &operator=(DominatorTreeBase &&RHS) {
  280. DominatorBase<NodeT>::operator=(
  281. std::move(static_cast<DominatorBase<NodeT> &>(RHS)));
  282. DomTreeNodes = std::move(RHS.DomTreeNodes);
  283. RootNode = std::move(RHS.RootNode);
  284. DFSInfoValid = std::move(RHS.DFSInfoValid);
  285. SlowQueries = std::move(RHS.SlowQueries);
  286. IDoms = std::move(RHS.IDoms);
  287. Vertex = std::move(RHS.Vertex);
  288. Info = std::move(RHS.Info);
  289. RHS.wipe();
  290. return *this;
  291. }
  292. /// compare - Return false if the other dominator tree base matches this
  293. /// dominator tree base. Otherwise return true.
  294. bool compare(const DominatorTreeBase &Other) const {
  295. const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
  296. if (DomTreeNodes.size() != OtherDomTreeNodes.size())
  297. return true;
  298. for (typename DomTreeNodeMapType::const_iterator
  299. I = this->DomTreeNodes.begin(),
  300. E = this->DomTreeNodes.end();
  301. I != E; ++I) {
  302. NodeT *BB = I->first;
  303. typename DomTreeNodeMapType::const_iterator OI =
  304. OtherDomTreeNodes.find(BB);
  305. if (OI == OtherDomTreeNodes.end())
  306. return true;
  307. DomTreeNodeBase<NodeT> &MyNd = *I->second;
  308. DomTreeNodeBase<NodeT> &OtherNd = *OI->second;
  309. if (MyNd.compare(&OtherNd))
  310. return true;
  311. }
  312. return false;
  313. }
  314. void releaseMemory() { reset(); }
  315. /// getNode - return the (Post)DominatorTree node for the specified basic
  316. /// block. This is the same as using operator[] on this class.
  317. ///
  318. DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
  319. auto I = DomTreeNodes.find(BB);
  320. if (I != DomTreeNodes.end())
  321. return I->second.get();
  322. return nullptr;
  323. }
  324. DomTreeNodeBase<NodeT> *operator[](NodeT *BB) const { return getNode(BB); }
  325. /// getRootNode - This returns the entry node for the CFG of the function. If
  326. /// this tree represents the post-dominance relations for a function, however,
  327. /// this root may be a node with the block == NULL. This is the case when
  328. /// there are multiple exit nodes from a particular function. Consumers of
  329. /// post-dominance information must be capable of dealing with this
  330. /// possibility.
  331. ///
  332. DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
  333. const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
  334. /// Get all nodes dominated by R, including R itself.
  335. void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const {
  336. Result.clear();
  337. const DomTreeNodeBase<NodeT> *RN = getNode(R);
  338. if (!RN)
  339. return; // If R is unreachable, it will not be present in the DOM tree.
  340. SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL;
  341. WL.push_back(RN);
  342. while (!WL.empty()) {
  343. const DomTreeNodeBase<NodeT> *N = WL.pop_back_val();
  344. Result.push_back(N->getBlock());
  345. WL.append(N->begin(), N->end());
  346. }
  347. }
  348. /// properlyDominates - Returns true iff A dominates B and A != B.
  349. /// Note that this is not a constant time operation!
  350. ///
  351. bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
  352. const DomTreeNodeBase<NodeT> *B) const {
  353. if (!A || !B)
  354. return false;
  355. if (A == B)
  356. return false;
  357. return dominates(A, B);
  358. }
  359. bool properlyDominates(const NodeT *A, const NodeT *B) const;
  360. /// isReachableFromEntry - Return true if A is dominated by the entry
  361. /// block of the function containing it.
  362. bool isReachableFromEntry(const NodeT *A) const {
  363. assert(!this->isPostDominator() &&
  364. "This is not implemented for post dominators");
  365. return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
  366. }
  367. bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; }
  368. /// dominates - Returns true iff A dominates B. Note that this is not a
  369. /// constant time operation!
  370. ///
  371. bool dominates(const DomTreeNodeBase<NodeT> *A,
  372. const DomTreeNodeBase<NodeT> *B) const {
  373. // A node trivially dominates itself.
  374. if (B == A)
  375. return true;
  376. // An unreachable node is dominated by anything.
  377. if (!isReachableFromEntry(B))
  378. return true;
  379. // And dominates nothing.
  380. if (!isReachableFromEntry(A))
  381. return false;
  382. // Compare the result of the tree walk and the dfs numbers, if expensive
  383. // checks are enabled.
  384. #ifdef XDEBUG
  385. assert((!DFSInfoValid ||
  386. (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&
  387. "Tree walk disagrees with dfs numbers!");
  388. #endif
  389. if (DFSInfoValid)
  390. return B->DominatedBy(A);
  391. // If we end up with too many slow queries, just update the
  392. // DFS numbers on the theory that we are going to keep querying.
  393. SlowQueries++;
  394. if (SlowQueries > 32) {
  395. updateDFSNumbers();
  396. return B->DominatedBy(A);
  397. }
  398. return dominatedBySlowTreeWalk(A, B);
  399. }
  400. bool dominates(const NodeT *A, const NodeT *B) const;
  401. NodeT *getRoot() const {
  402. assert(this->Roots.size() == 1 && "Should always have entry node!");
  403. return this->Roots[0];
  404. }
  405. /// findNearestCommonDominator - Find nearest common dominator basic block
  406. /// for basic block A and B. If there is no such block then return NULL.
  407. NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
  408. assert(A->getParent() == B->getParent() &&
  409. "Two blocks are not in same function");
  410. // If either A or B is a entry block then it is nearest common dominator
  411. // (for forward-dominators).
  412. if (!this->isPostDominator()) {
  413. NodeT &Entry = A->getParent()->front();
  414. if (A == &Entry || B == &Entry)
  415. return &Entry;
  416. }
  417. // If B dominates A then B is nearest common dominator.
  418. if (dominates(B, A))
  419. return B;
  420. // If A dominates B then A is nearest common dominator.
  421. if (dominates(A, B))
  422. return A;
  423. DomTreeNodeBase<NodeT> *NodeA = getNode(A);
  424. DomTreeNodeBase<NodeT> *NodeB = getNode(B);
  425. // If we have DFS info, then we can avoid all allocations by just querying
  426. // it from each IDom. Note that because we call 'dominates' twice above, we
  427. // expect to call through this code at most 16 times in a row without
  428. // building valid DFS information. This is important as below is a *very*
  429. // slow tree walk.
  430. if (DFSInfoValid) {
  431. DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
  432. while (IDomA) {
  433. if (NodeB->DominatedBy(IDomA))
  434. return IDomA->getBlock();
  435. IDomA = IDomA->getIDom();
  436. }
  437. return nullptr;
  438. }
  439. // Collect NodeA dominators set.
  440. SmallPtrSet<DomTreeNodeBase<NodeT> *, 16> NodeADoms;
  441. NodeADoms.insert(NodeA);
  442. DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
  443. while (IDomA) {
  444. NodeADoms.insert(IDomA);
  445. IDomA = IDomA->getIDom();
  446. }
  447. // Walk NodeB immediate dominators chain and find common dominator node.
  448. DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
  449. while (IDomB) {
  450. if (NodeADoms.count(IDomB) != 0)
  451. return IDomB->getBlock();
  452. IDomB = IDomB->getIDom();
  453. }
  454. return nullptr;
  455. }
  456. const NodeT *findNearestCommonDominator(const NodeT *A, const NodeT *B) {
  457. // Cast away the const qualifiers here. This is ok since
  458. // const is re-introduced on the return type.
  459. return findNearestCommonDominator(const_cast<NodeT *>(A),
  460. const_cast<NodeT *>(B));
  461. }
  462. //===--------------------------------------------------------------------===//
  463. // API to update (Post)DominatorTree information based on modifications to
  464. // the CFG...
  465. /// addNewBlock - Add a new node to the dominator tree information. This
  466. /// creates a new node as a child of DomBB dominator node,linking it into
  467. /// the children list of the immediate dominator.
  468. DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
  469. assert(getNode(BB) == nullptr && "Block already in dominator tree!");
  470. DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
  471. assert(IDomNode && "Not immediate dominator specified for block!");
  472. DFSInfoValid = false;
  473. return (DomTreeNodes[BB] = IDomNode->addChild(
  474. llvm::make_unique<DomTreeNodeBase<NodeT>>(BB, IDomNode))).get();
  475. }
  476. /// changeImmediateDominator - This method is used to update the dominator
  477. /// tree information when a node's immediate dominator changes.
  478. ///
  479. void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
  480. DomTreeNodeBase<NodeT> *NewIDom) {
  481. assert(N && NewIDom && "Cannot change null node pointers!");
  482. DFSInfoValid = false;
  483. N->setIDom(NewIDom);
  484. }
  485. void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
  486. changeImmediateDominator(getNode(BB), getNode(NewBB));
  487. }
  488. /// eraseNode - Removes a node from the dominator tree. Block must not
  489. /// dominate any other blocks. Removes node from its immediate dominator's
  490. /// children list. Deletes dominator node associated with basic block BB.
  491. void eraseNode(NodeT *BB) {
  492. DomTreeNodeBase<NodeT> *Node = getNode(BB);
  493. assert(Node && "Removing node that isn't in dominator tree.");
  494. assert(Node->getChildren().empty() && "Node is not a leaf node.");
  495. // Remove node from immediate dominator's children list.
  496. DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
  497. if (IDom) {
  498. typename std::vector<DomTreeNodeBase<NodeT> *>::iterator I =
  499. std::find(IDom->Children.begin(), IDom->Children.end(), Node);
  500. assert(I != IDom->Children.end() &&
  501. "Not in immediate dominator children set!");
  502. // I am no longer your child...
  503. IDom->Children.erase(I);
  504. }
  505. DomTreeNodes.erase(BB);
  506. }
  507. /// splitBlock - BB is split and now it has one successor. Update dominator
  508. /// tree to reflect this change.
  509. void splitBlock(NodeT *NewBB) {
  510. if (this->IsPostDominators)
  511. this->Split<Inverse<NodeT *>, GraphTraits<Inverse<NodeT *>>>(*this,
  512. NewBB);
  513. else
  514. this->Split<NodeT *, GraphTraits<NodeT *>>(*this, NewBB);
  515. }
  516. /// print - Convert to human readable form
  517. ///
  518. void print(raw_ostream &o) const {
  519. o << "=============================--------------------------------\n";
  520. if (this->isPostDominator())
  521. o << "Inorder PostDominator Tree: ";
  522. else
  523. o << "Inorder Dominator Tree: ";
  524. if (!this->DFSInfoValid)
  525. o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
  526. o << "\n";
  527. // The postdom tree can have a null root if there are no returns.
  528. if (getRootNode())
  529. PrintDomTree<NodeT>(getRootNode(), o, 1);
  530. }
  531. protected:
  532. template <class GraphT>
  533. friend typename GraphT::NodeType *
  534. Eval(DominatorTreeBase<typename GraphT::NodeType> &DT,
  535. typename GraphT::NodeType *V, unsigned LastLinked);
  536. template <class GraphT>
  537. friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType> &DT,
  538. typename GraphT::NodeType *V, unsigned N);
  539. template <class FuncT, class N>
  540. friend void
  541. Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType> &DT, FuncT &F);
  542. DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
  543. if (DomTreeNodeBase<NodeT> *Node = getNode(BB))
  544. return Node;
  545. // Haven't calculated this node yet? Get or calculate the node for the
  546. // immediate dominator.
  547. NodeT *IDom = getIDom(BB);
  548. assert(IDom || this->DomTreeNodes[nullptr]);
  549. DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
  550. // Add a new tree node for this NodeT, and link it as a child of
  551. // IDomNode
  552. return (this->DomTreeNodes[BB] = IDomNode->addChild(
  553. llvm::make_unique<DomTreeNodeBase<NodeT>>(BB, IDomNode))).get();
  554. }
  555. NodeT *getIDom(NodeT *BB) const { return IDoms.lookup(BB); }
  556. void addRoot(NodeT *BB) { this->Roots.push_back(BB); }
  557. public:
  558. /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
  559. /// dominator tree in dfs order.
  560. void updateDFSNumbers() const {
  561. if (DFSInfoValid) {
  562. SlowQueries = 0;
  563. return;
  564. }
  565. unsigned DFSNum = 0;
  566. SmallVector<std::pair<const DomTreeNodeBase<NodeT> *,
  567. typename DomTreeNodeBase<NodeT>::const_iterator>,
  568. 32> WorkStack;
  569. const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode();
  570. if (!ThisRoot)
  571. return;
  572. // Even in the case of multiple exits that form the post dominator root
  573. // nodes, do not iterate over all exits, but start from the virtual root
  574. // node. Otherwise bbs, that are not post dominated by any exit but by the
  575. // virtual root node, will never be assigned a DFS number.
  576. WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
  577. ThisRoot->DFSNumIn = DFSNum++;
  578. while (!WorkStack.empty()) {
  579. const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
  580. typename DomTreeNodeBase<NodeT>::const_iterator ChildIt =
  581. WorkStack.back().second;
  582. // If we visited all of the children of this node, "recurse" back up the
  583. // stack setting the DFOutNum.
  584. if (ChildIt == Node->end()) {
  585. Node->DFSNumOut = DFSNum++;
  586. WorkStack.pop_back();
  587. } else {
  588. // Otherwise, recursively visit this child.
  589. const DomTreeNodeBase<NodeT> *Child = *ChildIt;
  590. ++WorkStack.back().second;
  591. WorkStack.push_back(std::make_pair(Child, Child->begin()));
  592. Child->DFSNumIn = DFSNum++;
  593. }
  594. }
  595. SlowQueries = 0;
  596. DFSInfoValid = true;
  597. }
  598. /// recalculate - compute a dominator tree for the given function
  599. template <class FT> void recalculate(FT &F) {
  600. typedef GraphTraits<FT *> TraitsTy;
  601. reset();
  602. this->Vertex.push_back(nullptr);
  603. if (!this->IsPostDominators) {
  604. // Initialize root
  605. NodeT *entry = TraitsTy::getEntryNode(&F);
  606. this->Roots.push_back(entry);
  607. this->IDoms[entry] = nullptr;
  608. this->DomTreeNodes[entry] = nullptr;
  609. Calculate<FT, NodeT *>(*this, F);
  610. } else {
  611. // Initialize the roots list
  612. for (typename TraitsTy::nodes_iterator I = TraitsTy::nodes_begin(&F),
  613. E = TraitsTy::nodes_end(&F);
  614. I != E; ++I) {
  615. if (TraitsTy::child_begin(I) == TraitsTy::child_end(I))
  616. addRoot(I);
  617. // Prepopulate maps so that we don't get iterator invalidation issues
  618. // later.
  619. this->IDoms[I] = nullptr;
  620. this->DomTreeNodes[I] = nullptr;
  621. }
  622. Calculate<FT, Inverse<NodeT *>>(*this, F);
  623. }
  624. }
  625. };
  626. // These two functions are declared out of line as a workaround for building
  627. // with old (< r147295) versions of clang because of pr11642.
  628. template <class NodeT>
  629. bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) const {
  630. if (A == B)
  631. return true;
  632. // Cast away the const qualifiers here. This is ok since
  633. // this function doesn't actually return the values returned
  634. // from getNode.
  635. return dominates(getNode(const_cast<NodeT *>(A)),
  636. getNode(const_cast<NodeT *>(B)));
  637. }
  638. template <class NodeT>
  639. bool DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A,
  640. const NodeT *B) const {
  641. if (A == B)
  642. return false;
  643. // Cast away the const qualifiers here. This is ok since
  644. // this function doesn't actually return the values returned
  645. // from getNode.
  646. return dominates(getNode(const_cast<NodeT *>(A)),
  647. getNode(const_cast<NodeT *>(B)));
  648. }
  649. }
  650. #endif