]> granicus.if.org Git - clang/blob - include/clang/Analysis/CFG.h
Added CFGTerminator class, that holds information about CFGBlock terminator statement.
[clang] / include / clang / Analysis / CFG.h
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 "clang/Analysis/Support/BumpVector.h"
23 #include "clang/Basic/SourceLocation.h"
24 #include <cassert>
25
26 namespace llvm {
27   class raw_ostream;
28 }
29
30 namespace clang {
31   class Decl;
32   class Stmt;
33   class Expr;
34   class FieldDecl;
35   class VarDecl;
36   class CXXBaseOrMemberInitializer;
37   class CXXBaseSpecifier;
38   class CFG;
39   class PrinterHelper;
40   class LangOptions;
41   class ASTContext;
42
43 /// CFGElement - Represents a top-level expression in a basic block.
44 class CFGElement {
45 public:
46   enum Kind {
47     // main kind
48     Statement,
49     StatementAsLValue,
50     Initializer,
51     Dtor,
52     // dtor kind
53     AutomaticObjectDtor,
54     BaseDtor,
55     MemberDtor,
56     TemporaryDtor,
57     DTOR_BEGIN = AutomaticObjectDtor
58   };
59
60 protected:
61   // The int bits are used to mark the main kind.
62   llvm::PointerIntPair<void *, 2> Data1;
63   // The int bits are used to mark the dtor kind.
64   llvm::PointerIntPair<void *, 2> Data2;
65
66   CFGElement(void *Ptr, unsigned Int) : Data1(Ptr, Int) {}
67   CFGElement(void *Ptr1, unsigned Int1, void *Ptr2, unsigned Int2)
68       : Data1(Ptr1, Int1), Data2(Ptr2, Int2) {}
69
70 public:
71   CFGElement() {}
72
73   Kind getKind() const { return static_cast<Kind>(Data1.getInt()); }
74
75   Kind getDtorKind() const {
76     assert(getKind() == Dtor);
77     return static_cast<Kind>(Data2.getInt() + DTOR_BEGIN);
78   }
79
80   bool isValid() const { return Data1.getPointer(); }
81
82   operator bool() const { return isValid(); }
83
84   template<class ElemTy> ElemTy getAs() const {
85     if (llvm::isa<ElemTy>(this))
86       return *static_cast<const ElemTy*>(this);
87     return ElemTy();
88   }
89
90   static bool classof(const CFGElement *E) { return true; }
91 };
92
93 class CFGStmt : public CFGElement {
94 public:
95   CFGStmt() {}
96   CFGStmt(Stmt *S, bool asLValue) : CFGElement(S, asLValue) {}
97
98   Stmt *getStmt() const { return static_cast<Stmt *>(Data1.getPointer()); }
99
100   operator Stmt*() const { return getStmt(); }
101
102   bool asLValue() const { 
103     return static_cast<Kind>(Data1.getInt()) == StatementAsLValue;
104   }
105
106   static bool classof(const CFGElement *E) {
107     return E->getKind() == Statement || E->getKind() == StatementAsLValue;
108   }
109 };
110
111 /// CFGInitializer - Represents C++ base or member initializer from
112 /// constructor's initialization list.
113 class CFGInitializer : public CFGElement {
114 public:
115   CFGInitializer() {}
116   CFGInitializer(CXXBaseOrMemberInitializer* I)
117       : CFGElement(I, Initializer) {}
118
119   CXXBaseOrMemberInitializer* getInitializer() const {
120     return static_cast<CXXBaseOrMemberInitializer*>(Data1.getPointer());
121   }
122   operator CXXBaseOrMemberInitializer*() const { return getInitializer(); }
123
124   static bool classof(const CFGElement *E) {
125     return E->getKind() == Initializer;
126   }
127 };
128
129 /// CFGImplicitDtor - Represents C++ object destructor implicitly generated
130 /// by compiler on various occasions.
131 class CFGImplicitDtor : public CFGElement {
132 protected:
133   CFGImplicitDtor(unsigned K, void* P, void* S)
134       : CFGElement(P, Dtor, S, K - DTOR_BEGIN) {}
135
136 public:
137   CFGImplicitDtor() {}
138
139   static bool classof(const CFGElement *E) {
140     return E->getKind() == Dtor;
141   }
142 };
143
144 /// CFGAutomaticObjDtor - Represents C++ object destructor implicitly generated
145 /// for automatic object or temporary bound to const reference at the point
146 /// of leaving its local scope.
147 class CFGAutomaticObjDtor: public CFGImplicitDtor {
148 public:
149   CFGAutomaticObjDtor() {}
150   CFGAutomaticObjDtor(VarDecl* VD, Stmt* S)
151       : CFGImplicitDtor(AutomaticObjectDtor, VD, S) {}
152
153   VarDecl* getVarDecl() const {
154     return static_cast<VarDecl*>(Data1.getPointer());
155   }
156
157   // Get statement end of which triggered the destructor call.
158   Stmt* getTriggerStmt() const {
159     return static_cast<Stmt*>(Data2.getPointer());
160   }
161
162   static bool classof(const CFGElement *E) {
163     return E->getKind() == Dtor && E->getDtorKind() == AutomaticObjectDtor;
164   }
165 };
166
167 /// CFGBaseDtor - Represents C++ object destructor implicitly generated for
168 /// base object in destructor.
169 class CFGBaseDtor : public CFGImplicitDtor {
170 public:
171   CFGBaseDtor() {}
172   CFGBaseDtor(const CXXBaseSpecifier *BS)
173       : CFGImplicitDtor(BaseDtor, const_cast<CXXBaseSpecifier*>(BS), NULL) {}
174
175   const CXXBaseSpecifier *getBaseSpecifier() const {
176     return static_cast<const CXXBaseSpecifier*>(Data1.getPointer());
177   }
178
179   static bool classof(const CFGElement *E) {
180     return E->getKind() == Dtor && E->getDtorKind() == BaseDtor;
181   }
182 };
183
184 /// CFGMemberDtor - Represents C++ object destructor implicitly generated for
185 /// member object in destructor.
186 class CFGMemberDtor : public CFGImplicitDtor {
187 public:
188   CFGMemberDtor() {}
189   CFGMemberDtor(FieldDecl *FD)
190       : CFGImplicitDtor(MemberDtor, FD, NULL) {}
191
192   FieldDecl *getFieldDecl() const {
193     return static_cast<FieldDecl*>(Data1.getPointer());
194   }
195
196   static bool classof(const CFGElement *E) {
197     return E->getKind() == Dtor && E->getDtorKind() == MemberDtor;
198   }
199 };
200
201 class CFGTemporaryDtor : public CFGImplicitDtor {
202 public:
203   static bool classof(const CFGElement *E) {
204     return E->getKind() == Dtor && E->getDtorKind() == TemporaryDtor;
205   }
206 };
207
208 /// CFGTerminator - Represents CFGBlock terminator statement.
209 ///
210 /// TemporaryDtorsBranch bit is set to true if the terminator marks a branch
211 /// in control flow of destructors of temporaries. In this case terminator
212 /// statement is the same statement that branches control flow in evaluation
213 /// of matching full expression.
214 class CFGTerminator {
215   llvm::PointerIntPair<Stmt *, 1> Data;
216 public:
217   CFGTerminator() {}
218   CFGTerminator(Stmt *S, bool TemporaryDtorsBranch = false)
219       : Data(S, TemporaryDtorsBranch) {}
220
221   Stmt *getStmt() { return Data.getPointer(); }
222   const Stmt *getStmt() const { return Data.getPointer(); }
223
224   bool isTemporaryDtorsBranch() const { return Data.getInt(); }
225
226   operator Stmt *() { return getStmt(); }
227   operator const Stmt *() const { return getStmt(); }
228
229   Stmt *operator->() { return getStmt(); }
230   const Stmt *operator->() const { return getStmt(); }
231
232   Stmt &operator*() { return *getStmt(); }
233   const Stmt &operator*() const { return *getStmt(); }
234
235   operator bool() const { return getStmt(); }
236 };
237
238 /// CFGBlock - Represents a single basic block in a source-level CFG.
239 ///  It consists of:
240 ///
241 ///  (1) A set of statements/expressions (which may contain subexpressions).
242 ///  (2) A "terminator" statement (not in the set of statements).
243 ///  (3) A list of successors and predecessors.
244 ///
245 /// Terminator: The terminator represents the type of control-flow that occurs
246 /// at the end of the basic block.  The terminator is a Stmt* referring to an
247 /// AST node that has control-flow: if-statements, breaks, loops, etc.
248 /// If the control-flow is conditional, the condition expression will appear
249 /// within the set of statements in the block (usually the last statement).
250 ///
251 /// Predecessors: the order in the set of predecessors is arbitrary.
252 ///
253 /// Successors: the order in the set of successors is NOT arbitrary.  We
254 ///  currently have the following orderings based on the terminator:
255 ///
256 ///     Terminator       Successor Ordering
257 ///  -----------------------------------------------------
258 ///       if            Then Block;  Else Block
259 ///     ? operator      LHS expression;  RHS expression
260 ///     &&, ||          expression that uses result of && or ||, RHS
261 ///
262 class CFGBlock {
263   class ElementList {
264     typedef BumpVector<CFGElement> ImplTy;
265     ImplTy Impl;
266   public:
267     ElementList(BumpVectorContext &C) : Impl(C, 4) {}
268     
269     typedef std::reverse_iterator<ImplTy::iterator>       iterator;
270     typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
271     typedef ImplTy::iterator                              reverse_iterator;
272     typedef ImplTy::const_iterator                        const_reverse_iterator;
273   
274     void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
275     reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
276         BumpVectorContext& C) {
277       return Impl.insert(I, Cnt, E, C);
278     }
279
280     CFGElement front() const { return Impl.back(); }
281     CFGElement back() const { return Impl.front(); }
282     
283     iterator begin() { return Impl.rbegin(); }
284     iterator end() { return Impl.rend(); }
285     const_iterator begin() const { return Impl.rbegin(); }
286     const_iterator end() const { return Impl.rend(); }
287     reverse_iterator rbegin() { return Impl.begin(); }
288     reverse_iterator rend() { return Impl.end(); }
289     const_reverse_iterator rbegin() const { return Impl.begin(); }
290     const_reverse_iterator rend() const { return Impl.end(); }
291
292    CFGElement operator[](size_t i) const  {
293      assert(i < Impl.size());
294      return Impl[Impl.size() - 1 - i];
295    }
296     
297     size_t size() const { return Impl.size(); }
298     bool empty() const { return Impl.empty(); }
299   };
300
301   /// Stmts - The set of statements in the basic block.
302   ElementList Elements;
303
304   /// Label - An (optional) label that prefixes the executable
305   ///  statements in the block.  When this variable is non-NULL, it is
306   ///  either an instance of LabelStmt, SwitchCase or CXXCatchStmt.
307   Stmt *Label;
308
309   /// Terminator - The terminator for a basic block that
310   ///  indicates the type of control-flow that occurs between a block
311   ///  and its successors.
312   CFGTerminator Terminator;
313
314   /// LoopTarget - Some blocks are used to represent the "loop edge" to
315   ///  the start of a loop from within the loop body.  This Stmt* will be
316   ///  refer to the loop statement for such blocks (and be null otherwise).
317   const Stmt *LoopTarget;
318
319   /// BlockID - A numerical ID assigned to a CFGBlock during construction
320   ///   of the CFG.
321   unsigned BlockID;
322
323   /// Predecessors/Successors - Keep track of the predecessor / successor
324   /// CFG blocks.
325   typedef BumpVector<CFGBlock*> AdjacentBlocks;
326   AdjacentBlocks Preds;
327   AdjacentBlocks Succs;
328
329 public:
330   explicit CFGBlock(unsigned blockid, BumpVectorContext &C)
331     : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
332       BlockID(blockid), Preds(C, 1), Succs(C, 1) {}
333   ~CFGBlock() {}
334
335   // Statement iterators
336   typedef ElementList::iterator                      iterator;
337   typedef ElementList::const_iterator                const_iterator;
338   typedef ElementList::reverse_iterator              reverse_iterator;
339   typedef ElementList::const_reverse_iterator        const_reverse_iterator;
340
341   CFGElement                 front()       const { return Elements.front();   }
342   CFGElement                 back()        const { return Elements.back();    }
343
344   iterator                   begin()             { return Elements.begin();   }
345   iterator                   end()               { return Elements.end();     }
346   const_iterator             begin()       const { return Elements.begin();   }
347   const_iterator             end()         const { return Elements.end();     }
348
349   reverse_iterator           rbegin()            { return Elements.rbegin();  }
350   reverse_iterator           rend()              { return Elements.rend();    }
351   const_reverse_iterator     rbegin()      const { return Elements.rbegin();  }
352   const_reverse_iterator     rend()        const { return Elements.rend();    }
353
354   unsigned                   size()        const { return Elements.size();    }
355   bool                       empty()       const { return Elements.empty();   }
356
357   CFGElement operator[](size_t i) const  { return Elements[i]; }
358
359   // CFG iterators
360   typedef AdjacentBlocks::iterator                              pred_iterator;
361   typedef AdjacentBlocks::const_iterator                  const_pred_iterator;
362   typedef AdjacentBlocks::reverse_iterator              pred_reverse_iterator;
363   typedef AdjacentBlocks::const_reverse_iterator  const_pred_reverse_iterator;
364
365   typedef AdjacentBlocks::iterator                              succ_iterator;
366   typedef AdjacentBlocks::const_iterator                  const_succ_iterator;
367   typedef AdjacentBlocks::reverse_iterator              succ_reverse_iterator;
368   typedef AdjacentBlocks::const_reverse_iterator  const_succ_reverse_iterator;
369
370   pred_iterator                pred_begin()        { return Preds.begin();   }
371   pred_iterator                pred_end()          { return Preds.end();     }
372   const_pred_iterator          pred_begin()  const { return Preds.begin();   }
373   const_pred_iterator          pred_end()    const { return Preds.end();     }
374
375   pred_reverse_iterator        pred_rbegin()       { return Preds.rbegin();  }
376   pred_reverse_iterator        pred_rend()         { return Preds.rend();    }
377   const_pred_reverse_iterator  pred_rbegin() const { return Preds.rbegin();  }
378   const_pred_reverse_iterator  pred_rend()   const { return Preds.rend();    }
379
380   succ_iterator                succ_begin()        { return Succs.begin();   }
381   succ_iterator                succ_end()          { return Succs.end();     }
382   const_succ_iterator          succ_begin()  const { return Succs.begin();   }
383   const_succ_iterator          succ_end()    const { return Succs.end();     }
384
385   succ_reverse_iterator        succ_rbegin()       { return Succs.rbegin();  }
386   succ_reverse_iterator        succ_rend()         { return Succs.rend();    }
387   const_succ_reverse_iterator  succ_rbegin() const { return Succs.rbegin();  }
388   const_succ_reverse_iterator  succ_rend()   const { return Succs.rend();    }
389
390   unsigned                     succ_size()   const { return Succs.size();    }
391   bool                         succ_empty()  const { return Succs.empty();   }
392
393   unsigned                     pred_size()   const { return Preds.size();    }
394   bool                         pred_empty()  const { return Preds.empty();   }
395
396
397   class FilterOptions {
398   public:
399     FilterOptions() {
400       IgnoreDefaultsWithCoveredEnums = 0;
401     }
402
403     unsigned IgnoreDefaultsWithCoveredEnums : 1;
404   };
405
406   static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
407        const CFGBlock *Dst);
408
409   template <typename IMPL, bool IsPred>
410   class FilteredCFGBlockIterator {
411   private:
412     IMPL I, E;
413     const FilterOptions F;
414     const CFGBlock *From;
415    public:
416     explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
417               const CFGBlock *from,
418               const FilterOptions &f)
419       : I(i), E(e), F(f), From(from) {}
420
421     bool hasMore() const { return I != E; }
422
423     FilteredCFGBlockIterator &operator++() {
424       do { ++I; } while (hasMore() && Filter(*I));
425       return *this;
426     }
427
428     const CFGBlock *operator*() const { return *I; }
429   private:
430     bool Filter(const CFGBlock *To) {
431       return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
432     }
433   };
434
435   typedef FilteredCFGBlockIterator<const_pred_iterator, true>
436           filtered_pred_iterator;
437
438   typedef FilteredCFGBlockIterator<const_succ_iterator, false>
439           filtered_succ_iterator;
440
441   filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
442     return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
443   }
444
445   filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
446     return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
447   }
448
449   // Manipulation of block contents
450
451   void setTerminator(Stmt* Statement) { Terminator = Statement; }
452   void setLabel(Stmt* Statement) { Label = Statement; }
453   void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
454
455   CFGTerminator getTerminator() { return Terminator; }
456   const CFGTerminator getTerminator() const { return Terminator; }
457
458   Stmt* getTerminatorCondition();
459
460   const Stmt* getTerminatorCondition() const {
461     return const_cast<CFGBlock*>(this)->getTerminatorCondition();
462   }
463
464   const Stmt *getLoopTarget() const { return LoopTarget; }
465
466   bool hasBinaryBranchTerminator() const;
467
468   Stmt* getLabel() { return Label; }
469   const Stmt* getLabel() const { return Label; }
470
471   unsigned getBlockID() const { return BlockID; }
472
473   void dump(const CFG *cfg, const LangOptions &LO) const;
474   void print(llvm::raw_ostream &OS, const CFG* cfg, const LangOptions &LO) const;
475   void printTerminator(llvm::raw_ostream &OS, const LangOptions &LO) const;
476   
477   void addSuccessor(CFGBlock* Block, BumpVectorContext &C) {
478     if (Block)
479       Block->Preds.push_back(this, C);
480     Succs.push_back(Block, C);
481   }
482   
483   void appendStmt(Stmt* Statement, BumpVectorContext &C, bool asLValue) {
484     Elements.push_back(CFGStmt(Statement, asLValue), C);
485   }
486
487   void appendInitializer(CXXBaseOrMemberInitializer *I, BumpVectorContext& C) {
488     Elements.push_back(CFGInitializer(I), C);
489   }
490
491   void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
492     Elements.push_back(CFGBaseDtor(BS), C);
493   }
494
495   void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
496     Elements.push_back(CFGMemberDtor(FD), C);
497   }
498
499   // Destructors must be inserted in reversed order. So insertion is in two
500   // steps. First we prepare space for some number of elements, then we insert
501   // the elements beginning at the last position in prepared space.
502   iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
503       BumpVectorContext& C) {
504     return iterator(Elements.insert(I.base(), Cnt, CFGElement(), C));
505   }
506   iterator insertAutomaticObjDtor(iterator I, VarDecl* VD, Stmt* S) {
507     *I = CFGAutomaticObjDtor(VD, S);
508     return ++I;
509   }
510 };
511
512 /// CFG - Represents a source-level, intra-procedural CFG that represents the
513 ///  control-flow of a Stmt.  The Stmt can represent an entire function body,
514 ///  or a single expression.  A CFG will always contain one empty block that
515 ///  represents the Exit point of the CFG.  A CFG will also contain a designated
516 ///  Entry block.  The CFG solely represents control-flow; it consists of
517 ///  CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
518 ///  was constructed from.
519 class CFG {
520 public:
521   //===--------------------------------------------------------------------===//
522   // CFG Construction & Manipulation.
523   //===--------------------------------------------------------------------===//
524
525   class BuildOptions {
526   public:
527     bool PruneTriviallyFalseEdges:1;
528     bool AddEHEdges:1;
529     bool AddInitializers:1;
530     bool AddImplicitDtors:1;
531
532     BuildOptions()
533         : PruneTriviallyFalseEdges(true)
534         , AddEHEdges(false)
535         , AddInitializers(false)
536         , AddImplicitDtors(false) {}
537   };
538
539   /// buildCFG - Builds a CFG from an AST.  The responsibility to free the
540   ///   constructed CFG belongs to the caller.
541   static CFG* buildCFG(const Decl *D, Stmt* AST, ASTContext *C,
542       BuildOptions BO = BuildOptions());
543
544   /// createBlock - Create a new block in the CFG.  The CFG owns the block;
545   ///  the caller should not directly free it.
546   CFGBlock* createBlock();
547
548   /// setEntry - Set the entry block of the CFG.  This is typically used
549   ///  only during CFG construction.  Most CFG clients expect that the
550   ///  entry block has no predecessors and contains no statements.
551   void setEntry(CFGBlock *B) { Entry = B; }
552
553   /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
554   ///  This is typically used only during CFG construction.
555   void setIndirectGotoBlock(CFGBlock* B) { IndirectGotoBlock = B; }
556
557   //===--------------------------------------------------------------------===//
558   // Block Iterators
559   //===--------------------------------------------------------------------===//
560
561   typedef BumpVector<CFGBlock*>                    CFGBlockListTy;    
562   typedef CFGBlockListTy::iterator                 iterator;
563   typedef CFGBlockListTy::const_iterator           const_iterator;
564   typedef std::reverse_iterator<iterator>          reverse_iterator;
565   typedef std::reverse_iterator<const_iterator>    const_reverse_iterator;
566
567   CFGBlock&                 front()                { return *Blocks.front(); }
568   CFGBlock&                 back()                 { return *Blocks.back(); }
569
570   iterator                  begin()                { return Blocks.begin(); }
571   iterator                  end()                  { return Blocks.end(); }
572   const_iterator            begin()       const    { return Blocks.begin(); }
573   const_iterator            end()         const    { return Blocks.end(); }
574
575   reverse_iterator          rbegin()               { return Blocks.rbegin(); }
576   reverse_iterator          rend()                 { return Blocks.rend(); }
577   const_reverse_iterator    rbegin()      const    { return Blocks.rbegin(); }
578   const_reverse_iterator    rend()        const    { return Blocks.rend(); }
579
580   CFGBlock&                 getEntry()             { return *Entry; }
581   const CFGBlock&           getEntry()    const    { return *Entry; }
582   CFGBlock&                 getExit()              { return *Exit; }
583   const CFGBlock&           getExit()     const    { return *Exit; }
584
585   CFGBlock*        getIndirectGotoBlock() { return IndirectGotoBlock; }
586   const CFGBlock*  getIndirectGotoBlock() const { return IndirectGotoBlock; }
587
588   //===--------------------------------------------------------------------===//
589   // Member templates useful for various batch operations over CFGs.
590   //===--------------------------------------------------------------------===//
591
592   template <typename CALLBACK>
593   void VisitBlockStmts(CALLBACK& O) const {
594     for (const_iterator I=begin(), E=end(); I != E; ++I)
595       for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
596            BI != BE; ++BI) {
597         if (CFGStmt S = BI->getAs<CFGStmt>())
598           O(S);
599       }
600   }
601
602   //===--------------------------------------------------------------------===//
603   // CFG Introspection.
604   //===--------------------------------------------------------------------===//
605
606   struct   BlkExprNumTy {
607     const signed Idx;
608     explicit BlkExprNumTy(signed idx) : Idx(idx) {}
609     explicit BlkExprNumTy() : Idx(-1) {}
610     operator bool() const { return Idx >= 0; }
611     operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; }
612   };
613
614   bool          isBlkExpr(const Stmt* S) { return getBlkExprNum(S); }
615   BlkExprNumTy  getBlkExprNum(const Stmt* S);
616   unsigned      getNumBlkExprs();
617
618   /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
619   /// start at 0).
620   unsigned getNumBlockIDs() const { return NumBlockIDs; }
621
622   //===--------------------------------------------------------------------===//
623   // CFG Debugging: Pretty-Printing and Visualization.
624   //===--------------------------------------------------------------------===//
625
626   void viewCFG(const LangOptions &LO) const;
627   void print(llvm::raw_ostream& OS, const LangOptions &LO) const;
628   void dump(const LangOptions &LO) const;
629
630   //===--------------------------------------------------------------------===//
631   // Internal: constructors and data.
632   //===--------------------------------------------------------------------===//
633
634   CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
635           BlkExprMap(NULL), Blocks(BlkBVC, 10) {}
636
637   ~CFG();
638
639   llvm::BumpPtrAllocator& getAllocator() {
640     return BlkBVC.getAllocator();
641   }
642   
643   BumpVectorContext &getBumpVectorContext() {
644     return BlkBVC;
645   }
646
647 private:
648   CFGBlock* Entry;
649   CFGBlock* Exit;
650   CFGBlock* IndirectGotoBlock;  // Special block to contain collective dispatch
651                                 // for indirect gotos
652   unsigned  NumBlockIDs;
653
654   // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h.
655   //  It represents a map from Expr* to integers to record the set of
656   //  block-level expressions and their "statement number" in the CFG.
657   void*     BlkExprMap;
658   
659   BumpVectorContext BlkBVC;
660   
661   CFGBlockListTy Blocks;
662
663 };
664 } // end namespace clang
665
666 //===----------------------------------------------------------------------===//
667 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
668 //===----------------------------------------------------------------------===//
669
670 namespace llvm {
671
672 /// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
673 /// CFGTerminator to a specific Stmt class.
674 template <> struct simplify_type<const ::clang::CFGTerminator> {
675   typedef const ::clang::Stmt *SimpleType;
676   static SimpleType getSimplifiedValue(const ::clang::CFGTerminator &Val) {
677     return Val.getStmt();
678   }
679 };
680
681 template <> struct simplify_type< ::clang::CFGTerminator> {
682   typedef ::clang::Stmt *SimpleType;
683   static SimpleType getSimplifiedValue(const ::clang::CFGTerminator &Val) {
684     return const_cast<SimpleType>(Val.getStmt());
685   }
686 };
687
688 // Traits for: CFGBlock
689
690 template <> struct GraphTraits< ::clang::CFGBlock* > {
691   typedef ::clang::CFGBlock NodeType;
692   typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
693
694   static NodeType* getEntryNode(::clang::CFGBlock* BB)
695   { return BB; }
696
697   static inline ChildIteratorType child_begin(NodeType* N)
698   { return N->succ_begin(); }
699
700   static inline ChildIteratorType child_end(NodeType* N)
701   { return N->succ_end(); }
702 };
703
704 template <> struct GraphTraits< const ::clang::CFGBlock* > {
705   typedef const ::clang::CFGBlock NodeType;
706   typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
707
708   static NodeType* getEntryNode(const 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
718 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
719   typedef const ::clang::CFGBlock NodeType;
720   typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
721
722   static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
723   { return G.Graph; }
724
725   static inline ChildIteratorType child_begin(NodeType* N)
726   { return N->pred_begin(); }
727
728   static inline ChildIteratorType child_end(NodeType* N)
729   { return N->pred_end(); }
730 };
731
732 // Traits for: CFG
733
734 template <> struct GraphTraits< ::clang::CFG* >
735     : public GraphTraits< ::clang::CFGBlock* >  {
736
737   typedef ::clang::CFG::iterator nodes_iterator;
738
739   static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
740   static nodes_iterator nodes_begin(::clang::CFG* F) { return F->begin(); }
741   static nodes_iterator nodes_end(::clang::CFG* F) { return F->end(); }
742 };
743
744 template <> struct GraphTraits<const ::clang::CFG* >
745     : public GraphTraits<const ::clang::CFGBlock* >  {
746
747   typedef ::clang::CFG::const_iterator nodes_iterator;
748
749   static NodeType *getEntryNode( const ::clang::CFG* F) {
750     return &F->getEntry();
751   }
752   static nodes_iterator nodes_begin( const ::clang::CFG* F) {
753     return F->begin();
754   }
755   static nodes_iterator nodes_end( const ::clang::CFG* F) {
756     return F->end();
757   }
758 };
759
760 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
761   : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
762
763   typedef ::clang::CFG::const_iterator nodes_iterator;
764
765   static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
766   static nodes_iterator nodes_begin(const ::clang::CFG* F) { return F->begin();}
767   static nodes_iterator nodes_end(const ::clang::CFG* F) { return F->end(); }
768 };
769 } // end llvm namespace
770 #endif