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