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