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