CFG.cpp revision 4f15dd00ce7ce04b016613f49241c91c685efbed
1fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//
3fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//                     The LLVM Compiler Infrastructure
4fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//
50bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// This file is distributed under the University of Illinois Open Source
60bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// License. See LICENSE.TXT for details.
7fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//
8fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//===----------------------------------------------------------------------===//
9fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//
10fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//  This file defines the CFG and CFGBuilder classes for representing and
11fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//  building Control-Flow Graphs (CFGs) from ASTs.
12fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//
13fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek//===----------------------------------------------------------------------===//
14fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
15cd881d534517f09a2fae10445f9b865f49ccc6c8Ted Kremenek#include "clang/Analysis/Support/SaveAndRestore.h"
16cd881d534517f09a2fae10445f9b865f49ccc6c8Ted Kremenek#include "clang/Analysis/CFG.h"
17cd881d534517f09a2fae10445f9b865f49ccc6c8Ted Kremenek#include "clang/AST/DeclCXX.h"
18852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek#include "clang/AST/StmtVisitor.h"
197dba8607e59096014b7139ff20ef00870041d518Ted Kremenek#include "clang/AST/PrettyPrinter.h"
20ce1eb34bbea1e0408f1952776d7d52ccde1bd275Ted Kremenek#include "llvm/Support/GraphWriter.h"
21852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek#include "llvm/Support/Allocator.h"
22ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek#include "llvm/Support/Format.h"
23079bd72439448b78629a28da6b1f8abe2cdeaf4dMike Stump#include "llvm/ADT/DenseMap.h"
24c1581a0d64b0ee4f822ed2fca4442a111d03569aHartmut Kaiser#include "llvm/ADT/SmallPtrSet.h"
25fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek#include "llvm/ADT/OwningPtr.h"
26e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner
27e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattnerusing namespace clang;
28e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner
292a4cd498ff9b2b126de3e370b768ab307c221ab8Marcin Swiderskinamespace {
30fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
31b978a441c7d8bf59e7fede938e1f3b672573b443Mike Stumpstatic SourceLocation GetEndLoc(Decl* D) {
3242a509f6a4f71bb805cc4abbb26722a34dffdddeTed Kremenek  if (VarDecl* VD = dyn_cast<VarDecl>(D))
3363f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek    if (Expr* Ex = VD->getInit())
347c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski      return Ex->getSourceRange().getEnd();
351cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski
361cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski  return D->getLocation();
377c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski}
388599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski
3942a509f6a4f71bb805cc4abbb26722a34dffdddeTed Kremenekclass AddStmtChoice {
4042a509f6a4f71bb805cc4abbb26722a34dffdddeTed Kremenekpublic:
41e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner  enum Kind { NotAlwaysAdd = 0,
42e5af3ce53ec58995b09381ba645ab2117a46647bMike Stump              AlwaysAdd = 1,
43e5af3ce53ec58995b09381ba645ab2117a46647bMike Stump              AsLValueNotAlwaysAdd = 2,
44852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek              AlwaysAddAsLValue = 3 };
45852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
46852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek  AddStmtChoice(Kind kind) : k(kind) {}
47b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
48b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  bool alwaysAdd() const { return (unsigned)k & 0x1; }
49b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  bool asLValue() const { return k >= AsLValueNotAlwaysAdd; }
50b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
519c6cd67ea416bace666d614c84d5531124287653Zhongxing Xuprivate:
52b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  Kind k;
53b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu};
54b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
55b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu/// LocalScope - Node in tree of local scopes created for C++ implicit
56b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu/// destructor calls generation. It contains list of automatic variables
57b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu/// declared in the scope and link to position in previous scope this scope
58b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu/// began in.
59b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///
60b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu/// The process of creating local scopes is as follows:
61b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
62b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu/// - Before processing statements in scope (e.g. CompoundStmt) create
63b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///   LocalScope object using CFGBuilder::ScopePos as link to previous scope
64b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///   and set CFGBuilder::ScopePos to the end of new scope,
65b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
661cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski///   at this VarDecl,
671cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski/// - For every normal (without jump) end of scope add to CFGBlock destructors
681cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski///   for objects in the current scope,
691cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski/// - For every jump add to CFGBlock destructors for objects
70b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///   between CFGBuilder::ScopePos and local scope position saved for jump
71b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///   target. Thanks to C++ restrictions on goto jumps we can be sure that
72b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///   jump target position will be on the path to root from CFGBuilder::ScopePos
73b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///   (adding any variable that doesn't need constructor to be called to
74b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///   LocalScope can break this assumption),
75b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///
769c6cd67ea416bace666d614c84d5531124287653Zhongxing Xuclass LocalScope {
77b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xupublic:
78b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  typedef llvm::SmallVector<VarDecl*, 4> AutomaticVarsTy;
79b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
80b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  /// const_iterator - Iterates local scope backwards and jumps to previous
81b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  /// scope on reaching the beginning of currently iterated scope.
82b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  class const_iterator {
83b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    const LocalScope* Scope;
84b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
85b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    /// VarIter is guaranteed to be greater then 0 for every valid iterator.
86b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    /// Invalid iterator (with null Scope) has VarIter equal to 0.
87b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    unsigned VarIter;
88b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
89b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  public:
90b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
91b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    /// Incrementing invalid iterator is allowed and will result in invalid
92b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    /// iterator.
93b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    const_iterator()
94b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu        : Scope(NULL), VarIter(0) {}
95b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
96892697dd2287caf7c29aaaa82909b0e90b8b63feTed Kremenek    /// Create valid iterator. In case when S.Prev is an invalid iterator and
97b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    /// I is equal to 0, this will create invalid iterator.
98b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    const_iterator(const LocalScope& S, unsigned I)
99b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu        : Scope(&S), VarIter(I) {
100852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      // Iterator to "end" of scope is not allowed. Handle it by going up
101b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      // in scopes tree possibly up to invalid iterator in the root.
102b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      if (VarIter == 0 && Scope)
103892697dd2287caf7c29aaaa82909b0e90b8b63feTed Kremenek        *this = Scope->Prev;
104b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    }
105b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
106b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    VarDecl* const* operator->() const {
1071cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski      assert (Scope && "Dereferencing invalid iterator is not allowed");
1081cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski      assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
109b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      return &Scope->Vars[VarIter - 1];
110b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    }
1111cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski    VarDecl* operator*() const {
1121cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski      return *this->operator->();
1131cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski    }
1141cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski
1151cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski    const_iterator& operator++() {
1161cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski      if (!Scope)
1171cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski        return *this;
1181cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski
1191cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski      assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
120b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      --VarIter;
121b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      if (VarIter == 0)
122b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu        *this = Scope->Prev;
123b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      return *this;
124b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    }
12553de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski    const_iterator operator++(int) {
1261cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski      const_iterator P = *this;
127b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      ++*this;
1281cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski      return P;
1291cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski    }
1309c6cd67ea416bace666d614c84d5531124287653Zhongxing Xu
1311cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski    bool operator==(const const_iterator& rhs) const {
132b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      return Scope == rhs.Scope && VarIter == rhs.VarIter;
1331cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski    }
1341cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski    bool operator!=(const const_iterator& rhs) const {
135b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      return !(*this == rhs);
1369c6cd67ea416bace666d614c84d5531124287653Zhongxing Xu    }
137b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
138b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    operator bool() const {
139b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      return *this != const_iterator();
1407c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski    }
1411cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski
1421cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski    int distance(const_iterator L);
143b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  };
144b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
1451cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski  friend class const_iterator;
1461cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski
1471cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderskiprivate:
1481cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski  /// Automatic variables in order of declaration.
1491cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski  AutomaticVarsTy Vars;
1501cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski  /// Iterator to variable in previous scope that was declared just before
1511cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski  /// begin of this scope.
1521cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski  const_iterator Prev;
1531cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski
1541cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderskipublic:
1551cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski  /// Constructs empty scope linked to previous scope in specified place.
1561cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski  LocalScope(const_iterator P)
1571cff132e48e0ccc253c34e5a2fb12718bd4e7d2eMarcin Swiderski      : Vars()
158b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      , Prev(P) {}
1599c6cd67ea416bace666d614c84d5531124287653Zhongxing Xu
1609c6cd67ea416bace666d614c84d5531124287653Zhongxing Xu  /// Begin of scope in direction of CFG building (backwards).
161b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  const_iterator begin() const { return const_iterator(*this, Vars.size()); }
162b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
163b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  void addVar(VarDecl* VD) {
1647c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski    Vars.push_back(VD);
1657c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski  }
166b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu};
167b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
1687c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski/// distance - Calculates distance from this to L. L must be reachable from this
1697c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
1707c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski/// number of scopes between this and L.
1717c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderskiint LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
1727c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski  int D = 0;
1737c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski  const_iterator F = *this;
1747c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski  while (F.Scope != L.Scope) {
1757c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski    assert (F != const_iterator()
176b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu        && "L iterator is not reachable from F iterator.");
1779c6cd67ea416bace666d614c84d5531124287653Zhongxing Xu    D += F.VarIter;
178b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    F = F.Scope->Prev;
179b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  }
180b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  D += F.VarIter - L.VarIter;
1817c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski  return D;
1827c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski}
183b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
184b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu/// BlockScopePosPair - Structure for specifying position in CFG during its
1857c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski/// build process. It consists of CFGBlock that specifies position in CFG graph
1867c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski/// and  LocalScope::const_iterator that specifies position in LocalScope graph.
1877c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderskistruct BlockScopePosPair {
1887c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski  BlockScopePosPair() {}
1897c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski  BlockScopePosPair(CFGBlock* B, LocalScope::const_iterator S)
1907c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski      : Block(B), ScopePos(S) {}
1917c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski
1927c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski  CFGBlock*                   Block;
193b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  LocalScope::const_iterator  ScopePos;
1949c6cd67ea416bace666d614c84d5531124287653Zhongxing Xu};
195b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
196b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu/// CFGBuilder - This class implements CFG construction from an AST.
197b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///   The builder is stateful: an instance of the builder should be used to only
1988599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski///   construct a single CFG.
1998599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski///
200b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///   Example usage:
201b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu///
2028599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski///     CFGBuilder builder;
2038599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski///     CFG* cfg = builder.BuildAST(stmt1);
2048599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski///
2058599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski///  CFG construction is done via a recursive walk of an AST.  We actually parse
2068599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski///  the AST in reverse order so that the successor of a basic block is
2078599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski///  constructed prior to its predecessor.  This allows us to nicely capture
2088599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski///  implicit fall-throughs without extra basic blocks.
2098599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski///
210b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xuclass CFGBuilder {
2119c6cd67ea416bace666d614c84d5531124287653Zhongxing Xu  typedef BlockScopePosPair JumpTarget;
212b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  typedef BlockScopePosPair JumpSource;
213852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
214852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek  ASTContext *Context;
2154ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  llvm::OwningPtr<CFG> cfg;
2164ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski
2174ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  CFGBlock* Block;
2184ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  CFGBlock* Succ;
2194ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  JumpTarget ContinueJumpTarget;
2204ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  JumpTarget BreakJumpTarget;
2214ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  CFGBlock* SwitchTerminatedBlock;
2224ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  CFGBlock* DefaultCaseBlock;
2234ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  CFGBlock* TryTerminatedBlock;
2244ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski
2254ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  // Current position in local scope.
2264ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  LocalScope::const_iterator ScopePos;
2274ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski
2284ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  // LabelMap records the mapping from Label expressions to their jump targets.
2294ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  typedef llvm::DenseMap<LabelStmt*, JumpTarget> LabelMapTy;
2304ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  LabelMapTy LabelMap;
2314ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski
2324ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  // A list of blocks that end with a "goto" that must be backpatched to their
2334ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  // resolved targets upon completion of CFG construction.
2344ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  typedef std::vector<JumpSource> BackpatchBlocksTy;
2354ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  BackpatchBlocksTy BackpatchBlocks;
2364ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski
2374ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  // A list of labels whose address has been taken (for indirect gotos).
2384ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
2394ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  LabelSetTy AddressTakenLabels;
2404ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski
2414ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  bool badCFG;
2424ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  CFG::BuildOptions BuildOpts;
2434ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski
2444ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderskipublic:
245fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  explicit CFGBuilder() : cfg(new CFG()), // crew a new CFG
246fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek                          Block(NULL), Succ(NULL),
247fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek                          SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL),
248fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek                          TryTerminatedBlock(NULL), badCFG(false) {}
249fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
250fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  // buildCFG - Used by external clients to construct the CFG.
251fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFG* buildCFG(const Decl *D, Stmt *Statement, ASTContext *C,
252fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek      CFG::BuildOptions BO);
253fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
254fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenekprivate:
255fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  // Visitors to walk an AST and construct the CFG.
256fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
257fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
258fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitBlockExpr(BlockExpr* E, AddStmtChoice asc);
259fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitBreakStmt(BreakStmt *B);
260fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
261fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
262fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
263fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
264fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
265fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek                                        AddStmtChoice asc);
2669cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek  CFGBlock *VisitCXXMemberCallExpr(CXXMemberCallExpr *C, AddStmtChoice asc);
2679cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek  CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
268fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitCaseStmt(CaseStmt *C);
269fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
270b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  CFGBlock *VisitCompoundStmt(CompoundStmt *C);
271852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek  CFGBlock *VisitConditionalOperator(ConditionalOperator *C, AddStmtChoice asc);
2726c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitContinueStmt(ContinueStmt *C);
2736c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitDeclStmt(DeclStmt *DS);
274b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  CFGBlock *VisitDeclSubExpr(Decl* D);
275ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  CFGBlock *VisitDefaultStmt(DefaultStmt *D);
2766c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitDoStmt(DoStmt *D);
2776c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitForStmt(ForStmt *F);
2786c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitGotoStmt(GotoStmt* G);
2796c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitIfStmt(IfStmt *I);
2806c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
281852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek  CFGBlock *VisitLabelStmt(LabelStmt *L);
28253de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski  CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
28353de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski  CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
28453de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski  CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
28553de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski  CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
28653de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski  CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
287852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek  CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
288852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek  CFGBlock *VisitReturnStmt(ReturnStmt* R);
2896c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, AddStmtChoice asc);
2906c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
2916c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitSwitchStmt(SwitchStmt *S);
2926c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitWhileStmt(WhileStmt *W);
2936c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek
2946c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
2956c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
2966c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *VisitChildren(Stmt* S);
2976c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek
2986c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  // NYS == Not Yet Supported
299852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek  CFGBlock* NYS() {
3006c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek    badCFG = true;
3016c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek    return Block;
3026c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  }
3036c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek
3046c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  void autoCreateBlock() { if (!Block) Block = createBlock(); }
3056c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *createBlock(bool add_successor = true);
3066c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek
3076c2497248bc4f7fd8e5fb0a206d20abbf0e16645Ted Kremenek  CFGBlock *addStmt(Stmt *S) {
308fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    return Visit(S, AddStmtChoice::AlwaysAdd);
309b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  }
3109cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek  CFGBlock *addInitializer(CXXBaseOrMemberInitializer *I);
3119cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek  void addAutomaticObjDtors(LocalScope::const_iterator B,
3129cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek                            LocalScope::const_iterator E, Stmt* S);
3134c45aa1b00b91847acfb082acfaced3ffa294d1dMike Stump  void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
3143575f84e459033d6427b84b4b795b22c85c4d27dTed Kremenek
3151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Local scopes creation.
3169cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek  LocalScope* createOrReuseLocalScope(LocalScope* Scope);
317fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
318fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  void addLocalScopeForStmt(Stmt* S);
3194ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  LocalScope* addLocalScopeForDeclStmt(DeclStmt* DS, LocalScope* Scope = NULL);
3201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  LocalScope* addLocalScopeForVarDecl(VarDecl* VD, LocalScope* Scope = NULL);
3213575f84e459033d6427b84b4b795b22c85c4d27dTed Kremenek
3223575f84e459033d6427b84b4b795b22c85c4d27dTed Kremenek  void addLocalScopeAndDtors(Stmt* S);
3233575f84e459033d6427b84b4b795b22c85c4d27dTed Kremenek
3241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Interface to CFGBlock - adding CFGElements.
3251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  void AppendStmt(CFGBlock *B, Stmt *S,
326fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek                  AddStmtChoice asc = AddStmtChoice::AlwaysAdd) {
327fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    B->appendStmt(S, cfg->getBumpVectorContext(), asc.asLValue());
328fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  }
3291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  void appendInitializer(CFGBlock *B, CXXBaseOrMemberInitializer *I) {
330fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    B->appendInitializer(I, cfg->getBumpVectorContext());
331fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  }
332ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
333fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    B->appendBaseDtor(BS, cfg->getBumpVectorContext());
334fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  }
3351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
336fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    B->appendMemberDtor(FD, cfg->getBumpVectorContext());
337ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  }
338b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
339ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  void insertAutomaticObjDtors(CFGBlock* Blk, CFGBlock::iterator I,
3407177dee8aee4b432911c91f1b788963bec0cac9fDaniel Dunbar    LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S);
341fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  void appendAutomaticObjDtors(CFGBlock* Blk, LocalScope::const_iterator B,
342fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek      LocalScope::const_iterator E, Stmt* S);
343b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  void prependAutomaticObjDtorsWithTerminator(CFGBlock* Blk,
344b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      LocalScope::const_iterator B, LocalScope::const_iterator E);
345b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
346b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  void AddSuccessor(CFGBlock *B, CFGBlock *S) {
3471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    B->addSuccessor(S, cfg->getBumpVectorContext());
348b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  }
349b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
3501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  /// TryResult - a class representing a variant over the values
351b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  ///  'true', 'false', or 'unknown'.  This is returned by TryEvaluateBool,
352b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  ///  and is used by the CFGBuilder to decide if a branch condition
353b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  ///  can be decided up front during CFG construction.
354b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  class TryResult {
355fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    int X;
356b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  public:
357b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    TryResult(bool b) : X(b ? 1 : 0) {}
358b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    TryResult() : X(-1) {}
359b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu
3601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    bool isTrue() const { return X == 1; }
361b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    bool isFalse() const { return X == 0; }
362b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    bool isKnown() const { return X >= 0; }
363be7a7d6f2e5b86807afd08a568863df973baaa38Ted Kremenek    void negate() {
364b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu      assert(isKnown());
3651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      X ^= 0x1;
366fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    }
367fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  };
368fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
369fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  /// TryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
370fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  /// if we can evaluate to a known value, otherwise return -1.
371fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  TryResult TryEvaluateBool(Expr *S) {
372fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    if (!BuildOpts.PruneTriviallyFalseEdges)
373fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek      return TryResult();
374fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
375fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    Expr::EvalResult Result;
3761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    if (!S->isTypeDependent() && !S->isValueDependent() &&
377fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek        S->Evaluate(Result, *Context) && Result.Val.isInt())
378fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek      return Result.Val.getInt().getBoolValue();
379fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
380fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    return TryResult();
3811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
382fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek};
3831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
384fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek// FIXME: Add support for dependent-sized array types in C++?
385fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek// Does it even make sense to build a CFG for an uninstantiated template?
386fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenekstatic VariableArrayType* FindVA(Type* t) {
3871eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
388fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
389fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek      if (vat->getSizeExpr())
3901eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        return vat;
3911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
392fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    t = vt->getElementType().getTypePtr();
393fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  }
394fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
395fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  return 0;
396fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek}
397fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
398fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek/// BuildCFG - Constructs a CFG from an AST (a Stmt*).  The AST can represent an
399fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek///  arbitrary statement.  Examples include a single expression or a function
400fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek///  body (compound statement).  The ownership of the returned CFG is
401fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek///  transferred to the caller.  If CFG construction fails, this method returns
4021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump///  NULL.
403ee7f84d509c6382491673883598eb9ed2d3a6a8bTed KremenekCFG* CFGBuilder::buildCFG(const Decl *D, Stmt* Statement, ASTContext* C,
404ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    CFG::BuildOptions BO) {
405ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
406ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  Context = C;
407ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  assert(cfg.get());
408be39a566a914df8561d7a1e9654708297f0908c1Ted Kremenek  if (!Statement)
409ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    return NULL;
410ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
411ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  BuildOpts = BO;
412ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
413ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  // Create an empty block that will serve as the exit block for the CFG.  Since
414be39a566a914df8561d7a1e9654708297f0908c1Ted Kremenek  // this is the first block added to the CFG, it will be implicitly registered
415ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  // as the exit block.
416ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  Succ = createBlock();
417ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  assert(Succ == &cfg->getExit());
418ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  Block = NULL;  // the EXIT block is empty.  Create all other blocks lazily.
419ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
420ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  if (BuildOpts.AddImplicitDtors)
421ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
422ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek      addImplicitDtorsForDestructor(DD);
423ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
424be39a566a914df8561d7a1e9654708297f0908c1Ted Kremenek  // Visit the statements and create the CFG.
425be39a566a914df8561d7a1e9654708297f0908c1Ted Kremenek  CFGBlock *B = addStmt(Statement);
426ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
427ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  if (badCFG)
428ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    return NULL;
429ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
430ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  // For C++ constructor add initializers to CFG.
431ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
432ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
433ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek        E = CD->init_rend(); I != E; ++I) {
434ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek      B = addInitializer(*I);
435ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek      if (badCFG)
436ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek        return NULL;
437ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    }
438ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  }
439ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
440ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  if (B)
441ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    Succ = B;
442ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
443ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  // Backpatch the gotos whose label -> block mappings we didn't know when we
444ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  // encountered them.
445ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek  for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
446ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek                                   E = BackpatchBlocks.end(); I != E; ++I ) {
447ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
448ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    CFGBlock* B = I->Block;
449ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    GotoStmt* G = cast<GotoStmt>(B->getTerminator());
450ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
451ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
452ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    // If there is no target for the goto, then we are looking at an
453ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    // incomplete AST.  Handle this by not registering a successor.
454ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek    if (LI == LabelMap.end()) continue;
455ee7f84d509c6382491673883598eb9ed2d3a6a8bTed Kremenek
456fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    JumpTarget JT = LI->second;
4571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    prependAutomaticObjDtorsWithTerminator(B, I->ScopePos, JT.ScopePos);
4589cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek    AddSuccessor(B, JT.Block);
4599cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek  }
4603575f84e459033d6427b84b4b795b22c85c4d27dTed Kremenek
4619cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek  // Add successors to the Indirect Goto Dispatch block (if we have one).
4624ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  if (CFGBlock* B = cfg->getIndirectGotoBlock())
4634ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski    for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
4641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                              E = AddressTakenLabels.end(); I != E; ++I ) {
465390e48b15ad93f85bfd1e33b9992c198fa0db475Ted Kremenek
4661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      // Lookup the target block.
467390e48b15ad93f85bfd1e33b9992c198fa0db475Ted Kremenek      LabelMapTy::iterator LI = LabelMap.find(*I);
468411cdee0b490f79428c9eb977f25199eb7d21cd8Ted Kremenek
469411cdee0b490f79428c9eb977f25199eb7d21cd8Ted Kremenek      // If there is no target block that contains label, then we are looking
4701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      // at an incomplete AST.  Handle this by not registering a successor.
4713575f84e459033d6427b84b4b795b22c85c4d27dTed Kremenek      if (LI == LabelMap.end()) continue;
4721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4739c2535a35db35b3a821a0d0c36a01a16f52f1ad0Ted Kremenek      AddSuccessor(B, LI->second.Block);
4741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    }
4759cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek
4769cffe7366ea3beb33c2d58f43a8c3a04c1873e11Ted Kremenek  // Create an empty entry block that has no predecessors.
4771eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  cfg->setEntry(createBlock());
478fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
4791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  return cfg.take();
480e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner}
481e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner
482e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner/// createBlock - Used to lazily create blocks that are connected
483ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek///  to the current (global) succcessor.
484ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted KremenekCFGBlock* CFGBuilder::createBlock(bool add_successor) {
485ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  CFGBlock* B = cfg->createBlock();
486ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  if (add_successor && Succ)
487ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek    AddSuccessor(B, Succ);
488ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  return B;
489ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek}
490892697dd2287caf7c29aaaa82909b0e90b8b63feTed Kremenek
491892697dd2287caf7c29aaaa82909b0e90b8b63feTed Kremenek/// addInitializer - Add C++ base or member initializer element to CFG.
492079bd72439448b78629a28da6b1f8abe2cdeaf4dMike StumpCFGBlock *CFGBuilder::addInitializer(CXXBaseOrMemberInitializer *I) {
49382bc3fd823d85ee3ef9a641c0975b6ad25f55047Marcin Swiderski  if (!BuildOpts.AddInitializers)
494892697dd2287caf7c29aaaa82909b0e90b8b63feTed Kremenek    return Block;
495892697dd2287caf7c29aaaa82909b0e90b8b63feTed Kremenek
496892697dd2287caf7c29aaaa82909b0e90b8b63feTed Kremenek  autoCreateBlock();
49782bc3fd823d85ee3ef9a641c0975b6ad25f55047Marcin Swiderski  appendInitializer(Block, I);
49882bc3fd823d85ee3ef9a641c0975b6ad25f55047Marcin Swiderski
4997c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski  if (Expr *Init = I->getInit()) {
5007c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski    AddStmtChoice::Kind K = AddStmtChoice::NotAlwaysAdd;
5017c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski    if (FieldDecl *FD = I->getMember())
5027c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski      if (FD->getType()->isReferenceType())
5037c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski        K = AddStmtChoice::AsLValueNotAlwaysAdd;
5047c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski
5057c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski    return Visit(Init, AddStmtChoice(K));
5068599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski  }
5078599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski
5088599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski  return Block;
5098599e7677e067fd01d3b2ee4c0875747d367fd8eMarcin Swiderski}
5107c625d8ffc20b92fff9e1690cd2484fcb6498183Marcin Swiderski
51153de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski/// addAutomaticObjDtors - Add to current block automatic objects destructors
51253de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski/// for objects in range of local scope positions. Use S as trigger statement
51353de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski/// for destructors.
51453de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderskivoid CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
51553de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski                                      LocalScope::const_iterator E, Stmt* S) {
51653de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski  if (!BuildOpts.AddImplicitDtors)
51753de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski    return;
51853de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski
51953de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski  if (B == E)
52053de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski    return;
52153de134e7b4686eed40bc031438d8a4560a2cda4Marcin Swiderski
522fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  autoCreateBlock();
5231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  appendAutomaticObjDtors(Block, B, E, S);
524fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek}
525fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
526fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek/// addImplicitDtorsForDestructor - Add implicit destructors generated for
527fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek/// base and member objects in destructor.
528fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenekvoid CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
529fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  assert (BuildOpts.AddImplicitDtors
530fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek      && "Can be called only when dtors should be added");
531fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek  const CXXRecordDecl *RD = DD->getParent();
532fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek
533a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  // At the end destroy virtual base objects.
534a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  for (CXXRecordDecl::base_class_const_iterator VI = RD->vbases_begin(),
535a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek      VE = RD->vbases_end(); VI != VE; ++VI) {
536a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek    const CXXRecordDecl *CD = VI->getType()->getAsCXXRecordDecl();
5376c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek    if (!CD->hasTrivialDestructor()) {
5386c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek      autoCreateBlock();
5396c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek      appendBaseDtor(Block, VI);
5406c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek    }
5416c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek  }
5426c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek
5436c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek  // Before virtual bases destroy direct base objects.
5446c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek  for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
5456c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek      BE = RD->bases_end(); BI != BE; ++BI) {
5466c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek    if (!BI->isVirtual()) {
5476c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek      const CXXRecordDecl *CD = BI->getType()->getAsCXXRecordDecl();
5486c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek      if (!CD->hasTrivialDestructor()) {
5496c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek        autoCreateBlock();
5506c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek        appendBaseDtor(Block, BI);
551a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek      }
5521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    }
553b978a441c7d8bf59e7fede938e1f3b672573b443Mike Stump  }
5546c52c7850bccb6991470668429a1e1edf01b0873Ted Kremenek
5551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // First destroy member objects.
556a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
557a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek      FE = RD->field_end(); FI != FE; ++FI) {
558a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek    // Check for constant size array. Set type to array element type.
5591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    QualType QT = FI->getType();
560a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek    if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
561a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek      if (AT->getSize() == 0)
562a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek        continue;
563a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek      QT = AT->getElementType();
5641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    }
565e38158de9236dfcded7da56126134e5e3e49cb01Ted Kremenek
566e38158de9236dfcded7da56126134e5e3e49cb01Ted Kremenek    if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
567a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek      if (!CD->hasTrivialDestructor()) {
5681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        autoCreateBlock();
569a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek        appendMemberDtor(Block, *FI);
570a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek      }
571a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  }
572a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek}
573ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek
574a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
575a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek/// way return valid LocalScope object.
576a36c6540346266f570b2fc7457950dea45d89988Ted KremenekLocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
577a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  if (!Scope) {
578fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenek    Scope = cfg->getAllocator().Allocate<LocalScope>();
579ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek    new (Scope) LocalScope(ScopePos);
580ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  }
5811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  return Scope;
58219bb356317952445b03ee341c02f6147083c9eeaTed Kremenek}
58319bb356317952445b03ee341c02f6147083c9eeaTed Kremenek
58419bb356317952445b03ee341c02f6147083c9eeaTed Kremenek/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
5851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// that should create implicit scope (e.g. if/else substatements).
5861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CFGBuilder::addLocalScopeForStmt(Stmt* S) {
58719bb356317952445b03ee341c02f6147083c9eeaTed Kremenek  if (!BuildOpts.AddImplicitDtors)
58819bb356317952445b03ee341c02f6147083c9eeaTed Kremenek    return;
58919bb356317952445b03ee341c02f6147083c9eeaTed Kremenek
59019bb356317952445b03ee341c02f6147083c9eeaTed Kremenek  LocalScope *Scope = 0;
5911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
59219bb356317952445b03ee341c02f6147083c9eeaTed Kremenek  // For compound statement we will be creating explicit scope.
5937dba8607e59096014b7139ff20ef00870041d518Ted Kremenek  if (CompoundStmt* CS = dyn_cast<CompoundStmt>(S)) {
59419bb356317952445b03ee341c02f6147083c9eeaTed Kremenek    for (CompoundStmt::body_iterator BI = CS->body_begin(), BE = CS->body_end()
5957dba8607e59096014b7139ff20ef00870041d518Ted Kremenek        ; BI != BE; ++BI) {
5967dba8607e59096014b7139ff20ef00870041d518Ted Kremenek      Stmt* SI = *BI;
5977dba8607e59096014b7139ff20ef00870041d518Ted Kremenek      if (LabelStmt* LS = dyn_cast<LabelStmt>(SI))
5987dba8607e59096014b7139ff20ef00870041d518Ted Kremenek        SI = LS->getSubStmt();
5991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      if (DeclStmt* DS = dyn_cast<DeclStmt>(SI))
600a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek        Scope = addLocalScopeForDeclStmt(DS, Scope);
601a90b0d1e585d993621a342d0b2874e61941372d5Ted Kremenek    }
602a90b0d1e585d993621a342d0b2874e61941372d5Ted Kremenek    return;
6031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
604a90b0d1e585d993621a342d0b2874e61941372d5Ted Kremenek
605a90b0d1e585d993621a342d0b2874e61941372d5Ted Kremenek  // For any other statement scope will be implicit and as such will be
606a90b0d1e585d993621a342d0b2874e61941372d5Ted Kremenek  // interesting only for DeclStmt.
607ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  if (LabelStmt* LS = dyn_cast<LabelStmt>(S))
608b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    S = LS->getSubStmt();
609b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu  if (DeclStmt* DS = dyn_cast<DeclStmt>(S))
610b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu    addLocalScopeForDeclStmt(DS);
611b36cd3e1757fb4fcd9509f35558c847b04bef35fZhongxing Xu}
6121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
614a90b0d1e585d993621a342d0b2874e61941372d5Ted Kremenek/// reuse Scope if not NULL.
615a36c6540346266f570b2fc7457950dea45d89988Ted KremenekLocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt* DS,
616a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek                                                 LocalScope* Scope) {
617a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  if (!BuildOpts.AddImplicitDtors)
61863f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek    return Scope;
61963f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek
62063f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek  for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end()
62163f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek      ; DI != DE; ++DI) {
62263f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek    if (VarDecl* VD = dyn_cast<VarDecl>(*DI))
62363f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek      Scope = addLocalScopeForVarDecl(VD, Scope);
62463f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek  }
6251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  return Scope;
62686946745225096243f6969dc745267b78fc211a6Ted Kremenek}
62786946745225096243f6969dc745267b78fc211a6Ted Kremenek
62863f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
6291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// create add scope for automatic objects and temporary objects bound to
6300c8c5365be0176e8399e97d7da3293c79bc9da24Mike Stump/// const reference. Will reuse Scope if not NULL.
6310c8c5365be0176e8399e97d7da3293c79bc9da24Mike StumpLocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl* VD,
6329438252ad2ecae5338df565ca33c6969e4fbfa41Ted Kremenek                                                LocalScope* Scope) {
633a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  if (!BuildOpts.AddImplicitDtors)
634a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek    return Scope;
635a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek
636a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  // Check if variable is local.
637a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  switch (VD->getStorageClass()) {
638e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner  case SC_None:
639e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner  case SC_Auto:
640e4f2142d00fa5fdb580c4e2413da91882d955381Chris Lattner  case SC_Register:
641a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek    break;
642a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  default: return Scope;
643a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  }
644a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek
645a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  // Check for const references bound to temporary. Set type to pointee.
6461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  QualType QT = VD->getType();
6477177dee8aee4b432911c91f1b788963bec0cac9fDaniel Dunbar  if (const ReferenceType* RT = QT.getTypePtr()->getAs<ReferenceType>()) {
6481eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    QT = RT->getPointeeType();
64963f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek    if (!QT.isConstQualified())
6501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      return Scope;
651ce1eb34bbea1e0408f1952776d7d52ccde1bd275Ted Kremenek    if (!VD->getInit() || !VD->getInit()->Classify(*Context).isRValue())
652ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek      return Scope;
653ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  }
654ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek
655ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  // Check for constant size array. Set type to array element type.
656ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
657ce1eb34bbea1e0408f1952776d7d52ccde1bd275Ted Kremenek    if (AT->getSize() == 0)
6581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      return Scope;
659a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek    QT = AT->getElementType();
660a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  }
661a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek
662a36c6540346266f570b2fc7457950dea45d89988Ted Kremenek  // Check if type is a C++ class with non-trivial destructor.
663ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  if (const CXXRecordDecl* CD = QT->getAsCXXRecordDecl())
66463f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek    if (!CD->hasTrivialDestructor()) {
6651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      // Add the variable to scope
66686d1777a6b7723865c1e67a7aafc797ec0a574ffTed Kremenek      Scope = createOrReuseLocalScope(Scope);
6671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      Scope->addVar(VD);
66886d1777a6b7723865c1e67a7aafc797ec0a574ffTed Kremenek      ScopePos = Scope->begin();
66963f5887f316fb52d243fcbb3631c039de6c4b993Ted Kremenek    }
670ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek  return Scope;
671ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek}
672ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek
673ee82d9bdc5025b82de8ce2a4ad4685e0a8b79da9Ted Kremenek/// addLocalScopeAndDtors - For given statement add local scope for it and
6741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
675fddd51853f8ccaa1df2476376e6fd74d2f315c73Ted Kremenekvoid CFGBuilder::addLocalScopeAndDtors(Stmt* S) {
676fa2be43dbd6fdc4414e261db69aaf35dfb21a416Ted Kremenek  if (!BuildOpts.AddImplicitDtors)
6777dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    return;
6787dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
6797dba8607e59096014b7139ff20ef00870041d518Ted Kremenek  LocalScope::const_iterator scopeBeginPos = ScopePos;
6807dba8607e59096014b7139ff20ef00870041d518Ted Kremenek  addLocalScopeForStmt(S);
6817dba8607e59096014b7139ff20ef00870041d518Ted Kremenek  addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
6827dba8607e59096014b7139ff20ef00870041d518Ted Kremenek}
6837dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
6844ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski/// insertAutomaticObjDtors - Insert destructor CFGElements for variables with
6854ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski/// automatic storage duration to CFGBlock's elements vector. Insertion will be
6864ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski/// performed in place specified with iterator.
6874ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderskivoid CFGBuilder::insertAutomaticObjDtors(CFGBlock* Blk, CFGBlock::iterator I,
6884ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski    LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S) {
6894ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  BumpVectorContext& C = cfg->getBumpVectorContext();
6904ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  I = Blk->beginAutomaticObjDtorsInsert(I, B.distance(E), C);
6914ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski  while (B != E)
6924ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski    I = Blk->insertAutomaticObjDtor(I, *B++, S);
6934ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski}
6944ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski
6954ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski/// appendAutomaticObjDtors - Append destructor CFGElements for variables with
6964ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski/// automatic storage duration to CFGBlock's elements vector. Elements will be
6974ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski/// appended to physical end of the vector which happens to be logical
6984ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderski/// beginning.
6994ba72a0b28135209c435630682febe1f854ccfa6Marcin Swiderskivoid CFGBuilder::appendAutomaticObjDtors(CFGBlock* Blk,
7007dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S) {
7017dba8607e59096014b7139ff20ef00870041d518Ted Kremenek  insertAutomaticObjDtors(Blk, Blk->begin(), B, E, S);
702852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek}
703852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
704852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
7051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// variables with automatic storage duration to CFGBlock's elements vector.
706852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek/// Elements will be prepended to physical beginning of the vector which
7077dba8607e59096014b7139ff20ef00870041d518Ted Kremenek/// happens to be logical end. Use blocks terminator as statement that specifies
7087dba8607e59096014b7139ff20ef00870041d518Ted Kremenek/// destructors call site.
7097dba8607e59096014b7139ff20ef00870041d518Ted Kremenekvoid CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock* Blk,
7107dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    LocalScope::const_iterator B, LocalScope::const_iterator E) {
7111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  insertAutomaticObjDtors(Blk, Blk->end(), B, E, Blk->getTerminator());
7127dba8607e59096014b7139ff20ef00870041d518Ted Kremenek}
7137dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
7147dba8607e59096014b7139ff20ef00870041d518Ted Kremenek/// Visit - Walk the subtree of a statement and add extra
7157dba8607e59096014b7139ff20ef00870041d518Ted Kremenek///   blocks for ternary operators, &&, and ||.  We also process "," and
716852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek///   DeclStmts (which may contain nested control-flow).
717852274d4257134906995cb252fb3dfd2d71deae8Ted KremenekCFGBlock* CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
718852274d4257134906995cb252fb3dfd2d71deae8Ted KremenektryAgain:
7191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (!S) {
7207dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    badCFG = true;
7217dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    return 0;
7221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
7237dba8607e59096014b7139ff20ef00870041d518Ted Kremenek  switch (S->getStmtClass()) {
7247dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    default:
7251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      return VisitStmt(S, asc);
7267dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
7277dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    case Stmt::AddrLabelExprClass:
7287dba8607e59096014b7139ff20ef00870041d518Ted Kremenek      return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
7297dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
730852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek    case Stmt::BinaryOperatorClass:
731852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
732852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
7337dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    case Stmt::BlockExprClass:
734852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      return VisitBlockExpr(cast<BlockExpr>(S), asc);
7357dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
7367dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    case Stmt::BreakStmtClass:
7377dba8607e59096014b7139ff20ef00870041d518Ted Kremenek      return VisitBreakStmt(cast<BreakStmt>(S));
7387dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
7391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    case Stmt::CallExprClass:
7407dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    case Stmt::CXXOperatorCallExprClass:
7417dba8607e59096014b7139ff20ef00870041d518Ted Kremenek      return VisitCallExpr(cast<CallExpr>(S), asc);
7427dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
7437dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    case Stmt::CaseStmtClass:
7447dba8607e59096014b7139ff20ef00870041d518Ted Kremenek      return VisitCaseStmt(cast<CaseStmt>(S));
7457dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
746852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek    case Stmt::ChooseExprClass:
747852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      return VisitChooseExpr(cast<ChooseExpr>(S), asc);
7487dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
749852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek    case Stmt::CompoundStmtClass:
7501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      return VisitCompoundStmt(cast<CompoundStmt>(S));
751852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
752852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek    case Stmt::ConditionalOperatorClass:
753852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
7547dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
7557dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    case Stmt::ContinueStmtClass:
756852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      return VisitContinueStmt(cast<ContinueStmt>(S));
757852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
7587dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    case Stmt::CXXCatchStmtClass:
759852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
7607dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
761852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek    case Stmt::CXXExprWithTemporariesClass: {
762852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      // FIXME: Handle temporaries.  For now, just visit the subexpression
763852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      // so we don't artificially create extra blocks.
764852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      return Visit(cast<CXXExprWithTemporaries>(S)->getSubExpr(), asc);
765852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek    }
766852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
767852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek    case Stmt::CXXConstructExprClass:
768852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
769852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
7707dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    case Stmt::CXXTemporaryObjectExprClass:
7717dba8607e59096014b7139ff20ef00870041d518Ted Kremenek      return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
772852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
773852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek    case Stmt::CXXMemberCallExprClass:
7747dba8607e59096014b7139ff20ef00870041d518Ted Kremenek      return VisitCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), asc);
775852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
7767dba8607e59096014b7139ff20ef00870041d518Ted Kremenek    case Stmt::CXXThrowExprClass:
777852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek      return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
778852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek
779852274d4257134906995cb252fb3dfd2d71deae8Ted Kremenek    case Stmt::CXXTryStmtClass:
7807dba8607e59096014b7139ff20ef00870041d518Ted Kremenek      return VisitCXXTryStmt(cast<CXXTryStmt>(S));
7817dba8607e59096014b7139ff20ef00870041d518Ted Kremenek
782cd881d534517f09a2fae10445f9b865f49ccc6c8Ted Kremenek    case Stmt::DeclStmtClass:
783      return VisitDeclStmt(cast<DeclStmt>(S));
784
785    case Stmt::DefaultStmtClass:
786      return VisitDefaultStmt(cast<DefaultStmt>(S));
787
788    case Stmt::DoStmtClass:
789      return VisitDoStmt(cast<DoStmt>(S));
790
791    case Stmt::ForStmtClass:
792      return VisitForStmt(cast<ForStmt>(S));
793
794    case Stmt::GotoStmtClass:
795      return VisitGotoStmt(cast<GotoStmt>(S));
796
797    case Stmt::IfStmtClass:
798      return VisitIfStmt(cast<IfStmt>(S));
799
800    case Stmt::IndirectGotoStmtClass:
801      return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
802
803    case Stmt::LabelStmtClass:
804      return VisitLabelStmt(cast<LabelStmt>(S));
805
806    case Stmt::MemberExprClass:
807      return VisitMemberExpr(cast<MemberExpr>(S), asc);
808
809    case Stmt::ObjCAtCatchStmtClass:
810      return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
811
812    case Stmt::ObjCAtSynchronizedStmtClass:
813      return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
814
815    case Stmt::ObjCAtThrowStmtClass:
816      return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
817
818    case Stmt::ObjCAtTryStmtClass:
819      return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
820
821    case Stmt::ObjCForCollectionStmtClass:
822      return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
823
824    case Stmt::ParenExprClass:
825      S = cast<ParenExpr>(S)->getSubExpr();
826      goto tryAgain;
827
828    case Stmt::NullStmtClass:
829      return Block;
830
831    case Stmt::ReturnStmtClass:
832      return VisitReturnStmt(cast<ReturnStmt>(S));
833
834    case Stmt::SizeOfAlignOfExprClass:
835      return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), asc);
836
837    case Stmt::StmtExprClass:
838      return VisitStmtExpr(cast<StmtExpr>(S), asc);
839
840    case Stmt::SwitchStmtClass:
841      return VisitSwitchStmt(cast<SwitchStmt>(S));
842
843    case Stmt::WhileStmtClass:
844      return VisitWhileStmt(cast<WhileStmt>(S));
845  }
846}
847
848CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
849  if (asc.alwaysAdd()) {
850    autoCreateBlock();
851    AppendStmt(Block, S, asc);
852  }
853
854  return VisitChildren(S);
855}
856
857/// VisitChildren - Visit the children of a Stmt.
858CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) {
859  CFGBlock *B = Block;
860  for (Stmt::child_iterator I = Terminator->child_begin(),
861         E = Terminator->child_end(); I != E; ++I) {
862    if (*I) B = Visit(*I);
863  }
864  return B;
865}
866
867CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
868                                         AddStmtChoice asc) {
869  AddressTakenLabels.insert(A->getLabel());
870
871  if (asc.alwaysAdd()) {
872    autoCreateBlock();
873    AppendStmt(Block, A, asc);
874  }
875
876  return Block;
877}
878
879CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
880                                          AddStmtChoice asc) {
881  if (B->isLogicalOp()) { // && or ||
882    CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
883    AppendStmt(ConfluenceBlock, B, asc);
884
885    if (badCFG)
886      return 0;
887
888    // create the block evaluating the LHS
889    CFGBlock* LHSBlock = createBlock(false);
890    LHSBlock->setTerminator(B);
891
892    // create the block evaluating the RHS
893    Succ = ConfluenceBlock;
894    Block = NULL;
895    CFGBlock* RHSBlock = addStmt(B->getRHS());
896
897    if (RHSBlock) {
898      if (badCFG)
899        return 0;
900    }
901    else {
902      // Create an empty block for cases where the RHS doesn't require
903      // any explicit statements in the CFG.
904      RHSBlock = createBlock();
905    }
906
907    // See if this is a known constant.
908    TryResult KnownVal = TryEvaluateBool(B->getLHS());
909    if (KnownVal.isKnown() && (B->getOpcode() == BO_LOr))
910      KnownVal.negate();
911
912    // Now link the LHSBlock with RHSBlock.
913    if (B->getOpcode() == BO_LOr) {
914      AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
915      AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
916    } else {
917      assert(B->getOpcode() == BO_LAnd);
918      AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
919      AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
920    }
921
922    // Generate the blocks for evaluating the LHS.
923    Block = LHSBlock;
924    return addStmt(B->getLHS());
925  }
926  else if (B->getOpcode() == BO_Comma) { // ,
927    autoCreateBlock();
928    AppendStmt(Block, B, asc);
929    addStmt(B->getRHS());
930    return addStmt(B->getLHS());
931  }
932  else if (B->isAssignmentOp()) {
933    if (asc.alwaysAdd()) {
934      autoCreateBlock();
935      AppendStmt(Block, B, asc);
936    }
937
938    Visit(B->getLHS(), AddStmtChoice::AsLValueNotAlwaysAdd);
939    return Visit(B->getRHS());
940  }
941
942  if (asc.alwaysAdd()) {
943    autoCreateBlock();
944    AppendStmt(Block, B, asc);
945  }
946
947  CFGBlock *RBlock = Visit(B->getRHS());
948  CFGBlock *LBlock = Visit(B->getLHS());
949  // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
950  // containing a DoStmt, and the LHS doesn't create a new block, then we should
951  // return RBlock.  Otherwise we'll incorrectly return NULL.
952  return (LBlock ? LBlock : RBlock);
953}
954
955CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
956  if (asc.alwaysAdd()) {
957    autoCreateBlock();
958    AppendStmt(Block, E, asc);
959  }
960  return Block;
961}
962
963CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
964  // "break" is a control-flow statement.  Thus we stop processing the current
965  // block.
966  if (badCFG)
967    return 0;
968
969  // Now create a new block that ends with the break statement.
970  Block = createBlock(false);
971  Block->setTerminator(B);
972
973  // If there is no target for the break, then we are looking at an incomplete
974  // AST.  This means that the CFG cannot be constructed.
975  if (BreakJumpTarget.Block) {
976    addAutomaticObjDtors(ScopePos, BreakJumpTarget.ScopePos, B);
977    AddSuccessor(Block, BreakJumpTarget.Block);
978  } else
979    badCFG = true;
980
981
982  return Block;
983}
984
985static bool CanThrow(Expr *E) {
986  QualType Ty = E->getType();
987  if (Ty->isFunctionPointerType())
988    Ty = Ty->getAs<PointerType>()->getPointeeType();
989  else if (Ty->isBlockPointerType())
990    Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
991
992  const FunctionType *FT = Ty->getAs<FunctionType>();
993  if (FT) {
994    if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
995      if (Proto->hasEmptyExceptionSpec())
996        return false;
997  }
998  return true;
999}
1000
1001CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
1002  // If this is a call to a no-return function, this stops the block here.
1003  bool NoReturn = false;
1004  if (getFunctionExtInfo(*C->getCallee()->getType()).getNoReturn()) {
1005    NoReturn = true;
1006  }
1007
1008  bool AddEHEdge = false;
1009
1010  // Languages without exceptions are assumed to not throw.
1011  if (Context->getLangOptions().Exceptions) {
1012    if (BuildOpts.AddEHEdges)
1013      AddEHEdge = true;
1014  }
1015
1016  if (FunctionDecl *FD = C->getDirectCallee()) {
1017    if (FD->hasAttr<NoReturnAttr>())
1018      NoReturn = true;
1019    if (FD->hasAttr<NoThrowAttr>())
1020      AddEHEdge = false;
1021  }
1022
1023  if (!CanThrow(C->getCallee()))
1024    AddEHEdge = false;
1025
1026  if (!NoReturn && !AddEHEdge) {
1027    if (asc.asLValue())
1028      return VisitStmt(C, AddStmtChoice::AlwaysAddAsLValue);
1029    else
1030      return VisitStmt(C, AddStmtChoice::AlwaysAdd);
1031  }
1032
1033  if (Block) {
1034    Succ = Block;
1035    if (badCFG)
1036      return 0;
1037  }
1038
1039  Block = createBlock(!NoReturn);
1040  AppendStmt(Block, C, asc);
1041
1042  if (NoReturn) {
1043    // Wire this to the exit block directly.
1044    AddSuccessor(Block, &cfg->getExit());
1045  }
1046  if (AddEHEdge) {
1047    // Add exceptional edges.
1048    if (TryTerminatedBlock)
1049      AddSuccessor(Block, TryTerminatedBlock);
1050    else
1051      AddSuccessor(Block, &cfg->getExit());
1052  }
1053
1054  return VisitChildren(C);
1055}
1056
1057CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1058                                      AddStmtChoice asc) {
1059  CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
1060  AppendStmt(ConfluenceBlock, C, asc);
1061  if (badCFG)
1062    return 0;
1063
1064  asc = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
1065                       : AddStmtChoice::AlwaysAdd;
1066
1067  Succ = ConfluenceBlock;
1068  Block = NULL;
1069  CFGBlock* LHSBlock = Visit(C->getLHS(), asc);
1070  if (badCFG)
1071    return 0;
1072
1073  Succ = ConfluenceBlock;
1074  Block = NULL;
1075  CFGBlock* RHSBlock = Visit(C->getRHS(), asc);
1076  if (badCFG)
1077    return 0;
1078
1079  Block = createBlock(false);
1080  // See if this is a known constant.
1081  const TryResult& KnownVal = TryEvaluateBool(C->getCond());
1082  AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1083  AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1084  Block->setTerminator(C);
1085  return addStmt(C->getCond());
1086}
1087
1088
1089CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
1090  addLocalScopeAndDtors(C);
1091  CFGBlock* LastBlock = Block;
1092
1093  for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1094       I != E; ++I ) {
1095    // If we hit a segment of code just containing ';' (NullStmts), we can
1096    // get a null block back.  In such cases, just use the LastBlock
1097    if (CFGBlock *newBlock = addStmt(*I))
1098      LastBlock = newBlock;
1099
1100    if (badCFG)
1101      return NULL;
1102  }
1103
1104  return LastBlock;
1105}
1106
1107CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C,
1108                                               AddStmtChoice asc) {
1109  // Create the confluence block that will "merge" the results of the ternary
1110  // expression.
1111  CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
1112  AppendStmt(ConfluenceBlock, C, asc);
1113  if (badCFG)
1114    return 0;
1115
1116  asc = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
1117                       : AddStmtChoice::AlwaysAdd;
1118
1119  // Create a block for the LHS expression if there is an LHS expression.  A
1120  // GCC extension allows LHS to be NULL, causing the condition to be the
1121  // value that is returned instead.
1122  //  e.g: x ?: y is shorthand for: x ? x : y;
1123  Succ = ConfluenceBlock;
1124  Block = NULL;
1125  CFGBlock* LHSBlock = NULL;
1126  if (C->getLHS()) {
1127    LHSBlock = Visit(C->getLHS(), asc);
1128    if (badCFG)
1129      return 0;
1130    Block = NULL;
1131  }
1132
1133  // Create the block for the RHS expression.
1134  Succ = ConfluenceBlock;
1135  CFGBlock* RHSBlock = Visit(C->getRHS(), asc);
1136  if (badCFG)
1137    return 0;
1138
1139  // Create the block that will contain the condition.
1140  Block = createBlock(false);
1141
1142  // See if this is a known constant.
1143  const TryResult& KnownVal = TryEvaluateBool(C->getCond());
1144  if (LHSBlock) {
1145    AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1146  } else {
1147    if (KnownVal.isFalse()) {
1148      // If we know the condition is false, add NULL as the successor for
1149      // the block containing the condition.  In this case, the confluence
1150      // block will have just one predecessor.
1151      AddSuccessor(Block, 0);
1152      assert(ConfluenceBlock->pred_size() == 1);
1153    } else {
1154      // If we have no LHS expression, add the ConfluenceBlock as a direct
1155      // successor for the block containing the condition.  Moreover, we need to
1156      // reverse the order of the predecessors in the ConfluenceBlock because
1157      // the RHSBlock will have been added to the succcessors already, and we
1158      // want the first predecessor to the the block containing the expression
1159      // for the case when the ternary expression evaluates to true.
1160      AddSuccessor(Block, ConfluenceBlock);
1161      assert(ConfluenceBlock->pred_size() == 2);
1162      std::reverse(ConfluenceBlock->pred_begin(),
1163                   ConfluenceBlock->pred_end());
1164    }
1165  }
1166
1167  AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1168  Block->setTerminator(C);
1169  return addStmt(C->getCond());
1170}
1171
1172CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
1173  autoCreateBlock();
1174
1175  if (DS->isSingleDecl()) {
1176    AppendStmt(Block, DS);
1177    return VisitDeclSubExpr(DS->getSingleDecl());
1178  }
1179
1180  CFGBlock *B = 0;
1181
1182  // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy.
1183  typedef llvm::SmallVector<Decl*,10> BufTy;
1184  BufTy Buf(DS->decl_begin(), DS->decl_end());
1185
1186  for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) {
1187    // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
1188    unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
1189               ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
1190
1191    // Allocate the DeclStmt using the BumpPtrAllocator.  It will get
1192    // automatically freed with the CFG.
1193    DeclGroupRef DG(*I);
1194    Decl *D = *I;
1195    void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
1196    DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
1197
1198    // Append the fake DeclStmt to block.
1199    AppendStmt(Block, DSNew);
1200    B = VisitDeclSubExpr(D);
1201  }
1202
1203  return B;
1204}
1205
1206/// VisitDeclSubExpr - Utility method to add block-level expressions for
1207///  initializers in Decls.
1208CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) {
1209  assert(Block);
1210
1211  VarDecl *VD = dyn_cast<VarDecl>(D);
1212
1213  if (!VD)
1214    return Block;
1215
1216  Expr *Init = VD->getInit();
1217
1218  if (Init) {
1219    AddStmtChoice::Kind k =
1220      VD->getType()->isReferenceType() ? AddStmtChoice::AsLValueNotAlwaysAdd
1221                                       : AddStmtChoice::NotAlwaysAdd;
1222    Visit(Init, AddStmtChoice(k));
1223  }
1224
1225  // If the type of VD is a VLA, then we must process its size expressions.
1226  for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
1227       VA = FindVA(VA->getElementType().getTypePtr()))
1228    Block = addStmt(VA->getSizeExpr());
1229
1230  // Remove variable from local scope.
1231  if (ScopePos && VD == *ScopePos)
1232    ++ScopePos;
1233
1234  return Block;
1235}
1236
1237CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
1238  // We may see an if statement in the middle of a basic block, or it may be the
1239  // first statement we are processing.  In either case, we create a new basic
1240  // block.  First, we create the blocks for the then...else statements, and
1241  // then we create the block containing the if statement.  If we were in the
1242  // middle of a block, we stop processing that block.  That block is then the
1243  // implicit successor for the "then" and "else" clauses.
1244
1245  // Save local scope position because in case of condition variable ScopePos
1246  // won't be restored when traversing AST.
1247  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1248
1249  // Create local scope for possible condition variable.
1250  // Store scope position. Add implicit destructor.
1251  if (VarDecl* VD = I->getConditionVariable()) {
1252    LocalScope::const_iterator BeginScopePos = ScopePos;
1253    addLocalScopeForVarDecl(VD);
1254    addAutomaticObjDtors(ScopePos, BeginScopePos, I);
1255  }
1256
1257  // The block we were proccessing is now finished.  Make it the successor
1258  // block.
1259  if (Block) {
1260    Succ = Block;
1261    if (badCFG)
1262      return 0;
1263  }
1264
1265  // Process the false branch.
1266  CFGBlock* ElseBlock = Succ;
1267
1268  if (Stmt* Else = I->getElse()) {
1269    SaveAndRestore<CFGBlock*> sv(Succ);
1270
1271    // NULL out Block so that the recursive call to Visit will
1272    // create a new basic block.
1273    Block = NULL;
1274
1275    // If branch is not a compound statement create implicit scope
1276    // and add destructors.
1277    if (!isa<CompoundStmt>(Else))
1278      addLocalScopeAndDtors(Else);
1279
1280    ElseBlock = addStmt(Else);
1281
1282    if (!ElseBlock) // Can occur when the Else body has all NullStmts.
1283      ElseBlock = sv.get();
1284    else if (Block) {
1285      if (badCFG)
1286        return 0;
1287    }
1288  }
1289
1290  // Process the true branch.
1291  CFGBlock* ThenBlock;
1292  {
1293    Stmt* Then = I->getThen();
1294    assert(Then);
1295    SaveAndRestore<CFGBlock*> sv(Succ);
1296    Block = NULL;
1297
1298    // If branch is not a compound statement create implicit scope
1299    // and add destructors.
1300    if (!isa<CompoundStmt>(Then))
1301      addLocalScopeAndDtors(Then);
1302
1303    ThenBlock = addStmt(Then);
1304
1305    if (!ThenBlock) {
1306      // We can reach here if the "then" body has all NullStmts.
1307      // Create an empty block so we can distinguish between true and false
1308      // branches in path-sensitive analyses.
1309      ThenBlock = createBlock(false);
1310      AddSuccessor(ThenBlock, sv.get());
1311    } else if (Block) {
1312      if (badCFG)
1313        return 0;
1314    }
1315  }
1316
1317  // Now create a new block containing the if statement.
1318  Block = createBlock(false);
1319
1320  // Set the terminator of the new block to the If statement.
1321  Block->setTerminator(I);
1322
1323  // See if this is a known constant.
1324  const TryResult &KnownVal = TryEvaluateBool(I->getCond());
1325
1326  // Now add the successors.
1327  AddSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
1328  AddSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
1329
1330  // Add the condition as the last statement in the new block.  This may create
1331  // new blocks as the condition may contain control-flow.  Any newly created
1332  // blocks will be pointed to be "Block".
1333  Block = addStmt(I->getCond());
1334
1335  // Finally, if the IfStmt contains a condition variable, add both the IfStmt
1336  // and the condition variable initialization to the CFG.
1337  if (VarDecl *VD = I->getConditionVariable()) {
1338    if (Expr *Init = VD->getInit()) {
1339      autoCreateBlock();
1340      AppendStmt(Block, I, AddStmtChoice::AlwaysAdd);
1341      addStmt(Init);
1342    }
1343  }
1344
1345  return Block;
1346}
1347
1348
1349CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
1350  // If we were in the middle of a block we stop processing that block.
1351  //
1352  // NOTE: If a "return" appears in the middle of a block, this means that the
1353  //       code afterwards is DEAD (unreachable).  We still keep a basic block
1354  //       for that code; a simple "mark-and-sweep" from the entry block will be
1355  //       able to report such dead blocks.
1356
1357  // Create the new block.
1358  Block = createBlock(false);
1359
1360  // The Exit block is the only successor.
1361  addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
1362  AddSuccessor(Block, &cfg->getExit());
1363
1364  // Add the return statement to the block.  This may create new blocks if R
1365  // contains control-flow (short-circuit operations).
1366  return VisitStmt(R, AddStmtChoice::AlwaysAdd);
1367}
1368
1369CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
1370  // Get the block of the labeled statement.  Add it to our map.
1371  addStmt(L->getSubStmt());
1372  CFGBlock* LabelBlock = Block;
1373
1374  if (!LabelBlock)              // This can happen when the body is empty, i.e.
1375    LabelBlock = createBlock(); // scopes that only contains NullStmts.
1376
1377  assert(LabelMap.find(L) == LabelMap.end() && "label already in map");
1378  LabelMap[ L ] = JumpTarget(LabelBlock, ScopePos);
1379
1380  // Labels partition blocks, so this is the end of the basic block we were
1381  // processing (L is the block's label).  Because this is label (and we have
1382  // already processed the substatement) there is no extra control-flow to worry
1383  // about.
1384  LabelBlock->setLabel(L);
1385  if (badCFG)
1386    return 0;
1387
1388  // We set Block to NULL to allow lazy creation of a new block (if necessary);
1389  Block = NULL;
1390
1391  // This block is now the implicit successor of other blocks.
1392  Succ = LabelBlock;
1393
1394  return LabelBlock;
1395}
1396
1397CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
1398  // Goto is a control-flow statement.  Thus we stop processing the current
1399  // block and create a new one.
1400
1401  Block = createBlock(false);
1402  Block->setTerminator(G);
1403
1404  // If we already know the mapping to the label block add the successor now.
1405  LabelMapTy::iterator I = LabelMap.find(G->getLabel());
1406
1407  if (I == LabelMap.end())
1408    // We will need to backpatch this block later.
1409    BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
1410  else {
1411    JumpTarget JT = I->second;
1412    addAutomaticObjDtors(ScopePos, JT.ScopePos, G);
1413    AddSuccessor(Block, JT.Block);
1414  }
1415
1416  return Block;
1417}
1418
1419CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
1420  CFGBlock* LoopSuccessor = NULL;
1421
1422  // Save local scope position because in case of condition variable ScopePos
1423  // won't be restored when traversing AST.
1424  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1425
1426  // Create local scope for init statement and possible condition variable.
1427  // Add destructor for init statement and condition variable.
1428  // Store scope position for continue statement.
1429  if (Stmt* Init = F->getInit())
1430    addLocalScopeForStmt(Init);
1431  LocalScope::const_iterator LoopBeginScopePos = ScopePos;
1432
1433  if (VarDecl* VD = F->getConditionVariable())
1434    addLocalScopeForVarDecl(VD);
1435  LocalScope::const_iterator ContinueScopePos = ScopePos;
1436
1437  addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
1438
1439  // "for" is a control-flow statement.  Thus we stop processing the current
1440  // block.
1441  if (Block) {
1442    if (badCFG)
1443      return 0;
1444    LoopSuccessor = Block;
1445  } else
1446    LoopSuccessor = Succ;
1447
1448  // Save the current value for the break targets.
1449  // All breaks should go to the code following the loop.
1450  SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
1451  BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1452
1453  // Because of short-circuit evaluation, the condition of the loop can span
1454  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1455  // evaluate the condition.
1456  CFGBlock* ExitConditionBlock = createBlock(false);
1457  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1458
1459  // Set the terminator for the "exit" condition block.
1460  ExitConditionBlock->setTerminator(F);
1461
1462  // Now add the actual condition to the condition block.  Because the condition
1463  // itself may contain control-flow, new blocks may be created.
1464  if (Stmt* C = F->getCond()) {
1465    Block = ExitConditionBlock;
1466    EntryConditionBlock = addStmt(C);
1467    assert(Block == EntryConditionBlock ||
1468           (Block == 0 && EntryConditionBlock == Succ));
1469
1470    // If this block contains a condition variable, add both the condition
1471    // variable and initializer to the CFG.
1472    if (VarDecl *VD = F->getConditionVariable()) {
1473      if (Expr *Init = VD->getInit()) {
1474        autoCreateBlock();
1475        AppendStmt(Block, F, AddStmtChoice::AlwaysAdd);
1476        EntryConditionBlock = addStmt(Init);
1477        assert(Block == EntryConditionBlock);
1478      }
1479    }
1480
1481    if (Block) {
1482      if (badCFG)
1483        return 0;
1484    }
1485  }
1486
1487  // The condition block is the implicit successor for the loop body as well as
1488  // any code above the loop.
1489  Succ = EntryConditionBlock;
1490
1491  // See if this is a known constant.
1492  TryResult KnownVal(true);
1493
1494  if (F->getCond())
1495    KnownVal = TryEvaluateBool(F->getCond());
1496
1497  // Now create the loop body.
1498  {
1499    assert(F->getBody());
1500
1501   // Save the current values for Block, Succ, and continue targets.
1502   SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
1503   SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
1504
1505    // Create a new block to contain the (bottom) of the loop body.
1506    Block = NULL;
1507
1508    // Loop body should end with destructor of Condition variable (if any).
1509    addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
1510
1511    if (Stmt* I = F->getInc()) {
1512      // Generate increment code in its own basic block.  This is the target of
1513      // continue statements.
1514      Succ = addStmt(I);
1515    } else {
1516      // No increment code.  Create a special, empty, block that is used as the
1517      // target block for "looping back" to the start of the loop.
1518      assert(Succ == EntryConditionBlock);
1519      Succ = Block ? Block : createBlock();
1520    }
1521
1522    // Finish up the increment (or empty) block if it hasn't been already.
1523    if (Block) {
1524      assert(Block == Succ);
1525      if (badCFG)
1526        return 0;
1527      Block = 0;
1528    }
1529
1530    ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
1531
1532    // The starting block for the loop increment is the block that should
1533    // represent the 'loop target' for looping back to the start of the loop.
1534    ContinueJumpTarget.Block->setLoopTarget(F);
1535
1536    // If body is not a compound statement create implicit scope
1537    // and add destructors.
1538    if (!isa<CompoundStmt>(F->getBody()))
1539      addLocalScopeAndDtors(F->getBody());
1540
1541    // Now populate the body block, and in the process create new blocks as we
1542    // walk the body of the loop.
1543    CFGBlock* BodyBlock = addStmt(F->getBody());
1544
1545    if (!BodyBlock)
1546      BodyBlock = ContinueJumpTarget.Block;//can happen for "for (...;...;...);"
1547    else if (badCFG)
1548      return 0;
1549
1550    // This new body block is a successor to our "exit" condition block.
1551    AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1552  }
1553
1554  // Link up the condition block with the code that follows the loop.  (the
1555  // false branch).
1556  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1557
1558  // If the loop contains initialization, create a new block for those
1559  // statements.  This block can also contain statements that precede the loop.
1560  if (Stmt* I = F->getInit()) {
1561    Block = createBlock();
1562    return addStmt(I);
1563  } else {
1564    // There is no loop initialization.  We are thus basically a while loop.
1565    // NULL out Block to force lazy block construction.
1566    Block = NULL;
1567    Succ = EntryConditionBlock;
1568    return EntryConditionBlock;
1569  }
1570}
1571
1572CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
1573  if (asc.alwaysAdd()) {
1574    autoCreateBlock();
1575    AppendStmt(Block, M, asc);
1576  }
1577  return Visit(M->getBase(),
1578               M->isArrow() ? AddStmtChoice::NotAlwaysAdd
1579                            : AddStmtChoice::AsLValueNotAlwaysAdd);
1580}
1581
1582CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
1583  // Objective-C fast enumeration 'for' statements:
1584  //  http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
1585  //
1586  //  for ( Type newVariable in collection_expression ) { statements }
1587  //
1588  //  becomes:
1589  //
1590  //   prologue:
1591  //     1. collection_expression
1592  //     T. jump to loop_entry
1593  //   loop_entry:
1594  //     1. side-effects of element expression
1595  //     1. ObjCForCollectionStmt [performs binding to newVariable]
1596  //     T. ObjCForCollectionStmt  TB, FB  [jumps to TB if newVariable != nil]
1597  //   TB:
1598  //     statements
1599  //     T. jump to loop_entry
1600  //   FB:
1601  //     what comes after
1602  //
1603  //  and
1604  //
1605  //  Type existingItem;
1606  //  for ( existingItem in expression ) { statements }
1607  //
1608  //  becomes:
1609  //
1610  //   the same with newVariable replaced with existingItem; the binding works
1611  //   the same except that for one ObjCForCollectionStmt::getElement() returns
1612  //   a DeclStmt and the other returns a DeclRefExpr.
1613  //
1614
1615  CFGBlock* LoopSuccessor = 0;
1616
1617  if (Block) {
1618    if (badCFG)
1619      return 0;
1620    LoopSuccessor = Block;
1621    Block = 0;
1622  } else
1623    LoopSuccessor = Succ;
1624
1625  // Build the condition blocks.
1626  CFGBlock* ExitConditionBlock = createBlock(false);
1627  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1628
1629  // Set the terminator for the "exit" condition block.
1630  ExitConditionBlock->setTerminator(S);
1631
1632  // The last statement in the block should be the ObjCForCollectionStmt, which
1633  // performs the actual binding to 'element' and determines if there are any
1634  // more items in the collection.
1635  AppendStmt(ExitConditionBlock, S);
1636  Block = ExitConditionBlock;
1637
1638  // Walk the 'element' expression to see if there are any side-effects.  We
1639  // generate new blocks as necesary.  We DON'T add the statement by default to
1640  // the CFG unless it contains control-flow.
1641  EntryConditionBlock = Visit(S->getElement(), AddStmtChoice::NotAlwaysAdd);
1642  if (Block) {
1643    if (badCFG)
1644      return 0;
1645    Block = 0;
1646  }
1647
1648  // The condition block is the implicit successor for the loop body as well as
1649  // any code above the loop.
1650  Succ = EntryConditionBlock;
1651
1652  // Now create the true branch.
1653  {
1654    // Save the current values for Succ, continue and break targets.
1655    SaveAndRestore<CFGBlock*> save_Succ(Succ);
1656    SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
1657        save_break(BreakJumpTarget);
1658
1659    BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1660    ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
1661
1662    CFGBlock* BodyBlock = addStmt(S->getBody());
1663
1664    if (!BodyBlock)
1665      BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
1666    else if (Block) {
1667      if (badCFG)
1668        return 0;
1669    }
1670
1671    // This new body block is a successor to our "exit" condition block.
1672    AddSuccessor(ExitConditionBlock, BodyBlock);
1673  }
1674
1675  // Link up the condition block with the code that follows the loop.
1676  // (the false branch).
1677  AddSuccessor(ExitConditionBlock, LoopSuccessor);
1678
1679  // Now create a prologue block to contain the collection expression.
1680  Block = createBlock();
1681  return addStmt(S->getCollection());
1682}
1683
1684CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
1685  // FIXME: Add locking 'primitives' to CFG for @synchronized.
1686
1687  // Inline the body.
1688  CFGBlock *SyncBlock = addStmt(S->getSynchBody());
1689
1690  // The sync body starts its own basic block.  This makes it a little easier
1691  // for diagnostic clients.
1692  if (SyncBlock) {
1693    if (badCFG)
1694      return 0;
1695
1696    Block = 0;
1697    Succ = SyncBlock;
1698  }
1699
1700  // Add the @synchronized to the CFG.
1701  autoCreateBlock();
1702  AppendStmt(Block, S, AddStmtChoice::AlwaysAdd);
1703
1704  // Inline the sync expression.
1705  return addStmt(S->getSynchExpr());
1706}
1707
1708CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
1709  // FIXME
1710  return NYS();
1711}
1712
1713CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
1714  CFGBlock* LoopSuccessor = NULL;
1715
1716  // Save local scope position because in case of condition variable ScopePos
1717  // won't be restored when traversing AST.
1718  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1719
1720  // Create local scope for possible condition variable.
1721  // Store scope position for continue statement.
1722  LocalScope::const_iterator LoopBeginScopePos = ScopePos;
1723  if (VarDecl* VD = W->getConditionVariable()) {
1724    addLocalScopeForVarDecl(VD);
1725    addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
1726  }
1727
1728  // "while" is a control-flow statement.  Thus we stop processing the current
1729  // block.
1730  if (Block) {
1731    if (badCFG)
1732      return 0;
1733    LoopSuccessor = Block;
1734  } else
1735    LoopSuccessor = Succ;
1736
1737  // Because of short-circuit evaluation, the condition of the loop can span
1738  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1739  // evaluate the condition.
1740  CFGBlock* ExitConditionBlock = createBlock(false);
1741  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1742
1743  // Set the terminator for the "exit" condition block.
1744  ExitConditionBlock->setTerminator(W);
1745
1746  // Now add the actual condition to the condition block.  Because the condition
1747  // itself may contain control-flow, new blocks may be created.  Thus we update
1748  // "Succ" after adding the condition.
1749  if (Stmt* C = W->getCond()) {
1750    Block = ExitConditionBlock;
1751    EntryConditionBlock = addStmt(C);
1752    // The condition might finish the current 'Block'.
1753    Block = EntryConditionBlock;
1754
1755    // If this block contains a condition variable, add both the condition
1756    // variable and initializer to the CFG.
1757    if (VarDecl *VD = W->getConditionVariable()) {
1758      if (Expr *Init = VD->getInit()) {
1759        autoCreateBlock();
1760        AppendStmt(Block, W, AddStmtChoice::AlwaysAdd);
1761        EntryConditionBlock = addStmt(Init);
1762        assert(Block == EntryConditionBlock);
1763      }
1764    }
1765
1766    if (Block) {
1767      if (badCFG)
1768        return 0;
1769    }
1770  }
1771
1772  // The condition block is the implicit successor for the loop body as well as
1773  // any code above the loop.
1774  Succ = EntryConditionBlock;
1775
1776  // See if this is a known constant.
1777  const TryResult& KnownVal = TryEvaluateBool(W->getCond());
1778
1779  // Process the loop body.
1780  {
1781    assert(W->getBody());
1782
1783    // Save the current values for Block, Succ, and continue and break targets
1784    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
1785    SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
1786        save_break(BreakJumpTarget);
1787
1788    // Create an empty block to represent the transition block for looping back
1789    // to the head of the loop.
1790    Block = 0;
1791    assert(Succ == EntryConditionBlock);
1792    Succ = createBlock();
1793    Succ->setLoopTarget(W);
1794    ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
1795
1796    // All breaks should go to the code following the loop.
1797    BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1798
1799    // NULL out Block to force lazy instantiation of blocks for the body.
1800    Block = NULL;
1801
1802    // Loop body should end with destructor of Condition variable (if any).
1803    addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
1804
1805    // If body is not a compound statement create implicit scope
1806    // and add destructors.
1807    if (!isa<CompoundStmt>(W->getBody()))
1808      addLocalScopeAndDtors(W->getBody());
1809
1810    // Create the body.  The returned block is the entry to the loop body.
1811    CFGBlock* BodyBlock = addStmt(W->getBody());
1812
1813    if (!BodyBlock)
1814      BodyBlock = ContinueJumpTarget.Block; // can happen for "while(...) ;"
1815    else if (Block) {
1816      if (badCFG)
1817        return 0;
1818    }
1819
1820    // Add the loop body entry as a successor to the condition.
1821    AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1822  }
1823
1824  // Link up the condition block with the code that follows the loop.  (the
1825  // false branch).
1826  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1827
1828  // There can be no more statements in the condition block since we loop back
1829  // to this block.  NULL out Block to force lazy creation of another block.
1830  Block = NULL;
1831
1832  // Return the condition block, which is the dominating block for the loop.
1833  Succ = EntryConditionBlock;
1834  return EntryConditionBlock;
1835}
1836
1837
1838CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
1839  // FIXME: For now we pretend that @catch and the code it contains does not
1840  //  exit.
1841  return Block;
1842}
1843
1844CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1845  // FIXME: This isn't complete.  We basically treat @throw like a return
1846  //  statement.
1847
1848  // If we were in the middle of a block we stop processing that block.
1849  if (badCFG)
1850    return 0;
1851
1852  // Create the new block.
1853  Block = createBlock(false);
1854
1855  // The Exit block is the only successor.
1856  AddSuccessor(Block, &cfg->getExit());
1857
1858  // Add the statement to the block.  This may create new blocks if S contains
1859  // control-flow (short-circuit operations).
1860  return VisitStmt(S, AddStmtChoice::AlwaysAdd);
1861}
1862
1863CFGBlock* CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr* T) {
1864  // If we were in the middle of a block we stop processing that block.
1865  if (badCFG)
1866    return 0;
1867
1868  // Create the new block.
1869  Block = createBlock(false);
1870
1871  if (TryTerminatedBlock)
1872    // The current try statement is the only successor.
1873    AddSuccessor(Block, TryTerminatedBlock);
1874  else
1875    // otherwise the Exit block is the only successor.
1876    AddSuccessor(Block, &cfg->getExit());
1877
1878  // Add the statement to the block.  This may create new blocks if S contains
1879  // control-flow (short-circuit operations).
1880  return VisitStmt(T, AddStmtChoice::AlwaysAdd);
1881}
1882
1883CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) {
1884  CFGBlock* LoopSuccessor = NULL;
1885
1886  // "do...while" is a control-flow statement.  Thus we stop processing the
1887  // current block.
1888  if (Block) {
1889    if (badCFG)
1890      return 0;
1891    LoopSuccessor = Block;
1892  } else
1893    LoopSuccessor = Succ;
1894
1895  // Because of short-circuit evaluation, the condition of the loop can span
1896  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1897  // evaluate the condition.
1898  CFGBlock* ExitConditionBlock = createBlock(false);
1899  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1900
1901  // Set the terminator for the "exit" condition block.
1902  ExitConditionBlock->setTerminator(D);
1903
1904  // Now add the actual condition to the condition block.  Because the condition
1905  // itself may contain control-flow, new blocks may be created.
1906  if (Stmt* C = D->getCond()) {
1907    Block = ExitConditionBlock;
1908    EntryConditionBlock = addStmt(C);
1909    if (Block) {
1910      if (badCFG)
1911        return 0;
1912    }
1913  }
1914
1915  // The condition block is the implicit successor for the loop body.
1916  Succ = EntryConditionBlock;
1917
1918  // See if this is a known constant.
1919  const TryResult &KnownVal = TryEvaluateBool(D->getCond());
1920
1921  // Process the loop body.
1922  CFGBlock* BodyBlock = NULL;
1923  {
1924    assert(D->getBody());
1925
1926    // Save the current values for Block, Succ, and continue and break targets
1927    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
1928    SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
1929        save_break(BreakJumpTarget);
1930
1931    // All continues within this loop should go to the condition block
1932    ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
1933
1934    // All breaks should go to the code following the loop.
1935    BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1936
1937    // NULL out Block to force lazy instantiation of blocks for the body.
1938    Block = NULL;
1939
1940    // If body is not a compound statement create implicit scope
1941    // and add destructors.
1942    if (!isa<CompoundStmt>(D->getBody()))
1943      addLocalScopeAndDtors(D->getBody());
1944
1945    // Create the body.  The returned block is the entry to the loop body.
1946    BodyBlock = addStmt(D->getBody());
1947
1948    if (!BodyBlock)
1949      BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
1950    else if (Block) {
1951      if (badCFG)
1952        return 0;
1953    }
1954
1955    if (!KnownVal.isFalse()) {
1956      // Add an intermediate block between the BodyBlock and the
1957      // ExitConditionBlock to represent the "loop back" transition.  Create an
1958      // empty block to represent the transition block for looping back to the
1959      // head of the loop.
1960      // FIXME: Can we do this more efficiently without adding another block?
1961      Block = NULL;
1962      Succ = BodyBlock;
1963      CFGBlock *LoopBackBlock = createBlock();
1964      LoopBackBlock->setLoopTarget(D);
1965
1966      // Add the loop body entry as a successor to the condition.
1967      AddSuccessor(ExitConditionBlock, LoopBackBlock);
1968    }
1969    else
1970      AddSuccessor(ExitConditionBlock, NULL);
1971  }
1972
1973  // Link up the condition block with the code that follows the loop.
1974  // (the false branch).
1975  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1976
1977  // There can be no more statements in the body block(s) since we loop back to
1978  // the body.  NULL out Block to force lazy creation of another block.
1979  Block = NULL;
1980
1981  // Return the loop body, which is the dominating block for the loop.
1982  Succ = BodyBlock;
1983  return BodyBlock;
1984}
1985
1986CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1987  // "continue" is a control-flow statement.  Thus we stop processing the
1988  // current block.
1989  if (badCFG)
1990    return 0;
1991
1992  // Now create a new block that ends with the continue statement.
1993  Block = createBlock(false);
1994  Block->setTerminator(C);
1995
1996  // If there is no target for the continue, then we are looking at an
1997  // incomplete AST.  This means the CFG cannot be constructed.
1998  if (ContinueJumpTarget.Block) {
1999    addAutomaticObjDtors(ScopePos, ContinueJumpTarget.ScopePos, C);
2000    AddSuccessor(Block, ContinueJumpTarget.Block);
2001  } else
2002    badCFG = true;
2003
2004  return Block;
2005}
2006
2007CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E,
2008                                             AddStmtChoice asc) {
2009
2010  if (asc.alwaysAdd()) {
2011    autoCreateBlock();
2012    AppendStmt(Block, E);
2013  }
2014
2015  // VLA types have expressions that must be evaluated.
2016  if (E->isArgumentType()) {
2017    for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
2018         VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
2019      addStmt(VA->getSizeExpr());
2020  }
2021
2022  return Block;
2023}
2024
2025/// VisitStmtExpr - Utility method to handle (nested) statement
2026///  expressions (a GCC extension).
2027CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
2028  if (asc.alwaysAdd()) {
2029    autoCreateBlock();
2030    AppendStmt(Block, SE);
2031  }
2032  return VisitCompoundStmt(SE->getSubStmt());
2033}
2034
2035CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
2036  // "switch" is a control-flow statement.  Thus we stop processing the current
2037  // block.
2038  CFGBlock* SwitchSuccessor = NULL;
2039
2040  // Save local scope position because in case of condition variable ScopePos
2041  // won't be restored when traversing AST.
2042  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2043
2044  // Create local scope for possible condition variable.
2045  // Store scope position. Add implicit destructor.
2046  if (VarDecl* VD = Terminator->getConditionVariable()) {
2047    LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
2048    addLocalScopeForVarDecl(VD);
2049    addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
2050  }
2051
2052  if (Block) {
2053    if (badCFG)
2054      return 0;
2055    SwitchSuccessor = Block;
2056  } else SwitchSuccessor = Succ;
2057
2058  // Save the current "switch" context.
2059  SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
2060                            save_default(DefaultCaseBlock);
2061  SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2062
2063  // Set the "default" case to be the block after the switch statement.  If the
2064  // switch statement contains a "default:", this value will be overwritten with
2065  // the block for that code.
2066  DefaultCaseBlock = SwitchSuccessor;
2067
2068  // Create a new block that will contain the switch statement.
2069  SwitchTerminatedBlock = createBlock(false);
2070
2071  // Now process the switch body.  The code after the switch is the implicit
2072  // successor.
2073  Succ = SwitchSuccessor;
2074  BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
2075
2076  // When visiting the body, the case statements should automatically get linked
2077  // up to the switch.  We also don't keep a pointer to the body, since all
2078  // control-flow from the switch goes to case/default statements.
2079  assert(Terminator->getBody() && "switch must contain a non-NULL body");
2080  Block = NULL;
2081
2082  // If body is not a compound statement create implicit scope
2083  // and add destructors.
2084  if (!isa<CompoundStmt>(Terminator->getBody()))
2085    addLocalScopeAndDtors(Terminator->getBody());
2086
2087  addStmt(Terminator->getBody());
2088  if (Block) {
2089    if (badCFG)
2090      return 0;
2091  }
2092
2093  // If we have no "default:" case, the default transition is to the code
2094  // following the switch body.
2095  AddSuccessor(SwitchTerminatedBlock, DefaultCaseBlock);
2096
2097  // Add the terminator and condition in the switch block.
2098  SwitchTerminatedBlock->setTerminator(Terminator);
2099  assert(Terminator->getCond() && "switch condition must be non-NULL");
2100  Block = SwitchTerminatedBlock;
2101  Block = addStmt(Terminator->getCond());
2102
2103  // Finally, if the SwitchStmt contains a condition variable, add both the
2104  // SwitchStmt and the condition variable initialization to the CFG.
2105  if (VarDecl *VD = Terminator->getConditionVariable()) {
2106    if (Expr *Init = VD->getInit()) {
2107      autoCreateBlock();
2108      AppendStmt(Block, Terminator, AddStmtChoice::AlwaysAdd);
2109      addStmt(Init);
2110    }
2111  }
2112
2113  return Block;
2114}
2115
2116CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) {
2117  // CaseStmts are essentially labels, so they are the first statement in a
2118  // block.
2119  CFGBlock *TopBlock = 0, *LastBlock = 0;
2120
2121  if (Stmt *Sub = CS->getSubStmt()) {
2122    // For deeply nested chains of CaseStmts, instead of doing a recursion
2123    // (which can blow out the stack), manually unroll and create blocks
2124    // along the way.
2125    while (isa<CaseStmt>(Sub)) {
2126      CFGBlock *CurrentBlock = createBlock(false);
2127      CurrentBlock->setLabel(CS);
2128
2129      if (TopBlock)
2130        AddSuccessor(LastBlock, CurrentBlock);
2131      else
2132        TopBlock = CurrentBlock;
2133
2134      AddSuccessor(SwitchTerminatedBlock, CurrentBlock);
2135      LastBlock = CurrentBlock;
2136
2137      CS = cast<CaseStmt>(Sub);
2138      Sub = CS->getSubStmt();
2139    }
2140
2141    addStmt(Sub);
2142  }
2143
2144  CFGBlock* CaseBlock = Block;
2145  if (!CaseBlock)
2146    CaseBlock = createBlock();
2147
2148  // Cases statements partition blocks, so this is the top of the basic block we
2149  // were processing (the "case XXX:" is the label).
2150  CaseBlock->setLabel(CS);
2151
2152  if (badCFG)
2153    return 0;
2154
2155  // Add this block to the list of successors for the block with the switch
2156  // statement.
2157  assert(SwitchTerminatedBlock);
2158  AddSuccessor(SwitchTerminatedBlock, CaseBlock);
2159
2160  // We set Block to NULL to allow lazy creation of a new block (if necessary)
2161  Block = NULL;
2162
2163  if (TopBlock) {
2164    AddSuccessor(LastBlock, CaseBlock);
2165    Succ = TopBlock;
2166  }
2167  else {
2168    // This block is now the implicit successor of other blocks.
2169    Succ = CaseBlock;
2170  }
2171
2172  return Succ;
2173}
2174
2175CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
2176  if (Terminator->getSubStmt())
2177    addStmt(Terminator->getSubStmt());
2178
2179  DefaultCaseBlock = Block;
2180
2181  if (!DefaultCaseBlock)
2182    DefaultCaseBlock = createBlock();
2183
2184  // Default statements partition blocks, so this is the top of the basic block
2185  // we were processing (the "default:" is the label).
2186  DefaultCaseBlock->setLabel(Terminator);
2187
2188  if (badCFG)
2189    return 0;
2190
2191  // Unlike case statements, we don't add the default block to the successors
2192  // for the switch statement immediately.  This is done when we finish
2193  // processing the switch statement.  This allows for the default case
2194  // (including a fall-through to the code after the switch statement) to always
2195  // be the last successor of a switch-terminated block.
2196
2197  // We set Block to NULL to allow lazy creation of a new block (if necessary)
2198  Block = NULL;
2199
2200  // This block is now the implicit successor of other blocks.
2201  Succ = DefaultCaseBlock;
2202
2203  return DefaultCaseBlock;
2204}
2205
2206CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
2207  // "try"/"catch" is a control-flow statement.  Thus we stop processing the
2208  // current block.
2209  CFGBlock* TrySuccessor = NULL;
2210
2211  if (Block) {
2212    if (badCFG)
2213      return 0;
2214    TrySuccessor = Block;
2215  } else TrySuccessor = Succ;
2216
2217  CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
2218
2219  // Create a new block that will contain the try statement.
2220  CFGBlock *NewTryTerminatedBlock = createBlock(false);
2221  // Add the terminator in the try block.
2222  NewTryTerminatedBlock->setTerminator(Terminator);
2223
2224  bool HasCatchAll = false;
2225  for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
2226    // The code after the try is the implicit successor.
2227    Succ = TrySuccessor;
2228    CXXCatchStmt *CS = Terminator->getHandler(h);
2229    if (CS->getExceptionDecl() == 0) {
2230      HasCatchAll = true;
2231    }
2232    Block = NULL;
2233    CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
2234    if (CatchBlock == 0)
2235      return 0;
2236    // Add this block to the list of successors for the block with the try
2237    // statement.
2238    AddSuccessor(NewTryTerminatedBlock, CatchBlock);
2239  }
2240  if (!HasCatchAll) {
2241    if (PrevTryTerminatedBlock)
2242      AddSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
2243    else
2244      AddSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2245  }
2246
2247  // The code after the try is the implicit successor.
2248  Succ = TrySuccessor;
2249
2250  // Save the current "try" context.
2251  SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock);
2252  TryTerminatedBlock = NewTryTerminatedBlock;
2253
2254  assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
2255  Block = NULL;
2256  Block = addStmt(Terminator->getTryBlock());
2257  return Block;
2258}
2259
2260CFGBlock* CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt* CS) {
2261  // CXXCatchStmt are treated like labels, so they are the first statement in a
2262  // block.
2263
2264  // Save local scope position because in case of exception variable ScopePos
2265  // won't be restored when traversing AST.
2266  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2267
2268  // Create local scope for possible exception variable.
2269  // Store scope position. Add implicit destructor.
2270  if (VarDecl* VD = CS->getExceptionDecl()) {
2271    LocalScope::const_iterator BeginScopePos = ScopePos;
2272    addLocalScopeForVarDecl(VD);
2273    addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
2274  }
2275
2276  if (CS->getHandlerBlock())
2277    addStmt(CS->getHandlerBlock());
2278
2279  CFGBlock* CatchBlock = Block;
2280  if (!CatchBlock)
2281    CatchBlock = createBlock();
2282
2283  CatchBlock->setLabel(CS);
2284
2285  if (badCFG)
2286    return 0;
2287
2288  // We set Block to NULL to allow lazy creation of a new block (if necessary)
2289  Block = NULL;
2290
2291  return CatchBlock;
2292}
2293
2294CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
2295                                            AddStmtChoice asc) {
2296  AddStmtChoice::Kind K = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
2297                                         : AddStmtChoice::AlwaysAdd;
2298  autoCreateBlock();
2299  AppendStmt(Block, C, AddStmtChoice(K));
2300  return VisitChildren(C);
2301}
2302
2303CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
2304                                                  AddStmtChoice asc) {
2305  AddStmtChoice::Kind K = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
2306                                         : AddStmtChoice::AlwaysAdd;
2307  autoCreateBlock();
2308  AppendStmt(Block, C, AddStmtChoice(K));
2309  return VisitChildren(C);
2310}
2311
2312CFGBlock *CFGBuilder::VisitCXXMemberCallExpr(CXXMemberCallExpr *C,
2313                                             AddStmtChoice asc) {
2314  AddStmtChoice::Kind K = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
2315                                         : AddStmtChoice::AlwaysAdd;
2316  autoCreateBlock();
2317  AppendStmt(Block, C, AddStmtChoice(K));
2318  return VisitChildren(C);
2319}
2320
2321CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
2322  // Lazily create the indirect-goto dispatch block if there isn't one already.
2323  CFGBlock* IBlock = cfg->getIndirectGotoBlock();
2324
2325  if (!IBlock) {
2326    IBlock = createBlock(false);
2327    cfg->setIndirectGotoBlock(IBlock);
2328  }
2329
2330  // IndirectGoto is a control-flow statement.  Thus we stop processing the
2331  // current block and create a new one.
2332  if (badCFG)
2333    return 0;
2334
2335  Block = createBlock(false);
2336  Block->setTerminator(I);
2337  AddSuccessor(Block, IBlock);
2338  return addStmt(I->getTarget());
2339}
2340
2341} // end anonymous namespace
2342
2343/// createBlock - Constructs and adds a new CFGBlock to the CFG.  The block has
2344///  no successors or predecessors.  If this is the first block created in the
2345///  CFG, it is automatically set to be the Entry and Exit of the CFG.
2346CFGBlock* CFG::createBlock() {
2347  bool first_block = begin() == end();
2348
2349  // Create the block.
2350  CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
2351  new (Mem) CFGBlock(NumBlockIDs++, BlkBVC);
2352  Blocks.push_back(Mem, BlkBVC);
2353
2354  // If this is the first block, set it as the Entry and Exit.
2355  if (first_block)
2356    Entry = Exit = &back();
2357
2358  // Return the block.
2359  return &back();
2360}
2361
2362/// buildCFG - Constructs a CFG from an AST.  Ownership of the returned
2363///  CFG is returned to the caller.
2364CFG* CFG::buildCFG(const Decl *D, Stmt* Statement, ASTContext *C,
2365    BuildOptions BO) {
2366  CFGBuilder Builder;
2367  return Builder.buildCFG(D, Statement, C, BO);
2368}
2369
2370//===----------------------------------------------------------------------===//
2371// CFG: Queries for BlkExprs.
2372//===----------------------------------------------------------------------===//
2373
2374namespace {
2375  typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
2376}
2377
2378static void FindSubExprAssignments(Stmt *S,
2379                                   llvm::SmallPtrSet<Expr*,50>& Set) {
2380  if (!S)
2381    return;
2382
2383  for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
2384    Stmt *child = *I;
2385    if (!child)
2386      continue;
2387
2388    if (BinaryOperator* B = dyn_cast<BinaryOperator>(child))
2389      if (B->isAssignmentOp()) Set.insert(B);
2390
2391    FindSubExprAssignments(child, Set);
2392  }
2393}
2394
2395static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
2396  BlkExprMapTy* M = new BlkExprMapTy();
2397
2398  // Look for assignments that are used as subexpressions.  These are the only
2399  // assignments that we want to *possibly* register as a block-level
2400  // expression.  Basically, if an assignment occurs both in a subexpression and
2401  // at the block-level, it is a block-level expression.
2402  llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
2403
2404  for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
2405    for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
2406      if (CFGStmt S = BI->getAs<CFGStmt>())
2407        FindSubExprAssignments(S, SubExprAssignments);
2408
2409  for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
2410
2411    // Iterate over the statements again on identify the Expr* and Stmt* at the
2412    // block-level that are block-level expressions.
2413
2414    for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) {
2415      CFGStmt CS = BI->getAs<CFGStmt>();
2416      if (!CS.isValid())
2417        continue;
2418      if (Expr* Exp = dyn_cast<Expr>(CS.getStmt())) {
2419
2420        if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
2421          // Assignment expressions that are not nested within another
2422          // expression are really "statements" whose value is never used by
2423          // another expression.
2424          if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
2425            continue;
2426        } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
2427          // Special handling for statement expressions.  The last statement in
2428          // the statement expression is also a block-level expr.
2429          const CompoundStmt* C = Terminator->getSubStmt();
2430          if (!C->body_empty()) {
2431            unsigned x = M->size();
2432            (*M)[C->body_back()] = x;
2433          }
2434        }
2435
2436        unsigned x = M->size();
2437        (*M)[Exp] = x;
2438      }
2439    }
2440
2441    // Look at terminators.  The condition is a block-level expression.
2442
2443    Stmt* S = (*I)->getTerminatorCondition();
2444
2445    if (S && M->find(S) == M->end()) {
2446        unsigned x = M->size();
2447        (*M)[S] = x;
2448    }
2449  }
2450
2451  return M;
2452}
2453
2454CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
2455  assert(S != NULL);
2456  if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
2457
2458  BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
2459  BlkExprMapTy::iterator I = M->find(S);
2460  return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second);
2461}
2462
2463unsigned CFG::getNumBlkExprs() {
2464  if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
2465    return M->size();
2466  else {
2467    // We assume callers interested in the number of BlkExprs will want
2468    // the map constructed if it doesn't already exist.
2469    BlkExprMap = (void*) PopulateBlkExprMap(*this);
2470    return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
2471  }
2472}
2473
2474//===----------------------------------------------------------------------===//
2475// Filtered walking of the CFG.
2476//===----------------------------------------------------------------------===//
2477
2478bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
2479        const CFGBlock *From, const CFGBlock *To) {
2480
2481  if (F.IgnoreDefaultsWithCoveredEnums) {
2482    // If the 'To' has no label or is labeled but the label isn't a
2483    // CaseStmt then filter this edge.
2484    if (const SwitchStmt *S =
2485  dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
2486      if (S->isAllEnumCasesCovered()) {
2487  const Stmt *L = To->getLabel();
2488  if (!L || !isa<CaseStmt>(L))
2489    return true;
2490      }
2491    }
2492  }
2493
2494  return false;
2495}
2496
2497//===----------------------------------------------------------------------===//
2498// Cleanup: CFG dstor.
2499//===----------------------------------------------------------------------===//
2500
2501CFG::~CFG() {
2502  delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
2503}
2504
2505//===----------------------------------------------------------------------===//
2506// CFG pretty printing
2507//===----------------------------------------------------------------------===//
2508
2509namespace {
2510
2511class StmtPrinterHelper : public PrinterHelper  {
2512  typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
2513  typedef llvm::DenseMap<Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
2514  StmtMapTy StmtMap;
2515  DeclMapTy DeclMap;
2516  signed CurrentBlock;
2517  unsigned CurrentStmt;
2518  const LangOptions &LangOpts;
2519public:
2520
2521  StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
2522    : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) {
2523    for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
2524      unsigned j = 1;
2525      for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
2526           BI != BEnd; ++BI, ++j ) {
2527        if (CFGStmt SE = BI->getAs<CFGStmt>()) {
2528          std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
2529          StmtMap[SE] = P;
2530
2531          if (DeclStmt* DS = dyn_cast<DeclStmt>(SE.getStmt())) {
2532              DeclMap[DS->getSingleDecl()] = P;
2533
2534          } else if (IfStmt* IS = dyn_cast<IfStmt>(SE.getStmt())) {
2535            if (VarDecl* VD = IS->getConditionVariable())
2536              DeclMap[VD] = P;
2537
2538          } else if (ForStmt* FS = dyn_cast<ForStmt>(SE.getStmt())) {
2539            if (VarDecl* VD = FS->getConditionVariable())
2540              DeclMap[VD] = P;
2541
2542          } else if (WhileStmt* WS = dyn_cast<WhileStmt>(SE.getStmt())) {
2543            if (VarDecl* VD = WS->getConditionVariable())
2544              DeclMap[VD] = P;
2545
2546          } else if (SwitchStmt* SS = dyn_cast<SwitchStmt>(SE.getStmt())) {
2547            if (VarDecl* VD = SS->getConditionVariable())
2548              DeclMap[VD] = P;
2549
2550          } else if (CXXCatchStmt* CS = dyn_cast<CXXCatchStmt>(SE.getStmt())) {
2551            if (VarDecl* VD = CS->getExceptionDecl())
2552              DeclMap[VD] = P;
2553          }
2554        }
2555      }
2556    }
2557  }
2558
2559  virtual ~StmtPrinterHelper() {}
2560
2561  const LangOptions &getLangOpts() const { return LangOpts; }
2562  void setBlockID(signed i) { CurrentBlock = i; }
2563  void setStmtID(unsigned i) { CurrentStmt = i; }
2564
2565  virtual bool handledStmt(Stmt* S, llvm::raw_ostream& OS) {
2566    StmtMapTy::iterator I = StmtMap.find(S);
2567
2568    if (I == StmtMap.end())
2569      return false;
2570
2571    if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
2572                          && I->second.second == CurrentStmt) {
2573      return false;
2574    }
2575
2576    OS << "[B" << I->second.first << "." << I->second.second << "]";
2577    return true;
2578  }
2579
2580  bool handleDecl(Decl* D, llvm::raw_ostream& OS) {
2581    DeclMapTy::iterator I = DeclMap.find(D);
2582
2583    if (I == DeclMap.end())
2584      return false;
2585
2586    if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
2587                          && I->second.second == CurrentStmt) {
2588      return false;
2589    }
2590
2591    OS << "[B" << I->second.first << "." << I->second.second << "]";
2592    return true;
2593  }
2594};
2595} // end anonymous namespace
2596
2597
2598namespace {
2599class CFGBlockTerminatorPrint
2600  : public StmtVisitor<CFGBlockTerminatorPrint,void> {
2601
2602  llvm::raw_ostream& OS;
2603  StmtPrinterHelper* Helper;
2604  PrintingPolicy Policy;
2605public:
2606  CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
2607                          const PrintingPolicy &Policy)
2608    : OS(os), Helper(helper), Policy(Policy) {}
2609
2610  void VisitIfStmt(IfStmt* I) {
2611    OS << "if ";
2612    I->getCond()->printPretty(OS,Helper,Policy);
2613  }
2614
2615  // Default case.
2616  void VisitStmt(Stmt* Terminator) {
2617    Terminator->printPretty(OS, Helper, Policy);
2618  }
2619
2620  void VisitForStmt(ForStmt* F) {
2621    OS << "for (" ;
2622    if (F->getInit())
2623      OS << "...";
2624    OS << "; ";
2625    if (Stmt* C = F->getCond())
2626      C->printPretty(OS, Helper, Policy);
2627    OS << "; ";
2628    if (F->getInc())
2629      OS << "...";
2630    OS << ")";
2631  }
2632
2633  void VisitWhileStmt(WhileStmt* W) {
2634    OS << "while " ;
2635    if (Stmt* C = W->getCond())
2636      C->printPretty(OS, Helper, Policy);
2637  }
2638
2639  void VisitDoStmt(DoStmt* D) {
2640    OS << "do ... while ";
2641    if (Stmt* C = D->getCond())
2642      C->printPretty(OS, Helper, Policy);
2643  }
2644
2645  void VisitSwitchStmt(SwitchStmt* Terminator) {
2646    OS << "switch ";
2647    Terminator->getCond()->printPretty(OS, Helper, Policy);
2648  }
2649
2650  void VisitCXXTryStmt(CXXTryStmt* CS) {
2651    OS << "try ...";
2652  }
2653
2654  void VisitConditionalOperator(ConditionalOperator* C) {
2655    C->getCond()->printPretty(OS, Helper, Policy);
2656    OS << " ? ... : ...";
2657  }
2658
2659  void VisitChooseExpr(ChooseExpr* C) {
2660    OS << "__builtin_choose_expr( ";
2661    C->getCond()->printPretty(OS, Helper, Policy);
2662    OS << " )";
2663  }
2664
2665  void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
2666    OS << "goto *";
2667    I->getTarget()->printPretty(OS, Helper, Policy);
2668  }
2669
2670  void VisitBinaryOperator(BinaryOperator* B) {
2671    if (!B->isLogicalOp()) {
2672      VisitExpr(B);
2673      return;
2674    }
2675
2676    B->getLHS()->printPretty(OS, Helper, Policy);
2677
2678    switch (B->getOpcode()) {
2679      case BO_LOr:
2680        OS << " || ...";
2681        return;
2682      case BO_LAnd:
2683        OS << " && ...";
2684        return;
2685      default:
2686        assert(false && "Invalid logical operator.");
2687    }
2688  }
2689
2690  void VisitExpr(Expr* E) {
2691    E->printPretty(OS, Helper, Policy);
2692  }
2693};
2694} // end anonymous namespace
2695
2696static void print_elem(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
2697                       const CFGElement &E) {
2698  if (CFGStmt CS = E.getAs<CFGStmt>()) {
2699    Stmt *S = CS;
2700
2701    if (Helper) {
2702
2703      // special printing for statement-expressions.
2704      if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
2705        CompoundStmt* Sub = SE->getSubStmt();
2706
2707        if (Sub->child_begin() != Sub->child_end()) {
2708          OS << "({ ... ; ";
2709          Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
2710          OS << " })\n";
2711          return;
2712        }
2713      }
2714      // special printing for comma expressions.
2715      if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
2716        if (B->getOpcode() == BO_Comma) {
2717          OS << "... , ";
2718          Helper->handledStmt(B->getRHS(),OS);
2719          OS << '\n';
2720          return;
2721        }
2722      }
2723    }
2724    S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
2725
2726    if (isa<CXXOperatorCallExpr>(S)) {
2727      OS << " (OperatorCall)";
2728    }
2729    else if (isa<CXXBindTemporaryExpr>(S)) {
2730      OS << " (BindTemporary)";
2731    }
2732
2733    // Expressions need a newline.
2734    if (isa<Expr>(S))
2735      OS << '\n';
2736
2737  } else if (CFGInitializer IE = E.getAs<CFGInitializer>()) {
2738    CXXBaseOrMemberInitializer* I = IE;
2739    if (I->isBaseInitializer())
2740      OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
2741    else OS << I->getMember()->getName();
2742
2743    OS << "(";
2744    if (Expr* IE = I->getInit())
2745      IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
2746    OS << ")";
2747
2748    if (I->isBaseInitializer())
2749      OS << " (Base initializer)\n";
2750    else OS << " (Member initializer)\n";
2751
2752  } else if (CFGAutomaticObjDtor DE = E.getAs<CFGAutomaticObjDtor>()){
2753    VarDecl* VD = DE.getVarDecl();
2754    Helper->handleDecl(VD, OS);
2755
2756    const Type* T = VD->getType().getTypePtr();
2757    if (const ReferenceType* RT = T->getAs<ReferenceType>())
2758      T = RT->getPointeeType().getTypePtr();
2759    else if (const Type *ET = T->getArrayElementTypeNoTypeQual())
2760      T = ET;
2761
2762    OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
2763    OS << " (Implicit destructor)\n";
2764
2765  } else if (CFGBaseDtor BE = E.getAs<CFGBaseDtor>()) {
2766    const CXXBaseSpecifier *BS = BE.getBaseSpecifier();
2767    OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
2768    OS << " (Base object destructor)\n";
2769
2770  } else if (CFGMemberDtor ME = E.getAs<CFGMemberDtor>()) {
2771    FieldDecl *FD = ME.getFieldDecl();
2772
2773    const Type *T = FD->getType().getTypePtr();
2774    if (const Type *ET = T->getArrayElementTypeNoTypeQual())
2775      T = ET;
2776
2777    OS << "this->" << FD->getName();
2778    OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
2779    OS << " (Member object destructor)\n";
2780  }
2781}
2782
2783static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
2784                        const CFGBlock& B,
2785                        StmtPrinterHelper* Helper, bool print_edges) {
2786
2787  if (Helper) Helper->setBlockID(B.getBlockID());
2788
2789  // Print the header.
2790  OS << "\n [ B" << B.getBlockID();
2791
2792  if (&B == &cfg->getEntry())
2793    OS << " (ENTRY) ]\n";
2794  else if (&B == &cfg->getExit())
2795    OS << " (EXIT) ]\n";
2796  else if (&B == cfg->getIndirectGotoBlock())
2797    OS << " (INDIRECT GOTO DISPATCH) ]\n";
2798  else
2799    OS << " ]\n";
2800
2801  // Print the label of this block.
2802  if (Stmt* Label = const_cast<Stmt*>(B.getLabel())) {
2803
2804    if (print_edges)
2805      OS << "    ";
2806
2807    if (LabelStmt* L = dyn_cast<LabelStmt>(Label))
2808      OS << L->getName();
2809    else if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) {
2810      OS << "case ";
2811      C->getLHS()->printPretty(OS, Helper,
2812                               PrintingPolicy(Helper->getLangOpts()));
2813      if (C->getRHS()) {
2814        OS << " ... ";
2815        C->getRHS()->printPretty(OS, Helper,
2816                                 PrintingPolicy(Helper->getLangOpts()));
2817      }
2818    } else if (isa<DefaultStmt>(Label))
2819      OS << "default";
2820    else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
2821      OS << "catch (";
2822      if (CS->getExceptionDecl())
2823        CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()),
2824                                      0);
2825      else
2826        OS << "...";
2827      OS << ")";
2828
2829    } else
2830      assert(false && "Invalid label statement in CFGBlock.");
2831
2832    OS << ":\n";
2833  }
2834
2835  // Iterate through the statements in the block and print them.
2836  unsigned j = 1;
2837
2838  for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
2839       I != E ; ++I, ++j ) {
2840
2841    // Print the statement # in the basic block and the statement itself.
2842    if (print_edges)
2843      OS << "    ";
2844
2845    OS << llvm::format("%3d", j) << ": ";
2846
2847    if (Helper)
2848      Helper->setStmtID(j);
2849
2850    print_elem(OS,Helper,*I);
2851  }
2852
2853  // Print the terminator of this block.
2854  if (B.getTerminator()) {
2855    if (print_edges)
2856      OS << "    ";
2857
2858    OS << "  T: ";
2859
2860    if (Helper) Helper->setBlockID(-1);
2861
2862    CFGBlockTerminatorPrint TPrinter(OS, Helper,
2863                                     PrintingPolicy(Helper->getLangOpts()));
2864    TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt()));
2865    OS << '\n';
2866  }
2867
2868  if (print_edges) {
2869    // Print the predecessors of this block.
2870    OS << "    Predecessors (" << B.pred_size() << "):";
2871    unsigned i = 0;
2872
2873    for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
2874         I != E; ++I, ++i) {
2875
2876      if (i == 8 || (i-8) == 0)
2877        OS << "\n     ";
2878
2879      OS << " B" << (*I)->getBlockID();
2880    }
2881
2882    OS << '\n';
2883
2884    // Print the successors of this block.
2885    OS << "    Successors (" << B.succ_size() << "):";
2886    i = 0;
2887
2888    for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
2889         I != E; ++I, ++i) {
2890
2891      if (i == 8 || (i-8) % 10 == 0)
2892        OS << "\n    ";
2893
2894      if (*I)
2895        OS << " B" << (*I)->getBlockID();
2896      else
2897        OS  << " NULL";
2898    }
2899
2900    OS << '\n';
2901  }
2902}
2903
2904
2905/// dump - A simple pretty printer of a CFG that outputs to stderr.
2906void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
2907
2908/// print - A simple pretty printer of a CFG that outputs to an ostream.
2909void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
2910  StmtPrinterHelper Helper(this, LO);
2911
2912  // Print the entry block.
2913  print_block(OS, this, getEntry(), &Helper, true);
2914
2915  // Iterate through the CFGBlocks and print them one by one.
2916  for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
2917    // Skip the entry block, because we already printed it.
2918    if (&(**I) == &getEntry() || &(**I) == &getExit())
2919      continue;
2920
2921    print_block(OS, this, **I, &Helper, true);
2922  }
2923
2924  // Print the exit block.
2925  print_block(OS, this, getExit(), &Helper, true);
2926  OS.flush();
2927}
2928
2929/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
2930void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
2931  print(llvm::errs(), cfg, LO);
2932}
2933
2934/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
2935///   Generally this will only be called from CFG::print.
2936void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
2937                     const LangOptions &LO) const {
2938  StmtPrinterHelper Helper(cfg, LO);
2939  print_block(OS, cfg, *this, &Helper, true);
2940}
2941
2942/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
2943void CFGBlock::printTerminator(llvm::raw_ostream &OS,
2944                               const LangOptions &LO) const {
2945  CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
2946  TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt()));
2947}
2948
2949Stmt* CFGBlock::getTerminatorCondition() {
2950  Stmt *Terminator = this->Terminator;
2951  if (!Terminator)
2952    return NULL;
2953
2954  Expr* E = NULL;
2955
2956  switch (Terminator->getStmtClass()) {
2957    default:
2958      break;
2959
2960    case Stmt::ForStmtClass:
2961      E = cast<ForStmt>(Terminator)->getCond();
2962      break;
2963
2964    case Stmt::WhileStmtClass:
2965      E = cast<WhileStmt>(Terminator)->getCond();
2966      break;
2967
2968    case Stmt::DoStmtClass:
2969      E = cast<DoStmt>(Terminator)->getCond();
2970      break;
2971
2972    case Stmt::IfStmtClass:
2973      E = cast<IfStmt>(Terminator)->getCond();
2974      break;
2975
2976    case Stmt::ChooseExprClass:
2977      E = cast<ChooseExpr>(Terminator)->getCond();
2978      break;
2979
2980    case Stmt::IndirectGotoStmtClass:
2981      E = cast<IndirectGotoStmt>(Terminator)->getTarget();
2982      break;
2983
2984    case Stmt::SwitchStmtClass:
2985      E = cast<SwitchStmt>(Terminator)->getCond();
2986      break;
2987
2988    case Stmt::ConditionalOperatorClass:
2989      E = cast<ConditionalOperator>(Terminator)->getCond();
2990      break;
2991
2992    case Stmt::BinaryOperatorClass: // '&&' and '||'
2993      E = cast<BinaryOperator>(Terminator)->getLHS();
2994      break;
2995
2996    case Stmt::ObjCForCollectionStmtClass:
2997      return Terminator;
2998  }
2999
3000  return E ? E->IgnoreParens() : NULL;
3001}
3002
3003bool CFGBlock::hasBinaryBranchTerminator() const {
3004  const Stmt *Terminator = this->Terminator;
3005  if (!Terminator)
3006    return false;
3007
3008  Expr* E = NULL;
3009
3010  switch (Terminator->getStmtClass()) {
3011    default:
3012      return false;
3013
3014    case Stmt::ForStmtClass:
3015    case Stmt::WhileStmtClass:
3016    case Stmt::DoStmtClass:
3017    case Stmt::IfStmtClass:
3018    case Stmt::ChooseExprClass:
3019    case Stmt::ConditionalOperatorClass:
3020    case Stmt::BinaryOperatorClass:
3021      return true;
3022  }
3023
3024  return E ? E->IgnoreParens() : NULL;
3025}
3026
3027
3028//===----------------------------------------------------------------------===//
3029// CFG Graphviz Visualization
3030//===----------------------------------------------------------------------===//
3031
3032
3033#ifndef NDEBUG
3034static StmtPrinterHelper* GraphHelper;
3035#endif
3036
3037void CFG::viewCFG(const LangOptions &LO) const {
3038#ifndef NDEBUG
3039  StmtPrinterHelper H(this, LO);
3040  GraphHelper = &H;
3041  llvm::ViewGraph(this,"CFG");
3042  GraphHelper = NULL;
3043#endif
3044}
3045
3046namespace llvm {
3047template<>
3048struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
3049
3050  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3051
3052  static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
3053
3054#ifndef NDEBUG
3055    std::string OutSStr;
3056    llvm::raw_string_ostream Out(OutSStr);
3057    print_block(Out,Graph, *Node, GraphHelper, false);
3058    std::string& OutStr = Out.str();
3059
3060    if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
3061
3062    // Process string output to make it nicer...
3063    for (unsigned i = 0; i != OutStr.length(); ++i)
3064      if (OutStr[i] == '\n') {                            // Left justify
3065        OutStr[i] = '\\';
3066        OutStr.insert(OutStr.begin()+i+1, 'l');
3067      }
3068
3069    return OutStr;
3070#else
3071    return "";
3072#endif
3073  }
3074};
3075} // end namespace llvm
3076