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