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