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