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