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