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