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