1 //===--- CFG.h - Classes for representing and building CFGs------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the CFG and CFGBuilder classes for representing and
11 // building Control-Flow Graphs (CFGs) from ASTs.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_CFG_H
16 #define LLVM_CLANG_CFG_H
18 #include "clang/AST/Stmt.h"
19 #include "clang/Analysis/Support/BumpVector.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/GraphTraits.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/OwningPtr.h"
25 #include "llvm/ADT/PointerIntPair.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/raw_ostream.h"
34 class CXXDestructorDecl;
40 class CXXCtorInitializer;
41 class CXXBaseSpecifier;
42 class CXXBindTemporaryExpr;
51 /// CFGElement - Represents a top-level expression in a basic block.
65 DTOR_BEGIN = AutomaticObjectDtor,
66 DTOR_END = TemporaryDtor
70 // The int bits are used to mark the kind.
71 llvm::PointerIntPair<void *, 2> Data1;
72 llvm::PointerIntPair<void *, 2> Data2;
74 CFGElement(Kind kind, const void *Ptr1, const void *Ptr2 = 0)
75 : Data1(const_cast<void*>(Ptr1), ((unsigned) kind) & 0x3),
76 Data2(const_cast<void*>(Ptr2), (((unsigned) kind) >> 2) & 0x3) {
77 assert(getKind() == kind);
83 /// \brief Convert to the specified CFGElement type, asserting that this
84 /// CFGElement is of the desired type.
87 assert(T::isKind(*this));
94 /// \brief Convert to the specified CFGElement type, returning None if this
95 /// CFGElement is not of the desired type.
97 Optional<T> getAs() const {
98 if (!T::isKind(*this))
106 Kind getKind() const {
107 unsigned x = Data2.getInt();
114 class CFGStmt : public CFGElement {
116 CFGStmt(Stmt *S) : CFGElement(Statement, S) {}
118 const Stmt *getStmt() const {
119 return static_cast<const Stmt *>(Data1.getPointer());
123 friend class CFGElement;
125 static bool isKind(const CFGElement &E) {
126 return E.getKind() == Statement;
130 /// CFGInitializer - Represents C++ base or member initializer from
131 /// constructor's initialization list.
132 class CFGInitializer : public CFGElement {
134 CFGInitializer(CXXCtorInitializer *initializer)
135 : CFGElement(Initializer, initializer) {}
137 CXXCtorInitializer* getInitializer() const {
138 return static_cast<CXXCtorInitializer*>(Data1.getPointer());
142 friend class CFGElement;
144 static bool isKind(const CFGElement &E) {
145 return E.getKind() == Initializer;
149 /// CFGNewAllocator - Represents C++ allocator call.
150 class CFGNewAllocator : public CFGElement {
152 explicit CFGNewAllocator(const CXXNewExpr *S)
153 : CFGElement(NewAllocator, S) {}
155 // Get the new expression.
156 const CXXNewExpr *getAllocatorExpr() const {
157 return static_cast<CXXNewExpr *>(Data1.getPointer());
161 friend class CFGElement;
163 static bool isKind(const CFGElement &elem) {
164 return elem.getKind() == NewAllocator;
168 /// CFGImplicitDtor - Represents C++ object destructor implicitly generated
169 /// by compiler on various occasions.
170 class CFGImplicitDtor : public CFGElement {
173 CFGImplicitDtor(Kind kind, const void *data1, const void *data2 = 0)
174 : CFGElement(kind, data1, data2) {
175 assert(kind >= DTOR_BEGIN && kind <= DTOR_END);
179 const CXXDestructorDecl *getDestructorDecl(ASTContext &astContext) const;
180 bool isNoReturn(ASTContext &astContext) const;
183 friend class CFGElement;
184 static bool isKind(const CFGElement &E) {
185 Kind kind = E.getKind();
186 return kind >= DTOR_BEGIN && kind <= DTOR_END;
190 /// CFGAutomaticObjDtor - Represents C++ object destructor implicitly generated
191 /// for automatic object or temporary bound to const reference at the point
192 /// of leaving its local scope.
193 class CFGAutomaticObjDtor: public CFGImplicitDtor {
195 CFGAutomaticObjDtor(const VarDecl *var, const Stmt *stmt)
196 : CFGImplicitDtor(AutomaticObjectDtor, var, stmt) {}
198 const VarDecl *getVarDecl() const {
199 return static_cast<VarDecl*>(Data1.getPointer());
202 // Get statement end of which triggered the destructor call.
203 const Stmt *getTriggerStmt() const {
204 return static_cast<Stmt*>(Data2.getPointer());
208 friend class CFGElement;
209 CFGAutomaticObjDtor() {}
210 static bool isKind(const CFGElement &elem) {
211 return elem.getKind() == AutomaticObjectDtor;
215 /// CFGDeleteDtor - Represents C++ object destructor generated
216 /// from a call to delete.
217 class CFGDeleteDtor : public CFGImplicitDtor {
219 CFGDeleteDtor(const CXXRecordDecl *RD, const CXXDeleteExpr *DE)
220 : CFGImplicitDtor(DeleteDtor, RD, DE) {}
222 const CXXRecordDecl *getCXXRecordDecl() const {
223 return static_cast<CXXRecordDecl*>(Data1.getPointer());
226 // Get Delete expression which triggered the destructor call.
227 const CXXDeleteExpr *getDeleteExpr() const {
228 return static_cast<CXXDeleteExpr *>(Data2.getPointer());
233 friend class CFGElement;
235 static bool isKind(const CFGElement &elem) {
236 return elem.getKind() == DeleteDtor;
240 /// CFGBaseDtor - Represents C++ object destructor implicitly generated for
241 /// base object in destructor.
242 class CFGBaseDtor : public CFGImplicitDtor {
244 CFGBaseDtor(const CXXBaseSpecifier *base)
245 : CFGImplicitDtor(BaseDtor, base) {}
247 const CXXBaseSpecifier *getBaseSpecifier() const {
248 return static_cast<const CXXBaseSpecifier*>(Data1.getPointer());
252 friend class CFGElement;
254 static bool isKind(const CFGElement &E) {
255 return E.getKind() == BaseDtor;
259 /// CFGMemberDtor - Represents C++ object destructor implicitly generated for
260 /// member object in destructor.
261 class CFGMemberDtor : public CFGImplicitDtor {
263 CFGMemberDtor(const FieldDecl *field)
264 : CFGImplicitDtor(MemberDtor, field, 0) {}
266 const FieldDecl *getFieldDecl() const {
267 return static_cast<const FieldDecl*>(Data1.getPointer());
271 friend class CFGElement;
273 static bool isKind(const CFGElement &E) {
274 return E.getKind() == MemberDtor;
278 /// CFGTemporaryDtor - Represents C++ object destructor implicitly generated
279 /// at the end of full expression for temporary object.
280 class CFGTemporaryDtor : public CFGImplicitDtor {
282 CFGTemporaryDtor(CXXBindTemporaryExpr *expr)
283 : CFGImplicitDtor(TemporaryDtor, expr, 0) {}
285 const CXXBindTemporaryExpr *getBindTemporaryExpr() const {
286 return static_cast<const CXXBindTemporaryExpr *>(Data1.getPointer());
290 friend class CFGElement;
291 CFGTemporaryDtor() {}
292 static bool isKind(const CFGElement &E) {
293 return E.getKind() == TemporaryDtor;
297 /// CFGTerminator - Represents CFGBlock terminator statement.
299 /// TemporaryDtorsBranch bit is set to true if the terminator marks a branch
300 /// in control flow of destructors of temporaries. In this case terminator
301 /// statement is the same statement that branches control flow in evaluation
302 /// of matching full expression.
303 class CFGTerminator {
304 llvm::PointerIntPair<Stmt *, 1> Data;
307 CFGTerminator(Stmt *S, bool TemporaryDtorsBranch = false)
308 : Data(S, TemporaryDtorsBranch) {}
310 Stmt *getStmt() { return Data.getPointer(); }
311 const Stmt *getStmt() const { return Data.getPointer(); }
313 bool isTemporaryDtorsBranch() const { return Data.getInt(); }
315 operator Stmt *() { return getStmt(); }
316 operator const Stmt *() const { return getStmt(); }
318 Stmt *operator->() { return getStmt(); }
319 const Stmt *operator->() const { return getStmt(); }
321 Stmt &operator*() { return *getStmt(); }
322 const Stmt &operator*() const { return *getStmt(); }
324 LLVM_EXPLICIT operator bool() const { return getStmt(); }
327 /// CFGBlock - Represents a single basic block in a source-level CFG.
330 /// (1) A set of statements/expressions (which may contain subexpressions).
331 /// (2) A "terminator" statement (not in the set of statements).
332 /// (3) A list of successors and predecessors.
334 /// Terminator: The terminator represents the type of control-flow that occurs
335 /// at the end of the basic block. The terminator is a Stmt* referring to an
336 /// AST node that has control-flow: if-statements, breaks, loops, etc.
337 /// If the control-flow is conditional, the condition expression will appear
338 /// within the set of statements in the block (usually the last statement).
340 /// Predecessors: the order in the set of predecessors is arbitrary.
342 /// Successors: the order in the set of successors is NOT arbitrary. We
343 /// currently have the following orderings based on the terminator:
345 /// Terminator Successor Ordering
346 /// -----------------------------------------------------
347 /// if Then Block; Else Block
348 /// ? operator LHS expression; RHS expression
349 /// &&, || expression that uses result of && or ||, RHS
351 /// But note that any of that may be NULL in case of optimized-out edges.
355 typedef BumpVector<CFGElement> ImplTy;
358 ElementList(BumpVectorContext &C) : Impl(C, 4) {}
360 typedef std::reverse_iterator<ImplTy::iterator> iterator;
361 typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
362 typedef ImplTy::iterator reverse_iterator;
363 typedef ImplTy::const_iterator const_reverse_iterator;
364 typedef ImplTy::const_reference const_reference;
366 void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
367 reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
368 BumpVectorContext &C) {
369 return Impl.insert(I, Cnt, E, C);
372 const_reference front() const { return Impl.back(); }
373 const_reference back() const { return Impl.front(); }
375 iterator begin() { return Impl.rbegin(); }
376 iterator end() { return Impl.rend(); }
377 const_iterator begin() const { return Impl.rbegin(); }
378 const_iterator end() const { return Impl.rend(); }
379 reverse_iterator rbegin() { return Impl.begin(); }
380 reverse_iterator rend() { return Impl.end(); }
381 const_reverse_iterator rbegin() const { return Impl.begin(); }
382 const_reverse_iterator rend() const { return Impl.end(); }
384 CFGElement operator[](size_t i) const {
385 assert(i < Impl.size());
386 return Impl[Impl.size() - 1 - i];
389 size_t size() const { return Impl.size(); }
390 bool empty() const { return Impl.empty(); }
393 /// Stmts - The set of statements in the basic block.
394 ElementList Elements;
396 /// Label - An (optional) label that prefixes the executable
397 /// statements in the block. When this variable is non-NULL, it is
398 /// either an instance of LabelStmt, SwitchCase or CXXCatchStmt.
401 /// Terminator - The terminator for a basic block that
402 /// indicates the type of control-flow that occurs between a block
403 /// and its successors.
404 CFGTerminator Terminator;
406 /// LoopTarget - Some blocks are used to represent the "loop edge" to
407 /// the start of a loop from within the loop body. This Stmt* will be
408 /// refer to the loop statement for such blocks (and be null otherwise).
409 const Stmt *LoopTarget;
411 /// BlockID - A numerical ID assigned to a CFGBlock during construction
415 /// Predecessors/Successors - Keep track of the predecessor / successor
417 typedef BumpVector<CFGBlock*> AdjacentBlocks;
418 AdjacentBlocks Preds;
419 AdjacentBlocks Succs;
421 /// NoReturn - This bit is set when the basic block contains a function call
422 /// or implicit destructor that is attributed as 'noreturn'. In that case,
423 /// control cannot technically ever proceed past this block. All such blocks
424 /// will have a single immediate successor: the exit block. This allows them
425 /// to be easily reached from the exit block and using this bit quickly
426 /// recognized without scanning the contents of the block.
428 /// Optimization Note: This bit could be profitably folded with Terminator's
429 /// storage if the memory usage of CFGBlock becomes an issue.
430 unsigned HasNoReturnElement : 1;
432 /// Parent - The parent CFG that owns this CFGBlock.
436 explicit CFGBlock(unsigned blockid, BumpVectorContext &C, CFG *parent)
437 : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
438 BlockID(blockid), Preds(C, 1), Succs(C, 1), HasNoReturnElement(false),
442 // Statement iterators
443 typedef ElementList::iterator iterator;
444 typedef ElementList::const_iterator const_iterator;
445 typedef ElementList::reverse_iterator reverse_iterator;
446 typedef ElementList::const_reverse_iterator const_reverse_iterator;
448 CFGElement front() const { return Elements.front(); }
449 CFGElement back() const { return Elements.back(); }
451 iterator begin() { return Elements.begin(); }
452 iterator end() { return Elements.end(); }
453 const_iterator begin() const { return Elements.begin(); }
454 const_iterator end() const { return Elements.end(); }
456 reverse_iterator rbegin() { return Elements.rbegin(); }
457 reverse_iterator rend() { return Elements.rend(); }
458 const_reverse_iterator rbegin() const { return Elements.rbegin(); }
459 const_reverse_iterator rend() const { return Elements.rend(); }
461 unsigned size() const { return Elements.size(); }
462 bool empty() const { return Elements.empty(); }
464 CFGElement operator[](size_t i) const { return Elements[i]; }
467 typedef AdjacentBlocks::iterator pred_iterator;
468 typedef AdjacentBlocks::const_iterator const_pred_iterator;
469 typedef AdjacentBlocks::reverse_iterator pred_reverse_iterator;
470 typedef AdjacentBlocks::const_reverse_iterator const_pred_reverse_iterator;
472 typedef AdjacentBlocks::iterator succ_iterator;
473 typedef AdjacentBlocks::const_iterator const_succ_iterator;
474 typedef AdjacentBlocks::reverse_iterator succ_reverse_iterator;
475 typedef AdjacentBlocks::const_reverse_iterator const_succ_reverse_iterator;
477 pred_iterator pred_begin() { return Preds.begin(); }
478 pred_iterator pred_end() { return Preds.end(); }
479 const_pred_iterator pred_begin() const { return Preds.begin(); }
480 const_pred_iterator pred_end() const { return Preds.end(); }
482 pred_reverse_iterator pred_rbegin() { return Preds.rbegin(); }
483 pred_reverse_iterator pred_rend() { return Preds.rend(); }
484 const_pred_reverse_iterator pred_rbegin() const { return Preds.rbegin(); }
485 const_pred_reverse_iterator pred_rend() const { return Preds.rend(); }
487 succ_iterator succ_begin() { return Succs.begin(); }
488 succ_iterator succ_end() { return Succs.end(); }
489 const_succ_iterator succ_begin() const { return Succs.begin(); }
490 const_succ_iterator succ_end() const { return Succs.end(); }
492 succ_reverse_iterator succ_rbegin() { return Succs.rbegin(); }
493 succ_reverse_iterator succ_rend() { return Succs.rend(); }
494 const_succ_reverse_iterator succ_rbegin() const { return Succs.rbegin(); }
495 const_succ_reverse_iterator succ_rend() const { return Succs.rend(); }
497 unsigned succ_size() const { return Succs.size(); }
498 bool succ_empty() const { return Succs.empty(); }
500 unsigned pred_size() const { return Preds.size(); }
501 bool pred_empty() const { return Preds.empty(); }
504 class FilterOptions {
507 IgnoreDefaultsWithCoveredEnums = 0;
510 unsigned IgnoreDefaultsWithCoveredEnums : 1;
513 static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
514 const CFGBlock *Dst);
516 template <typename IMPL, bool IsPred>
517 class FilteredCFGBlockIterator {
520 const FilterOptions F;
521 const CFGBlock *From;
523 explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
524 const CFGBlock *from,
525 const FilterOptions &f)
526 : I(i), E(e), F(f), From(from) {}
528 bool hasMore() const { return I != E; }
530 FilteredCFGBlockIterator &operator++() {
531 do { ++I; } while (hasMore() && Filter(*I));
535 const CFGBlock *operator*() const { return *I; }
537 bool Filter(const CFGBlock *To) {
538 return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
542 typedef FilteredCFGBlockIterator<const_pred_iterator, true>
543 filtered_pred_iterator;
545 typedef FilteredCFGBlockIterator<const_succ_iterator, false>
546 filtered_succ_iterator;
548 filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
549 return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
552 filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
553 return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
556 // Manipulation of block contents
558 void setTerminator(Stmt *Statement) { Terminator = Statement; }
559 void setLabel(Stmt *Statement) { Label = Statement; }
560 void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
561 void setHasNoReturnElement() { HasNoReturnElement = true; }
563 CFGTerminator getTerminator() { return Terminator; }
564 const CFGTerminator getTerminator() const { return Terminator; }
566 Stmt *getTerminatorCondition();
568 const Stmt *getTerminatorCondition() const {
569 return const_cast<CFGBlock*>(this)->getTerminatorCondition();
572 const Stmt *getLoopTarget() const { return LoopTarget; }
574 Stmt *getLabel() { return Label; }
575 const Stmt *getLabel() const { return Label; }
577 bool hasNoReturnElement() const { return HasNoReturnElement; }
579 unsigned getBlockID() const { return BlockID; }
581 CFG *getParent() const { return Parent; }
583 void dump(const CFG *cfg, const LangOptions &LO, bool ShowColors = false) const;
584 void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO,
585 bool ShowColors) const;
586 void printTerminator(raw_ostream &OS, const LangOptions &LO) const;
587 void printAsOperand(raw_ostream &OS, bool /*PrintType*/) {
588 OS << "BB#" << getBlockID();
591 void addSuccessor(CFGBlock *Block, BumpVectorContext &C) {
593 Block->Preds.push_back(this, C);
594 Succs.push_back(Block, C);
597 void appendStmt(Stmt *statement, BumpVectorContext &C) {
598 Elements.push_back(CFGStmt(statement), C);
601 void appendInitializer(CXXCtorInitializer *initializer,
602 BumpVectorContext &C) {
603 Elements.push_back(CFGInitializer(initializer), C);
606 void appendNewAllocator(CXXNewExpr *NE,
607 BumpVectorContext &C) {
608 Elements.push_back(CFGNewAllocator(NE), C);
611 void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
612 Elements.push_back(CFGBaseDtor(BS), C);
615 void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
616 Elements.push_back(CFGMemberDtor(FD), C);
619 void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
620 Elements.push_back(CFGTemporaryDtor(E), C);
623 void appendAutomaticObjDtor(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
624 Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
627 void appendDeleteDtor(CXXRecordDecl *RD, CXXDeleteExpr *DE, BumpVectorContext &C) {
628 Elements.push_back(CFGDeleteDtor(RD, DE), C);
631 // Destructors must be inserted in reversed order. So insertion is in two
632 // steps. First we prepare space for some number of elements, then we insert
633 // the elements beginning at the last position in prepared space.
634 iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
635 BumpVectorContext &C) {
636 return iterator(Elements.insert(I.base(), Cnt, CFGAutomaticObjDtor(0, 0), C));
638 iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
639 *I = CFGAutomaticObjDtor(VD, S);
644 /// CFG - Represents a source-level, intra-procedural CFG that represents the
645 /// control-flow of a Stmt. The Stmt can represent an entire function body,
646 /// or a single expression. A CFG will always contain one empty block that
647 /// represents the Exit point of the CFG. A CFG will also contain a designated
648 /// Entry block. The CFG solely represents control-flow; it consists of
649 /// CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
650 /// was constructed from.
653 //===--------------------------------------------------------------------===//
654 // CFG Construction & Manipulation.
655 //===--------------------------------------------------------------------===//
658 std::bitset<Stmt::lastStmtConstant> alwaysAddMask;
660 typedef llvm::DenseMap<const Stmt *, const CFGBlock*> ForcedBlkExprs;
661 ForcedBlkExprs **forcedBlkExprs;
663 bool PruneTriviallyFalseEdges;
665 bool AddInitializers;
666 bool AddImplicitDtors;
667 bool AddTemporaryDtors;
668 bool AddStaticInitBranches;
669 bool AddCXXNewAllocator;
671 bool alwaysAdd(const Stmt *stmt) const {
672 return alwaysAddMask[stmt->getStmtClass()];
675 BuildOptions &setAlwaysAdd(Stmt::StmtClass stmtClass, bool val = true) {
676 alwaysAddMask[stmtClass] = val;
680 BuildOptions &setAllAlwaysAdd() {
686 : forcedBlkExprs(0), PruneTriviallyFalseEdges(true)
688 ,AddInitializers(false)
689 ,AddImplicitDtors(false)
690 ,AddTemporaryDtors(false)
691 ,AddStaticInitBranches(false)
692 ,AddCXXNewAllocator(false) {}
695 /// \brief Provides a custom implementation of the iterator class to have the
696 /// same interface as Function::iterator - iterator returns CFGBlock
697 /// (not a pointer to CFGBlock).
698 class graph_iterator {
700 typedef const CFGBlock value_type;
701 typedef value_type& reference;
702 typedef value_type* pointer;
703 typedef BumpVector<CFGBlock*>::iterator ImplTy;
705 graph_iterator(const ImplTy &i) : I(i) {}
707 bool operator==(const graph_iterator &X) const { return I == X.I; }
708 bool operator!=(const graph_iterator &X) const { return I != X.I; }
710 reference operator*() const { return **I; }
711 pointer operator->() const { return *I; }
712 operator CFGBlock* () { return *I; }
714 graph_iterator &operator++() { ++I; return *this; }
715 graph_iterator &operator--() { --I; return *this; }
721 class const_graph_iterator {
723 typedef const CFGBlock value_type;
724 typedef value_type& reference;
725 typedef value_type* pointer;
726 typedef BumpVector<CFGBlock*>::const_iterator ImplTy;
728 const_graph_iterator(const ImplTy &i) : I(i) {}
730 bool operator==(const const_graph_iterator &X) const { return I == X.I; }
731 bool operator!=(const const_graph_iterator &X) const { return I != X.I; }
733 reference operator*() const { return **I; }
734 pointer operator->() const { return *I; }
735 operator CFGBlock* () const { return *I; }
737 const_graph_iterator &operator++() { ++I; return *this; }
738 const_graph_iterator &operator--() { --I; return *this; }
744 /// buildCFG - Builds a CFG from an AST. The responsibility to free the
745 /// constructed CFG belongs to the caller.
746 static CFG* buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
747 const BuildOptions &BO);
749 /// createBlock - Create a new block in the CFG. The CFG owns the block;
750 /// the caller should not directly free it.
751 CFGBlock *createBlock();
753 /// setEntry - Set the entry block of the CFG. This is typically used
754 /// only during CFG construction. Most CFG clients expect that the
755 /// entry block has no predecessors and contains no statements.
756 void setEntry(CFGBlock *B) { Entry = B; }
758 /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
759 /// This is typically used only during CFG construction.
760 void setIndirectGotoBlock(CFGBlock *B) { IndirectGotoBlock = B; }
762 //===--------------------------------------------------------------------===//
764 //===--------------------------------------------------------------------===//
766 typedef BumpVector<CFGBlock*> CFGBlockListTy;
767 typedef CFGBlockListTy::iterator iterator;
768 typedef CFGBlockListTy::const_iterator const_iterator;
769 typedef std::reverse_iterator<iterator> reverse_iterator;
770 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
772 CFGBlock & front() { return *Blocks.front(); }
773 CFGBlock & back() { return *Blocks.back(); }
775 iterator begin() { return Blocks.begin(); }
776 iterator end() { return Blocks.end(); }
777 const_iterator begin() const { return Blocks.begin(); }
778 const_iterator end() const { return Blocks.end(); }
780 graph_iterator nodes_begin() { return graph_iterator(Blocks.begin()); }
781 graph_iterator nodes_end() { return graph_iterator(Blocks.end()); }
782 const_graph_iterator nodes_begin() const {
783 return const_graph_iterator(Blocks.begin());
785 const_graph_iterator nodes_end() const {
786 return const_graph_iterator(Blocks.end());
789 reverse_iterator rbegin() { return Blocks.rbegin(); }
790 reverse_iterator rend() { return Blocks.rend(); }
791 const_reverse_iterator rbegin() const { return Blocks.rbegin(); }
792 const_reverse_iterator rend() const { return Blocks.rend(); }
794 CFGBlock & getEntry() { return *Entry; }
795 const CFGBlock & getEntry() const { return *Entry; }
796 CFGBlock & getExit() { return *Exit; }
797 const CFGBlock & getExit() const { return *Exit; }
799 CFGBlock * getIndirectGotoBlock() { return IndirectGotoBlock; }
800 const CFGBlock * getIndirectGotoBlock() const { return IndirectGotoBlock; }
802 typedef std::vector<const CFGBlock*>::const_iterator try_block_iterator;
803 try_block_iterator try_blocks_begin() const {
804 return TryDispatchBlocks.begin();
806 try_block_iterator try_blocks_end() const {
807 return TryDispatchBlocks.end();
810 void addTryDispatchBlock(const CFGBlock *block) {
811 TryDispatchBlocks.push_back(block);
814 /// Records a synthetic DeclStmt and the DeclStmt it was constructed from.
816 /// The CFG uses synthetic DeclStmts when a single AST DeclStmt contains
818 void addSyntheticDeclStmt(const DeclStmt *Synthetic,
819 const DeclStmt *Source) {
820 assert(Synthetic->isSingleDecl() && "Can handle single declarations only");
821 assert(Synthetic != Source && "Don't include original DeclStmts in map");
822 assert(!SyntheticDeclStmts.count(Synthetic) && "Already in map");
823 SyntheticDeclStmts[Synthetic] = Source;
826 typedef llvm::DenseMap<const DeclStmt *, const DeclStmt *>::const_iterator
827 synthetic_stmt_iterator;
829 /// Iterates over synthetic DeclStmts in the CFG.
831 /// Each element is a (synthetic statement, source statement) pair.
833 /// \sa addSyntheticDeclStmt
834 synthetic_stmt_iterator synthetic_stmt_begin() const {
835 return SyntheticDeclStmts.begin();
838 /// \sa synthetic_stmt_begin
839 synthetic_stmt_iterator synthetic_stmt_end() const {
840 return SyntheticDeclStmts.end();
843 //===--------------------------------------------------------------------===//
844 // Member templates useful for various batch operations over CFGs.
845 //===--------------------------------------------------------------------===//
847 template <typename CALLBACK>
848 void VisitBlockStmts(CALLBACK& O) const {
849 for (const_iterator I=begin(), E=end(); I != E; ++I)
850 for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
852 if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>())
853 O(const_cast<Stmt*>(stmt->getStmt()));
857 //===--------------------------------------------------------------------===//
858 // CFG Introspection.
859 //===--------------------------------------------------------------------===//
861 /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
863 unsigned getNumBlockIDs() const { return NumBlockIDs; }
865 /// size - Return the total number of CFGBlocks within the CFG
866 /// This is simply a renaming of the getNumBlockIDs(). This is necessary
867 /// because the dominator implementation needs such an interface.
868 unsigned size() const { return NumBlockIDs; }
870 //===--------------------------------------------------------------------===//
871 // CFG Debugging: Pretty-Printing and Visualization.
872 //===--------------------------------------------------------------------===//
874 void viewCFG(const LangOptions &LO) const;
875 void print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const;
876 void dump(const LangOptions &LO, bool ShowColors) const;
878 //===--------------------------------------------------------------------===//
879 // Internal: constructors and data.
880 //===--------------------------------------------------------------------===//
882 CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
883 Blocks(BlkBVC, 10) {}
885 llvm::BumpPtrAllocator& getAllocator() {
886 return BlkBVC.getAllocator();
889 BumpVectorContext &getBumpVectorContext() {
896 CFGBlock* IndirectGotoBlock; // Special block to contain collective dispatch
897 // for indirect gotos
898 unsigned NumBlockIDs;
900 BumpVectorContext BlkBVC;
902 CFGBlockListTy Blocks;
904 /// C++ 'try' statements are modeled with an indirect dispatch block.
905 /// This is the collection of such blocks present in the CFG.
906 std::vector<const CFGBlock *> TryDispatchBlocks;
908 /// Collects DeclStmts synthesized for this CFG and maps each one back to its
910 llvm::DenseMap<const DeclStmt *, const DeclStmt *> SyntheticDeclStmts;
912 } // end namespace clang
914 //===----------------------------------------------------------------------===//
915 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
916 //===----------------------------------------------------------------------===//
920 /// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
921 /// CFGTerminator to a specific Stmt class.
922 template <> struct simplify_type< ::clang::CFGTerminator> {
923 typedef ::clang::Stmt *SimpleType;
924 static SimpleType getSimplifiedValue(::clang::CFGTerminator Val) {
925 return Val.getStmt();
929 // Traits for: CFGBlock
931 template <> struct GraphTraits< ::clang::CFGBlock *> {
932 typedef ::clang::CFGBlock NodeType;
933 typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
935 static NodeType* getEntryNode(::clang::CFGBlock *BB)
938 static inline ChildIteratorType child_begin(NodeType* N)
939 { return N->succ_begin(); }
941 static inline ChildIteratorType child_end(NodeType* N)
942 { return N->succ_end(); }
945 template <> struct GraphTraits< const ::clang::CFGBlock *> {
946 typedef const ::clang::CFGBlock NodeType;
947 typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
949 static NodeType* getEntryNode(const clang::CFGBlock *BB)
952 static inline ChildIteratorType child_begin(NodeType* N)
953 { return N->succ_begin(); }
955 static inline ChildIteratorType child_end(NodeType* N)
956 { return N->succ_end(); }
959 template <> struct GraphTraits<Inverse< ::clang::CFGBlock*> > {
960 typedef ::clang::CFGBlock NodeType;
961 typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
963 static NodeType *getEntryNode(Inverse< ::clang::CFGBlock*> G)
966 static inline ChildIteratorType child_begin(NodeType* N)
967 { return N->pred_begin(); }
969 static inline ChildIteratorType child_end(NodeType* N)
970 { return N->pred_end(); }
973 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
974 typedef const ::clang::CFGBlock NodeType;
975 typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
977 static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
980 static inline ChildIteratorType child_begin(NodeType* N)
981 { return N->pred_begin(); }
983 static inline ChildIteratorType child_end(NodeType* N)
984 { return N->pred_end(); }
989 template <> struct GraphTraits< ::clang::CFG* >
990 : public GraphTraits< ::clang::CFGBlock *> {
992 typedef ::clang::CFG::graph_iterator nodes_iterator;
994 static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
995 static nodes_iterator nodes_begin(::clang::CFG* F) { return F->nodes_begin();}
996 static nodes_iterator nodes_end(::clang::CFG* F) { return F->nodes_end(); }
997 static unsigned size(::clang::CFG* F) { return F->size(); }
1000 template <> struct GraphTraits<const ::clang::CFG* >
1001 : public GraphTraits<const ::clang::CFGBlock *> {
1003 typedef ::clang::CFG::const_graph_iterator nodes_iterator;
1005 static NodeType *getEntryNode( const ::clang::CFG* F) {
1006 return &F->getEntry();
1008 static nodes_iterator nodes_begin( const ::clang::CFG* F) {
1009 return F->nodes_begin();
1011 static nodes_iterator nodes_end( const ::clang::CFG* F) {
1012 return F->nodes_end();
1014 static unsigned size(const ::clang::CFG* F) {
1019 template <> struct GraphTraits<Inverse< ::clang::CFG*> >
1020 : public GraphTraits<Inverse< ::clang::CFGBlock*> > {
1022 typedef ::clang::CFG::graph_iterator nodes_iterator;
1024 static NodeType *getEntryNode( ::clang::CFG* F) { return &F->getExit(); }
1025 static nodes_iterator nodes_begin( ::clang::CFG* F) {return F->nodes_begin();}
1026 static nodes_iterator nodes_end( ::clang::CFG* F) { return F->nodes_end(); }
1029 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
1030 : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
1032 typedef ::clang::CFG::const_graph_iterator nodes_iterator;
1034 static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
1035 static nodes_iterator nodes_begin(const ::clang::CFG* F) {
1036 return F->nodes_begin();
1038 static nodes_iterator nodes_end(const ::clang::CFG* F) {
1039 return F->nodes_end();
1042 } // end llvm namespace