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