CFG.h revision 26517e4ffe7c2c366496feb02370ba24ab5ae8f5
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/Analysis/Support/BumpVector.h"
25#include "clang/Basic/SourceLocation.h"
26#include <cassert>
27#include <iterator>
28
29namespace llvm {
30  class raw_ostream;
31}
32
33namespace clang {
34  class CXXDestructorDecl;
35  class Decl;
36  class Stmt;
37  class Expr;
38  class FieldDecl;
39  class VarDecl;
40  class CXXCtorInitializer;
41  class CXXBaseSpecifier;
42  class CXXBindTemporaryExpr;
43  class CFG;
44  class PrinterHelper;
45  class LangOptions;
46  class ASTContext;
47
48/// CFGElement - Represents a top-level expression in a basic block.
49class CFGElement {
50public:
51  enum Kind {
52    // main kind
53    Invalid,
54    Statement,
55    Initializer,
56    // dtor kind
57    AutomaticObjectDtor,
58    BaseDtor,
59    MemberDtor,
60    TemporaryDtor,
61    DTOR_BEGIN = AutomaticObjectDtor,
62    DTOR_END = TemporaryDtor
63  };
64
65protected:
66  // The int bits are used to mark the kind.
67  llvm::PointerIntPair<void *, 2> Data1;
68  llvm::PointerIntPair<void *, 2> Data2;
69
70  CFGElement(Kind kind, const void *Ptr1, const void *Ptr2 = 0)
71    : Data1(const_cast<void*>(Ptr1), ((unsigned) kind) & 0x3),
72      Data2(const_cast<void*>(Ptr2), (((unsigned) kind) >> 2) & 0x3) {}
73
74public:
75  CFGElement() {}
76
77  Kind getKind() const {
78    unsigned x = Data2.getInt();
79    x <<= 2;
80    x |= Data1.getInt();
81    return (Kind) x;
82  }
83
84  bool isValid() const { return getKind() != Invalid; }
85
86  operator bool() const { return isValid(); }
87
88  template<class ElemTy> const ElemTy *getAs() const {
89    if (llvm::isa<ElemTy>(this))
90      return static_cast<const ElemTy*>(this);
91    return 0;
92  }
93
94  static bool classof(const CFGElement *E) { return true; }
95};
96
97class CFGStmt : public CFGElement {
98public:
99  CFGStmt(Stmt *S) : CFGElement(Statement, S) {}
100
101  Stmt *getStmt() const { return static_cast<Stmt *>(Data1.getPointer()); }
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///
267class CFGBlock {
268  class ElementList {
269    typedef BumpVector<CFGElement> ImplTy;
270    ImplTy Impl;
271  public:
272    ElementList(BumpVectorContext &C) : Impl(C, 4) {}
273
274    typedef std::reverse_iterator<ImplTy::iterator>       iterator;
275    typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
276    typedef ImplTy::iterator                              reverse_iterator;
277    typedef ImplTy::const_iterator                        const_reverse_iterator;
278
279    void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
280    reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
281        BumpVectorContext& C) {
282      return Impl.insert(I, Cnt, E, C);
283    }
284
285    CFGElement front() const { return Impl.back(); }
286    CFGElement back() const { return Impl.front(); }
287
288    iterator begin() { return Impl.rbegin(); }
289    iterator end() { return Impl.rend(); }
290    const_iterator begin() const { return Impl.rbegin(); }
291    const_iterator end() const { return Impl.rend(); }
292    reverse_iterator rbegin() { return Impl.begin(); }
293    reverse_iterator rend() { return Impl.end(); }
294    const_reverse_iterator rbegin() const { return Impl.begin(); }
295    const_reverse_iterator rend() const { return Impl.end(); }
296
297   CFGElement operator[](size_t i) const  {
298     assert(i < Impl.size());
299     return Impl[Impl.size() - 1 - i];
300   }
301
302    size_t size() const { return Impl.size(); }
303    bool empty() const { return Impl.empty(); }
304  };
305
306  /// Stmts - The set of statements in the basic block.
307  ElementList Elements;
308
309  /// Label - An (optional) label that prefixes the executable
310  ///  statements in the block.  When this variable is non-NULL, it is
311  ///  either an instance of LabelStmt, SwitchCase or CXXCatchStmt.
312  Stmt *Label;
313
314  /// Terminator - The terminator for a basic block that
315  ///  indicates the type of control-flow that occurs between a block
316  ///  and its successors.
317  CFGTerminator Terminator;
318
319  /// LoopTarget - Some blocks are used to represent the "loop edge" to
320  ///  the start of a loop from within the loop body.  This Stmt* will be
321  ///  refer to the loop statement for such blocks (and be null otherwise).
322  const Stmt *LoopTarget;
323
324  /// BlockID - A numerical ID assigned to a CFGBlock during construction
325  ///   of the CFG.
326  unsigned BlockID;
327
328  /// Predecessors/Successors - Keep track of the predecessor / successor
329  /// CFG blocks.
330  typedef BumpVector<CFGBlock*> AdjacentBlocks;
331  AdjacentBlocks Preds;
332  AdjacentBlocks Succs;
333
334public:
335  explicit CFGBlock(unsigned blockid, BumpVectorContext &C)
336    : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
337      BlockID(blockid), Preds(C, 1), Succs(C, 1) {}
338  ~CFGBlock() {}
339
340  // Statement iterators
341  typedef ElementList::iterator                      iterator;
342  typedef ElementList::const_iterator                const_iterator;
343  typedef ElementList::reverse_iterator              reverse_iterator;
344  typedef ElementList::const_reverse_iterator        const_reverse_iterator;
345
346  CFGElement                 front()       const { return Elements.front();   }
347  CFGElement                 back()        const { return Elements.back();    }
348
349  iterator                   begin()             { return Elements.begin();   }
350  iterator                   end()               { return Elements.end();     }
351  const_iterator             begin()       const { return Elements.begin();   }
352  const_iterator             end()         const { return Elements.end();     }
353
354  reverse_iterator           rbegin()            { return Elements.rbegin();  }
355  reverse_iterator           rend()              { return Elements.rend();    }
356  const_reverse_iterator     rbegin()      const { return Elements.rbegin();  }
357  const_reverse_iterator     rend()        const { return Elements.rend();    }
358
359  unsigned                   size()        const { return Elements.size();    }
360  bool                       empty()       const { return Elements.empty();   }
361
362  CFGElement operator[](size_t i) const  { return Elements[i]; }
363
364  // CFG iterators
365  typedef AdjacentBlocks::iterator                              pred_iterator;
366  typedef AdjacentBlocks::const_iterator                  const_pred_iterator;
367  typedef AdjacentBlocks::reverse_iterator              pred_reverse_iterator;
368  typedef AdjacentBlocks::const_reverse_iterator  const_pred_reverse_iterator;
369
370  typedef AdjacentBlocks::iterator                              succ_iterator;
371  typedef AdjacentBlocks::const_iterator                  const_succ_iterator;
372  typedef AdjacentBlocks::reverse_iterator              succ_reverse_iterator;
373  typedef AdjacentBlocks::const_reverse_iterator  const_succ_reverse_iterator;
374
375  pred_iterator                pred_begin()        { return Preds.begin();   }
376  pred_iterator                pred_end()          { return Preds.end();     }
377  const_pred_iterator          pred_begin()  const { return Preds.begin();   }
378  const_pred_iterator          pred_end()    const { return Preds.end();     }
379
380  pred_reverse_iterator        pred_rbegin()       { return Preds.rbegin();  }
381  pred_reverse_iterator        pred_rend()         { return Preds.rend();    }
382  const_pred_reverse_iterator  pred_rbegin() const { return Preds.rbegin();  }
383  const_pred_reverse_iterator  pred_rend()   const { return Preds.rend();    }
384
385  succ_iterator                succ_begin()        { return Succs.begin();   }
386  succ_iterator                succ_end()          { return Succs.end();     }
387  const_succ_iterator          succ_begin()  const { return Succs.begin();   }
388  const_succ_iterator          succ_end()    const { return Succs.end();     }
389
390  succ_reverse_iterator        succ_rbegin()       { return Succs.rbegin();  }
391  succ_reverse_iterator        succ_rend()         { return Succs.rend();    }
392  const_succ_reverse_iterator  succ_rbegin() const { return Succs.rbegin();  }
393  const_succ_reverse_iterator  succ_rend()   const { return Succs.rend();    }
394
395  unsigned                     succ_size()   const { return Succs.size();    }
396  bool                         succ_empty()  const { return Succs.empty();   }
397
398  unsigned                     pred_size()   const { return Preds.size();    }
399  bool                         pred_empty()  const { return Preds.empty();   }
400
401
402  class FilterOptions {
403  public:
404    FilterOptions() {
405      IgnoreDefaultsWithCoveredEnums = 0;
406    }
407
408    unsigned IgnoreDefaultsWithCoveredEnums : 1;
409  };
410
411  static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
412       const CFGBlock *Dst);
413
414  template <typename IMPL, bool IsPred>
415  class FilteredCFGBlockIterator {
416  private:
417    IMPL I, E;
418    const FilterOptions F;
419    const CFGBlock *From;
420   public:
421    explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
422              const CFGBlock *from,
423              const FilterOptions &f)
424      : I(i), E(e), F(f), From(from) {}
425
426    bool hasMore() const { return I != E; }
427
428    FilteredCFGBlockIterator &operator++() {
429      do { ++I; } while (hasMore() && Filter(*I));
430      return *this;
431    }
432
433    const CFGBlock *operator*() const { return *I; }
434  private:
435    bool Filter(const CFGBlock *To) {
436      return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
437    }
438  };
439
440  typedef FilteredCFGBlockIterator<const_pred_iterator, true>
441          filtered_pred_iterator;
442
443  typedef FilteredCFGBlockIterator<const_succ_iterator, false>
444          filtered_succ_iterator;
445
446  filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
447    return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
448  }
449
450  filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
451    return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
452  }
453
454  // Manipulation of block contents
455
456  void setTerminator(Stmt* Statement) { Terminator = Statement; }
457  void setLabel(Stmt* Statement) { Label = Statement; }
458  void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
459
460  CFGTerminator getTerminator() { return Terminator; }
461  const CFGTerminator getTerminator() const { return Terminator; }
462
463  Stmt* getTerminatorCondition();
464
465  const Stmt* getTerminatorCondition() const {
466    return const_cast<CFGBlock*>(this)->getTerminatorCondition();
467  }
468
469  const Stmt *getLoopTarget() const { return LoopTarget; }
470
471  Stmt* getLabel() { return Label; }
472  const Stmt* getLabel() const { return Label; }
473
474  unsigned getBlockID() const { return BlockID; }
475
476  void dump(const CFG *cfg, const LangOptions &LO) const;
477  void print(llvm::raw_ostream &OS, const CFG* cfg, const LangOptions &LO) const;
478  void printTerminator(llvm::raw_ostream &OS, const LangOptions &LO) const;
479
480  void addSuccessor(CFGBlock* Block, BumpVectorContext &C) {
481    if (Block)
482      Block->Preds.push_back(this, C);
483    Succs.push_back(Block, C);
484  }
485
486  void appendStmt(Stmt* statement, BumpVectorContext &C) {
487    Elements.push_back(CFGStmt(statement), C);
488  }
489
490  void appendInitializer(CXXCtorInitializer *initializer,
491                        BumpVectorContext& C) {
492    Elements.push_back(CFGInitializer(initializer), C);
493  }
494
495  void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
496    Elements.push_back(CFGBaseDtor(BS), C);
497  }
498
499  void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
500    Elements.push_back(CFGMemberDtor(FD), C);
501  }
502
503  void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
504    Elements.push_back(CFGTemporaryDtor(E), C);
505  }
506
507  // Destructors must be inserted in reversed order. So insertion is in two
508  // steps. First we prepare space for some number of elements, then we insert
509  // the elements beginning at the last position in prepared space.
510  iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
511      BumpVectorContext& C) {
512    return iterator(Elements.insert(I.base(), Cnt, CFGElement(), C));
513  }
514  iterator insertAutomaticObjDtor(iterator I, VarDecl* VD, Stmt* S) {
515    *I = CFGAutomaticObjDtor(VD, S);
516    return ++I;
517  }
518};
519
520/// CFG - Represents a source-level, intra-procedural CFG that represents the
521///  control-flow of a Stmt.  The Stmt can represent an entire function body,
522///  or a single expression.  A CFG will always contain one empty block that
523///  represents the Exit point of the CFG.  A CFG will also contain a designated
524///  Entry block.  The CFG solely represents control-flow; it consists of
525///  CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
526///  was constructed from.
527class CFG {
528public:
529  //===--------------------------------------------------------------------===//
530  // CFG Construction & Manipulation.
531  //===--------------------------------------------------------------------===//
532
533  class BuildOptions {
534  public:
535    typedef llvm::DenseMap<const Stmt *, const CFGBlock*> ForcedBlkExprs;
536    ForcedBlkExprs **forcedBlkExprs;
537
538    bool PruneTriviallyFalseEdges:1;
539    bool AddEHEdges:1;
540    bool AddInitializers:1;
541    bool AddImplicitDtors:1;
542
543    BuildOptions()
544        : forcedBlkExprs(0), PruneTriviallyFalseEdges(true)
545        , AddEHEdges(false)
546        , AddInitializers(false)
547        , AddImplicitDtors(false) {}
548  };
549
550  /// buildCFG - Builds a CFG from an AST.  The responsibility to free the
551  ///   constructed CFG belongs to the caller.
552  static CFG* buildCFG(const Decl *D, Stmt* AST, ASTContext *C,
553                       const BuildOptions &BO);
554
555  /// createBlock - Create a new block in the CFG.  The CFG owns the block;
556  ///  the caller should not directly free it.
557  CFGBlock* createBlock();
558
559  /// setEntry - Set the entry block of the CFG.  This is typically used
560  ///  only during CFG construction.  Most CFG clients expect that the
561  ///  entry block has no predecessors and contains no statements.
562  void setEntry(CFGBlock *B) { Entry = B; }
563
564  /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
565  ///  This is typically used only during CFG construction.
566  void setIndirectGotoBlock(CFGBlock* B) { IndirectGotoBlock = B; }
567
568  //===--------------------------------------------------------------------===//
569  // Block Iterators
570  //===--------------------------------------------------------------------===//
571
572  typedef BumpVector<CFGBlock*>                    CFGBlockListTy;
573  typedef CFGBlockListTy::iterator                 iterator;
574  typedef CFGBlockListTy::const_iterator           const_iterator;
575  typedef std::reverse_iterator<iterator>          reverse_iterator;
576  typedef std::reverse_iterator<const_iterator>    const_reverse_iterator;
577
578  CFGBlock&                 front()                { return *Blocks.front(); }
579  CFGBlock&                 back()                 { return *Blocks.back(); }
580
581  iterator                  begin()                { return Blocks.begin(); }
582  iterator                  end()                  { return Blocks.end(); }
583  const_iterator            begin()       const    { return Blocks.begin(); }
584  const_iterator            end()         const    { return Blocks.end(); }
585
586  reverse_iterator          rbegin()               { return Blocks.rbegin(); }
587  reverse_iterator          rend()                 { return Blocks.rend(); }
588  const_reverse_iterator    rbegin()      const    { return Blocks.rbegin(); }
589  const_reverse_iterator    rend()        const    { return Blocks.rend(); }
590
591  CFGBlock&                 getEntry()             { return *Entry; }
592  const CFGBlock&           getEntry()    const    { return *Entry; }
593  CFGBlock&                 getExit()              { return *Exit; }
594  const CFGBlock&           getExit()     const    { return *Exit; }
595
596  CFGBlock*        getIndirectGotoBlock() { return IndirectGotoBlock; }
597  const CFGBlock*  getIndirectGotoBlock() const { return IndirectGotoBlock; }
598
599  //===--------------------------------------------------------------------===//
600  // Member templates useful for various batch operations over CFGs.
601  //===--------------------------------------------------------------------===//
602
603  template <typename CALLBACK>
604  void VisitBlockStmts(CALLBACK& O) const {
605    for (const_iterator I=begin(), E=end(); I != E; ++I)
606      for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
607           BI != BE; ++BI) {
608        if (const CFGStmt *stmt = BI->getAs<CFGStmt>())
609          O(stmt->getStmt());
610      }
611  }
612
613  //===--------------------------------------------------------------------===//
614  // CFG Introspection.
615  //===--------------------------------------------------------------------===//
616
617  struct   BlkExprNumTy {
618    const signed Idx;
619    explicit BlkExprNumTy(signed idx) : Idx(idx) {}
620    explicit BlkExprNumTy() : Idx(-1) {}
621    operator bool() const { return Idx >= 0; }
622    operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; }
623  };
624
625  bool isBlkExpr(const Stmt* S) { return getBlkExprNum(S); }
626  bool isBlkExpr(const Stmt *S) const {
627    return const_cast<CFG*>(this)->isBlkExpr(S);
628  }
629  BlkExprNumTy  getBlkExprNum(const Stmt* S);
630  unsigned      getNumBlkExprs();
631
632  /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
633  /// start at 0).
634  unsigned getNumBlockIDs() const { return NumBlockIDs; }
635
636  //===--------------------------------------------------------------------===//
637  // CFG Debugging: Pretty-Printing and Visualization.
638  //===--------------------------------------------------------------------===//
639
640  void viewCFG(const LangOptions &LO) const;
641  void print(llvm::raw_ostream& OS, const LangOptions &LO) const;
642  void dump(const LangOptions &LO) const;
643
644  //===--------------------------------------------------------------------===//
645  // Internal: constructors and data.
646  //===--------------------------------------------------------------------===//
647
648  CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
649          BlkExprMap(NULL), Blocks(BlkBVC, 10) {}
650
651  ~CFG();
652
653  llvm::BumpPtrAllocator& getAllocator() {
654    return BlkBVC.getAllocator();
655  }
656
657  BumpVectorContext &getBumpVectorContext() {
658    return BlkBVC;
659  }
660
661private:
662  CFGBlock* Entry;
663  CFGBlock* Exit;
664  CFGBlock* IndirectGotoBlock;  // Special block to contain collective dispatch
665                                // for indirect gotos
666  unsigned  NumBlockIDs;
667
668  // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h.
669  //  It represents a map from Expr* to integers to record the set of
670  //  block-level expressions and their "statement number" in the CFG.
671  void*     BlkExprMap;
672
673  BumpVectorContext BlkBVC;
674
675  CFGBlockListTy Blocks;
676
677};
678} // end namespace clang
679
680//===----------------------------------------------------------------------===//
681// GraphTraits specializations for CFG basic block graphs (source-level CFGs)
682//===----------------------------------------------------------------------===//
683
684namespace llvm {
685
686/// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
687/// CFGTerminator to a specific Stmt class.
688template <> struct simplify_type<const ::clang::CFGTerminator> {
689  typedef const ::clang::Stmt *SimpleType;
690  static SimpleType getSimplifiedValue(const ::clang::CFGTerminator &Val) {
691    return Val.getStmt();
692  }
693};
694
695template <> struct simplify_type< ::clang::CFGTerminator> {
696  typedef ::clang::Stmt *SimpleType;
697  static SimpleType getSimplifiedValue(const ::clang::CFGTerminator &Val) {
698    return const_cast<SimpleType>(Val.getStmt());
699  }
700};
701
702// Traits for: CFGBlock
703
704template <> struct GraphTraits< ::clang::CFGBlock* > {
705  typedef ::clang::CFGBlock NodeType;
706  typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
707
708  static NodeType* getEntryNode(::clang::CFGBlock* BB)
709  { return BB; }
710
711  static inline ChildIteratorType child_begin(NodeType* N)
712  { return N->succ_begin(); }
713
714  static inline ChildIteratorType child_end(NodeType* N)
715  { return N->succ_end(); }
716};
717
718template <> struct GraphTraits< const ::clang::CFGBlock* > {
719  typedef const ::clang::CFGBlock NodeType;
720  typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
721
722  static NodeType* getEntryNode(const clang::CFGBlock* BB)
723  { return BB; }
724
725  static inline ChildIteratorType child_begin(NodeType* N)
726  { return N->succ_begin(); }
727
728  static inline ChildIteratorType child_end(NodeType* N)
729  { return N->succ_end(); }
730};
731
732template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
733  typedef const ::clang::CFGBlock NodeType;
734  typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
735
736  static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
737  { return G.Graph; }
738
739  static inline ChildIteratorType child_begin(NodeType* N)
740  { return N->pred_begin(); }
741
742  static inline ChildIteratorType child_end(NodeType* N)
743  { return N->pred_end(); }
744};
745
746// Traits for: CFG
747
748template <> struct GraphTraits< ::clang::CFG* >
749    : public GraphTraits< ::clang::CFGBlock* >  {
750
751  typedef ::clang::CFG::iterator nodes_iterator;
752
753  static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
754  static nodes_iterator nodes_begin(::clang::CFG* F) { return F->begin(); }
755  static nodes_iterator nodes_end(::clang::CFG* F) { return F->end(); }
756};
757
758template <> struct GraphTraits<const ::clang::CFG* >
759    : public GraphTraits<const ::clang::CFGBlock* >  {
760
761  typedef ::clang::CFG::const_iterator nodes_iterator;
762
763  static NodeType *getEntryNode( const ::clang::CFG* F) {
764    return &F->getEntry();
765  }
766  static nodes_iterator nodes_begin( const ::clang::CFG* F) {
767    return F->begin();
768  }
769  static nodes_iterator nodes_end( const ::clang::CFG* F) {
770    return F->end();
771  }
772};
773
774template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
775  : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
776
777  typedef ::clang::CFG::const_iterator nodes_iterator;
778
779  static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
780  static nodes_iterator nodes_begin(const ::clang::CFG* F) { return F->begin();}
781  static nodes_iterator nodes_end(const ::clang::CFG* F) { return F->end(); }
782};
783} // end llvm namespace
784#endif
785