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