CFG.h revision 683b70c70dc47532af1215e4b1566de9d47a3be5
1//===--- CFG.h - Classes for representing and building CFGs------*- 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//
10//  This file defines the CFG and CFGBuilder classes for representing and
11//  building Control-Flow Graphs (CFGs) from ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_CFG_H
16#define LLVM_CLANG_CFG_H
17
18#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/ADT/GraphTraits.h"
20#include "llvm/Support/Allocator.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/ADT/OwningPtr.h"
23#include "llvm/ADT/DenseMap.h"
24#include "clang/AST/Stmt.h"
25#include "clang/Analysis/Support/BumpVector.h"
26#include "clang/Basic/SourceLocation.h"
27#include <bitset>
28#include <cassert>
29#include <iterator>
30
31namespace clang {
32  class CXXDestructorDecl;
33  class Decl;
34  class Stmt;
35  class Expr;
36  class FieldDecl;
37  class VarDecl;
38  class CXXCtorInitializer;
39  class CXXBaseSpecifier;
40  class CXXBindTemporaryExpr;
41  class CFG;
42  class PrinterHelper;
43  class LangOptions;
44  class ASTContext;
45
46/// CFGElement - Represents a top-level expression in a basic block.
47class CFGElement {
48public:
49  enum Kind {
50    // main kind
51    Invalid,
52    Statement,
53    Initializer,
54    // dtor kind
55    AutomaticObjectDtor,
56    BaseDtor,
57    MemberDtor,
58    TemporaryDtor,
59    DTOR_BEGIN = AutomaticObjectDtor,
60    DTOR_END = TemporaryDtor
61  };
62
63protected:
64  // The int bits are used to mark the kind.
65  llvm::PointerIntPair<void *, 2> Data1;
66  llvm::PointerIntPair<void *, 2> Data2;
67
68  CFGElement(Kind kind, const void *Ptr1, const void *Ptr2 = 0)
69    : Data1(const_cast<void*>(Ptr1), ((unsigned) kind) & 0x3),
70      Data2(const_cast<void*>(Ptr2), (((unsigned) kind) >> 2) & 0x3) {}
71
72public:
73  CFGElement() {}
74
75  Kind getKind() const {
76    unsigned x = Data2.getInt();
77    x <<= 2;
78    x |= Data1.getInt();
79    return (Kind) x;
80  }
81
82  bool isValid() const { return getKind() != Invalid; }
83
84  operator bool() const { return isValid(); }
85
86  template<class ElemTy> const ElemTy *getAs() const LLVM_LVALUE_FUNCTION {
87    return dyn_cast<ElemTy>(this);
88  }
89
90#if LLVM_HAS_RVALUE_REFERENCE_THIS
91  template<class ElemTy> void getAs() && LLVM_DELETED_FUNCTION;
92#endif
93};
94
95class CFGStmt : public CFGElement {
96public:
97  CFGStmt(Stmt *S) : CFGElement(Statement, S) {}
98
99  const Stmt *getStmt() const {
100    return static_cast<const Stmt *>(Data1.getPointer());
101  }
102
103  static bool classof(const CFGElement *E) {
104    return E->getKind() == Statement;
105  }
106};
107
108/// CFGInitializer - Represents C++ base or member initializer from
109/// constructor's initialization list.
110class CFGInitializer : public CFGElement {
111public:
112  CFGInitializer(CXXCtorInitializer *initializer)
113      : CFGElement(Initializer, initializer) {}
114
115  CXXCtorInitializer* getInitializer() const {
116    return static_cast<CXXCtorInitializer*>(Data1.getPointer());
117  }
118
119  static bool classof(const CFGElement *E) {
120    return E->getKind() == Initializer;
121  }
122};
123
124/// CFGImplicitDtor - Represents C++ object destructor implicitly generated
125/// by compiler on various occasions.
126class CFGImplicitDtor : public CFGElement {
127protected:
128  CFGImplicitDtor(Kind kind, const void *data1, const void *data2 = 0)
129    : CFGElement(kind, data1, data2) {
130    assert(kind >= DTOR_BEGIN && kind <= DTOR_END);
131  }
132
133public:
134  const CXXDestructorDecl *getDestructorDecl(ASTContext &astContext) const;
135  bool isNoReturn(ASTContext &astContext) const;
136
137  static bool classof(const CFGElement *E) {
138    Kind kind = E->getKind();
139    return kind >= DTOR_BEGIN && kind <= DTOR_END;
140  }
141};
142
143/// CFGAutomaticObjDtor - Represents C++ object destructor implicitly generated
144/// for automatic object or temporary bound to const reference at the point
145/// of leaving its local scope.
146class CFGAutomaticObjDtor: public CFGImplicitDtor {
147public:
148  CFGAutomaticObjDtor(const VarDecl *var, const Stmt *stmt)
149      : CFGImplicitDtor(AutomaticObjectDtor, var, stmt) {}
150
151  const VarDecl *getVarDecl() const {
152    return static_cast<VarDecl*>(Data1.getPointer());
153  }
154
155  // Get statement end of which triggered the destructor call.
156  const Stmt *getTriggerStmt() const {
157    return static_cast<Stmt*>(Data2.getPointer());
158  }
159
160  static bool classof(const CFGElement *elem) {
161    return elem->getKind() == AutomaticObjectDtor;
162  }
163};
164
165/// CFGBaseDtor - Represents C++ object destructor implicitly generated for
166/// base object in destructor.
167class CFGBaseDtor : public CFGImplicitDtor {
168public:
169  CFGBaseDtor(const CXXBaseSpecifier *base)
170      : CFGImplicitDtor(BaseDtor, base) {}
171
172  const CXXBaseSpecifier *getBaseSpecifier() const {
173    return static_cast<const CXXBaseSpecifier*>(Data1.getPointer());
174  }
175
176  static bool classof(const CFGElement *E) {
177    return E->getKind() == BaseDtor;
178  }
179};
180
181/// CFGMemberDtor - Represents C++ object destructor implicitly generated for
182/// member object in destructor.
183class CFGMemberDtor : public CFGImplicitDtor {
184public:
185  CFGMemberDtor(const FieldDecl *field)
186      : CFGImplicitDtor(MemberDtor, field, 0) {}
187
188  const FieldDecl *getFieldDecl() const {
189    return static_cast<const FieldDecl*>(Data1.getPointer());
190  }
191
192  static bool classof(const CFGElement *E) {
193    return E->getKind() == MemberDtor;
194  }
195};
196
197/// CFGTemporaryDtor - Represents C++ object destructor implicitly generated
198/// at the end of full expression for temporary object.
199class CFGTemporaryDtor : public CFGImplicitDtor {
200public:
201  CFGTemporaryDtor(CXXBindTemporaryExpr *expr)
202      : CFGImplicitDtor(TemporaryDtor, expr, 0) {}
203
204  const CXXBindTemporaryExpr *getBindTemporaryExpr() const {
205    return static_cast<const CXXBindTemporaryExpr *>(Data1.getPointer());
206  }
207
208  static bool classof(const CFGElement *E) {
209    return E->getKind() == TemporaryDtor;
210  }
211};
212
213/// CFGTerminator - Represents CFGBlock terminator statement.
214///
215/// TemporaryDtorsBranch bit is set to true if the terminator marks a branch
216/// in control flow of destructors of temporaries. In this case terminator
217/// statement is the same statement that branches control flow in evaluation
218/// of matching full expression.
219class CFGTerminator {
220  llvm::PointerIntPair<Stmt *, 1> Data;
221public:
222  CFGTerminator() {}
223  CFGTerminator(Stmt *S, bool TemporaryDtorsBranch = false)
224      : Data(S, TemporaryDtorsBranch) {}
225
226  Stmt *getStmt() { return Data.getPointer(); }
227  const Stmt *getStmt() const { return Data.getPointer(); }
228
229  bool isTemporaryDtorsBranch() const { return Data.getInt(); }
230
231  operator Stmt *() { return getStmt(); }
232  operator const Stmt *() const { return getStmt(); }
233
234  Stmt *operator->() { return getStmt(); }
235  const Stmt *operator->() const { return getStmt(); }
236
237  Stmt &operator*() { return *getStmt(); }
238  const Stmt &operator*() const { return *getStmt(); }
239
240  operator bool() const { return getStmt(); }
241};
242
243/// CFGBlock - Represents a single basic block in a source-level CFG.
244///  It consists of:
245///
246///  (1) A set of statements/expressions (which may contain subexpressions).
247///  (2) A "terminator" statement (not in the set of statements).
248///  (3) A list of successors and predecessors.
249///
250/// Terminator: The terminator represents the type of control-flow that occurs
251/// at the end of the basic block.  The terminator is a Stmt* referring to an
252/// AST node that has control-flow: if-statements, breaks, loops, etc.
253/// If the control-flow is conditional, the condition expression will appear
254/// within the set of statements in the block (usually the last statement).
255///
256/// Predecessors: the order in the set of predecessors is arbitrary.
257///
258/// Successors: the order in the set of successors is NOT arbitrary.  We
259///  currently have the following orderings based on the terminator:
260///
261///     Terminator       Successor Ordering
262///  -----------------------------------------------------
263///       if            Then Block;  Else Block
264///     ? operator      LHS expression;  RHS expression
265///     &&, ||          expression that uses result of && or ||, RHS
266///
267/// But note that any of that may be NULL in case of optimized-out edges.
268///
269class CFGBlock {
270  class ElementList {
271    typedef BumpVector<CFGElement> ImplTy;
272    ImplTy Impl;
273  public:
274    ElementList(BumpVectorContext &C) : Impl(C, 4) {}
275
276    typedef std::reverse_iterator<ImplTy::iterator>       iterator;
277    typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
278    typedef ImplTy::iterator                              reverse_iterator;
279    typedef ImplTy::const_iterator                       const_reverse_iterator;
280    typedef ImplTy::const_reference                       const_reference;
281
282    void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
283    reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
284        BumpVectorContext &C) {
285      return Impl.insert(I, Cnt, E, C);
286    }
287
288    const_reference front() const { return Impl.back(); }
289    const_reference back() const { return Impl.front(); }
290
291    iterator begin() { return Impl.rbegin(); }
292    iterator end() { return Impl.rend(); }
293    const_iterator begin() const { return Impl.rbegin(); }
294    const_iterator end() const { return Impl.rend(); }
295    reverse_iterator rbegin() { return Impl.begin(); }
296    reverse_iterator rend() { return Impl.end(); }
297    const_reverse_iterator rbegin() const { return Impl.begin(); }
298    const_reverse_iterator rend() const { return Impl.end(); }
299
300   CFGElement operator[](size_t i) const  {
301     assert(i < Impl.size());
302     return Impl[Impl.size() - 1 - i];
303   }
304
305    size_t size() const { return Impl.size(); }
306    bool empty() const { return Impl.empty(); }
307  };
308
309  /// Stmts - The set of statements in the basic block.
310  ElementList Elements;
311
312  /// Label - An (optional) label that prefixes the executable
313  ///  statements in the block.  When this variable is non-NULL, it is
314  ///  either an instance of LabelStmt, SwitchCase or CXXCatchStmt.
315  Stmt *Label;
316
317  /// Terminator - The terminator for a basic block that
318  ///  indicates the type of control-flow that occurs between a block
319  ///  and its successors.
320  CFGTerminator Terminator;
321
322  /// LoopTarget - Some blocks are used to represent the "loop edge" to
323  ///  the start of a loop from within the loop body.  This Stmt* will be
324  ///  refer to the loop statement for such blocks (and be null otherwise).
325  const Stmt *LoopTarget;
326
327  /// BlockID - A numerical ID assigned to a CFGBlock during construction
328  ///   of the CFG.
329  unsigned BlockID;
330
331  /// Predecessors/Successors - Keep track of the predecessor / successor
332  /// CFG blocks.
333  typedef BumpVector<CFGBlock*> AdjacentBlocks;
334  AdjacentBlocks Preds;
335  AdjacentBlocks Succs;
336
337  /// NoReturn - This bit is set when the basic block contains a function call
338  /// or implicit destructor that is attributed as 'noreturn'. In that case,
339  /// control cannot technically ever proceed past this block. All such blocks
340  /// will have a single immediate successor: the exit block. This allows them
341  /// to be easily reached from the exit block and using this bit quickly
342  /// recognized without scanning the contents of the block.
343  ///
344  /// Optimization Note: This bit could be profitably folded with Terminator's
345  /// storage if the memory usage of CFGBlock becomes an issue.
346  unsigned HasNoReturnElement : 1;
347
348  /// Parent - The parent CFG that owns this CFGBlock.
349  CFG *Parent;
350
351public:
352  explicit CFGBlock(unsigned blockid, BumpVectorContext &C, CFG *parent)
353    : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
354      BlockID(blockid), Preds(C, 1), Succs(C, 1), HasNoReturnElement(false),
355      Parent(parent) {}
356  ~CFGBlock() {}
357
358  // Statement iterators
359  typedef ElementList::iterator                      iterator;
360  typedef ElementList::const_iterator                const_iterator;
361  typedef ElementList::reverse_iterator              reverse_iterator;
362  typedef ElementList::const_reverse_iterator        const_reverse_iterator;
363
364  CFGElement                 front()       const { return Elements.front();   }
365  CFGElement                 back()        const { return Elements.back();    }
366
367  iterator                   begin()             { return Elements.begin();   }
368  iterator                   end()               { return Elements.end();     }
369  const_iterator             begin()       const { return Elements.begin();   }
370  const_iterator             end()         const { return Elements.end();     }
371
372  reverse_iterator           rbegin()            { return Elements.rbegin();  }
373  reverse_iterator           rend()              { return Elements.rend();    }
374  const_reverse_iterator     rbegin()      const { return Elements.rbegin();  }
375  const_reverse_iterator     rend()        const { return Elements.rend();    }
376
377  unsigned                   size()        const { return Elements.size();    }
378  bool                       empty()       const { return Elements.empty();   }
379
380  CFGElement operator[](size_t i) const  { return Elements[i]; }
381
382  // CFG iterators
383  typedef AdjacentBlocks::iterator                              pred_iterator;
384  typedef AdjacentBlocks::const_iterator                  const_pred_iterator;
385  typedef AdjacentBlocks::reverse_iterator              pred_reverse_iterator;
386  typedef AdjacentBlocks::const_reverse_iterator  const_pred_reverse_iterator;
387
388  typedef AdjacentBlocks::iterator                              succ_iterator;
389  typedef AdjacentBlocks::const_iterator                  const_succ_iterator;
390  typedef AdjacentBlocks::reverse_iterator              succ_reverse_iterator;
391  typedef AdjacentBlocks::const_reverse_iterator  const_succ_reverse_iterator;
392
393  pred_iterator                pred_begin()        { return Preds.begin();   }
394  pred_iterator                pred_end()          { return Preds.end();     }
395  const_pred_iterator          pred_begin()  const { return Preds.begin();   }
396  const_pred_iterator          pred_end()    const { return Preds.end();     }
397
398  pred_reverse_iterator        pred_rbegin()       { return Preds.rbegin();  }
399  pred_reverse_iterator        pred_rend()         { return Preds.rend();    }
400  const_pred_reverse_iterator  pred_rbegin() const { return Preds.rbegin();  }
401  const_pred_reverse_iterator  pred_rend()   const { return Preds.rend();    }
402
403  succ_iterator                succ_begin()        { return Succs.begin();   }
404  succ_iterator                succ_end()          { return Succs.end();     }
405  const_succ_iterator          succ_begin()  const { return Succs.begin();   }
406  const_succ_iterator          succ_end()    const { return Succs.end();     }
407
408  succ_reverse_iterator        succ_rbegin()       { return Succs.rbegin();  }
409  succ_reverse_iterator        succ_rend()         { return Succs.rend();    }
410  const_succ_reverse_iterator  succ_rbegin() const { return Succs.rbegin();  }
411  const_succ_reverse_iterator  succ_rend()   const { return Succs.rend();    }
412
413  unsigned                     succ_size()   const { return Succs.size();    }
414  bool                         succ_empty()  const { return Succs.empty();   }
415
416  unsigned                     pred_size()   const { return Preds.size();    }
417  bool                         pred_empty()  const { return Preds.empty();   }
418
419
420  class FilterOptions {
421  public:
422    FilterOptions() {
423      IgnoreDefaultsWithCoveredEnums = 0;
424    }
425
426    unsigned IgnoreDefaultsWithCoveredEnums : 1;
427  };
428
429  static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
430       const CFGBlock *Dst);
431
432  template <typename IMPL, bool IsPred>
433  class FilteredCFGBlockIterator {
434  private:
435    IMPL I, E;
436    const FilterOptions F;
437    const CFGBlock *From;
438   public:
439    explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
440              const CFGBlock *from,
441              const FilterOptions &f)
442      : I(i), E(e), F(f), From(from) {}
443
444    bool hasMore() const { return I != E; }
445
446    FilteredCFGBlockIterator &operator++() {
447      do { ++I; } while (hasMore() && Filter(*I));
448      return *this;
449    }
450
451    const CFGBlock *operator*() const { return *I; }
452  private:
453    bool Filter(const CFGBlock *To) {
454      return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
455    }
456  };
457
458  typedef FilteredCFGBlockIterator<const_pred_iterator, true>
459          filtered_pred_iterator;
460
461  typedef FilteredCFGBlockIterator<const_succ_iterator, false>
462          filtered_succ_iterator;
463
464  filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
465    return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
466  }
467
468  filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
469    return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
470  }
471
472  // Manipulation of block contents
473
474  void setTerminator(Stmt *Statement) { Terminator = Statement; }
475  void setLabel(Stmt *Statement) { Label = Statement; }
476  void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
477  void setHasNoReturnElement() { HasNoReturnElement = true; }
478
479  CFGTerminator getTerminator() { return Terminator; }
480  const CFGTerminator getTerminator() const { return Terminator; }
481
482  Stmt *getTerminatorCondition();
483
484  const Stmt *getTerminatorCondition() const {
485    return const_cast<CFGBlock*>(this)->getTerminatorCondition();
486  }
487
488  const Stmt *getLoopTarget() const { return LoopTarget; }
489
490  Stmt *getLabel() { return Label; }
491  const Stmt *getLabel() const { return Label; }
492
493  bool hasNoReturnElement() const { return HasNoReturnElement; }
494
495  unsigned getBlockID() const { return BlockID; }
496
497  CFG *getParent() const { return Parent; }
498
499  void dump(const CFG *cfg, const LangOptions &LO, bool ShowColors = false) const;
500  void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO,
501             bool ShowColors) const;
502  void printTerminator(raw_ostream &OS, const LangOptions &LO) const;
503
504  void addSuccessor(CFGBlock *Block, BumpVectorContext &C) {
505    if (Block)
506      Block->Preds.push_back(this, C);
507    Succs.push_back(Block, C);
508  }
509
510  void appendStmt(Stmt *statement, BumpVectorContext &C) {
511    Elements.push_back(CFGStmt(statement), C);
512  }
513
514  void appendInitializer(CXXCtorInitializer *initializer,
515                        BumpVectorContext &C) {
516    Elements.push_back(CFGInitializer(initializer), C);
517  }
518
519  void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
520    Elements.push_back(CFGBaseDtor(BS), C);
521  }
522
523  void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
524    Elements.push_back(CFGMemberDtor(FD), C);
525  }
526
527  void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
528    Elements.push_back(CFGTemporaryDtor(E), C);
529  }
530
531  void appendAutomaticObjDtor(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
532    Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
533  }
534
535  // Destructors must be inserted in reversed order. So insertion is in two
536  // steps. First we prepare space for some number of elements, then we insert
537  // the elements beginning at the last position in prepared space.
538  iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
539      BumpVectorContext &C) {
540    return iterator(Elements.insert(I.base(), Cnt, CFGElement(), C));
541  }
542  iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
543    *I = CFGAutomaticObjDtor(VD, S);
544    return ++I;
545  }
546};
547
548/// CFG - Represents a source-level, intra-procedural CFG that represents the
549///  control-flow of a Stmt.  The Stmt can represent an entire function body,
550///  or a single expression.  A CFG will always contain one empty block that
551///  represents the Exit point of the CFG.  A CFG will also contain a designated
552///  Entry block.  The CFG solely represents control-flow; it consists of
553///  CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
554///  was constructed from.
555class CFG {
556public:
557  //===--------------------------------------------------------------------===//
558  // CFG Construction & Manipulation.
559  //===--------------------------------------------------------------------===//
560
561  class BuildOptions {
562    std::bitset<Stmt::lastStmtConstant> alwaysAddMask;
563  public:
564    typedef llvm::DenseMap<const Stmt *, const CFGBlock*> ForcedBlkExprs;
565    ForcedBlkExprs **forcedBlkExprs;
566
567    bool PruneTriviallyFalseEdges;
568    bool AddEHEdges;
569    bool AddInitializers;
570    bool AddImplicitDtors;
571    bool AddTemporaryDtors;
572
573    bool alwaysAdd(const Stmt *stmt) const {
574      return alwaysAddMask[stmt->getStmtClass()];
575    }
576
577    BuildOptions &setAlwaysAdd(Stmt::StmtClass stmtClass, bool val = true) {
578      alwaysAddMask[stmtClass] = val;
579      return *this;
580    }
581
582    BuildOptions &setAllAlwaysAdd() {
583      alwaysAddMask.set();
584      return *this;
585    }
586
587    BuildOptions()
588    : forcedBlkExprs(0), PruneTriviallyFalseEdges(true)
589      ,AddEHEdges(false)
590      ,AddInitializers(false)
591      ,AddImplicitDtors(false)
592      ,AddTemporaryDtors(false) {}
593  };
594
595  /// \brief Provides a custom implementation of the iterator class to have the
596  /// same interface as Function::iterator - iterator returns CFGBlock
597  /// (not a pointer to CFGBlock).
598  class graph_iterator {
599  public:
600    typedef const CFGBlock                  value_type;
601    typedef value_type&                     reference;
602    typedef value_type*                     pointer;
603    typedef BumpVector<CFGBlock*>::iterator ImplTy;
604
605    graph_iterator(const ImplTy &i) : I(i) {}
606
607    bool operator==(const graph_iterator &X) const { return I == X.I; }
608    bool operator!=(const graph_iterator &X) const { return I != X.I; }
609
610    reference operator*()    const { return **I; }
611    pointer operator->()     const { return  *I; }
612    operator CFGBlock* ()          { return  *I; }
613
614    graph_iterator &operator++() { ++I; return *this; }
615    graph_iterator &operator--() { --I; return *this; }
616
617  private:
618    ImplTy I;
619  };
620
621  class const_graph_iterator {
622  public:
623    typedef const CFGBlock                  value_type;
624    typedef value_type&                     reference;
625    typedef value_type*                     pointer;
626    typedef BumpVector<CFGBlock*>::const_iterator ImplTy;
627
628    const_graph_iterator(const ImplTy &i) : I(i) {}
629
630    bool operator==(const const_graph_iterator &X) const { return I == X.I; }
631    bool operator!=(const const_graph_iterator &X) const { return I != X.I; }
632
633    reference operator*() const { return **I; }
634    pointer operator->()  const { return  *I; }
635    operator CFGBlock* () const { return  *I; }
636
637    const_graph_iterator &operator++() { ++I; return *this; }
638    const_graph_iterator &operator--() { --I; return *this; }
639
640  private:
641    ImplTy I;
642  };
643
644  /// buildCFG - Builds a CFG from an AST.  The responsibility to free the
645  ///   constructed CFG belongs to the caller.
646  static CFG* buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
647                       const BuildOptions &BO);
648
649  /// createBlock - Create a new block in the CFG.  The CFG owns the block;
650  ///  the caller should not directly free it.
651  CFGBlock *createBlock();
652
653  /// setEntry - Set the entry block of the CFG.  This is typically used
654  ///  only during CFG construction.  Most CFG clients expect that the
655  ///  entry block has no predecessors and contains no statements.
656  void setEntry(CFGBlock *B) { Entry = B; }
657
658  /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
659  ///  This is typically used only during CFG construction.
660  void setIndirectGotoBlock(CFGBlock *B) { IndirectGotoBlock = B; }
661
662  //===--------------------------------------------------------------------===//
663  // Block Iterators
664  //===--------------------------------------------------------------------===//
665
666  typedef BumpVector<CFGBlock*>                    CFGBlockListTy;
667  typedef CFGBlockListTy::iterator                 iterator;
668  typedef CFGBlockListTy::const_iterator           const_iterator;
669  typedef std::reverse_iterator<iterator>          reverse_iterator;
670  typedef std::reverse_iterator<const_iterator>    const_reverse_iterator;
671
672  CFGBlock &                front()                { return *Blocks.front(); }
673  CFGBlock &                back()                 { return *Blocks.back(); }
674
675  iterator                  begin()                { return Blocks.begin(); }
676  iterator                  end()                  { return Blocks.end(); }
677  const_iterator            begin()       const    { return Blocks.begin(); }
678  const_iterator            end()         const    { return Blocks.end(); }
679
680  graph_iterator nodes_begin() { return graph_iterator(Blocks.begin()); }
681  graph_iterator nodes_end() { return graph_iterator(Blocks.end()); }
682  const_graph_iterator nodes_begin() const {
683    return const_graph_iterator(Blocks.begin());
684  }
685  const_graph_iterator nodes_end() const {
686    return const_graph_iterator(Blocks.end());
687  }
688
689  reverse_iterator          rbegin()               { return Blocks.rbegin(); }
690  reverse_iterator          rend()                 { return Blocks.rend(); }
691  const_reverse_iterator    rbegin()      const    { return Blocks.rbegin(); }
692  const_reverse_iterator    rend()        const    { return Blocks.rend(); }
693
694  CFGBlock &                getEntry()             { return *Entry; }
695  const CFGBlock &          getEntry()    const    { return *Entry; }
696  CFGBlock &                getExit()              { return *Exit; }
697  const CFGBlock &          getExit()     const    { return *Exit; }
698
699  CFGBlock *       getIndirectGotoBlock() { return IndirectGotoBlock; }
700  const CFGBlock * getIndirectGotoBlock() const { return IndirectGotoBlock; }
701
702  typedef std::vector<const CFGBlock*>::const_iterator try_block_iterator;
703  try_block_iterator try_blocks_begin() const {
704    return TryDispatchBlocks.begin();
705  }
706  try_block_iterator try_blocks_end() const {
707    return TryDispatchBlocks.end();
708  }
709
710  void addTryDispatchBlock(const CFGBlock *block) {
711    TryDispatchBlocks.push_back(block);
712  }
713
714  //===--------------------------------------------------------------------===//
715  // Member templates useful for various batch operations over CFGs.
716  //===--------------------------------------------------------------------===//
717
718  template <typename CALLBACK>
719  void VisitBlockStmts(CALLBACK& O) const {
720    for (const_iterator I=begin(), E=end(); I != E; ++I)
721      for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
722           BI != BE; ++BI) {
723        if (const CFGStmt *stmt = BI->getAs<CFGStmt>())
724          O(const_cast<Stmt*>(stmt->getStmt()));
725      }
726  }
727
728  //===--------------------------------------------------------------------===//
729  // CFG Introspection.
730  //===--------------------------------------------------------------------===//
731
732  struct   BlkExprNumTy {
733    const signed Idx;
734    explicit BlkExprNumTy(signed idx) : Idx(idx) {}
735    explicit BlkExprNumTy() : Idx(-1) {}
736    operator bool() const { return Idx >= 0; }
737    operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; }
738  };
739
740  bool isBlkExpr(const Stmt *S) { return getBlkExprNum(S); }
741  bool isBlkExpr(const Stmt *S) const {
742    return const_cast<CFG*>(this)->isBlkExpr(S);
743  }
744  BlkExprNumTy  getBlkExprNum(const Stmt *S);
745  unsigned      getNumBlkExprs();
746
747  /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
748  /// start at 0).
749  unsigned getNumBlockIDs() const { return NumBlockIDs; }
750
751  /// size - Return the total number of CFGBlocks within the CFG
752  /// This is simply a renaming of the getNumBlockIDs(). This is necessary
753  /// because the dominator implementation needs such an interface.
754  unsigned size() const { return NumBlockIDs; }
755
756  //===--------------------------------------------------------------------===//
757  // CFG Debugging: Pretty-Printing and Visualization.
758  //===--------------------------------------------------------------------===//
759
760  void viewCFG(const LangOptions &LO) const;
761  void print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const;
762  void dump(const LangOptions &LO, bool ShowColors) const;
763
764  //===--------------------------------------------------------------------===//
765  // Internal: constructors and data.
766  //===--------------------------------------------------------------------===//
767
768  CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
769          BlkExprMap(NULL), Blocks(BlkBVC, 10) {}
770
771  ~CFG();
772
773  llvm::BumpPtrAllocator& getAllocator() {
774    return BlkBVC.getAllocator();
775  }
776
777  BumpVectorContext &getBumpVectorContext() {
778    return BlkBVC;
779  }
780
781private:
782  CFGBlock *Entry;
783  CFGBlock *Exit;
784  CFGBlock* IndirectGotoBlock;  // Special block to contain collective dispatch
785                                // for indirect gotos
786  unsigned  NumBlockIDs;
787
788  // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h.
789  //  It represents a map from Expr* to integers to record the set of
790  //  block-level expressions and their "statement number" in the CFG.
791  void *    BlkExprMap;
792
793  BumpVectorContext BlkBVC;
794
795  CFGBlockListTy Blocks;
796
797  /// C++ 'try' statements are modeled with an indirect dispatch block.
798  /// This is the collection of such blocks present in the CFG.
799  std::vector<const CFGBlock *> TryDispatchBlocks;
800
801};
802} // end namespace clang
803
804//===----------------------------------------------------------------------===//
805// GraphTraits specializations for CFG basic block graphs (source-level CFGs)
806//===----------------------------------------------------------------------===//
807
808namespace llvm {
809
810/// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
811/// CFGTerminator to a specific Stmt class.
812template <> struct simplify_type<const ::clang::CFGTerminator> {
813  typedef const ::clang::Stmt *SimpleType;
814  static SimpleType getSimplifiedValue(const ::clang::CFGTerminator &Val) {
815    return Val.getStmt();
816  }
817};
818
819template <> struct simplify_type< ::clang::CFGTerminator> {
820  typedef ::clang::Stmt *SimpleType;
821  static SimpleType getSimplifiedValue(const ::clang::CFGTerminator &Val) {
822    return const_cast<SimpleType>(Val.getStmt());
823  }
824};
825
826// Traits for: CFGBlock
827
828template <> struct GraphTraits< ::clang::CFGBlock *> {
829  typedef ::clang::CFGBlock NodeType;
830  typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
831
832  static NodeType* getEntryNode(::clang::CFGBlock *BB)
833  { return BB; }
834
835  static inline ChildIteratorType child_begin(NodeType* N)
836  { return N->succ_begin(); }
837
838  static inline ChildIteratorType child_end(NodeType* N)
839  { return N->succ_end(); }
840};
841
842template <> struct GraphTraits< const ::clang::CFGBlock *> {
843  typedef const ::clang::CFGBlock NodeType;
844  typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
845
846  static NodeType* getEntryNode(const clang::CFGBlock *BB)
847  { return BB; }
848
849  static inline ChildIteratorType child_begin(NodeType* N)
850  { return N->succ_begin(); }
851
852  static inline ChildIteratorType child_end(NodeType* N)
853  { return N->succ_end(); }
854};
855
856template <> struct GraphTraits<Inverse< ::clang::CFGBlock*> > {
857  typedef ::clang::CFGBlock NodeType;
858  typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
859
860  static NodeType *getEntryNode(Inverse< ::clang::CFGBlock*> G)
861  { return G.Graph; }
862
863  static inline ChildIteratorType child_begin(NodeType* N)
864  { return N->pred_begin(); }
865
866  static inline ChildIteratorType child_end(NodeType* N)
867  { return N->pred_end(); }
868};
869
870template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
871  typedef const ::clang::CFGBlock NodeType;
872  typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
873
874  static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
875  { return G.Graph; }
876
877  static inline ChildIteratorType child_begin(NodeType* N)
878  { return N->pred_begin(); }
879
880  static inline ChildIteratorType child_end(NodeType* N)
881  { return N->pred_end(); }
882};
883
884// Traits for: CFG
885
886template <> struct GraphTraits< ::clang::CFG* >
887    : public GraphTraits< ::clang::CFGBlock *>  {
888
889  typedef ::clang::CFG::graph_iterator nodes_iterator;
890
891  static NodeType     *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
892  static nodes_iterator nodes_begin(::clang::CFG* F) { return F->nodes_begin();}
893  static nodes_iterator   nodes_end(::clang::CFG* F) { return F->nodes_end(); }
894  static unsigned              size(::clang::CFG* F) { return F->size(); }
895};
896
897template <> struct GraphTraits<const ::clang::CFG* >
898    : public GraphTraits<const ::clang::CFGBlock *>  {
899
900  typedef ::clang::CFG::const_graph_iterator nodes_iterator;
901
902  static NodeType *getEntryNode( const ::clang::CFG* F) {
903    return &F->getEntry();
904  }
905  static nodes_iterator nodes_begin( const ::clang::CFG* F) {
906    return F->nodes_begin();
907  }
908  static nodes_iterator nodes_end( const ::clang::CFG* F) {
909    return F->nodes_end();
910  }
911  static unsigned size(const ::clang::CFG* F) {
912    return F->size();
913  }
914};
915
916template <> struct GraphTraits<Inverse< ::clang::CFG*> >
917  : public GraphTraits<Inverse< ::clang::CFGBlock*> > {
918
919  typedef ::clang::CFG::graph_iterator nodes_iterator;
920
921  static NodeType *getEntryNode( ::clang::CFG* F) { return &F->getExit(); }
922  static nodes_iterator nodes_begin( ::clang::CFG* F) {return F->nodes_begin();}
923  static nodes_iterator nodes_end( ::clang::CFG* F) { return F->nodes_end(); }
924};
925
926template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
927  : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
928
929  typedef ::clang::CFG::const_graph_iterator nodes_iterator;
930
931  static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
932  static nodes_iterator nodes_begin(const ::clang::CFG* F) {
933    return F->nodes_begin();
934  }
935  static nodes_iterator nodes_end(const ::clang::CFG* F) {
936    return F->nodes_end();
937  }
938};
939} // end llvm namespace
940#endif
941