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