CFG.cpp revision 247e9665d897a7bbbf60c1c0d3b6609c4504a961
1d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//
3d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//                     The LLVM Compiler Infrastructure
4d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//
5d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea// This file is distributed under the University of Illinois Open Source
6d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea// License. See LICENSE.TXT for details.
7d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//
8d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//===----------------------------------------------------------------------===//
9d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//
10d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//  This file defines the CFG and CFGBuilder classes for representing and
11d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//  building Control-Flow Graphs (CFGs) from ASTs.
12d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//
13d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea//===----------------------------------------------------------------------===//
14d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea
15d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "clang/Analysis/Support/SaveAndRestore.h"
16d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "clang/Analysis/CFG.h"
17d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "clang/AST/DeclCXX.h"
18d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "clang/AST/StmtVisitor.h"
19d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "clang/AST/PrettyPrinter.h"
20d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "clang/AST/CharUnits.h"
21d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "llvm/Support/GraphWriter.h"
22d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "llvm/Support/Allocator.h"
23d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "llvm/Support/Format.h"
24d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "llvm/ADT/DenseMap.h"
25d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "llvm/ADT/SmallPtrSet.h"
26d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea#include "llvm/ADT/OwningPtr.h"
27d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea
28d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Maleausing namespace clang;
29d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea
30d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Maleanamespace {
31d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea
32d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Maleastatic SourceLocation GetEndLoc(Decl* D) {
33d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea  if (VarDecl* VD = dyn_cast<VarDecl>(D))
34d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea    if (Expr* Ex = VD->getInit())
35d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea      return Ex->getSourceRange().getEnd();
36d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea  return D->getLocation();
37d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea}
38d2771ed2249c645019b7b1e46bdd677d2ed1cfe1Daniel Malea
39/// The CFG builder uses a recursive algorithm to build the CFG.  When
40///  we process an expression, sometimes we know that we must add the
41///  subexpressions as block-level expressions.  For example:
42///
43///    exp1 || exp2
44///
45///  When processing the '||' expression, we know that exp1 and exp2
46///  need to be added as block-level expressions, even though they
47///  might not normally need to be.  AddStmtChoice records this
48///  contextual information.  If AddStmtChoice is 'NotAlwaysAdd', then
49///  the builder has an option not to add a subexpression as a
50///  block-level expression.
51///
52class AddStmtChoice {
53public:
54  enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
55
56  AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
57
58  bool alwaysAdd() const { return kind & AlwaysAdd; }
59
60  /// Return a copy of this object, except with the 'always-add' bit
61  ///  set as specified.
62  AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
63    return AddStmtChoice(alwaysAdd ? Kind(kind | AlwaysAdd) :
64                                     Kind(kind & ~AlwaysAdd));
65  }
66
67private:
68  Kind kind;
69};
70
71/// LocalScope - Node in tree of local scopes created for C++ implicit
72/// destructor calls generation. It contains list of automatic variables
73/// declared in the scope and link to position in previous scope this scope
74/// began in.
75///
76/// The process of creating local scopes is as follows:
77/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
78/// - Before processing statements in scope (e.g. CompoundStmt) create
79///   LocalScope object using CFGBuilder::ScopePos as link to previous scope
80///   and set CFGBuilder::ScopePos to the end of new scope,
81/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
82///   at this VarDecl,
83/// - For every normal (without jump) end of scope add to CFGBlock destructors
84///   for objects in the current scope,
85/// - For every jump add to CFGBlock destructors for objects
86///   between CFGBuilder::ScopePos and local scope position saved for jump
87///   target. Thanks to C++ restrictions on goto jumps we can be sure that
88///   jump target position will be on the path to root from CFGBuilder::ScopePos
89///   (adding any variable that doesn't need constructor to be called to
90///   LocalScope can break this assumption),
91///
92class LocalScope {
93public:
94  typedef BumpVector<VarDecl*> AutomaticVarsTy;
95
96  /// const_iterator - Iterates local scope backwards and jumps to previous
97  /// scope on reaching the beginning of currently iterated scope.
98  class const_iterator {
99    const LocalScope* Scope;
100
101    /// VarIter is guaranteed to be greater then 0 for every valid iterator.
102    /// Invalid iterator (with null Scope) has VarIter equal to 0.
103    unsigned VarIter;
104
105  public:
106    /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
107    /// Incrementing invalid iterator is allowed and will result in invalid
108    /// iterator.
109    const_iterator()
110        : Scope(NULL), VarIter(0) {}
111
112    /// Create valid iterator. In case when S.Prev is an invalid iterator and
113    /// I is equal to 0, this will create invalid iterator.
114    const_iterator(const LocalScope& S, unsigned I)
115        : Scope(&S), VarIter(I) {
116      // Iterator to "end" of scope is not allowed. Handle it by going up
117      // in scopes tree possibly up to invalid iterator in the root.
118      if (VarIter == 0 && Scope)
119        *this = Scope->Prev;
120    }
121
122    VarDecl* const* operator->() const {
123      assert (Scope && "Dereferencing invalid iterator is not allowed");
124      assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
125      return &Scope->Vars[VarIter - 1];
126    }
127    VarDecl* operator*() const {
128      return *this->operator->();
129    }
130
131    const_iterator& operator++() {
132      if (!Scope)
133        return *this;
134
135      assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
136      --VarIter;
137      if (VarIter == 0)
138        *this = Scope->Prev;
139      return *this;
140    }
141    const_iterator operator++(int) {
142      const_iterator P = *this;
143      ++*this;
144      return P;
145    }
146
147    bool operator==(const const_iterator& rhs) const {
148      return Scope == rhs.Scope && VarIter == rhs.VarIter;
149    }
150    bool operator!=(const const_iterator& rhs) const {
151      return !(*this == rhs);
152    }
153
154    operator bool() const {
155      return *this != const_iterator();
156    }
157
158    int distance(const_iterator L);
159  };
160
161  friend class const_iterator;
162
163private:
164  BumpVectorContext ctx;
165
166  /// Automatic variables in order of declaration.
167  AutomaticVarsTy Vars;
168  /// Iterator to variable in previous scope that was declared just before
169  /// begin of this scope.
170  const_iterator Prev;
171
172public:
173  /// Constructs empty scope linked to previous scope in specified place.
174  LocalScope(BumpVectorContext &ctx, const_iterator P)
175      : ctx(ctx), Vars(ctx, 4), Prev(P) {}
176
177  /// Begin of scope in direction of CFG building (backwards).
178  const_iterator begin() const { return const_iterator(*this, Vars.size()); }
179
180  void addVar(VarDecl* VD) {
181    Vars.push_back(VD, ctx);
182  }
183};
184
185/// distance - Calculates distance from this to L. L must be reachable from this
186/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
187/// number of scopes between this and L.
188int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
189  int D = 0;
190  const_iterator F = *this;
191  while (F.Scope != L.Scope) {
192    assert (F != const_iterator()
193        && "L iterator is not reachable from F iterator.");
194    D += F.VarIter;
195    F = F.Scope->Prev;
196  }
197  D += F.VarIter - L.VarIter;
198  return D;
199}
200
201/// BlockScopePosPair - Structure for specifying position in CFG during its
202/// build process. It consists of CFGBlock that specifies position in CFG graph
203/// and  LocalScope::const_iterator that specifies position in LocalScope graph.
204struct BlockScopePosPair {
205  BlockScopePosPair() : block(0) {}
206  BlockScopePosPair(CFGBlock* b, LocalScope::const_iterator scopePos)
207      : block(b), scopePosition(scopePos) {}
208
209  CFGBlock *block;
210  LocalScope::const_iterator scopePosition;
211};
212
213/// TryResult - a class representing a variant over the values
214///  'true', 'false', or 'unknown'.  This is returned by tryEvaluateBool,
215///  and is used by the CFGBuilder to decide if a branch condition
216///  can be decided up front during CFG construction.
217class TryResult {
218  int X;
219public:
220  TryResult(bool b) : X(b ? 1 : 0) {}
221  TryResult() : X(-1) {}
222
223  bool isTrue() const { return X == 1; }
224  bool isFalse() const { return X == 0; }
225  bool isKnown() const { return X >= 0; }
226  void negate() {
227    assert(isKnown());
228    X ^= 0x1;
229  }
230};
231
232/// CFGBuilder - This class implements CFG construction from an AST.
233///   The builder is stateful: an instance of the builder should be used to only
234///   construct a single CFG.
235///
236///   Example usage:
237///
238///     CFGBuilder builder;
239///     CFG* cfg = builder.BuildAST(stmt1);
240///
241///  CFG construction is done via a recursive walk of an AST.  We actually parse
242///  the AST in reverse order so that the successor of a basic block is
243///  constructed prior to its predecessor.  This allows us to nicely capture
244///  implicit fall-throughs without extra basic blocks.
245///
246class CFGBuilder {
247  typedef BlockScopePosPair JumpTarget;
248  typedef BlockScopePosPair JumpSource;
249
250  ASTContext *Context;
251  llvm::OwningPtr<CFG> cfg;
252
253  CFGBlock* Block;
254  CFGBlock* Succ;
255  JumpTarget ContinueJumpTarget;
256  JumpTarget BreakJumpTarget;
257  CFGBlock* SwitchTerminatedBlock;
258  CFGBlock* DefaultCaseBlock;
259  CFGBlock* TryTerminatedBlock;
260
261  // Current position in local scope.
262  LocalScope::const_iterator ScopePos;
263
264  // LabelMap records the mapping from Label expressions to their jump targets.
265  typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
266  LabelMapTy LabelMap;
267
268  // A list of blocks that end with a "goto" that must be backpatched to their
269  // resolved targets upon completion of CFG construction.
270  typedef std::vector<JumpSource> BackpatchBlocksTy;
271  BackpatchBlocksTy BackpatchBlocks;
272
273  // A list of labels whose address has been taken (for indirect gotos).
274  typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
275  LabelSetTy AddressTakenLabels;
276
277  bool badCFG;
278  const CFG::BuildOptions &BuildOpts;
279
280  // State to track for building switch statements.
281  bool switchExclusivelyCovered;
282  Expr::EvalResult *switchCond;
283
284public:
285  explicit CFGBuilder(ASTContext *astContext,
286                      const CFG::BuildOptions &buildOpts)
287    : Context(astContext), cfg(new CFG()), // crew a new CFG
288      Block(NULL), Succ(NULL),
289      SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL),
290      TryTerminatedBlock(NULL), badCFG(false), BuildOpts(buildOpts),
291      switchExclusivelyCovered(false), switchCond(0) {}
292
293  // buildCFG - Used by external clients to construct the CFG.
294  CFG* buildCFG(const Decl *D, Stmt *Statement);
295
296private:
297  // Visitors to walk an AST and construct the CFG.
298  CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
299  CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
300  CFGBlock *VisitBlockExpr(BlockExpr* E, AddStmtChoice asc);
301  CFGBlock *VisitBreakStmt(BreakStmt *B);
302  CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
303  CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
304      AddStmtChoice asc);
305  CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
306  CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
307  CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
308                                      AddStmtChoice asc);
309  CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
310  CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
311                                       AddStmtChoice asc);
312  CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
313                                        AddStmtChoice asc);
314  CFGBlock *VisitCXXMemberCallExpr(CXXMemberCallExpr *C, AddStmtChoice asc);
315  CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
316  CFGBlock *VisitCaseStmt(CaseStmt *C);
317  CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
318  CFGBlock *VisitCompoundStmt(CompoundStmt *C);
319  CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
320                                     AddStmtChoice asc);
321  CFGBlock *VisitContinueStmt(ContinueStmt *C);
322  CFGBlock *VisitDeclStmt(DeclStmt *DS);
323  CFGBlock *VisitDeclSubExpr(DeclStmt* DS);
324  CFGBlock *VisitDefaultStmt(DefaultStmt *D);
325  CFGBlock *VisitDoStmt(DoStmt *D);
326  CFGBlock *VisitForStmt(ForStmt *F);
327  CFGBlock *VisitGotoStmt(GotoStmt* G);
328  CFGBlock *VisitIfStmt(IfStmt *I);
329  CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
330  CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
331  CFGBlock *VisitLabelStmt(LabelStmt *L);
332  CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
333  CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
334  CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
335  CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
336  CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
337  CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
338  CFGBlock *VisitReturnStmt(ReturnStmt* R);
339  CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, AddStmtChoice asc);
340  CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
341  CFGBlock *VisitSwitchStmt(SwitchStmt *S);
342  CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
343  CFGBlock *VisitWhileStmt(WhileStmt *W);
344
345  CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
346  CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
347  CFGBlock *VisitChildren(Stmt* S);
348
349  // Visitors to walk an AST and generate destructors of temporaries in
350  // full expression.
351  CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary = false);
352  CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E);
353  CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E);
354  CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(CXXBindTemporaryExpr *E,
355      bool BindToTemporary);
356  CFGBlock *
357  VisitConditionalOperatorForTemporaryDtors(AbstractConditionalOperator *E,
358                                            bool BindToTemporary);
359
360  // NYS == Not Yet Supported
361  CFGBlock* NYS() {
362    badCFG = true;
363    return Block;
364  }
365
366  void autoCreateBlock() { if (!Block) Block = createBlock(); }
367  CFGBlock *createBlock(bool add_successor = true);
368
369  CFGBlock *addStmt(Stmt *S) {
370    return Visit(S, AddStmtChoice::AlwaysAdd);
371  }
372  CFGBlock *addInitializer(CXXCtorInitializer *I);
373  void addAutomaticObjDtors(LocalScope::const_iterator B,
374                            LocalScope::const_iterator E, Stmt* S);
375  void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
376
377  // Local scopes creation.
378  LocalScope* createOrReuseLocalScope(LocalScope* Scope);
379
380  void addLocalScopeForStmt(Stmt* S);
381  LocalScope* addLocalScopeForDeclStmt(DeclStmt* DS, LocalScope* Scope = NULL);
382  LocalScope* addLocalScopeForVarDecl(VarDecl* VD, LocalScope* Scope = NULL);
383
384  void addLocalScopeAndDtors(Stmt* S);
385
386  // Interface to CFGBlock - adding CFGElements.
387  void appendStmt(CFGBlock *B, Stmt *S) {
388    B->appendStmt(S, cfg->getBumpVectorContext());
389  }
390  void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
391    B->appendInitializer(I, cfg->getBumpVectorContext());
392  }
393  void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
394    B->appendBaseDtor(BS, cfg->getBumpVectorContext());
395  }
396  void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
397    B->appendMemberDtor(FD, cfg->getBumpVectorContext());
398  }
399  void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
400    B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
401  }
402
403  void insertAutomaticObjDtors(CFGBlock* Blk, CFGBlock::iterator I,
404    LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S);
405  void appendAutomaticObjDtors(CFGBlock* Blk, LocalScope::const_iterator B,
406      LocalScope::const_iterator E, Stmt* S);
407  void prependAutomaticObjDtorsWithTerminator(CFGBlock* Blk,
408      LocalScope::const_iterator B, LocalScope::const_iterator E);
409
410  void addSuccessor(CFGBlock *B, CFGBlock *S) {
411    B->addSuccessor(S, cfg->getBumpVectorContext());
412  }
413
414  /// Try and evaluate an expression to an integer constant.
415  bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
416    if (!BuildOpts.PruneTriviallyFalseEdges)
417      return false;
418    return !S->isTypeDependent() &&
419    !S->isValueDependent() &&
420    S->Evaluate(outResult, *Context);
421  }
422
423  /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
424  /// if we can evaluate to a known value, otherwise return -1.
425  TryResult tryEvaluateBool(Expr *S) {
426    Expr::EvalResult Result;
427    if (!tryEvaluate(S, Result))
428      return TryResult();
429
430    if (Result.Val.isInt())
431      return Result.Val.getInt().getBoolValue();
432
433    if (Result.Val.isLValue()) {
434      Expr *e = Result.Val.getLValueBase();
435      const CharUnits &c = Result.Val.getLValueOffset();
436      if (!e && c.isZero())
437        return false;
438    }
439    return TryResult();
440  }
441
442};
443
444// FIXME: Add support for dependent-sized array types in C++?
445// Does it even make sense to build a CFG for an uninstantiated template?
446static const VariableArrayType *FindVA(const Type *t) {
447  while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
448    if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
449      if (vat->getSizeExpr())
450        return vat;
451
452    t = vt->getElementType().getTypePtr();
453  }
454
455  return 0;
456}
457
458/// BuildCFG - Constructs a CFG from an AST (a Stmt*).  The AST can represent an
459///  arbitrary statement.  Examples include a single expression or a function
460///  body (compound statement).  The ownership of the returned CFG is
461///  transferred to the caller.  If CFG construction fails, this method returns
462///  NULL.
463CFG* CFGBuilder::buildCFG(const Decl *D, Stmt* Statement) {
464  assert(cfg.get());
465  if (!Statement)
466    return NULL;
467
468  // Create an empty block that will serve as the exit block for the CFG.  Since
469  // this is the first block added to the CFG, it will be implicitly registered
470  // as the exit block.
471  Succ = createBlock();
472  assert(Succ == &cfg->getExit());
473  Block = NULL;  // the EXIT block is empty.  Create all other blocks lazily.
474
475  if (BuildOpts.AddImplicitDtors)
476    if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
477      addImplicitDtorsForDestructor(DD);
478
479  // Visit the statements and create the CFG.
480  CFGBlock *B = addStmt(Statement);
481
482  if (badCFG)
483    return NULL;
484
485  // For C++ constructor add initializers to CFG.
486  if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
487    for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
488        E = CD->init_rend(); I != E; ++I) {
489      B = addInitializer(*I);
490      if (badCFG)
491        return NULL;
492    }
493  }
494
495  if (B)
496    Succ = B;
497
498  // Backpatch the gotos whose label -> block mappings we didn't know when we
499  // encountered them.
500  for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
501                                   E = BackpatchBlocks.end(); I != E; ++I ) {
502
503    CFGBlock* B = I->block;
504    GotoStmt* G = cast<GotoStmt>(B->getTerminator());
505    LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
506
507    // If there is no target for the goto, then we are looking at an
508    // incomplete AST.  Handle this by not registering a successor.
509    if (LI == LabelMap.end()) continue;
510
511    JumpTarget JT = LI->second;
512    prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
513                                           JT.scopePosition);
514    addSuccessor(B, JT.block);
515  }
516
517  // Add successors to the Indirect Goto Dispatch block (if we have one).
518  if (CFGBlock* B = cfg->getIndirectGotoBlock())
519    for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
520                              E = AddressTakenLabels.end(); I != E; ++I ) {
521
522      // Lookup the target block.
523      LabelMapTy::iterator LI = LabelMap.find(*I);
524
525      // If there is no target block that contains label, then we are looking
526      // at an incomplete AST.  Handle this by not registering a successor.
527      if (LI == LabelMap.end()) continue;
528
529      addSuccessor(B, LI->second.block);
530    }
531
532  // Create an empty entry block that has no predecessors.
533  cfg->setEntry(createBlock());
534
535  return cfg.take();
536}
537
538/// createBlock - Used to lazily create blocks that are connected
539///  to the current (global) succcessor.
540CFGBlock* CFGBuilder::createBlock(bool add_successor) {
541  CFGBlock* B = cfg->createBlock();
542  if (add_successor && Succ)
543    addSuccessor(B, Succ);
544  return B;
545}
546
547/// addInitializer - Add C++ base or member initializer element to CFG.
548CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
549  if (!BuildOpts.AddInitializers)
550    return Block;
551
552  bool IsReference = false;
553  bool HasTemporaries = false;
554
555  // Destructors of temporaries in initialization expression should be called
556  // after initialization finishes.
557  Expr *Init = I->getInit();
558  if (Init) {
559    if (FieldDecl *FD = I->getAnyMember())
560      IsReference = FD->getType()->isReferenceType();
561    HasTemporaries = isa<ExprWithCleanups>(Init);
562
563    if (BuildOpts.AddImplicitDtors && HasTemporaries) {
564      // Generate destructors for temporaries in initialization expression.
565      VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
566          IsReference);
567    }
568  }
569
570  autoCreateBlock();
571  appendInitializer(Block, I);
572
573  if (Init) {
574    if (HasTemporaries) {
575      // For expression with temporaries go directly to subexpression to omit
576      // generating destructors for the second time.
577      return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
578    }
579    return Visit(Init);
580  }
581
582  return Block;
583}
584
585/// addAutomaticObjDtors - Add to current block automatic objects destructors
586/// for objects in range of local scope positions. Use S as trigger statement
587/// for destructors.
588void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
589                                      LocalScope::const_iterator E, Stmt* S) {
590  if (!BuildOpts.AddImplicitDtors)
591    return;
592
593  if (B == E)
594    return;
595
596  autoCreateBlock();
597  appendAutomaticObjDtors(Block, B, E, S);
598}
599
600/// addImplicitDtorsForDestructor - Add implicit destructors generated for
601/// base and member objects in destructor.
602void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
603  assert (BuildOpts.AddImplicitDtors
604      && "Can be called only when dtors should be added");
605  const CXXRecordDecl *RD = DD->getParent();
606
607  // At the end destroy virtual base objects.
608  for (CXXRecordDecl::base_class_const_iterator VI = RD->vbases_begin(),
609      VE = RD->vbases_end(); VI != VE; ++VI) {
610    const CXXRecordDecl *CD = VI->getType()->getAsCXXRecordDecl();
611    if (!CD->hasTrivialDestructor()) {
612      autoCreateBlock();
613      appendBaseDtor(Block, VI);
614    }
615  }
616
617  // Before virtual bases destroy direct base objects.
618  for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
619      BE = RD->bases_end(); BI != BE; ++BI) {
620    if (!BI->isVirtual()) {
621      const CXXRecordDecl *CD = BI->getType()->getAsCXXRecordDecl();
622      if (!CD->hasTrivialDestructor()) {
623        autoCreateBlock();
624        appendBaseDtor(Block, BI);
625      }
626    }
627  }
628
629  // First destroy member objects.
630  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
631      FE = RD->field_end(); FI != FE; ++FI) {
632    // Check for constant size array. Set type to array element type.
633    QualType QT = FI->getType();
634    if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
635      if (AT->getSize() == 0)
636        continue;
637      QT = AT->getElementType();
638    }
639
640    if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
641      if (!CD->hasTrivialDestructor()) {
642        autoCreateBlock();
643        appendMemberDtor(Block, *FI);
644      }
645  }
646}
647
648/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
649/// way return valid LocalScope object.
650LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
651  if (!Scope) {
652    llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
653    Scope = alloc.Allocate<LocalScope>();
654    BumpVectorContext ctx(alloc);
655    new (Scope) LocalScope(ctx, ScopePos);
656  }
657  return Scope;
658}
659
660/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
661/// that should create implicit scope (e.g. if/else substatements).
662void CFGBuilder::addLocalScopeForStmt(Stmt* S) {
663  if (!BuildOpts.AddImplicitDtors)
664    return;
665
666  LocalScope *Scope = 0;
667
668  // For compound statement we will be creating explicit scope.
669  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
670    for (CompoundStmt::body_iterator BI = CS->body_begin(), BE = CS->body_end()
671        ; BI != BE; ++BI) {
672      Stmt *SI = *BI;
673      if (LabelStmt *LS = dyn_cast<LabelStmt>(SI))
674        SI = LS->getSubStmt();
675      if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
676        Scope = addLocalScopeForDeclStmt(DS, Scope);
677    }
678    return;
679  }
680
681  // For any other statement scope will be implicit and as such will be
682  // interesting only for DeclStmt.
683  if (LabelStmt *LS = dyn_cast<LabelStmt>(S))
684    S = LS->getSubStmt();
685  if (DeclStmt *DS = dyn_cast<DeclStmt>(S))
686    addLocalScopeForDeclStmt(DS);
687}
688
689/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
690/// reuse Scope if not NULL.
691LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt* DS,
692                                                 LocalScope* Scope) {
693  if (!BuildOpts.AddImplicitDtors)
694    return Scope;
695
696  for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end()
697      ; DI != DE; ++DI) {
698    if (VarDecl* VD = dyn_cast<VarDecl>(*DI))
699      Scope = addLocalScopeForVarDecl(VD, Scope);
700  }
701  return Scope;
702}
703
704/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
705/// create add scope for automatic objects and temporary objects bound to
706/// const reference. Will reuse Scope if not NULL.
707LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl* VD,
708                                                LocalScope* Scope) {
709  if (!BuildOpts.AddImplicitDtors)
710    return Scope;
711
712  // Check if variable is local.
713  switch (VD->getStorageClass()) {
714  case SC_None:
715  case SC_Auto:
716  case SC_Register:
717    break;
718  default: return Scope;
719  }
720
721  // Check for const references bound to temporary. Set type to pointee.
722  QualType QT = VD->getType();
723  if (const ReferenceType* RT = QT.getTypePtr()->getAs<ReferenceType>()) {
724    QT = RT->getPointeeType();
725    if (!QT.isConstQualified())
726      return Scope;
727    if (!VD->getInit() || !VD->getInit()->Classify(*Context).isRValue())
728      return Scope;
729  }
730
731  // Check for constant size array. Set type to array element type.
732  if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
733    if (AT->getSize() == 0)
734      return Scope;
735    QT = AT->getElementType();
736  }
737
738  // Check if type is a C++ class with non-trivial destructor.
739  if (const CXXRecordDecl* CD = QT->getAsCXXRecordDecl())
740    if (!CD->hasTrivialDestructor()) {
741      // Add the variable to scope
742      Scope = createOrReuseLocalScope(Scope);
743      Scope->addVar(VD);
744      ScopePos = Scope->begin();
745    }
746  return Scope;
747}
748
749/// addLocalScopeAndDtors - For given statement add local scope for it and
750/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
751void CFGBuilder::addLocalScopeAndDtors(Stmt* S) {
752  if (!BuildOpts.AddImplicitDtors)
753    return;
754
755  LocalScope::const_iterator scopeBeginPos = ScopePos;
756  addLocalScopeForStmt(S);
757  addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
758}
759
760/// insertAutomaticObjDtors - Insert destructor CFGElements for variables with
761/// automatic storage duration to CFGBlock's elements vector. Insertion will be
762/// performed in place specified with iterator.
763void CFGBuilder::insertAutomaticObjDtors(CFGBlock* Blk, CFGBlock::iterator I,
764    LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S) {
765  BumpVectorContext& C = cfg->getBumpVectorContext();
766  I = Blk->beginAutomaticObjDtorsInsert(I, B.distance(E), C);
767  while (B != E)
768    I = Blk->insertAutomaticObjDtor(I, *B++, S);
769}
770
771/// appendAutomaticObjDtors - Append destructor CFGElements for variables with
772/// automatic storage duration to CFGBlock's elements vector. Elements will be
773/// appended to physical end of the vector which happens to be logical
774/// beginning.
775void CFGBuilder::appendAutomaticObjDtors(CFGBlock* Blk,
776    LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S) {
777  insertAutomaticObjDtors(Blk, Blk->begin(), B, E, S);
778}
779
780/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
781/// variables with automatic storage duration to CFGBlock's elements vector.
782/// Elements will be prepended to physical beginning of the vector which
783/// happens to be logical end. Use blocks terminator as statement that specifies
784/// destructors call site.
785void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock* Blk,
786    LocalScope::const_iterator B, LocalScope::const_iterator E) {
787  insertAutomaticObjDtors(Blk, Blk->end(), B, E, Blk->getTerminator());
788}
789
790/// Visit - Walk the subtree of a statement and add extra
791///   blocks for ternary operators, &&, and ||.  We also process "," and
792///   DeclStmts (which may contain nested control-flow).
793CFGBlock* CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
794tryAgain:
795  if (!S) {
796    badCFG = true;
797    return 0;
798  }
799  switch (S->getStmtClass()) {
800    default:
801      return VisitStmt(S, asc);
802
803    case Stmt::AddrLabelExprClass:
804      return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
805
806    case Stmt::BinaryConditionalOperatorClass:
807      return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
808
809    case Stmt::BinaryOperatorClass:
810      return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
811
812    case Stmt::BlockExprClass:
813      return VisitBlockExpr(cast<BlockExpr>(S), asc);
814
815    case Stmt::BreakStmtClass:
816      return VisitBreakStmt(cast<BreakStmt>(S));
817
818    case Stmt::CallExprClass:
819    case Stmt::CXXOperatorCallExprClass:
820      return VisitCallExpr(cast<CallExpr>(S), asc);
821
822    case Stmt::CaseStmtClass:
823      return VisitCaseStmt(cast<CaseStmt>(S));
824
825    case Stmt::ChooseExprClass:
826      return VisitChooseExpr(cast<ChooseExpr>(S), asc);
827
828    case Stmt::CompoundStmtClass:
829      return VisitCompoundStmt(cast<CompoundStmt>(S));
830
831    case Stmt::ConditionalOperatorClass:
832      return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
833
834    case Stmt::ContinueStmtClass:
835      return VisitContinueStmt(cast<ContinueStmt>(S));
836
837    case Stmt::CXXCatchStmtClass:
838      return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
839
840    case Stmt::ExprWithCleanupsClass:
841      return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
842
843    case Stmt::CXXBindTemporaryExprClass:
844      return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
845
846    case Stmt::CXXConstructExprClass:
847      return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
848
849    case Stmt::CXXFunctionalCastExprClass:
850      return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
851
852    case Stmt::CXXTemporaryObjectExprClass:
853      return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
854
855    case Stmt::CXXMemberCallExprClass:
856      return VisitCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), asc);
857
858    case Stmt::CXXThrowExprClass:
859      return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
860
861    case Stmt::CXXTryStmtClass:
862      return VisitCXXTryStmt(cast<CXXTryStmt>(S));
863
864    case Stmt::DeclStmtClass:
865      return VisitDeclStmt(cast<DeclStmt>(S));
866
867    case Stmt::DefaultStmtClass:
868      return VisitDefaultStmt(cast<DefaultStmt>(S));
869
870    case Stmt::DoStmtClass:
871      return VisitDoStmt(cast<DoStmt>(S));
872
873    case Stmt::ForStmtClass:
874      return VisitForStmt(cast<ForStmt>(S));
875
876    case Stmt::GotoStmtClass:
877      return VisitGotoStmt(cast<GotoStmt>(S));
878
879    case Stmt::IfStmtClass:
880      return VisitIfStmt(cast<IfStmt>(S));
881
882    case Stmt::ImplicitCastExprClass:
883      return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
884
885    case Stmt::IndirectGotoStmtClass:
886      return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
887
888    case Stmt::LabelStmtClass:
889      return VisitLabelStmt(cast<LabelStmt>(S));
890
891    case Stmt::MemberExprClass:
892      return VisitMemberExpr(cast<MemberExpr>(S), asc);
893
894    case Stmt::ObjCAtCatchStmtClass:
895      return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
896
897    case Stmt::ObjCAtSynchronizedStmtClass:
898      return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
899
900    case Stmt::ObjCAtThrowStmtClass:
901      return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
902
903    case Stmt::ObjCAtTryStmtClass:
904      return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
905
906    case Stmt::ObjCForCollectionStmtClass:
907      return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
908
909    case Stmt::ParenExprClass:
910      S = cast<ParenExpr>(S)->getSubExpr();
911      goto tryAgain;
912
913    case Stmt::NullStmtClass:
914      return Block;
915
916    case Stmt::ReturnStmtClass:
917      return VisitReturnStmt(cast<ReturnStmt>(S));
918
919    case Stmt::SizeOfAlignOfExprClass:
920      return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), asc);
921
922    case Stmt::StmtExprClass:
923      return VisitStmtExpr(cast<StmtExpr>(S), asc);
924
925    case Stmt::SwitchStmtClass:
926      return VisitSwitchStmt(cast<SwitchStmt>(S));
927
928    case Stmt::UnaryOperatorClass:
929      return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
930
931    case Stmt::WhileStmtClass:
932      return VisitWhileStmt(cast<WhileStmt>(S));
933  }
934}
935
936CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
937  if (asc.alwaysAdd()) {
938    autoCreateBlock();
939    appendStmt(Block, S);
940  }
941
942  return VisitChildren(S);
943}
944
945/// VisitChildren - Visit the children of a Stmt.
946CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) {
947  CFGBlock *lastBlock = Block;
948  for (Stmt::child_range I = Terminator->children(); I; ++I)
949    if (Stmt *child = *I)
950      if (CFGBlock *b = Visit(child))
951        lastBlock = b;
952
953  return lastBlock;
954}
955
956CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
957                                         AddStmtChoice asc) {
958  AddressTakenLabels.insert(A->getLabel());
959
960  if (asc.alwaysAdd()) {
961    autoCreateBlock();
962    appendStmt(Block, A);
963  }
964
965  return Block;
966}
967
968CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
969           AddStmtChoice asc) {
970  if (asc.alwaysAdd()) {
971    autoCreateBlock();
972    appendStmt(Block, U);
973  }
974
975  return Visit(U->getSubExpr(), AddStmtChoice());
976}
977
978CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
979                                          AddStmtChoice asc) {
980  if (B->isLogicalOp()) { // && or ||
981    CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
982    appendStmt(ConfluenceBlock, B);
983
984    if (badCFG)
985      return 0;
986
987    // create the block evaluating the LHS
988    CFGBlock* LHSBlock = createBlock(false);
989    LHSBlock->setTerminator(B);
990
991    // create the block evaluating the RHS
992    Succ = ConfluenceBlock;
993    Block = NULL;
994    CFGBlock* RHSBlock = addStmt(B->getRHS());
995
996    if (RHSBlock) {
997      if (badCFG)
998        return 0;
999    } else {
1000      // Create an empty block for cases where the RHS doesn't require
1001      // any explicit statements in the CFG.
1002      RHSBlock = createBlock();
1003    }
1004
1005    // See if this is a known constant.
1006    TryResult KnownVal = tryEvaluateBool(B->getLHS());
1007    if (KnownVal.isKnown() && (B->getOpcode() == BO_LOr))
1008      KnownVal.negate();
1009
1010    // Now link the LHSBlock with RHSBlock.
1011    if (B->getOpcode() == BO_LOr) {
1012      addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
1013      addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
1014    } else {
1015      assert(B->getOpcode() == BO_LAnd);
1016      addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
1017      addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
1018    }
1019
1020    // Generate the blocks for evaluating the LHS.
1021    Block = LHSBlock;
1022    return addStmt(B->getLHS());
1023  }
1024
1025  if (B->getOpcode() == BO_Comma) { // ,
1026    autoCreateBlock();
1027    appendStmt(Block, B);
1028    addStmt(B->getRHS());
1029    return addStmt(B->getLHS());
1030  }
1031
1032  if (B->isAssignmentOp()) {
1033    if (asc.alwaysAdd()) {
1034      autoCreateBlock();
1035      appendStmt(Block, B);
1036    }
1037    Visit(B->getLHS());
1038    return Visit(B->getRHS());
1039  }
1040
1041  if (asc.alwaysAdd()) {
1042    autoCreateBlock();
1043    appendStmt(Block, B);
1044  }
1045
1046  CFGBlock *RBlock = Visit(B->getRHS());
1047  CFGBlock *LBlock = Visit(B->getLHS());
1048  // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1049  // containing a DoStmt, and the LHS doesn't create a new block, then we should
1050  // return RBlock.  Otherwise we'll incorrectly return NULL.
1051  return (LBlock ? LBlock : RBlock);
1052}
1053
1054CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
1055  if (asc.alwaysAdd()) {
1056    autoCreateBlock();
1057    appendStmt(Block, E);
1058  }
1059  return Block;
1060}
1061
1062CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1063  // "break" is a control-flow statement.  Thus we stop processing the current
1064  // block.
1065  if (badCFG)
1066    return 0;
1067
1068  // Now create a new block that ends with the break statement.
1069  Block = createBlock(false);
1070  Block->setTerminator(B);
1071
1072  // If there is no target for the break, then we are looking at an incomplete
1073  // AST.  This means that the CFG cannot be constructed.
1074  if (BreakJumpTarget.block) {
1075    addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1076    addSuccessor(Block, BreakJumpTarget.block);
1077  } else
1078    badCFG = true;
1079
1080
1081  return Block;
1082}
1083
1084static bool CanThrow(Expr *E) {
1085  QualType Ty = E->getType();
1086  if (Ty->isFunctionPointerType())
1087    Ty = Ty->getAs<PointerType>()->getPointeeType();
1088  else if (Ty->isBlockPointerType())
1089    Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
1090
1091  const FunctionType *FT = Ty->getAs<FunctionType>();
1092  if (FT) {
1093    if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
1094      if (Proto->hasEmptyExceptionSpec())
1095        return false;
1096  }
1097  return true;
1098}
1099
1100CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
1101  // If this is a call to a no-return function, this stops the block here.
1102  bool NoReturn = false;
1103  if (getFunctionExtInfo(*C->getCallee()->getType()).getNoReturn()) {
1104    NoReturn = true;
1105  }
1106
1107  bool AddEHEdge = false;
1108
1109  // Languages without exceptions are assumed to not throw.
1110  if (Context->getLangOptions().Exceptions) {
1111    if (BuildOpts.AddEHEdges)
1112      AddEHEdge = true;
1113  }
1114
1115  if (FunctionDecl *FD = C->getDirectCallee()) {
1116    if (FD->hasAttr<NoReturnAttr>())
1117      NoReturn = true;
1118    if (FD->hasAttr<NoThrowAttr>())
1119      AddEHEdge = false;
1120  }
1121
1122  if (!CanThrow(C->getCallee()))
1123    AddEHEdge = false;
1124
1125  if (!NoReturn && !AddEHEdge)
1126    return VisitStmt(C, asc.withAlwaysAdd(true));
1127
1128  if (Block) {
1129    Succ = Block;
1130    if (badCFG)
1131      return 0;
1132  }
1133
1134  Block = createBlock(!NoReturn);
1135  appendStmt(Block, C);
1136
1137  if (NoReturn) {
1138    // Wire this to the exit block directly.
1139    addSuccessor(Block, &cfg->getExit());
1140  }
1141  if (AddEHEdge) {
1142    // Add exceptional edges.
1143    if (TryTerminatedBlock)
1144      addSuccessor(Block, TryTerminatedBlock);
1145    else
1146      addSuccessor(Block, &cfg->getExit());
1147  }
1148
1149  return VisitChildren(C);
1150}
1151
1152CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1153                                      AddStmtChoice asc) {
1154  CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
1155  appendStmt(ConfluenceBlock, C);
1156  if (badCFG)
1157    return 0;
1158
1159  AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1160  Succ = ConfluenceBlock;
1161  Block = NULL;
1162  CFGBlock* LHSBlock = Visit(C->getLHS(), alwaysAdd);
1163  if (badCFG)
1164    return 0;
1165
1166  Succ = ConfluenceBlock;
1167  Block = NULL;
1168  CFGBlock* RHSBlock = Visit(C->getRHS(), alwaysAdd);
1169  if (badCFG)
1170    return 0;
1171
1172  Block = createBlock(false);
1173  // See if this is a known constant.
1174  const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1175  addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1176  addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1177  Block->setTerminator(C);
1178  return addStmt(C->getCond());
1179}
1180
1181
1182CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
1183  addLocalScopeAndDtors(C);
1184  CFGBlock* LastBlock = Block;
1185
1186  for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1187       I != E; ++I ) {
1188    // If we hit a segment of code just containing ';' (NullStmts), we can
1189    // get a null block back.  In such cases, just use the LastBlock
1190    if (CFGBlock *newBlock = addStmt(*I))
1191      LastBlock = newBlock;
1192
1193    if (badCFG)
1194      return NULL;
1195  }
1196
1197  return LastBlock;
1198}
1199
1200CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
1201                                               AddStmtChoice asc) {
1202  const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
1203  const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : NULL);
1204
1205  // Create the confluence block that will "merge" the results of the ternary
1206  // expression.
1207  CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
1208  appendStmt(ConfluenceBlock, C);
1209  if (badCFG)
1210    return 0;
1211
1212  AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1213
1214  // Create a block for the LHS expression if there is an LHS expression.  A
1215  // GCC extension allows LHS to be NULL, causing the condition to be the
1216  // value that is returned instead.
1217  //  e.g: x ?: y is shorthand for: x ? x : y;
1218  Succ = ConfluenceBlock;
1219  Block = NULL;
1220  CFGBlock* LHSBlock = 0;
1221  const Expr *trueExpr = C->getTrueExpr();
1222  if (trueExpr != opaqueValue) {
1223    LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
1224    if (badCFG)
1225      return 0;
1226    Block = NULL;
1227  }
1228  else
1229    LHSBlock = ConfluenceBlock;
1230
1231  // Create the block for the RHS expression.
1232  Succ = ConfluenceBlock;
1233  CFGBlock* RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
1234  if (badCFG)
1235    return 0;
1236
1237  // Create the block that will contain the condition.
1238  Block = createBlock(false);
1239
1240  // See if this is a known constant.
1241  const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1242  addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1243  addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1244  Block->setTerminator(C);
1245  Expr *condExpr = C->getCond();
1246
1247  if (opaqueValue) {
1248    // Run the condition expression if it's not trivially expressed in
1249    // terms of the opaque value (or if there is no opaque value).
1250    if (condExpr != opaqueValue)
1251      addStmt(condExpr);
1252
1253    // Before that, run the common subexpression if there was one.
1254    // At least one of this or the above will be run.
1255    return addStmt(BCO->getCommon());
1256  }
1257
1258  return addStmt(condExpr);
1259}
1260
1261CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
1262  if (DS->isSingleDecl())
1263    return VisitDeclSubExpr(DS);
1264
1265  CFGBlock *B = 0;
1266
1267  // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy.
1268  typedef llvm::SmallVector<Decl*,10> BufTy;
1269  BufTy Buf(DS->decl_begin(), DS->decl_end());
1270
1271  for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) {
1272    // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
1273    unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
1274               ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
1275
1276    // Allocate the DeclStmt using the BumpPtrAllocator.  It will get
1277    // automatically freed with the CFG.
1278    DeclGroupRef DG(*I);
1279    Decl *D = *I;
1280    void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
1281    DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
1282
1283    // Append the fake DeclStmt to block.
1284    B = VisitDeclSubExpr(DSNew);
1285  }
1286
1287  return B;
1288}
1289
1290/// VisitDeclSubExpr - Utility method to add block-level expressions for
1291/// DeclStmts and initializers in them.
1292CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt* DS) {
1293  assert(DS->isSingleDecl() && "Can handle single declarations only.");
1294
1295  VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1296
1297  if (!VD) {
1298    autoCreateBlock();
1299    appendStmt(Block, DS);
1300    return Block;
1301  }
1302
1303  bool IsReference = false;
1304  bool HasTemporaries = false;
1305
1306  // Destructors of temporaries in initialization expression should be called
1307  // after initialization finishes.
1308  Expr *Init = VD->getInit();
1309  if (Init) {
1310    IsReference = VD->getType()->isReferenceType();
1311    HasTemporaries = isa<ExprWithCleanups>(Init);
1312
1313    if (BuildOpts.AddImplicitDtors && HasTemporaries) {
1314      // Generate destructors for temporaries in initialization expression.
1315      VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1316          IsReference);
1317    }
1318  }
1319
1320  autoCreateBlock();
1321  appendStmt(Block, DS);
1322
1323  if (Init) {
1324    if (HasTemporaries)
1325      // For expression with temporaries go directly to subexpression to omit
1326      // generating destructors for the second time.
1327      Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1328    else
1329      Visit(Init);
1330  }
1331
1332  // If the type of VD is a VLA, then we must process its size expressions.
1333  for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
1334       VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
1335    Block = addStmt(VA->getSizeExpr());
1336
1337  // Remove variable from local scope.
1338  if (ScopePos && VD == *ScopePos)
1339    ++ScopePos;
1340
1341  return Block;
1342}
1343
1344CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
1345  // We may see an if statement in the middle of a basic block, or it may be the
1346  // first statement we are processing.  In either case, we create a new basic
1347  // block.  First, we create the blocks for the then...else statements, and
1348  // then we create the block containing the if statement.  If we were in the
1349  // middle of a block, we stop processing that block.  That block is then the
1350  // implicit successor for the "then" and "else" clauses.
1351
1352  // Save local scope position because in case of condition variable ScopePos
1353  // won't be restored when traversing AST.
1354  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1355
1356  // Create local scope for possible condition variable.
1357  // Store scope position. Add implicit destructor.
1358  if (VarDecl* VD = I->getConditionVariable()) {
1359    LocalScope::const_iterator BeginScopePos = ScopePos;
1360    addLocalScopeForVarDecl(VD);
1361    addAutomaticObjDtors(ScopePos, BeginScopePos, I);
1362  }
1363
1364  // The block we were proccessing is now finished.  Make it the successor
1365  // block.
1366  if (Block) {
1367    Succ = Block;
1368    if (badCFG)
1369      return 0;
1370  }
1371
1372  // Process the false branch.
1373  CFGBlock* ElseBlock = Succ;
1374
1375  if (Stmt* Else = I->getElse()) {
1376    SaveAndRestore<CFGBlock*> sv(Succ);
1377
1378    // NULL out Block so that the recursive call to Visit will
1379    // create a new basic block.
1380    Block = NULL;
1381
1382    // If branch is not a compound statement create implicit scope
1383    // and add destructors.
1384    if (!isa<CompoundStmt>(Else))
1385      addLocalScopeAndDtors(Else);
1386
1387    ElseBlock = addStmt(Else);
1388
1389    if (!ElseBlock) // Can occur when the Else body has all NullStmts.
1390      ElseBlock = sv.get();
1391    else if (Block) {
1392      if (badCFG)
1393        return 0;
1394    }
1395  }
1396
1397  // Process the true branch.
1398  CFGBlock* ThenBlock;
1399  {
1400    Stmt* Then = I->getThen();
1401    assert(Then);
1402    SaveAndRestore<CFGBlock*> sv(Succ);
1403    Block = NULL;
1404
1405    // If branch is not a compound statement create implicit scope
1406    // and add destructors.
1407    if (!isa<CompoundStmt>(Then))
1408      addLocalScopeAndDtors(Then);
1409
1410    ThenBlock = addStmt(Then);
1411
1412    if (!ThenBlock) {
1413      // We can reach here if the "then" body has all NullStmts.
1414      // Create an empty block so we can distinguish between true and false
1415      // branches in path-sensitive analyses.
1416      ThenBlock = createBlock(false);
1417      addSuccessor(ThenBlock, sv.get());
1418    } else if (Block) {
1419      if (badCFG)
1420        return 0;
1421    }
1422  }
1423
1424  // Now create a new block containing the if statement.
1425  Block = createBlock(false);
1426
1427  // Set the terminator of the new block to the If statement.
1428  Block->setTerminator(I);
1429
1430  // See if this is a known constant.
1431  const TryResult &KnownVal = tryEvaluateBool(I->getCond());
1432
1433  // Now add the successors.
1434  addSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
1435  addSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
1436
1437  // Add the condition as the last statement in the new block.  This may create
1438  // new blocks as the condition may contain control-flow.  Any newly created
1439  // blocks will be pointed to be "Block".
1440  Block = addStmt(I->getCond());
1441
1442  // Finally, if the IfStmt contains a condition variable, add both the IfStmt
1443  // and the condition variable initialization to the CFG.
1444  if (VarDecl *VD = I->getConditionVariable()) {
1445    if (Expr *Init = VD->getInit()) {
1446      autoCreateBlock();
1447      appendStmt(Block, I);
1448      addStmt(Init);
1449    }
1450  }
1451
1452  return Block;
1453}
1454
1455
1456CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
1457  // If we were in the middle of a block we stop processing that block.
1458  //
1459  // NOTE: If a "return" appears in the middle of a block, this means that the
1460  //       code afterwards is DEAD (unreachable).  We still keep a basic block
1461  //       for that code; a simple "mark-and-sweep" from the entry block will be
1462  //       able to report such dead blocks.
1463
1464  // Create the new block.
1465  Block = createBlock(false);
1466
1467  // The Exit block is the only successor.
1468  addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
1469  addSuccessor(Block, &cfg->getExit());
1470
1471  // Add the return statement to the block.  This may create new blocks if R
1472  // contains control-flow (short-circuit operations).
1473  return VisitStmt(R, AddStmtChoice::AlwaysAdd);
1474}
1475
1476CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt *L) {
1477  // Get the block of the labeled statement.  Add it to our map.
1478  addStmt(L->getSubStmt());
1479  CFGBlock *LabelBlock = Block;
1480
1481  if (!LabelBlock)              // This can happen when the body is empty, i.e.
1482    LabelBlock = createBlock(); // scopes that only contains NullStmts.
1483
1484  assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
1485         "label already in map");
1486  LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
1487
1488  // Labels partition blocks, so this is the end of the basic block we were
1489  // processing (L is the block's label).  Because this is label (and we have
1490  // already processed the substatement) there is no extra control-flow to worry
1491  // about.
1492  LabelBlock->setLabel(L);
1493  if (badCFG)
1494    return 0;
1495
1496  // We set Block to NULL to allow lazy creation of a new block (if necessary);
1497  Block = NULL;
1498
1499  // This block is now the implicit successor of other blocks.
1500  Succ = LabelBlock;
1501
1502  return LabelBlock;
1503}
1504
1505CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
1506  // Goto is a control-flow statement.  Thus we stop processing the current
1507  // block and create a new one.
1508
1509  Block = createBlock(false);
1510  Block->setTerminator(G);
1511
1512  // If we already know the mapping to the label block add the successor now.
1513  LabelMapTy::iterator I = LabelMap.find(G->getLabel());
1514
1515  if (I == LabelMap.end())
1516    // We will need to backpatch this block later.
1517    BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
1518  else {
1519    JumpTarget JT = I->second;
1520    addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
1521    addSuccessor(Block, JT.block);
1522  }
1523
1524  return Block;
1525}
1526
1527CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
1528  CFGBlock* LoopSuccessor = NULL;
1529
1530  // Save local scope position because in case of condition variable ScopePos
1531  // won't be restored when traversing AST.
1532  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1533
1534  // Create local scope for init statement and possible condition variable.
1535  // Add destructor for init statement and condition variable.
1536  // Store scope position for continue statement.
1537  if (Stmt* Init = F->getInit())
1538    addLocalScopeForStmt(Init);
1539  LocalScope::const_iterator LoopBeginScopePos = ScopePos;
1540
1541  if (VarDecl* VD = F->getConditionVariable())
1542    addLocalScopeForVarDecl(VD);
1543  LocalScope::const_iterator ContinueScopePos = ScopePos;
1544
1545  addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
1546
1547  // "for" is a control-flow statement.  Thus we stop processing the current
1548  // block.
1549  if (Block) {
1550    if (badCFG)
1551      return 0;
1552    LoopSuccessor = Block;
1553  } else
1554    LoopSuccessor = Succ;
1555
1556  // Save the current value for the break targets.
1557  // All breaks should go to the code following the loop.
1558  SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
1559  BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1560
1561  // Because of short-circuit evaluation, the condition of the loop can span
1562  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1563  // evaluate the condition.
1564  CFGBlock* ExitConditionBlock = createBlock(false);
1565  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1566
1567  // Set the terminator for the "exit" condition block.
1568  ExitConditionBlock->setTerminator(F);
1569
1570  // Now add the actual condition to the condition block.  Because the condition
1571  // itself may contain control-flow, new blocks may be created.
1572  if (Stmt* C = F->getCond()) {
1573    Block = ExitConditionBlock;
1574    EntryConditionBlock = addStmt(C);
1575    if (badCFG)
1576      return 0;
1577    assert(Block == EntryConditionBlock ||
1578           (Block == 0 && EntryConditionBlock == Succ));
1579
1580    // If this block contains a condition variable, add both the condition
1581    // variable and initializer to the CFG.
1582    if (VarDecl *VD = F->getConditionVariable()) {
1583      if (Expr *Init = VD->getInit()) {
1584        autoCreateBlock();
1585        appendStmt(Block, F);
1586        EntryConditionBlock = addStmt(Init);
1587        assert(Block == EntryConditionBlock);
1588      }
1589    }
1590
1591    if (Block) {
1592      if (badCFG)
1593        return 0;
1594    }
1595  }
1596
1597  // The condition block is the implicit successor for the loop body as well as
1598  // any code above the loop.
1599  Succ = EntryConditionBlock;
1600
1601  // See if this is a known constant.
1602  TryResult KnownVal(true);
1603
1604  if (F->getCond())
1605    KnownVal = tryEvaluateBool(F->getCond());
1606
1607  // Now create the loop body.
1608  {
1609    assert(F->getBody());
1610
1611   // Save the current values for Block, Succ, and continue targets.
1612   SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
1613   SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
1614
1615    // Create a new block to contain the (bottom) of the loop body.
1616    Block = NULL;
1617
1618    // Loop body should end with destructor of Condition variable (if any).
1619    addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
1620
1621    if (Stmt* I = F->getInc()) {
1622      // Generate increment code in its own basic block.  This is the target of
1623      // continue statements.
1624      Succ = addStmt(I);
1625    } else {
1626      // No increment code.  Create a special, empty, block that is used as the
1627      // target block for "looping back" to the start of the loop.
1628      assert(Succ == EntryConditionBlock);
1629      Succ = Block ? Block : createBlock();
1630    }
1631
1632    // Finish up the increment (or empty) block if it hasn't been already.
1633    if (Block) {
1634      assert(Block == Succ);
1635      if (badCFG)
1636        return 0;
1637      Block = 0;
1638    }
1639
1640    ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
1641
1642    // The starting block for the loop increment is the block that should
1643    // represent the 'loop target' for looping back to the start of the loop.
1644    ContinueJumpTarget.block->setLoopTarget(F);
1645
1646    // If body is not a compound statement create implicit scope
1647    // and add destructors.
1648    if (!isa<CompoundStmt>(F->getBody()))
1649      addLocalScopeAndDtors(F->getBody());
1650
1651    // Now populate the body block, and in the process create new blocks as we
1652    // walk the body of the loop.
1653    CFGBlock* BodyBlock = addStmt(F->getBody());
1654
1655    if (!BodyBlock)
1656      BodyBlock = ContinueJumpTarget.block;//can happen for "for (...;...;...);"
1657    else if (badCFG)
1658      return 0;
1659
1660    // This new body block is a successor to our "exit" condition block.
1661    addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1662  }
1663
1664  // Link up the condition block with the code that follows the loop.  (the
1665  // false branch).
1666  addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1667
1668  // If the loop contains initialization, create a new block for those
1669  // statements.  This block can also contain statements that precede the loop.
1670  if (Stmt* I = F->getInit()) {
1671    Block = createBlock();
1672    return addStmt(I);
1673  }
1674
1675  // There is no loop initialization.  We are thus basically a while loop.
1676  // NULL out Block to force lazy block construction.
1677  Block = NULL;
1678  Succ = EntryConditionBlock;
1679  return EntryConditionBlock;
1680}
1681
1682CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
1683  if (asc.alwaysAdd()) {
1684    autoCreateBlock();
1685    appendStmt(Block, M);
1686  }
1687  return Visit(M->getBase());
1688}
1689
1690CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
1691  // Objective-C fast enumeration 'for' statements:
1692  //  http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
1693  //
1694  //  for ( Type newVariable in collection_expression ) { statements }
1695  //
1696  //  becomes:
1697  //
1698  //   prologue:
1699  //     1. collection_expression
1700  //     T. jump to loop_entry
1701  //   loop_entry:
1702  //     1. side-effects of element expression
1703  //     1. ObjCForCollectionStmt [performs binding to newVariable]
1704  //     T. ObjCForCollectionStmt  TB, FB  [jumps to TB if newVariable != nil]
1705  //   TB:
1706  //     statements
1707  //     T. jump to loop_entry
1708  //   FB:
1709  //     what comes after
1710  //
1711  //  and
1712  //
1713  //  Type existingItem;
1714  //  for ( existingItem in expression ) { statements }
1715  //
1716  //  becomes:
1717  //
1718  //   the same with newVariable replaced with existingItem; the binding works
1719  //   the same except that for one ObjCForCollectionStmt::getElement() returns
1720  //   a DeclStmt and the other returns a DeclRefExpr.
1721  //
1722
1723  CFGBlock* LoopSuccessor = 0;
1724
1725  if (Block) {
1726    if (badCFG)
1727      return 0;
1728    LoopSuccessor = Block;
1729    Block = 0;
1730  } else
1731    LoopSuccessor = Succ;
1732
1733  // Build the condition blocks.
1734  CFGBlock* ExitConditionBlock = createBlock(false);
1735  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1736
1737  // Set the terminator for the "exit" condition block.
1738  ExitConditionBlock->setTerminator(S);
1739
1740  // The last statement in the block should be the ObjCForCollectionStmt, which
1741  // performs the actual binding to 'element' and determines if there are any
1742  // more items in the collection.
1743  appendStmt(ExitConditionBlock, S);
1744  Block = ExitConditionBlock;
1745
1746  // Walk the 'element' expression to see if there are any side-effects.  We
1747  // generate new blocks as necesary.  We DON'T add the statement by default to
1748  // the CFG unless it contains control-flow.
1749  EntryConditionBlock = Visit(S->getElement(), AddStmtChoice::NotAlwaysAdd);
1750  if (Block) {
1751    if (badCFG)
1752      return 0;
1753    Block = 0;
1754  }
1755
1756  // The condition block is the implicit successor for the loop body as well as
1757  // any code above the loop.
1758  Succ = EntryConditionBlock;
1759
1760  // Now create the true branch.
1761  {
1762    // Save the current values for Succ, continue and break targets.
1763    SaveAndRestore<CFGBlock*> save_Succ(Succ);
1764    SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
1765        save_break(BreakJumpTarget);
1766
1767    BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1768    ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
1769
1770    CFGBlock* BodyBlock = addStmt(S->getBody());
1771
1772    if (!BodyBlock)
1773      BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
1774    else if (Block) {
1775      if (badCFG)
1776        return 0;
1777    }
1778
1779    // This new body block is a successor to our "exit" condition block.
1780    addSuccessor(ExitConditionBlock, BodyBlock);
1781  }
1782
1783  // Link up the condition block with the code that follows the loop.
1784  // (the false branch).
1785  addSuccessor(ExitConditionBlock, LoopSuccessor);
1786
1787  // Now create a prologue block to contain the collection expression.
1788  Block = createBlock();
1789  return addStmt(S->getCollection());
1790}
1791
1792CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
1793  // FIXME: Add locking 'primitives' to CFG for @synchronized.
1794
1795  // Inline the body.
1796  CFGBlock *SyncBlock = addStmt(S->getSynchBody());
1797
1798  // The sync body starts its own basic block.  This makes it a little easier
1799  // for diagnostic clients.
1800  if (SyncBlock) {
1801    if (badCFG)
1802      return 0;
1803
1804    Block = 0;
1805    Succ = SyncBlock;
1806  }
1807
1808  // Add the @synchronized to the CFG.
1809  autoCreateBlock();
1810  appendStmt(Block, S);
1811
1812  // Inline the sync expression.
1813  return addStmt(S->getSynchExpr());
1814}
1815
1816CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
1817  // FIXME
1818  return NYS();
1819}
1820
1821CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
1822  CFGBlock* LoopSuccessor = NULL;
1823
1824  // Save local scope position because in case of condition variable ScopePos
1825  // won't be restored when traversing AST.
1826  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1827
1828  // Create local scope for possible condition variable.
1829  // Store scope position for continue statement.
1830  LocalScope::const_iterator LoopBeginScopePos = ScopePos;
1831  if (VarDecl* VD = W->getConditionVariable()) {
1832    addLocalScopeForVarDecl(VD);
1833    addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
1834  }
1835
1836  // "while" is a control-flow statement.  Thus we stop processing the current
1837  // block.
1838  if (Block) {
1839    if (badCFG)
1840      return 0;
1841    LoopSuccessor = Block;
1842    Block = 0;
1843  } else
1844    LoopSuccessor = Succ;
1845
1846  // Because of short-circuit evaluation, the condition of the loop can span
1847  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1848  // evaluate the condition.
1849  CFGBlock* ExitConditionBlock = createBlock(false);
1850  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1851
1852  // Set the terminator for the "exit" condition block.
1853  ExitConditionBlock->setTerminator(W);
1854
1855  // Now add the actual condition to the condition block.  Because the condition
1856  // itself may contain control-flow, new blocks may be created.  Thus we update
1857  // "Succ" after adding the condition.
1858  if (Stmt* C = W->getCond()) {
1859    Block = ExitConditionBlock;
1860    EntryConditionBlock = addStmt(C);
1861    // The condition might finish the current 'Block'.
1862    Block = EntryConditionBlock;
1863
1864    // If this block contains a condition variable, add both the condition
1865    // variable and initializer to the CFG.
1866    if (VarDecl *VD = W->getConditionVariable()) {
1867      if (Expr *Init = VD->getInit()) {
1868        autoCreateBlock();
1869        appendStmt(Block, W);
1870        EntryConditionBlock = addStmt(Init);
1871        assert(Block == EntryConditionBlock);
1872      }
1873    }
1874
1875    if (Block) {
1876      if (badCFG)
1877        return 0;
1878    }
1879  }
1880
1881  // The condition block is the implicit successor for the loop body as well as
1882  // any code above the loop.
1883  Succ = EntryConditionBlock;
1884
1885  // See if this is a known constant.
1886  const TryResult& KnownVal = tryEvaluateBool(W->getCond());
1887
1888  // Process the loop body.
1889  {
1890    assert(W->getBody());
1891
1892    // Save the current values for Block, Succ, and continue and break targets
1893    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
1894    SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
1895        save_break(BreakJumpTarget);
1896
1897    // Create an empty block to represent the transition block for looping back
1898    // to the head of the loop.
1899    Block = 0;
1900    assert(Succ == EntryConditionBlock);
1901    Succ = createBlock();
1902    Succ->setLoopTarget(W);
1903    ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
1904
1905    // All breaks should go to the code following the loop.
1906    BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1907
1908    // NULL out Block to force lazy instantiation of blocks for the body.
1909    Block = NULL;
1910
1911    // Loop body should end with destructor of Condition variable (if any).
1912    addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
1913
1914    // If body is not a compound statement create implicit scope
1915    // and add destructors.
1916    if (!isa<CompoundStmt>(W->getBody()))
1917      addLocalScopeAndDtors(W->getBody());
1918
1919    // Create the body.  The returned block is the entry to the loop body.
1920    CFGBlock* BodyBlock = addStmt(W->getBody());
1921
1922    if (!BodyBlock)
1923      BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
1924    else if (Block) {
1925      if (badCFG)
1926        return 0;
1927    }
1928
1929    // Add the loop body entry as a successor to the condition.
1930    addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1931  }
1932
1933  // Link up the condition block with the code that follows the loop.  (the
1934  // false branch).
1935  addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1936
1937  // There can be no more statements in the condition block since we loop back
1938  // to this block.  NULL out Block to force lazy creation of another block.
1939  Block = NULL;
1940
1941  // Return the condition block, which is the dominating block for the loop.
1942  Succ = EntryConditionBlock;
1943  return EntryConditionBlock;
1944}
1945
1946
1947CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
1948  // FIXME: For now we pretend that @catch and the code it contains does not
1949  //  exit.
1950  return Block;
1951}
1952
1953CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1954  // FIXME: This isn't complete.  We basically treat @throw like a return
1955  //  statement.
1956
1957  // If we were in the middle of a block we stop processing that block.
1958  if (badCFG)
1959    return 0;
1960
1961  // Create the new block.
1962  Block = createBlock(false);
1963
1964  // The Exit block is the only successor.
1965  addSuccessor(Block, &cfg->getExit());
1966
1967  // Add the statement to the block.  This may create new blocks if S contains
1968  // control-flow (short-circuit operations).
1969  return VisitStmt(S, AddStmtChoice::AlwaysAdd);
1970}
1971
1972CFGBlock* CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr* T) {
1973  // If we were in the middle of a block we stop processing that block.
1974  if (badCFG)
1975    return 0;
1976
1977  // Create the new block.
1978  Block = createBlock(false);
1979
1980  if (TryTerminatedBlock)
1981    // The current try statement is the only successor.
1982    addSuccessor(Block, TryTerminatedBlock);
1983  else
1984    // otherwise the Exit block is the only successor.
1985    addSuccessor(Block, &cfg->getExit());
1986
1987  // Add the statement to the block.  This may create new blocks if S contains
1988  // control-flow (short-circuit operations).
1989  return VisitStmt(T, AddStmtChoice::AlwaysAdd);
1990}
1991
1992CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) {
1993  CFGBlock* LoopSuccessor = NULL;
1994
1995  // "do...while" is a control-flow statement.  Thus we stop processing the
1996  // current block.
1997  if (Block) {
1998    if (badCFG)
1999      return 0;
2000    LoopSuccessor = Block;
2001  } else
2002    LoopSuccessor = Succ;
2003
2004  // Because of short-circuit evaluation, the condition of the loop can span
2005  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
2006  // evaluate the condition.
2007  CFGBlock* ExitConditionBlock = createBlock(false);
2008  CFGBlock* EntryConditionBlock = ExitConditionBlock;
2009
2010  // Set the terminator for the "exit" condition block.
2011  ExitConditionBlock->setTerminator(D);
2012
2013  // Now add the actual condition to the condition block.  Because the condition
2014  // itself may contain control-flow, new blocks may be created.
2015  if (Stmt* C = D->getCond()) {
2016    Block = ExitConditionBlock;
2017    EntryConditionBlock = addStmt(C);
2018    if (Block) {
2019      if (badCFG)
2020        return 0;
2021    }
2022  }
2023
2024  // The condition block is the implicit successor for the loop body.
2025  Succ = EntryConditionBlock;
2026
2027  // See if this is a known constant.
2028  const TryResult &KnownVal = tryEvaluateBool(D->getCond());
2029
2030  // Process the loop body.
2031  CFGBlock* BodyBlock = NULL;
2032  {
2033    assert(D->getBody());
2034
2035    // Save the current values for Block, Succ, and continue and break targets
2036    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2037    SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2038        save_break(BreakJumpTarget);
2039
2040    // All continues within this loop should go to the condition block
2041    ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
2042
2043    // All breaks should go to the code following the loop.
2044    BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2045
2046    // NULL out Block to force lazy instantiation of blocks for the body.
2047    Block = NULL;
2048
2049    // If body is not a compound statement create implicit scope
2050    // and add destructors.
2051    if (!isa<CompoundStmt>(D->getBody()))
2052      addLocalScopeAndDtors(D->getBody());
2053
2054    // Create the body.  The returned block is the entry to the loop body.
2055    BodyBlock = addStmt(D->getBody());
2056
2057    if (!BodyBlock)
2058      BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
2059    else if (Block) {
2060      if (badCFG)
2061        return 0;
2062    }
2063
2064    if (!KnownVal.isFalse()) {
2065      // Add an intermediate block between the BodyBlock and the
2066      // ExitConditionBlock to represent the "loop back" transition.  Create an
2067      // empty block to represent the transition block for looping back to the
2068      // head of the loop.
2069      // FIXME: Can we do this more efficiently without adding another block?
2070      Block = NULL;
2071      Succ = BodyBlock;
2072      CFGBlock *LoopBackBlock = createBlock();
2073      LoopBackBlock->setLoopTarget(D);
2074
2075      // Add the loop body entry as a successor to the condition.
2076      addSuccessor(ExitConditionBlock, LoopBackBlock);
2077    }
2078    else
2079      addSuccessor(ExitConditionBlock, NULL);
2080  }
2081
2082  // Link up the condition block with the code that follows the loop.
2083  // (the false branch).
2084  addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
2085
2086  // There can be no more statements in the body block(s) since we loop back to
2087  // the body.  NULL out Block to force lazy creation of another block.
2088  Block = NULL;
2089
2090  // Return the loop body, which is the dominating block for the loop.
2091  Succ = BodyBlock;
2092  return BodyBlock;
2093}
2094
2095CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
2096  // "continue" is a control-flow statement.  Thus we stop processing the
2097  // current block.
2098  if (badCFG)
2099    return 0;
2100
2101  // Now create a new block that ends with the continue statement.
2102  Block = createBlock(false);
2103  Block->setTerminator(C);
2104
2105  // If there is no target for the continue, then we are looking at an
2106  // incomplete AST.  This means the CFG cannot be constructed.
2107  if (ContinueJumpTarget.block) {
2108    addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
2109    addSuccessor(Block, ContinueJumpTarget.block);
2110  } else
2111    badCFG = true;
2112
2113  return Block;
2114}
2115
2116CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E,
2117                                             AddStmtChoice asc) {
2118
2119  if (asc.alwaysAdd()) {
2120    autoCreateBlock();
2121    appendStmt(Block, E);
2122  }
2123
2124  // VLA types have expressions that must be evaluated.
2125  if (E->isArgumentType()) {
2126    for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
2127         VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
2128      addStmt(VA->getSizeExpr());
2129  }
2130
2131  return Block;
2132}
2133
2134/// VisitStmtExpr - Utility method to handle (nested) statement
2135///  expressions (a GCC extension).
2136CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
2137  if (asc.alwaysAdd()) {
2138    autoCreateBlock();
2139    appendStmt(Block, SE);
2140  }
2141  return VisitCompoundStmt(SE->getSubStmt());
2142}
2143
2144CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
2145  // "switch" is a control-flow statement.  Thus we stop processing the current
2146  // block.
2147  CFGBlock* SwitchSuccessor = NULL;
2148
2149  // Save local scope position because in case of condition variable ScopePos
2150  // won't be restored when traversing AST.
2151  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2152
2153  // Create local scope for possible condition variable.
2154  // Store scope position. Add implicit destructor.
2155  if (VarDecl* VD = Terminator->getConditionVariable()) {
2156    LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
2157    addLocalScopeForVarDecl(VD);
2158    addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
2159  }
2160
2161  if (Block) {
2162    if (badCFG)
2163      return 0;
2164    SwitchSuccessor = Block;
2165  } else SwitchSuccessor = Succ;
2166
2167  // Save the current "switch" context.
2168  SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
2169                            save_default(DefaultCaseBlock);
2170  SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2171
2172  // Set the "default" case to be the block after the switch statement.  If the
2173  // switch statement contains a "default:", this value will be overwritten with
2174  // the block for that code.
2175  DefaultCaseBlock = SwitchSuccessor;
2176
2177  // Create a new block that will contain the switch statement.
2178  SwitchTerminatedBlock = createBlock(false);
2179
2180  // Now process the switch body.  The code after the switch is the implicit
2181  // successor.
2182  Succ = SwitchSuccessor;
2183  BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
2184
2185  // When visiting the body, the case statements should automatically get linked
2186  // up to the switch.  We also don't keep a pointer to the body, since all
2187  // control-flow from the switch goes to case/default statements.
2188  assert(Terminator->getBody() && "switch must contain a non-NULL body");
2189  Block = NULL;
2190
2191  // For pruning unreachable case statements, save the current state
2192  // for tracking the condition value.
2193  SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
2194                                                     false);
2195
2196  // Determine if the switch condition can be explicitly evaluated.
2197  assert(Terminator->getCond() && "switch condition must be non-NULL");
2198  Expr::EvalResult result;
2199  tryEvaluate(Terminator->getCond(), result);
2200  SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond, &result);
2201
2202  // If body is not a compound statement create implicit scope
2203  // and add destructors.
2204  if (!isa<CompoundStmt>(Terminator->getBody()))
2205    addLocalScopeAndDtors(Terminator->getBody());
2206
2207  addStmt(Terminator->getBody());
2208  if (Block) {
2209    if (badCFG)
2210      return 0;
2211  }
2212
2213  // If we have no "default:" case, the default transition is to the code
2214  // following the switch body.
2215  addSuccessor(SwitchTerminatedBlock,
2216               switchExclusivelyCovered ? 0 : DefaultCaseBlock);
2217
2218  // Add the terminator and condition in the switch block.
2219  SwitchTerminatedBlock->setTerminator(Terminator);
2220  Block = SwitchTerminatedBlock;
2221  Block = addStmt(Terminator->getCond());
2222
2223  // Finally, if the SwitchStmt contains a condition variable, add both the
2224  // SwitchStmt and the condition variable initialization to the CFG.
2225  if (VarDecl *VD = Terminator->getConditionVariable()) {
2226    if (Expr *Init = VD->getInit()) {
2227      autoCreateBlock();
2228      appendStmt(Block, Terminator);
2229      addStmt(Init);
2230    }
2231  }
2232
2233  return Block;
2234}
2235
2236static bool shouldAddCase(bool &switchExclusivelyCovered,
2237                          const Expr::EvalResult &switchCond,
2238                          const CaseStmt *CS,
2239                          ASTContext &Ctx) {
2240  bool addCase = false;
2241
2242  if (!switchExclusivelyCovered) {
2243    if (switchCond.Val.isInt()) {
2244      // Evaluate the LHS of the case value.
2245      Expr::EvalResult V1;
2246      CS->getLHS()->Evaluate(V1, Ctx);
2247      assert(V1.Val.isInt());
2248      const llvm::APSInt &condInt = switchCond.Val.getInt();
2249      const llvm::APSInt &lhsInt = V1.Val.getInt();
2250
2251      if (condInt == lhsInt) {
2252        addCase = true;
2253        switchExclusivelyCovered = true;
2254      }
2255      else if (condInt < lhsInt) {
2256        if (const Expr *RHS = CS->getRHS()) {
2257          // Evaluate the RHS of the case value.
2258          Expr::EvalResult V2;
2259          RHS->Evaluate(V2, Ctx);
2260          assert(V2.Val.isInt());
2261          if (V2.Val.getInt() <= condInt) {
2262            addCase = true;
2263            switchExclusivelyCovered = true;
2264          }
2265        }
2266      }
2267    }
2268    else
2269      addCase = true;
2270  }
2271  return addCase;
2272}
2273
2274CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) {
2275  // CaseStmts are essentially labels, so they are the first statement in a
2276  // block.
2277  CFGBlock *TopBlock = 0, *LastBlock = 0;
2278  assert(switchCond);
2279
2280  if (Stmt *Sub = CS->getSubStmt()) {
2281    // For deeply nested chains of CaseStmts, instead of doing a recursion
2282    // (which can blow out the stack), manually unroll and create blocks
2283    // along the way.
2284    while (isa<CaseStmt>(Sub)) {
2285      CFGBlock *currentBlock = createBlock(false);
2286      currentBlock->setLabel(CS);
2287
2288      if (TopBlock)
2289        addSuccessor(LastBlock, currentBlock);
2290      else
2291        TopBlock = currentBlock;
2292
2293      addSuccessor(SwitchTerminatedBlock,
2294                   shouldAddCase(switchExclusivelyCovered, *switchCond,
2295                                 CS, *Context)
2296                   ? currentBlock : 0);
2297
2298      LastBlock = currentBlock;
2299      CS = cast<CaseStmt>(Sub);
2300      Sub = CS->getSubStmt();
2301    }
2302
2303    addStmt(Sub);
2304  }
2305
2306  CFGBlock* CaseBlock = Block;
2307  if (!CaseBlock)
2308    CaseBlock = createBlock();
2309
2310  // Cases statements partition blocks, so this is the top of the basic block we
2311  // were processing (the "case XXX:" is the label).
2312  CaseBlock->setLabel(CS);
2313
2314  if (badCFG)
2315    return 0;
2316
2317  // Add this block to the list of successors for the block with the switch
2318  // statement.
2319  assert(SwitchTerminatedBlock);
2320  addSuccessor(SwitchTerminatedBlock,
2321               shouldAddCase(switchExclusivelyCovered, *switchCond,
2322                             CS, *Context)
2323               ? CaseBlock : 0);
2324
2325  // We set Block to NULL to allow lazy creation of a new block (if necessary)
2326  Block = NULL;
2327
2328  if (TopBlock) {
2329    addSuccessor(LastBlock, CaseBlock);
2330    Succ = TopBlock;
2331  } else {
2332    // This block is now the implicit successor of other blocks.
2333    Succ = CaseBlock;
2334  }
2335
2336  return Succ;
2337}
2338
2339CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
2340  if (Terminator->getSubStmt())
2341    addStmt(Terminator->getSubStmt());
2342
2343  DefaultCaseBlock = Block;
2344
2345  if (!DefaultCaseBlock)
2346    DefaultCaseBlock = createBlock();
2347
2348  // Default statements partition blocks, so this is the top of the basic block
2349  // we were processing (the "default:" is the label).
2350  DefaultCaseBlock->setLabel(Terminator);
2351
2352  if (badCFG)
2353    return 0;
2354
2355  // Unlike case statements, we don't add the default block to the successors
2356  // for the switch statement immediately.  This is done when we finish
2357  // processing the switch statement.  This allows for the default case
2358  // (including a fall-through to the code after the switch statement) to always
2359  // be the last successor of a switch-terminated block.
2360
2361  // We set Block to NULL to allow lazy creation of a new block (if necessary)
2362  Block = NULL;
2363
2364  // This block is now the implicit successor of other blocks.
2365  Succ = DefaultCaseBlock;
2366
2367  return DefaultCaseBlock;
2368}
2369
2370CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
2371  // "try"/"catch" is a control-flow statement.  Thus we stop processing the
2372  // current block.
2373  CFGBlock* TrySuccessor = NULL;
2374
2375  if (Block) {
2376    if (badCFG)
2377      return 0;
2378    TrySuccessor = Block;
2379  } else TrySuccessor = Succ;
2380
2381  CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
2382
2383  // Create a new block that will contain the try statement.
2384  CFGBlock *NewTryTerminatedBlock = createBlock(false);
2385  // Add the terminator in the try block.
2386  NewTryTerminatedBlock->setTerminator(Terminator);
2387
2388  bool HasCatchAll = false;
2389  for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
2390    // The code after the try is the implicit successor.
2391    Succ = TrySuccessor;
2392    CXXCatchStmt *CS = Terminator->getHandler(h);
2393    if (CS->getExceptionDecl() == 0) {
2394      HasCatchAll = true;
2395    }
2396    Block = NULL;
2397    CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
2398    if (CatchBlock == 0)
2399      return 0;
2400    // Add this block to the list of successors for the block with the try
2401    // statement.
2402    addSuccessor(NewTryTerminatedBlock, CatchBlock);
2403  }
2404  if (!HasCatchAll) {
2405    if (PrevTryTerminatedBlock)
2406      addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
2407    else
2408      addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2409  }
2410
2411  // The code after the try is the implicit successor.
2412  Succ = TrySuccessor;
2413
2414  // Save the current "try" context.
2415  SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock);
2416  TryTerminatedBlock = NewTryTerminatedBlock;
2417
2418  assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
2419  Block = NULL;
2420  Block = addStmt(Terminator->getTryBlock());
2421  return Block;
2422}
2423
2424CFGBlock* CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt* CS) {
2425  // CXXCatchStmt are treated like labels, so they are the first statement in a
2426  // block.
2427
2428  // Save local scope position because in case of exception variable ScopePos
2429  // won't be restored when traversing AST.
2430  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2431
2432  // Create local scope for possible exception variable.
2433  // Store scope position. Add implicit destructor.
2434  if (VarDecl* VD = CS->getExceptionDecl()) {
2435    LocalScope::const_iterator BeginScopePos = ScopePos;
2436    addLocalScopeForVarDecl(VD);
2437    addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
2438  }
2439
2440  if (CS->getHandlerBlock())
2441    addStmt(CS->getHandlerBlock());
2442
2443  CFGBlock* CatchBlock = Block;
2444  if (!CatchBlock)
2445    CatchBlock = createBlock();
2446
2447  CatchBlock->setLabel(CS);
2448
2449  if (badCFG)
2450    return 0;
2451
2452  // We set Block to NULL to allow lazy creation of a new block (if necessary)
2453  Block = NULL;
2454
2455  return CatchBlock;
2456}
2457
2458CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
2459    AddStmtChoice asc) {
2460  if (BuildOpts.AddImplicitDtors) {
2461    // If adding implicit destructors visit the full expression for adding
2462    // destructors of temporaries.
2463    VisitForTemporaryDtors(E->getSubExpr());
2464
2465    // Full expression has to be added as CFGStmt so it will be sequenced
2466    // before destructors of it's temporaries.
2467    asc = asc.withAlwaysAdd(true);
2468  }
2469  return Visit(E->getSubExpr(), asc);
2470}
2471
2472CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
2473                                                AddStmtChoice asc) {
2474  if (asc.alwaysAdd()) {
2475    autoCreateBlock();
2476    appendStmt(Block, E);
2477
2478    // We do not want to propagate the AlwaysAdd property.
2479    asc = asc.withAlwaysAdd(false);
2480  }
2481  return Visit(E->getSubExpr(), asc);
2482}
2483
2484CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
2485                                            AddStmtChoice asc) {
2486  autoCreateBlock();
2487  if (!C->isElidable())
2488    appendStmt(Block, C);
2489
2490  return VisitChildren(C);
2491}
2492
2493CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
2494                                                 AddStmtChoice asc) {
2495  if (asc.alwaysAdd()) {
2496    autoCreateBlock();
2497    appendStmt(Block, E);
2498    // We do not want to propagate the AlwaysAdd property.
2499    asc = asc.withAlwaysAdd(false);
2500  }
2501  return Visit(E->getSubExpr(), asc);
2502}
2503
2504CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
2505                                                  AddStmtChoice asc) {
2506  autoCreateBlock();
2507  appendStmt(Block, C);
2508  return VisitChildren(C);
2509}
2510
2511CFGBlock *CFGBuilder::VisitCXXMemberCallExpr(CXXMemberCallExpr *C,
2512                                             AddStmtChoice asc) {
2513  autoCreateBlock();
2514  appendStmt(Block, C);
2515  return VisitChildren(C);
2516}
2517
2518CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
2519                                            AddStmtChoice asc) {
2520  if (asc.alwaysAdd()) {
2521    autoCreateBlock();
2522    appendStmt(Block, E);
2523  }
2524  return Visit(E->getSubExpr(), AddStmtChoice());
2525}
2526
2527CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
2528  // Lazily create the indirect-goto dispatch block if there isn't one already.
2529  CFGBlock* IBlock = cfg->getIndirectGotoBlock();
2530
2531  if (!IBlock) {
2532    IBlock = createBlock(false);
2533    cfg->setIndirectGotoBlock(IBlock);
2534  }
2535
2536  // IndirectGoto is a control-flow statement.  Thus we stop processing the
2537  // current block and create a new one.
2538  if (badCFG)
2539    return 0;
2540
2541  Block = createBlock(false);
2542  Block->setTerminator(I);
2543  addSuccessor(Block, IBlock);
2544  return addStmt(I->getTarget());
2545}
2546
2547CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) {
2548tryAgain:
2549  if (!E) {
2550    badCFG = true;
2551    return NULL;
2552  }
2553  switch (E->getStmtClass()) {
2554    default:
2555      return VisitChildrenForTemporaryDtors(E);
2556
2557    case Stmt::BinaryOperatorClass:
2558      return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E));
2559
2560    case Stmt::CXXBindTemporaryExprClass:
2561      return VisitCXXBindTemporaryExprForTemporaryDtors(
2562          cast<CXXBindTemporaryExpr>(E), BindToTemporary);
2563
2564    case Stmt::BinaryConditionalOperatorClass:
2565    case Stmt::ConditionalOperatorClass:
2566      return VisitConditionalOperatorForTemporaryDtors(
2567          cast<AbstractConditionalOperator>(E), BindToTemporary);
2568
2569    case Stmt::ImplicitCastExprClass:
2570      // For implicit cast we want BindToTemporary to be passed further.
2571      E = cast<CastExpr>(E)->getSubExpr();
2572      goto tryAgain;
2573
2574    case Stmt::ParenExprClass:
2575      E = cast<ParenExpr>(E)->getSubExpr();
2576      goto tryAgain;
2577  }
2578}
2579
2580CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) {
2581  // When visiting children for destructors we want to visit them in reverse
2582  // order. Because there's no reverse iterator for children must to reverse
2583  // them in helper vector.
2584  typedef llvm::SmallVector<Stmt *, 4> ChildrenVect;
2585  ChildrenVect ChildrenRev;
2586  for (Stmt::child_range I = E->children(); I; ++I) {
2587    if (*I) ChildrenRev.push_back(*I);
2588  }
2589
2590  CFGBlock *B = Block;
2591  for (ChildrenVect::reverse_iterator I = ChildrenRev.rbegin(),
2592      L = ChildrenRev.rend(); I != L; ++I) {
2593    if (CFGBlock *R = VisitForTemporaryDtors(*I))
2594      B = R;
2595  }
2596  return B;
2597}
2598
2599CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) {
2600  if (E->isLogicalOp()) {
2601    // Destructors for temporaries in LHS expression should be called after
2602    // those for RHS expression. Even if this will unnecessarily create a block,
2603    // this block will be used at least by the full expression.
2604    autoCreateBlock();
2605    CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS());
2606    if (badCFG)
2607      return NULL;
2608
2609    Succ = ConfluenceBlock;
2610    Block = NULL;
2611    CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
2612
2613    if (RHSBlock) {
2614      if (badCFG)
2615        return NULL;
2616
2617      // If RHS expression did produce destructors we need to connect created
2618      // blocks to CFG in same manner as for binary operator itself.
2619      CFGBlock *LHSBlock = createBlock(false);
2620      LHSBlock->setTerminator(CFGTerminator(E, true));
2621
2622      // For binary operator LHS block is before RHS in list of predecessors
2623      // of ConfluenceBlock.
2624      std::reverse(ConfluenceBlock->pred_begin(),
2625          ConfluenceBlock->pred_end());
2626
2627      // See if this is a known constant.
2628      TryResult KnownVal = tryEvaluateBool(E->getLHS());
2629      if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr))
2630        KnownVal.negate();
2631
2632      // Link LHSBlock with RHSBlock exactly the same way as for binary operator
2633      // itself.
2634      if (E->getOpcode() == BO_LOr) {
2635        addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
2636        addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
2637      } else {
2638        assert (E->getOpcode() == BO_LAnd);
2639        addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
2640        addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
2641      }
2642
2643      Block = LHSBlock;
2644      return LHSBlock;
2645    }
2646
2647    Block = ConfluenceBlock;
2648    return ConfluenceBlock;
2649  }
2650
2651  if (E->isAssignmentOp()) {
2652    // For assignment operator (=) LHS expression is visited
2653    // before RHS expression. For destructors visit them in reverse order.
2654    CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
2655    CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS());
2656    return LHSBlock ? LHSBlock : RHSBlock;
2657  }
2658
2659  // For any other binary operator RHS expression is visited before
2660  // LHS expression (order of children). For destructors visit them in reverse
2661  // order.
2662  CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS());
2663  CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
2664  return RHSBlock ? RHSBlock : LHSBlock;
2665}
2666
2667CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
2668    CXXBindTemporaryExpr *E, bool BindToTemporary) {
2669  // First add destructors for temporaries in subexpression.
2670  CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr());
2671  if (!BindToTemporary) {
2672    // If lifetime of temporary is not prolonged (by assigning to constant
2673    // reference) add destructor for it.
2674    autoCreateBlock();
2675    appendTemporaryDtor(Block, E);
2676    B = Block;
2677  }
2678  return B;
2679}
2680
2681CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
2682    AbstractConditionalOperator *E, bool BindToTemporary) {
2683  // First add destructors for condition expression.  Even if this will
2684  // unnecessarily create a block, this block will be used at least by the full
2685  // expression.
2686  autoCreateBlock();
2687  CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond());
2688  if (badCFG)
2689    return NULL;
2690  if (BinaryConditionalOperator *BCO
2691        = dyn_cast<BinaryConditionalOperator>(E)) {
2692    ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon());
2693    if (badCFG)
2694      return NULL;
2695  }
2696
2697  // Try to add block with destructors for LHS expression.
2698  CFGBlock *LHSBlock = NULL;
2699  Succ = ConfluenceBlock;
2700  Block = NULL;
2701  LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary);
2702  if (badCFG)
2703    return NULL;
2704
2705  // Try to add block with destructors for RHS expression;
2706  Succ = ConfluenceBlock;
2707  Block = NULL;
2708  CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(),
2709                                              BindToTemporary);
2710  if (badCFG)
2711    return NULL;
2712
2713  if (!RHSBlock && !LHSBlock) {
2714    // If neither LHS nor RHS expression had temporaries to destroy don't create
2715    // more blocks.
2716    Block = ConfluenceBlock;
2717    return Block;
2718  }
2719
2720  Block = createBlock(false);
2721  Block->setTerminator(CFGTerminator(E, true));
2722
2723  // See if this is a known constant.
2724  const TryResult &KnownVal = tryEvaluateBool(E->getCond());
2725
2726  if (LHSBlock) {
2727    addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
2728  } else if (KnownVal.isFalse()) {
2729    addSuccessor(Block, NULL);
2730  } else {
2731    addSuccessor(Block, ConfluenceBlock);
2732    std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end());
2733  }
2734
2735  if (!RHSBlock)
2736    RHSBlock = ConfluenceBlock;
2737  addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
2738
2739  return Block;
2740}
2741
2742} // end anonymous namespace
2743
2744/// createBlock - Constructs and adds a new CFGBlock to the CFG.  The block has
2745///  no successors or predecessors.  If this is the first block created in the
2746///  CFG, it is automatically set to be the Entry and Exit of the CFG.
2747CFGBlock* CFG::createBlock() {
2748  bool first_block = begin() == end();
2749
2750  // Create the block.
2751  CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
2752  new (Mem) CFGBlock(NumBlockIDs++, BlkBVC);
2753  Blocks.push_back(Mem, BlkBVC);
2754
2755  // If this is the first block, set it as the Entry and Exit.
2756  if (first_block)
2757    Entry = Exit = &back();
2758
2759  // Return the block.
2760  return &back();
2761}
2762
2763/// buildCFG - Constructs a CFG from an AST.  Ownership of the returned
2764///  CFG is returned to the caller.
2765CFG* CFG::buildCFG(const Decl *D, Stmt* Statement, ASTContext *C,
2766    const BuildOptions &BO) {
2767  CFGBuilder Builder(C, BO);
2768  return Builder.buildCFG(D, Statement);
2769}
2770
2771const CXXDestructorDecl *
2772CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
2773  switch (getKind()) {
2774    case CFGElement::Invalid:
2775    case CFGElement::Statement:
2776    case CFGElement::Initializer:
2777      llvm_unreachable("getDestructorDecl should only be used with "
2778                       "ImplicitDtors");
2779    case CFGElement::AutomaticObjectDtor: {
2780      const VarDecl *var = cast<CFGAutomaticObjDtor>(this)->getVarDecl();
2781      QualType ty = var->getType();
2782      ty = ty.getNonReferenceType();
2783      if (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
2784        ty = arrayType->getElementType();
2785      }
2786      const RecordType *recordType = ty->getAs<RecordType>();
2787      const CXXRecordDecl *classDecl =
2788      cast<CXXRecordDecl>(recordType->getDecl());
2789      return classDecl->getDestructor();
2790    }
2791    case CFGElement::TemporaryDtor: {
2792      const CXXBindTemporaryExpr *bindExpr =
2793        cast<CFGTemporaryDtor>(this)->getBindTemporaryExpr();
2794      const CXXTemporary *temp = bindExpr->getTemporary();
2795      return temp->getDestructor();
2796    }
2797    case CFGElement::BaseDtor:
2798    case CFGElement::MemberDtor:
2799
2800      // Not yet supported.
2801      return 0;
2802  }
2803  llvm_unreachable("getKind() returned bogus value");
2804  return 0;
2805}
2806
2807bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
2808  if (const CXXDestructorDecl *cdecl = getDestructorDecl(astContext)) {
2809    QualType ty = cdecl->getType();
2810    return cast<FunctionType>(ty)->getNoReturnAttr();
2811  }
2812  return false;
2813}
2814
2815//===----------------------------------------------------------------------===//
2816// CFG: Queries for BlkExprs.
2817//===----------------------------------------------------------------------===//
2818
2819namespace {
2820  typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
2821}
2822
2823static void FindSubExprAssignments(Stmt *S,
2824                                   llvm::SmallPtrSet<Expr*,50>& Set) {
2825  if (!S)
2826    return;
2827
2828  for (Stmt::child_range I = S->children(); I; ++I) {
2829    Stmt *child = *I;
2830    if (!child)
2831      continue;
2832
2833    if (BinaryOperator* B = dyn_cast<BinaryOperator>(child))
2834      if (B->isAssignmentOp()) Set.insert(B);
2835
2836    FindSubExprAssignments(child, Set);
2837  }
2838}
2839
2840static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
2841  BlkExprMapTy* M = new BlkExprMapTy();
2842
2843  // Look for assignments that are used as subexpressions.  These are the only
2844  // assignments that we want to *possibly* register as a block-level
2845  // expression.  Basically, if an assignment occurs both in a subexpression and
2846  // at the block-level, it is a block-level expression.
2847  llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
2848
2849  for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
2850    for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
2851      if (const CFGStmt *S = BI->getAs<CFGStmt>())
2852        FindSubExprAssignments(S->getStmt(), SubExprAssignments);
2853
2854  for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
2855
2856    // Iterate over the statements again on identify the Expr* and Stmt* at the
2857    // block-level that are block-level expressions.
2858
2859    for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) {
2860      const CFGStmt *CS = BI->getAs<CFGStmt>();
2861      if (!CS)
2862        continue;
2863      if (Expr* Exp = dyn_cast<Expr>(CS->getStmt())) {
2864
2865        if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
2866          // Assignment expressions that are not nested within another
2867          // expression are really "statements" whose value is never used by
2868          // another expression.
2869          if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
2870            continue;
2871        } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
2872          // Special handling for statement expressions.  The last statement in
2873          // the statement expression is also a block-level expr.
2874          const CompoundStmt* C = Terminator->getSubStmt();
2875          if (!C->body_empty()) {
2876            unsigned x = M->size();
2877            (*M)[C->body_back()] = x;
2878          }
2879        }
2880
2881        unsigned x = M->size();
2882        (*M)[Exp] = x;
2883      }
2884    }
2885
2886    // Look at terminators.  The condition is a block-level expression.
2887
2888    Stmt* S = (*I)->getTerminatorCondition();
2889
2890    if (S && M->find(S) == M->end()) {
2891        unsigned x = M->size();
2892        (*M)[S] = x;
2893    }
2894  }
2895
2896  return M;
2897}
2898
2899CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
2900  assert(S != NULL);
2901  if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
2902
2903  BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
2904  BlkExprMapTy::iterator I = M->find(S);
2905  return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second);
2906}
2907
2908unsigned CFG::getNumBlkExprs() {
2909  if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
2910    return M->size();
2911
2912  // We assume callers interested in the number of BlkExprs will want
2913  // the map constructed if it doesn't already exist.
2914  BlkExprMap = (void*) PopulateBlkExprMap(*this);
2915  return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
2916}
2917
2918//===----------------------------------------------------------------------===//
2919// Filtered walking of the CFG.
2920//===----------------------------------------------------------------------===//
2921
2922bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
2923        const CFGBlock *From, const CFGBlock *To) {
2924
2925  if (To && F.IgnoreDefaultsWithCoveredEnums) {
2926    // If the 'To' has no label or is labeled but the label isn't a
2927    // CaseStmt then filter this edge.
2928    if (const SwitchStmt *S =
2929        dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
2930      if (S->isAllEnumCasesCovered()) {
2931        const Stmt *L = To->getLabel();
2932        if (!L || !isa<CaseStmt>(L))
2933          return true;
2934      }
2935    }
2936  }
2937
2938  return false;
2939}
2940
2941//===----------------------------------------------------------------------===//
2942// Cleanup: CFG dstor.
2943//===----------------------------------------------------------------------===//
2944
2945CFG::~CFG() {
2946  delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
2947}
2948
2949//===----------------------------------------------------------------------===//
2950// CFG pretty printing
2951//===----------------------------------------------------------------------===//
2952
2953namespace {
2954
2955class StmtPrinterHelper : public PrinterHelper  {
2956  typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
2957  typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
2958  StmtMapTy StmtMap;
2959  DeclMapTy DeclMap;
2960  signed currentBlock;
2961  unsigned currentStmt;
2962  const LangOptions &LangOpts;
2963public:
2964
2965  StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
2966    : currentBlock(0), currentStmt(0), LangOpts(LO)
2967  {
2968    for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
2969      unsigned j = 1;
2970      for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
2971           BI != BEnd; ++BI, ++j ) {
2972        if (const CFGStmt *SE = BI->getAs<CFGStmt>()) {
2973          const Stmt *stmt= SE->getStmt();
2974          std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
2975          StmtMap[stmt] = P;
2976
2977          switch (stmt->getStmtClass()) {
2978            case Stmt::DeclStmtClass:
2979                DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
2980                break;
2981            case Stmt::IfStmtClass: {
2982              const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
2983              if (var)
2984                DeclMap[var] = P;
2985              break;
2986            }
2987            case Stmt::ForStmtClass: {
2988              const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
2989              if (var)
2990                DeclMap[var] = P;
2991              break;
2992            }
2993            case Stmt::WhileStmtClass: {
2994              const VarDecl *var =
2995                cast<WhileStmt>(stmt)->getConditionVariable();
2996              if (var)
2997                DeclMap[var] = P;
2998              break;
2999            }
3000            case Stmt::SwitchStmtClass: {
3001              const VarDecl *var =
3002                cast<SwitchStmt>(stmt)->getConditionVariable();
3003              if (var)
3004                DeclMap[var] = P;
3005              break;
3006            }
3007            case Stmt::CXXCatchStmtClass: {
3008              const VarDecl *var =
3009                cast<CXXCatchStmt>(stmt)->getExceptionDecl();
3010              if (var)
3011                DeclMap[var] = P;
3012              break;
3013            }
3014            default:
3015              break;
3016          }
3017        }
3018      }
3019    }
3020  }
3021
3022
3023  virtual ~StmtPrinterHelper() {}
3024
3025  const LangOptions &getLangOpts() const { return LangOpts; }
3026  void setBlockID(signed i) { currentBlock = i; }
3027  void setStmtID(unsigned i) { currentStmt = i; }
3028
3029  virtual bool handledStmt(Stmt* S, llvm::raw_ostream& OS) {
3030    StmtMapTy::iterator I = StmtMap.find(S);
3031
3032    if (I == StmtMap.end())
3033      return false;
3034
3035    if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
3036                          && I->second.second == currentStmt) {
3037      return false;
3038    }
3039
3040    OS << "[B" << I->second.first << "." << I->second.second << "]";
3041    return true;
3042  }
3043
3044  bool handleDecl(const Decl* D, llvm::raw_ostream& OS) {
3045    DeclMapTy::iterator I = DeclMap.find(D);
3046
3047    if (I == DeclMap.end())
3048      return false;
3049
3050    if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
3051                          && I->second.second == currentStmt) {
3052      return false;
3053    }
3054
3055    OS << "[B" << I->second.first << "." << I->second.second << "]";
3056    return true;
3057  }
3058};
3059} // end anonymous namespace
3060
3061
3062namespace {
3063class CFGBlockTerminatorPrint
3064  : public StmtVisitor<CFGBlockTerminatorPrint,void> {
3065
3066  llvm::raw_ostream& OS;
3067  StmtPrinterHelper* Helper;
3068  PrintingPolicy Policy;
3069public:
3070  CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
3071                          const PrintingPolicy &Policy)
3072    : OS(os), Helper(helper), Policy(Policy) {}
3073
3074  void VisitIfStmt(IfStmt* I) {
3075    OS << "if ";
3076    I->getCond()->printPretty(OS,Helper,Policy);
3077  }
3078
3079  // Default case.
3080  void VisitStmt(Stmt* Terminator) {
3081    Terminator->printPretty(OS, Helper, Policy);
3082  }
3083
3084  void VisitForStmt(ForStmt* F) {
3085    OS << "for (" ;
3086    if (F->getInit())
3087      OS << "...";
3088    OS << "; ";
3089    if (Stmt* C = F->getCond())
3090      C->printPretty(OS, Helper, Policy);
3091    OS << "; ";
3092    if (F->getInc())
3093      OS << "...";
3094    OS << ")";
3095  }
3096
3097  void VisitWhileStmt(WhileStmt* W) {
3098    OS << "while " ;
3099    if (Stmt* C = W->getCond())
3100      C->printPretty(OS, Helper, Policy);
3101  }
3102
3103  void VisitDoStmt(DoStmt* D) {
3104    OS << "do ... while ";
3105    if (Stmt* C = D->getCond())
3106      C->printPretty(OS, Helper, Policy);
3107  }
3108
3109  void VisitSwitchStmt(SwitchStmt* Terminator) {
3110    OS << "switch ";
3111    Terminator->getCond()->printPretty(OS, Helper, Policy);
3112  }
3113
3114  void VisitCXXTryStmt(CXXTryStmt* CS) {
3115    OS << "try ...";
3116  }
3117
3118  void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
3119    C->getCond()->printPretty(OS, Helper, Policy);
3120    OS << " ? ... : ...";
3121  }
3122
3123  void VisitChooseExpr(ChooseExpr* C) {
3124    OS << "__builtin_choose_expr( ";
3125    C->getCond()->printPretty(OS, Helper, Policy);
3126    OS << " )";
3127  }
3128
3129  void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
3130    OS << "goto *";
3131    I->getTarget()->printPretty(OS, Helper, Policy);
3132  }
3133
3134  void VisitBinaryOperator(BinaryOperator* B) {
3135    if (!B->isLogicalOp()) {
3136      VisitExpr(B);
3137      return;
3138    }
3139
3140    B->getLHS()->printPretty(OS, Helper, Policy);
3141
3142    switch (B->getOpcode()) {
3143      case BO_LOr:
3144        OS << " || ...";
3145        return;
3146      case BO_LAnd:
3147        OS << " && ...";
3148        return;
3149      default:
3150        assert(false && "Invalid logical operator.");
3151    }
3152  }
3153
3154  void VisitExpr(Expr* E) {
3155    E->printPretty(OS, Helper, Policy);
3156  }
3157};
3158} // end anonymous namespace
3159
3160static void print_elem(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
3161                       const CFGElement &E) {
3162  if (const CFGStmt *CS = E.getAs<CFGStmt>()) {
3163    Stmt *S = CS->getStmt();
3164
3165    if (Helper) {
3166
3167      // special printing for statement-expressions.
3168      if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
3169        CompoundStmt* Sub = SE->getSubStmt();
3170
3171        if (Sub->children()) {
3172          OS << "({ ... ; ";
3173          Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
3174          OS << " })\n";
3175          return;
3176        }
3177      }
3178      // special printing for comma expressions.
3179      if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
3180        if (B->getOpcode() == BO_Comma) {
3181          OS << "... , ";
3182          Helper->handledStmt(B->getRHS(),OS);
3183          OS << '\n';
3184          return;
3185        }
3186      }
3187    }
3188    S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
3189
3190    if (isa<CXXOperatorCallExpr>(S)) {
3191      OS << " (OperatorCall)";
3192    } else if (isa<CXXBindTemporaryExpr>(S)) {
3193      OS << " (BindTemporary)";
3194    }
3195
3196    // Expressions need a newline.
3197    if (isa<Expr>(S))
3198      OS << '\n';
3199
3200  } else if (const CFGInitializer *IE = E.getAs<CFGInitializer>()) {
3201    const CXXCtorInitializer *I = IE->getInitializer();
3202    if (I->isBaseInitializer())
3203      OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
3204    else OS << I->getAnyMember()->getName();
3205
3206    OS << "(";
3207    if (Expr* IE = I->getInit())
3208      IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
3209    OS << ")";
3210
3211    if (I->isBaseInitializer())
3212      OS << " (Base initializer)\n";
3213    else OS << " (Member initializer)\n";
3214
3215  } else if (const CFGAutomaticObjDtor *DE = E.getAs<CFGAutomaticObjDtor>()){
3216    const VarDecl* VD = DE->getVarDecl();
3217    Helper->handleDecl(VD, OS);
3218
3219    const Type* T = VD->getType().getTypePtr();
3220    if (const ReferenceType* RT = T->getAs<ReferenceType>())
3221      T = RT->getPointeeType().getTypePtr();
3222    else if (const Type *ET = T->getArrayElementTypeNoTypeQual())
3223      T = ET;
3224
3225    OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
3226    OS << " (Implicit destructor)\n";
3227
3228  } else if (const CFGBaseDtor *BE = E.getAs<CFGBaseDtor>()) {
3229    const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
3230    OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
3231    OS << " (Base object destructor)\n";
3232
3233  } else if (const CFGMemberDtor *ME = E.getAs<CFGMemberDtor>()) {
3234    const FieldDecl *FD = ME->getFieldDecl();
3235
3236    const Type *T = FD->getType().getTypePtr();
3237    if (const Type *ET = T->getArrayElementTypeNoTypeQual())
3238      T = ET;
3239
3240    OS << "this->" << FD->getName();
3241    OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
3242    OS << " (Member object destructor)\n";
3243
3244  } else if (const CFGTemporaryDtor *TE = E.getAs<CFGTemporaryDtor>()) {
3245    const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
3246    OS << "~" << BT->getType()->getAsCXXRecordDecl()->getName() << "()";
3247    OS << " (Temporary object destructor)\n";
3248  }
3249}
3250
3251static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
3252                        const CFGBlock& B,
3253                        StmtPrinterHelper* Helper, bool print_edges) {
3254
3255  if (Helper) Helper->setBlockID(B.getBlockID());
3256
3257  // Print the header.
3258  OS << "\n [ B" << B.getBlockID();
3259
3260  if (&B == &cfg->getEntry())
3261    OS << " (ENTRY) ]\n";
3262  else if (&B == &cfg->getExit())
3263    OS << " (EXIT) ]\n";
3264  else if (&B == cfg->getIndirectGotoBlock())
3265    OS << " (INDIRECT GOTO DISPATCH) ]\n";
3266  else
3267    OS << " ]\n";
3268
3269  // Print the label of this block.
3270  if (Stmt* Label = const_cast<Stmt*>(B.getLabel())) {
3271
3272    if (print_edges)
3273      OS << "    ";
3274
3275    if (LabelStmt* L = dyn_cast<LabelStmt>(Label))
3276      OS << L->getName();
3277    else if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) {
3278      OS << "case ";
3279      C->getLHS()->printPretty(OS, Helper,
3280                               PrintingPolicy(Helper->getLangOpts()));
3281      if (C->getRHS()) {
3282        OS << " ... ";
3283        C->getRHS()->printPretty(OS, Helper,
3284                                 PrintingPolicy(Helper->getLangOpts()));
3285      }
3286    } else if (isa<DefaultStmt>(Label))
3287      OS << "default";
3288    else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
3289      OS << "catch (";
3290      if (CS->getExceptionDecl())
3291        CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()),
3292                                      0);
3293      else
3294        OS << "...";
3295      OS << ")";
3296
3297    } else
3298      assert(false && "Invalid label statement in CFGBlock.");
3299
3300    OS << ":\n";
3301  }
3302
3303  // Iterate through the statements in the block and print them.
3304  unsigned j = 1;
3305
3306  for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
3307       I != E ; ++I, ++j ) {
3308
3309    // Print the statement # in the basic block and the statement itself.
3310    if (print_edges)
3311      OS << "    ";
3312
3313    OS << llvm::format("%3d", j) << ": ";
3314
3315    if (Helper)
3316      Helper->setStmtID(j);
3317
3318    print_elem(OS,Helper,*I);
3319  }
3320
3321  // Print the terminator of this block.
3322  if (B.getTerminator()) {
3323    if (print_edges)
3324      OS << "    ";
3325
3326    OS << "  T: ";
3327
3328    if (Helper) Helper->setBlockID(-1);
3329
3330    CFGBlockTerminatorPrint TPrinter(OS, Helper,
3331                                     PrintingPolicy(Helper->getLangOpts()));
3332    TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt()));
3333    OS << '\n';
3334  }
3335
3336  if (print_edges) {
3337    // Print the predecessors of this block.
3338    OS << "    Predecessors (" << B.pred_size() << "):";
3339    unsigned i = 0;
3340
3341    for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
3342         I != E; ++I, ++i) {
3343
3344      if (i == 8 || (i-8) == 0)
3345        OS << "\n     ";
3346
3347      OS << " B" << (*I)->getBlockID();
3348    }
3349
3350    OS << '\n';
3351
3352    // Print the successors of this block.
3353    OS << "    Successors (" << B.succ_size() << "):";
3354    i = 0;
3355
3356    for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
3357         I != E; ++I, ++i) {
3358
3359      if (i == 8 || (i-8) % 10 == 0)
3360        OS << "\n    ";
3361
3362      if (*I)
3363        OS << " B" << (*I)->getBlockID();
3364      else
3365        OS  << " NULL";
3366    }
3367
3368    OS << '\n';
3369  }
3370}
3371
3372
3373/// dump - A simple pretty printer of a CFG that outputs to stderr.
3374void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
3375
3376/// print - A simple pretty printer of a CFG that outputs to an ostream.
3377void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
3378  StmtPrinterHelper Helper(this, LO);
3379
3380  // Print the entry block.
3381  print_block(OS, this, getEntry(), &Helper, true);
3382
3383  // Iterate through the CFGBlocks and print them one by one.
3384  for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
3385    // Skip the entry block, because we already printed it.
3386    if (&(**I) == &getEntry() || &(**I) == &getExit())
3387      continue;
3388
3389    print_block(OS, this, **I, &Helper, true);
3390  }
3391
3392  // Print the exit block.
3393  print_block(OS, this, getExit(), &Helper, true);
3394  OS.flush();
3395}
3396
3397/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
3398void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
3399  print(llvm::errs(), cfg, LO);
3400}
3401
3402/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
3403///   Generally this will only be called from CFG::print.
3404void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
3405                     const LangOptions &LO) const {
3406  StmtPrinterHelper Helper(cfg, LO);
3407  print_block(OS, cfg, *this, &Helper, true);
3408}
3409
3410/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
3411void CFGBlock::printTerminator(llvm::raw_ostream &OS,
3412                               const LangOptions &LO) const {
3413  CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
3414  TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt()));
3415}
3416
3417Stmt* CFGBlock::getTerminatorCondition() {
3418  Stmt *Terminator = this->Terminator;
3419  if (!Terminator)
3420    return NULL;
3421
3422  Expr* E = NULL;
3423
3424  switch (Terminator->getStmtClass()) {
3425    default:
3426      break;
3427
3428    case Stmt::ForStmtClass:
3429      E = cast<ForStmt>(Terminator)->getCond();
3430      break;
3431
3432    case Stmt::WhileStmtClass:
3433      E = cast<WhileStmt>(Terminator)->getCond();
3434      break;
3435
3436    case Stmt::DoStmtClass:
3437      E = cast<DoStmt>(Terminator)->getCond();
3438      break;
3439
3440    case Stmt::IfStmtClass:
3441      E = cast<IfStmt>(Terminator)->getCond();
3442      break;
3443
3444    case Stmt::ChooseExprClass:
3445      E = cast<ChooseExpr>(Terminator)->getCond();
3446      break;
3447
3448    case Stmt::IndirectGotoStmtClass:
3449      E = cast<IndirectGotoStmt>(Terminator)->getTarget();
3450      break;
3451
3452    case Stmt::SwitchStmtClass:
3453      E = cast<SwitchStmt>(Terminator)->getCond();
3454      break;
3455
3456    case Stmt::BinaryConditionalOperatorClass:
3457      E = cast<BinaryConditionalOperator>(Terminator)->getCond();
3458      break;
3459
3460    case Stmt::ConditionalOperatorClass:
3461      E = cast<ConditionalOperator>(Terminator)->getCond();
3462      break;
3463
3464    case Stmt::BinaryOperatorClass: // '&&' and '||'
3465      E = cast<BinaryOperator>(Terminator)->getLHS();
3466      break;
3467
3468    case Stmt::ObjCForCollectionStmtClass:
3469      return Terminator;
3470  }
3471
3472  return E ? E->IgnoreParens() : NULL;
3473}
3474
3475bool CFGBlock::hasBinaryBranchTerminator() const {
3476  const Stmt *Terminator = this->Terminator;
3477  if (!Terminator)
3478    return false;
3479
3480  Expr* E = NULL;
3481
3482  switch (Terminator->getStmtClass()) {
3483    default:
3484      return false;
3485
3486    case Stmt::ForStmtClass:
3487    case Stmt::WhileStmtClass:
3488    case Stmt::DoStmtClass:
3489    case Stmt::IfStmtClass:
3490    case Stmt::ChooseExprClass:
3491    case Stmt::BinaryConditionalOperatorClass:
3492    case Stmt::ConditionalOperatorClass:
3493    case Stmt::BinaryOperatorClass:
3494      return true;
3495  }
3496
3497  return E ? E->IgnoreParens() : NULL;
3498}
3499
3500
3501//===----------------------------------------------------------------------===//
3502// CFG Graphviz Visualization
3503//===----------------------------------------------------------------------===//
3504
3505
3506#ifndef NDEBUG
3507static StmtPrinterHelper* GraphHelper;
3508#endif
3509
3510void CFG::viewCFG(const LangOptions &LO) const {
3511#ifndef NDEBUG
3512  StmtPrinterHelper H(this, LO);
3513  GraphHelper = &H;
3514  llvm::ViewGraph(this,"CFG");
3515  GraphHelper = NULL;
3516#endif
3517}
3518
3519namespace llvm {
3520template<>
3521struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
3522
3523  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3524
3525  static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
3526
3527#ifndef NDEBUG
3528    std::string OutSStr;
3529    llvm::raw_string_ostream Out(OutSStr);
3530    print_block(Out,Graph, *Node, GraphHelper, false);
3531    std::string& OutStr = Out.str();
3532
3533    if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
3534
3535    // Process string output to make it nicer...
3536    for (unsigned i = 0; i != OutStr.length(); ++i)
3537      if (OutStr[i] == '\n') {                            // Left justify
3538        OutStr[i] = '\\';
3539        OutStr.insert(OutStr.begin()+i+1, 'l');
3540      }
3541
3542    return OutStr;
3543#else
3544    return "";
3545#endif
3546  }
3547};
3548} // end namespace llvm
3549