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