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