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