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