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/PointerIntPair.h"
25 #include "llvm/Support/Allocator.h"
26 #include "llvm/Support/Casting.h"
27 #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
416 /// This class represents a potential adjacent block in the CFG. It encodes
417 /// whether or not the block is actually reachable, or can be proved to be
418 /// trivially unreachable. For some cases it allows one to encode scenarios
419 /// where a block was substituted because the original (now alternate) block
421 class AdjacentBlock {
428 CFGBlock *ReachableBlock;
429 llvm::PointerIntPair<CFGBlock*, 2> UnreachableBlock;
432 /// Construct an AdjacentBlock with a possibly unreachable block.
433 AdjacentBlock(CFGBlock *B, bool IsReachable);
435 /// Construct an AdjacentBlock with a reachable block and an alternate
436 /// unreachable block.
437 AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock);
439 /// Get the reachable block, if one exists.
440 CFGBlock *getReachableBlock() const {
441 return ReachableBlock;
444 /// Get the potentially unreachable block.
445 CFGBlock *getPossiblyUnreachableBlock() const {
446 return UnreachableBlock.getPointer();
449 /// Provide an implicit conversion to CFGBlock* so that
450 /// AdjacentBlock can be substituted for CFGBlock*.
451 operator CFGBlock*() const {
452 return getReachableBlock();
455 CFGBlock& operator *() const {
456 return *getReachableBlock();
459 CFGBlock* operator ->() const {
460 return getReachableBlock();
463 bool isReachable() const {
464 Kind K = (Kind) UnreachableBlock.getInt();
465 return K == AB_Normal || K == AB_Alternate;
470 /// Predecessors/Successors - Keep track of the predecessor / successor
472 typedef BumpVector<AdjacentBlock> AdjacentBlocks;
473 AdjacentBlocks Preds;
474 AdjacentBlocks Succs;
476 /// NoReturn - This bit is set when the basic block contains a function call
477 /// or implicit destructor that is attributed as 'noreturn'. In that case,
478 /// control cannot technically ever proceed past this block. All such blocks
479 /// will have a single immediate successor: the exit block. This allows them
480 /// to be easily reached from the exit block and using this bit quickly
481 /// recognized without scanning the contents of the block.
483 /// Optimization Note: This bit could be profitably folded with Terminator's
484 /// storage if the memory usage of CFGBlock becomes an issue.
485 unsigned HasNoReturnElement : 1;
487 /// Parent - The parent CFG that owns this CFGBlock.
491 explicit CFGBlock(unsigned blockid, BumpVectorContext &C, CFG *parent)
492 : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
493 BlockID(blockid), Preds(C, 1), Succs(C, 1), HasNoReturnElement(false),
497 // Statement iterators
498 typedef ElementList::iterator iterator;
499 typedef ElementList::const_iterator const_iterator;
500 typedef ElementList::reverse_iterator reverse_iterator;
501 typedef ElementList::const_reverse_iterator const_reverse_iterator;
503 CFGElement front() const { return Elements.front(); }
504 CFGElement back() const { return Elements.back(); }
506 iterator begin() { return Elements.begin(); }
507 iterator end() { return Elements.end(); }
508 const_iterator begin() const { return Elements.begin(); }
509 const_iterator end() const { return Elements.end(); }
511 reverse_iterator rbegin() { return Elements.rbegin(); }
512 reverse_iterator rend() { return Elements.rend(); }
513 const_reverse_iterator rbegin() const { return Elements.rbegin(); }
514 const_reverse_iterator rend() const { return Elements.rend(); }
516 unsigned size() const { return Elements.size(); }
517 bool empty() const { return Elements.empty(); }
519 CFGElement operator[](size_t i) const { return Elements[i]; }
522 typedef AdjacentBlocks::iterator pred_iterator;
523 typedef AdjacentBlocks::const_iterator const_pred_iterator;
524 typedef AdjacentBlocks::reverse_iterator pred_reverse_iterator;
525 typedef AdjacentBlocks::const_reverse_iterator const_pred_reverse_iterator;
527 typedef AdjacentBlocks::iterator succ_iterator;
528 typedef AdjacentBlocks::const_iterator const_succ_iterator;
529 typedef AdjacentBlocks::reverse_iterator succ_reverse_iterator;
530 typedef AdjacentBlocks::const_reverse_iterator const_succ_reverse_iterator;
532 pred_iterator pred_begin() { return Preds.begin(); }
533 pred_iterator pred_end() { return Preds.end(); }
534 const_pred_iterator pred_begin() const { return Preds.begin(); }
535 const_pred_iterator pred_end() const { return Preds.end(); }
537 pred_reverse_iterator pred_rbegin() { return Preds.rbegin(); }
538 pred_reverse_iterator pred_rend() { return Preds.rend(); }
539 const_pred_reverse_iterator pred_rbegin() const { return Preds.rbegin(); }
540 const_pred_reverse_iterator pred_rend() const { return Preds.rend(); }
542 succ_iterator succ_begin() { return Succs.begin(); }
543 succ_iterator succ_end() { return Succs.end(); }
544 const_succ_iterator succ_begin() const { return Succs.begin(); }
545 const_succ_iterator succ_end() const { return Succs.end(); }
547 succ_reverse_iterator succ_rbegin() { return Succs.rbegin(); }
548 succ_reverse_iterator succ_rend() { return Succs.rend(); }
549 const_succ_reverse_iterator succ_rbegin() const { return Succs.rbegin(); }
550 const_succ_reverse_iterator succ_rend() const { return Succs.rend(); }
552 unsigned succ_size() const { return Succs.size(); }
553 bool succ_empty() const { return Succs.empty(); }
555 unsigned pred_size() const { return Preds.size(); }
556 bool pred_empty() const { return Preds.empty(); }
559 class FilterOptions {
562 IgnoreNullPredecessors = 1;
563 IgnoreDefaultsWithCoveredEnums = 0;
566 unsigned IgnoreNullPredecessors : 1;
567 unsigned IgnoreDefaultsWithCoveredEnums : 1;
570 static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
571 const CFGBlock *Dst);
573 template <typename IMPL, bool IsPred>
574 class FilteredCFGBlockIterator {
577 const FilterOptions F;
578 const CFGBlock *From;
580 explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
581 const CFGBlock *from,
582 const FilterOptions &f)
583 : I(i), E(e), F(f), From(from) {
584 while (hasMore() && Filter(*I))
588 bool hasMore() const { return I != E; }
590 FilteredCFGBlockIterator &operator++() {
591 do { ++I; } while (hasMore() && Filter(*I));
595 const CFGBlock *operator*() const { return *I; }
597 bool Filter(const CFGBlock *To) {
598 return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
602 typedef FilteredCFGBlockIterator<const_pred_iterator, true>
603 filtered_pred_iterator;
605 typedef FilteredCFGBlockIterator<const_succ_iterator, false>
606 filtered_succ_iterator;
608 filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
609 return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
612 filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
613 return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
616 // Manipulation of block contents
618 void setTerminator(CFGTerminator Term) { Terminator = Term; }
619 void setLabel(Stmt *Statement) { Label = Statement; }
620 void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
621 void setHasNoReturnElement() { HasNoReturnElement = true; }
623 CFGTerminator getTerminator() { return Terminator; }
624 const CFGTerminator getTerminator() const { return Terminator; }
626 Stmt *getTerminatorCondition(bool StripParens = true);
628 const Stmt *getTerminatorCondition(bool StripParens = true) const {
629 return const_cast<CFGBlock*>(this)->getTerminatorCondition(StripParens);
632 const Stmt *getLoopTarget() const { return LoopTarget; }
634 Stmt *getLabel() { return Label; }
635 const Stmt *getLabel() const { return Label; }
637 bool hasNoReturnElement() const { return HasNoReturnElement; }
639 unsigned getBlockID() const { return BlockID; }
641 CFG *getParent() const { return Parent; }
643 void dump(const CFG *cfg, const LangOptions &LO, bool ShowColors = false) const;
644 void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO,
645 bool ShowColors) const;
646 void printTerminator(raw_ostream &OS, const LangOptions &LO) const;
647 void printAsOperand(raw_ostream &OS, bool /*PrintType*/) {
648 OS << "BB#" << getBlockID();
651 /// Adds a (potentially unreachable) successor block to the current block.
652 void addSuccessor(AdjacentBlock Succ, BumpVectorContext &C);
654 void appendStmt(Stmt *statement, BumpVectorContext &C) {
655 Elements.push_back(CFGStmt(statement), C);
658 void appendInitializer(CXXCtorInitializer *initializer,
659 BumpVectorContext &C) {
660 Elements.push_back(CFGInitializer(initializer), C);
663 void appendNewAllocator(CXXNewExpr *NE,
664 BumpVectorContext &C) {
665 Elements.push_back(CFGNewAllocator(NE), C);
668 void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
669 Elements.push_back(CFGBaseDtor(BS), C);
672 void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
673 Elements.push_back(CFGMemberDtor(FD), C);
676 void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
677 Elements.push_back(CFGTemporaryDtor(E), C);
680 void appendAutomaticObjDtor(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
681 Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
684 void appendDeleteDtor(CXXRecordDecl *RD, CXXDeleteExpr *DE, BumpVectorContext &C) {
685 Elements.push_back(CFGDeleteDtor(RD, DE), C);
688 // Destructors must be inserted in reversed order. So insertion is in two
689 // steps. First we prepare space for some number of elements, then we insert
690 // the elements beginning at the last position in prepared space.
691 iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
692 BumpVectorContext &C) {
693 return iterator(Elements.insert(I.base(), Cnt, CFGAutomaticObjDtor(0, 0), C));
695 iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
696 *I = CFGAutomaticObjDtor(VD, S);
701 /// CFG - Represents a source-level, intra-procedural CFG that represents the
702 /// control-flow of a Stmt. The Stmt can represent an entire function body,
703 /// or a single expression. A CFG will always contain one empty block that
704 /// represents the Exit point of the CFG. A CFG will also contain a designated
705 /// Entry block. The CFG solely represents control-flow; it consists of
706 /// CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
707 /// was constructed from.
710 //===--------------------------------------------------------------------===//
711 // CFG Construction & Manipulation.
712 //===--------------------------------------------------------------------===//
715 std::bitset<Stmt::lastStmtConstant> alwaysAddMask;
717 typedef llvm::DenseMap<const Stmt *, const CFGBlock*> ForcedBlkExprs;
718 ForcedBlkExprs **forcedBlkExprs;
720 bool PruneTriviallyFalseEdges;
722 bool AddInitializers;
723 bool AddImplicitDtors;
724 bool AddTemporaryDtors;
725 bool AddStaticInitBranches;
726 bool AddCXXNewAllocator;
728 bool alwaysAdd(const Stmt *stmt) const {
729 return alwaysAddMask[stmt->getStmtClass()];
732 BuildOptions &setAlwaysAdd(Stmt::StmtClass stmtClass, bool val = true) {
733 alwaysAddMask[stmtClass] = val;
737 BuildOptions &setAllAlwaysAdd() {
743 : forcedBlkExprs(0), PruneTriviallyFalseEdges(true)
745 ,AddInitializers(false)
746 ,AddImplicitDtors(false)
747 ,AddTemporaryDtors(false)
748 ,AddStaticInitBranches(false)
749 ,AddCXXNewAllocator(false) {}
752 /// \brief Provides a custom implementation of the iterator class to have the
753 /// same interface as Function::iterator - iterator returns CFGBlock
754 /// (not a pointer to CFGBlock).
755 class graph_iterator {
757 typedef const CFGBlock value_type;
758 typedef value_type& reference;
759 typedef value_type* pointer;
760 typedef BumpVector<CFGBlock*>::iterator ImplTy;
762 graph_iterator(const ImplTy &i) : I(i) {}
764 bool operator==(const graph_iterator &X) const { return I == X.I; }
765 bool operator!=(const graph_iterator &X) const { return I != X.I; }
767 reference operator*() const { return **I; }
768 pointer operator->() const { return *I; }
769 operator CFGBlock* () { return *I; }
771 graph_iterator &operator++() { ++I; return *this; }
772 graph_iterator &operator--() { --I; return *this; }
778 class const_graph_iterator {
780 typedef const CFGBlock value_type;
781 typedef value_type& reference;
782 typedef value_type* pointer;
783 typedef BumpVector<CFGBlock*>::const_iterator ImplTy;
785 const_graph_iterator(const ImplTy &i) : I(i) {}
787 bool operator==(const const_graph_iterator &X) const { return I == X.I; }
788 bool operator!=(const const_graph_iterator &X) const { return I != X.I; }
790 reference operator*() const { return **I; }
791 pointer operator->() const { return *I; }
792 operator CFGBlock* () const { return *I; }
794 const_graph_iterator &operator++() { ++I; return *this; }
795 const_graph_iterator &operator--() { --I; return *this; }
801 /// buildCFG - Builds a CFG from an AST. The responsibility to free the
802 /// constructed CFG belongs to the caller.
803 static CFG* buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
804 const BuildOptions &BO);
806 /// createBlock - Create a new block in the CFG. The CFG owns the block;
807 /// the caller should not directly free it.
808 CFGBlock *createBlock();
810 /// setEntry - Set the entry block of the CFG. This is typically used
811 /// only during CFG construction. Most CFG clients expect that the
812 /// entry block has no predecessors and contains no statements.
813 void setEntry(CFGBlock *B) { Entry = B; }
815 /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
816 /// This is typically used only during CFG construction.
817 void setIndirectGotoBlock(CFGBlock *B) { IndirectGotoBlock = B; }
819 //===--------------------------------------------------------------------===//
821 //===--------------------------------------------------------------------===//
823 typedef BumpVector<CFGBlock*> CFGBlockListTy;
824 typedef CFGBlockListTy::iterator iterator;
825 typedef CFGBlockListTy::const_iterator const_iterator;
826 typedef std::reverse_iterator<iterator> reverse_iterator;
827 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
829 CFGBlock & front() { return *Blocks.front(); }
830 CFGBlock & back() { return *Blocks.back(); }
832 iterator begin() { return Blocks.begin(); }
833 iterator end() { return Blocks.end(); }
834 const_iterator begin() const { return Blocks.begin(); }
835 const_iterator end() const { return Blocks.end(); }
837 graph_iterator nodes_begin() { return graph_iterator(Blocks.begin()); }
838 graph_iterator nodes_end() { return graph_iterator(Blocks.end()); }
839 const_graph_iterator nodes_begin() const {
840 return const_graph_iterator(Blocks.begin());
842 const_graph_iterator nodes_end() const {
843 return const_graph_iterator(Blocks.end());
846 reverse_iterator rbegin() { return Blocks.rbegin(); }
847 reverse_iterator rend() { return Blocks.rend(); }
848 const_reverse_iterator rbegin() const { return Blocks.rbegin(); }
849 const_reverse_iterator rend() const { return Blocks.rend(); }
851 CFGBlock & getEntry() { return *Entry; }
852 const CFGBlock & getEntry() const { return *Entry; }
853 CFGBlock & getExit() { return *Exit; }
854 const CFGBlock & getExit() const { return *Exit; }
856 CFGBlock * getIndirectGotoBlock() { return IndirectGotoBlock; }
857 const CFGBlock * getIndirectGotoBlock() const { return IndirectGotoBlock; }
859 typedef std::vector<const CFGBlock*>::const_iterator try_block_iterator;
860 try_block_iterator try_blocks_begin() const {
861 return TryDispatchBlocks.begin();
863 try_block_iterator try_blocks_end() const {
864 return TryDispatchBlocks.end();
867 void addTryDispatchBlock(const CFGBlock *block) {
868 TryDispatchBlocks.push_back(block);
871 /// Records a synthetic DeclStmt and the DeclStmt it was constructed from.
873 /// The CFG uses synthetic DeclStmts when a single AST DeclStmt contains
875 void addSyntheticDeclStmt(const DeclStmt *Synthetic,
876 const DeclStmt *Source) {
877 assert(Synthetic->isSingleDecl() && "Can handle single declarations only");
878 assert(Synthetic != Source && "Don't include original DeclStmts in map");
879 assert(!SyntheticDeclStmts.count(Synthetic) && "Already in map");
880 SyntheticDeclStmts[Synthetic] = Source;
883 typedef llvm::DenseMap<const DeclStmt *, const DeclStmt *>::const_iterator
884 synthetic_stmt_iterator;
886 /// Iterates over synthetic DeclStmts in the CFG.
888 /// Each element is a (synthetic statement, source statement) pair.
890 /// \sa addSyntheticDeclStmt
891 synthetic_stmt_iterator synthetic_stmt_begin() const {
892 return SyntheticDeclStmts.begin();
895 /// \sa synthetic_stmt_begin
896 synthetic_stmt_iterator synthetic_stmt_end() const {
897 return SyntheticDeclStmts.end();
900 //===--------------------------------------------------------------------===//
901 // Member templates useful for various batch operations over CFGs.
902 //===--------------------------------------------------------------------===//
904 template <typename CALLBACK>
905 void VisitBlockStmts(CALLBACK& O) const {
906 for (const_iterator I=begin(), E=end(); I != E; ++I)
907 for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
909 if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>())
910 O(const_cast<Stmt*>(stmt->getStmt()));
914 //===--------------------------------------------------------------------===//
915 // CFG Introspection.
916 //===--------------------------------------------------------------------===//
918 /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
920 unsigned getNumBlockIDs() const { return NumBlockIDs; }
922 /// size - Return the total number of CFGBlocks within the CFG
923 /// This is simply a renaming of the getNumBlockIDs(). This is necessary
924 /// because the dominator implementation needs such an interface.
925 unsigned size() const { return NumBlockIDs; }
927 //===--------------------------------------------------------------------===//
928 // CFG Debugging: Pretty-Printing and Visualization.
929 //===--------------------------------------------------------------------===//
931 void viewCFG(const LangOptions &LO) const;
932 void print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const;
933 void dump(const LangOptions &LO, bool ShowColors) const;
935 //===--------------------------------------------------------------------===//
936 // Internal: constructors and data.
937 //===--------------------------------------------------------------------===//
939 CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
940 Blocks(BlkBVC, 10) {}
942 llvm::BumpPtrAllocator& getAllocator() {
943 return BlkBVC.getAllocator();
946 BumpVectorContext &getBumpVectorContext() {
953 CFGBlock* IndirectGotoBlock; // Special block to contain collective dispatch
954 // for indirect gotos
955 unsigned NumBlockIDs;
957 BumpVectorContext BlkBVC;
959 CFGBlockListTy Blocks;
961 /// C++ 'try' statements are modeled with an indirect dispatch block.
962 /// This is the collection of such blocks present in the CFG.
963 std::vector<const CFGBlock *> TryDispatchBlocks;
965 /// Collects DeclStmts synthesized for this CFG and maps each one back to its
967 llvm::DenseMap<const DeclStmt *, const DeclStmt *> SyntheticDeclStmts;
969 } // end namespace clang
971 //===----------------------------------------------------------------------===//
972 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
973 //===----------------------------------------------------------------------===//
977 /// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
978 /// CFGTerminator to a specific Stmt class.
979 template <> struct simplify_type< ::clang::CFGTerminator> {
980 typedef ::clang::Stmt *SimpleType;
981 static SimpleType getSimplifiedValue(::clang::CFGTerminator Val) {
982 return Val.getStmt();
986 // Traits for: CFGBlock
988 template <> struct GraphTraits< ::clang::CFGBlock *> {
989 typedef ::clang::CFGBlock NodeType;
990 typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
992 static NodeType* getEntryNode(::clang::CFGBlock *BB)
995 static inline ChildIteratorType child_begin(NodeType* N)
996 { return N->succ_begin(); }
998 static inline ChildIteratorType child_end(NodeType* N)
999 { return N->succ_end(); }
1002 template <> struct GraphTraits< const ::clang::CFGBlock *> {
1003 typedef const ::clang::CFGBlock NodeType;
1004 typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
1006 static NodeType* getEntryNode(const clang::CFGBlock *BB)
1009 static inline ChildIteratorType child_begin(NodeType* N)
1010 { return N->succ_begin(); }
1012 static inline ChildIteratorType child_end(NodeType* N)
1013 { return N->succ_end(); }
1016 template <> struct GraphTraits<Inverse< ::clang::CFGBlock*> > {
1017 typedef ::clang::CFGBlock NodeType;
1018 typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
1020 static NodeType *getEntryNode(Inverse< ::clang::CFGBlock*> G)
1023 static inline ChildIteratorType child_begin(NodeType* N)
1024 { return N->pred_begin(); }
1026 static inline ChildIteratorType child_end(NodeType* N)
1027 { return N->pred_end(); }
1030 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
1031 typedef const ::clang::CFGBlock NodeType;
1032 typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
1034 static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
1037 static inline ChildIteratorType child_begin(NodeType* N)
1038 { return N->pred_begin(); }
1040 static inline ChildIteratorType child_end(NodeType* N)
1041 { return N->pred_end(); }
1046 template <> struct GraphTraits< ::clang::CFG* >
1047 : public GraphTraits< ::clang::CFGBlock *> {
1049 typedef ::clang::CFG::graph_iterator nodes_iterator;
1051 static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
1052 static nodes_iterator nodes_begin(::clang::CFG* F) { return F->nodes_begin();}
1053 static nodes_iterator nodes_end(::clang::CFG* F) { return F->nodes_end(); }
1054 static unsigned size(::clang::CFG* F) { return F->size(); }
1057 template <> struct GraphTraits<const ::clang::CFG* >
1058 : public GraphTraits<const ::clang::CFGBlock *> {
1060 typedef ::clang::CFG::const_graph_iterator nodes_iterator;
1062 static NodeType *getEntryNode( const ::clang::CFG* F) {
1063 return &F->getEntry();
1065 static nodes_iterator nodes_begin( const ::clang::CFG* F) {
1066 return F->nodes_begin();
1068 static nodes_iterator nodes_end( const ::clang::CFG* F) {
1069 return F->nodes_end();
1071 static unsigned size(const ::clang::CFG* F) {
1076 template <> struct GraphTraits<Inverse< ::clang::CFG*> >
1077 : public GraphTraits<Inverse< ::clang::CFGBlock*> > {
1079 typedef ::clang::CFG::graph_iterator nodes_iterator;
1081 static NodeType *getEntryNode( ::clang::CFG* F) { return &F->getExit(); }
1082 static nodes_iterator nodes_begin( ::clang::CFG* F) {return F->nodes_begin();}
1083 static nodes_iterator nodes_end( ::clang::CFG* F) { return F->nodes_end(); }
1086 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
1087 : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
1089 typedef ::clang::CFG::const_graph_iterator nodes_iterator;
1091 static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
1092 static nodes_iterator nodes_begin(const ::clang::CFG* F) {
1093 return F->nodes_begin();
1095 static nodes_iterator nodes_end(const ::clang::CFG* F) {
1096 return F->nodes_end();
1099 } // end llvm namespace