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