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