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