CFG.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- CFG.h ----------------------------------------------------*- 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. /// This file provides various utilities for inspecting and working with the
  16. /// control flow graph in LLVM IR. This includes generic facilities for
  17. /// iterating successors and predecessors of basic blocks, the successors of
  18. /// specific terminator instructions, etc. It also defines specializations of
  19. /// GraphTraits that allow Function and BasicBlock graphs to be treated as
  20. /// proper graphs for generic algorithms.
  21. ///
  22. //===----------------------------------------------------------------------===//
  23. #ifndef LLVM_IR_CFG_H
  24. #define LLVM_IR_CFG_H
  25. #include "llvm/ADT/GraphTraits.h"
  26. #include "llvm/ADT/iterator.h"
  27. #include "llvm/ADT/iterator_range.h"
  28. #include "llvm/IR/BasicBlock.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/Value.h"
  31. #include "llvm/Support/Casting.h"
  32. #include <cassert>
  33. #include <cstddef>
  34. #include <iterator>
  35. namespace llvm {
  36. class Instruction;
  37. class Use;
  38. //===----------------------------------------------------------------------===//
  39. // BasicBlock pred_iterator definition
  40. //===----------------------------------------------------------------------===//
  41. template <class Ptr, class USE_iterator> // Predecessor Iterator
  42. class PredIterator {
  43. public:
  44. using iterator_category = std::forward_iterator_tag;
  45. using value_type = Ptr;
  46. using difference_type = std::ptrdiff_t;
  47. using pointer = Ptr *;
  48. using reference = Ptr *;
  49. private:
  50. using Self = PredIterator<Ptr, USE_iterator>;
  51. USE_iterator It;
  52. inline void advancePastNonTerminators() {
  53. // Loop to ignore non-terminator uses (for example BlockAddresses).
  54. while (!It.atEnd()) {
  55. if (auto *Inst = dyn_cast<Instruction>(*It))
  56. if (Inst->isTerminator())
  57. break;
  58. ++It;
  59. }
  60. }
  61. public:
  62. PredIterator() = default;
  63. explicit inline PredIterator(Ptr *bb) : It(bb->user_begin()) {
  64. advancePastNonTerminators();
  65. }
  66. inline PredIterator(Ptr *bb, bool) : It(bb->user_end()) {}
  67. inline bool operator==(const Self& x) const { return It == x.It; }
  68. inline bool operator!=(const Self& x) const { return !operator==(x); }
  69. inline reference operator*() const {
  70. assert(!It.atEnd() && "pred_iterator out of range!");
  71. return cast<Instruction>(*It)->getParent();
  72. }
  73. inline pointer *operator->() const { return &operator*(); }
  74. inline Self& operator++() { // Preincrement
  75. assert(!It.atEnd() && "pred_iterator out of range!");
  76. ++It; advancePastNonTerminators();
  77. return *this;
  78. }
  79. inline Self operator++(int) { // Postincrement
  80. Self tmp = *this; ++*this; return tmp;
  81. }
  82. /// getOperandNo - Return the operand number in the predecessor's
  83. /// terminator of the successor.
  84. unsigned getOperandNo() const {
  85. return It.getOperandNo();
  86. }
  87. /// getUse - Return the operand Use in the predecessor's terminator
  88. /// of the successor.
  89. Use &getUse() const {
  90. return It.getUse();
  91. }
  92. };
  93. using pred_iterator = PredIterator<BasicBlock, Value::user_iterator>;
  94. using const_pred_iterator =
  95. PredIterator<const BasicBlock, Value::const_user_iterator>;
  96. using pred_range = iterator_range<pred_iterator>;
  97. using const_pred_range = iterator_range<const_pred_iterator>;
  98. inline pred_iterator pred_begin(BasicBlock *BB) { return pred_iterator(BB); }
  99. inline const_pred_iterator pred_begin(const BasicBlock *BB) {
  100. return const_pred_iterator(BB);
  101. }
  102. inline pred_iterator pred_end(BasicBlock *BB) { return pred_iterator(BB, true);}
  103. inline const_pred_iterator pred_end(const BasicBlock *BB) {
  104. return const_pred_iterator(BB, true);
  105. }
  106. inline bool pred_empty(const BasicBlock *BB) {
  107. return pred_begin(BB) == pred_end(BB);
  108. }
  109. /// Get the number of predecessors of \p BB. This is a linear time operation.
  110. /// Use \ref BasicBlock::hasNPredecessors() or hasNPredecessorsOrMore if able.
  111. inline unsigned pred_size(const BasicBlock *BB) {
  112. return std::distance(pred_begin(BB), pred_end(BB));
  113. }
  114. inline pred_range predecessors(BasicBlock *BB) {
  115. return pred_range(pred_begin(BB), pred_end(BB));
  116. }
  117. inline const_pred_range predecessors(const BasicBlock *BB) {
  118. return const_pred_range(pred_begin(BB), pred_end(BB));
  119. }
  120. //===----------------------------------------------------------------------===//
  121. // Instruction and BasicBlock succ_iterator helpers
  122. //===----------------------------------------------------------------------===//
  123. template <class InstructionT, class BlockT>
  124. class SuccIterator
  125. : public iterator_facade_base<SuccIterator<InstructionT, BlockT>,
  126. std::random_access_iterator_tag, BlockT, int,
  127. BlockT *, BlockT *> {
  128. public:
  129. using difference_type = int;
  130. using pointer = BlockT *;
  131. using reference = BlockT *;
  132. private:
  133. InstructionT *Inst;
  134. int Idx;
  135. using Self = SuccIterator<InstructionT, BlockT>;
  136. inline bool index_is_valid(int Idx) {
  137. // Note that we specially support the index of zero being valid even in the
  138. // face of a null instruction.
  139. return Idx >= 0 && (Idx == 0 || Idx <= (int)Inst->getNumSuccessors());
  140. }
  141. /// Proxy object to allow write access in operator[]
  142. class SuccessorProxy {
  143. Self It;
  144. public:
  145. explicit SuccessorProxy(const Self &It) : It(It) {}
  146. SuccessorProxy(const SuccessorProxy &) = default;
  147. SuccessorProxy &operator=(SuccessorProxy RHS) {
  148. *this = reference(RHS);
  149. return *this;
  150. }
  151. SuccessorProxy &operator=(reference RHS) {
  152. It.Inst->setSuccessor(It.Idx, RHS);
  153. return *this;
  154. }
  155. operator reference() const { return *It; }
  156. };
  157. public:
  158. // begin iterator
  159. explicit inline SuccIterator(InstructionT *Inst) : Inst(Inst), Idx(0) {}
  160. // end iterator
  161. inline SuccIterator(InstructionT *Inst, bool) : Inst(Inst) {
  162. if (Inst)
  163. Idx = Inst->getNumSuccessors();
  164. else
  165. // Inst == NULL happens, if a basic block is not fully constructed and
  166. // consequently getTerminator() returns NULL. In this case we construct
  167. // a SuccIterator which describes a basic block that has zero
  168. // successors.
  169. // Defining SuccIterator for incomplete and malformed CFGs is especially
  170. // useful for debugging.
  171. Idx = 0;
  172. }
  173. /// This is used to interface between code that wants to
  174. /// operate on terminator instructions directly.
  175. int getSuccessorIndex() const { return Idx; }
  176. inline bool operator==(const Self &x) const { return Idx == x.Idx; }
  177. inline BlockT *operator*() const { return Inst->getSuccessor(Idx); }
  178. // We use the basic block pointer directly for operator->.
  179. inline BlockT *operator->() const { return operator*(); }
  180. inline bool operator<(const Self &RHS) const {
  181. assert(Inst == RHS.Inst && "Cannot compare iterators of different blocks!");
  182. return Idx < RHS.Idx;
  183. }
  184. int operator-(const Self &RHS) const {
  185. assert(Inst == RHS.Inst && "Cannot compare iterators of different blocks!");
  186. return Idx - RHS.Idx;
  187. }
  188. inline Self &operator+=(int RHS) {
  189. int NewIdx = Idx + RHS;
  190. assert(index_is_valid(NewIdx) && "Iterator index out of bound");
  191. Idx = NewIdx;
  192. return *this;
  193. }
  194. inline Self &operator-=(int RHS) { return operator+=(-RHS); }
  195. // Specially implement the [] operation using a proxy object to support
  196. // assignment.
  197. inline SuccessorProxy operator[](int Offset) {
  198. Self TmpIt = *this;
  199. TmpIt += Offset;
  200. return SuccessorProxy(TmpIt);
  201. }
  202. /// Get the source BlockT of this iterator.
  203. inline BlockT *getSource() {
  204. assert(Inst && "Source not available, if basic block was malformed");
  205. return Inst->getParent();
  206. }
  207. };
  208. using succ_iterator = SuccIterator<Instruction, BasicBlock>;
  209. using const_succ_iterator = SuccIterator<const Instruction, const BasicBlock>;
  210. using succ_range = iterator_range<succ_iterator>;
  211. using const_succ_range = iterator_range<const_succ_iterator>;
  212. inline succ_iterator succ_begin(Instruction *I) { return succ_iterator(I); }
  213. inline const_succ_iterator succ_begin(const Instruction *I) {
  214. return const_succ_iterator(I);
  215. }
  216. inline succ_iterator succ_end(Instruction *I) { return succ_iterator(I, true); }
  217. inline const_succ_iterator succ_end(const Instruction *I) {
  218. return const_succ_iterator(I, true);
  219. }
  220. inline bool succ_empty(const Instruction *I) {
  221. return succ_begin(I) == succ_end(I);
  222. }
  223. inline unsigned succ_size(const Instruction *I) {
  224. return std::distance(succ_begin(I), succ_end(I));
  225. }
  226. inline succ_range successors(Instruction *I) {
  227. return succ_range(succ_begin(I), succ_end(I));
  228. }
  229. inline const_succ_range successors(const Instruction *I) {
  230. return const_succ_range(succ_begin(I), succ_end(I));
  231. }
  232. inline succ_iterator succ_begin(BasicBlock *BB) {
  233. return succ_iterator(BB->getTerminator());
  234. }
  235. inline const_succ_iterator succ_begin(const BasicBlock *BB) {
  236. return const_succ_iterator(BB->getTerminator());
  237. }
  238. inline succ_iterator succ_end(BasicBlock *BB) {
  239. return succ_iterator(BB->getTerminator(), true);
  240. }
  241. inline const_succ_iterator succ_end(const BasicBlock *BB) {
  242. return const_succ_iterator(BB->getTerminator(), true);
  243. }
  244. inline bool succ_empty(const BasicBlock *BB) {
  245. return succ_begin(BB) == succ_end(BB);
  246. }
  247. inline unsigned succ_size(const BasicBlock *BB) {
  248. return std::distance(succ_begin(BB), succ_end(BB));
  249. }
  250. inline succ_range successors(BasicBlock *BB) {
  251. return succ_range(succ_begin(BB), succ_end(BB));
  252. }
  253. inline const_succ_range successors(const BasicBlock *BB) {
  254. return const_succ_range(succ_begin(BB), succ_end(BB));
  255. }
  256. //===--------------------------------------------------------------------===//
  257. // GraphTraits specializations for basic block graphs (CFGs)
  258. //===--------------------------------------------------------------------===//
  259. // Provide specializations of GraphTraits to be able to treat a function as a
  260. // graph of basic blocks...
  261. template <> struct GraphTraits<BasicBlock*> {
  262. using NodeRef = BasicBlock *;
  263. using ChildIteratorType = succ_iterator;
  264. static NodeRef getEntryNode(BasicBlock *BB) { return BB; }
  265. static ChildIteratorType child_begin(NodeRef N) { return succ_begin(N); }
  266. static ChildIteratorType child_end(NodeRef N) { return succ_end(N); }
  267. };
  268. template <> struct GraphTraits<const BasicBlock*> {
  269. using NodeRef = const BasicBlock *;
  270. using ChildIteratorType = const_succ_iterator;
  271. static NodeRef getEntryNode(const BasicBlock *BB) { return BB; }
  272. static ChildIteratorType child_begin(NodeRef N) { return succ_begin(N); }
  273. static ChildIteratorType child_end(NodeRef N) { return succ_end(N); }
  274. };
  275. // Provide specializations of GraphTraits to be able to treat a function as a
  276. // graph of basic blocks... and to walk it in inverse order. Inverse order for
  277. // a function is considered to be when traversing the predecessor edges of a BB
  278. // instead of the successor edges.
  279. //
  280. template <> struct GraphTraits<Inverse<BasicBlock*>> {
  281. using NodeRef = BasicBlock *;
  282. using ChildIteratorType = pred_iterator;
  283. static NodeRef getEntryNode(Inverse<BasicBlock *> G) { return G.Graph; }
  284. static ChildIteratorType child_begin(NodeRef N) { return pred_begin(N); }
  285. static ChildIteratorType child_end(NodeRef N) { return pred_end(N); }
  286. };
  287. template <> struct GraphTraits<Inverse<const BasicBlock*>> {
  288. using NodeRef = const BasicBlock *;
  289. using ChildIteratorType = const_pred_iterator;
  290. static NodeRef getEntryNode(Inverse<const BasicBlock *> G) { return G.Graph; }
  291. static ChildIteratorType child_begin(NodeRef N) { return pred_begin(N); }
  292. static ChildIteratorType child_end(NodeRef N) { return pred_end(N); }
  293. };
  294. //===--------------------------------------------------------------------===//
  295. // GraphTraits specializations for function basic block graphs (CFGs)
  296. //===--------------------------------------------------------------------===//
  297. // Provide specializations of GraphTraits to be able to treat a function as a
  298. // graph of basic blocks... these are the same as the basic block iterators,
  299. // except that the root node is implicitly the first node of the function.
  300. //
  301. template <> struct GraphTraits<Function*> : public GraphTraits<BasicBlock*> {
  302. static NodeRef getEntryNode(Function *F) { return &F->getEntryBlock(); }
  303. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  304. using nodes_iterator = pointer_iterator<Function::iterator>;
  305. static nodes_iterator nodes_begin(Function *F) {
  306. return nodes_iterator(F->begin());
  307. }
  308. static nodes_iterator nodes_end(Function *F) {
  309. return nodes_iterator(F->end());
  310. }
  311. static size_t size(Function *F) { return F->size(); }
  312. };
  313. template <> struct GraphTraits<const Function*> :
  314. public GraphTraits<const BasicBlock*> {
  315. static NodeRef getEntryNode(const Function *F) { return &F->getEntryBlock(); }
  316. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  317. using nodes_iterator = pointer_iterator<Function::const_iterator>;
  318. static nodes_iterator nodes_begin(const Function *F) {
  319. return nodes_iterator(F->begin());
  320. }
  321. static nodes_iterator nodes_end(const Function *F) {
  322. return nodes_iterator(F->end());
  323. }
  324. static size_t size(const Function *F) { return F->size(); }
  325. };
  326. // Provide specializations of GraphTraits to be able to treat a function as a
  327. // graph of basic blocks... and to walk it in inverse order. Inverse order for
  328. // a function is considered to be when traversing the predecessor edges of a BB
  329. // instead of the successor edges.
  330. //
  331. template <> struct GraphTraits<Inverse<Function*>> :
  332. public GraphTraits<Inverse<BasicBlock*>> {
  333. static NodeRef getEntryNode(Inverse<Function *> G) {
  334. return &G.Graph->getEntryBlock();
  335. }
  336. };
  337. template <> struct GraphTraits<Inverse<const Function*>> :
  338. public GraphTraits<Inverse<const BasicBlock*>> {
  339. static NodeRef getEntryNode(Inverse<const Function *> G) {
  340. return &G.Graph->getEntryBlock();
  341. }
  342. };
  343. } // end namespace llvm
  344. #endif // LLVM_IR_CFG_H
  345. #ifdef __GNUC__
  346. #pragma GCC diagnostic pop
  347. #endif