CFG.cpp revision b219cfc4d75f0a03630b7c4509ef791b7e97b2c8
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 "clang/AST/CharUnits.h" 21#include "llvm/Support/GraphWriter.h" 22#include "llvm/Support/Allocator.h" 23#include "llvm/Support/Format.h" 24#include "llvm/ADT/DenseMap.h" 25#include "llvm/ADT/SmallPtrSet.h" 26#include "llvm/ADT/OwningPtr.h" 27 28using namespace clang; 29 30namespace { 31 32static SourceLocation GetEndLoc(Decl *D) { 33 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 34 if (Expr *Ex = VD->getInit()) 35 return Ex->getSourceRange().getEnd(); 36 return D->getLocation(); 37} 38 39class CFGBuilder; 40 41/// The CFG builder uses a recursive algorithm to build the CFG. When 42/// we process an expression, sometimes we know that we must add the 43/// subexpressions as block-level expressions. For example: 44/// 45/// exp1 || exp2 46/// 47/// When processing the '||' expression, we know that exp1 and exp2 48/// need to be added as block-level expressions, even though they 49/// might not normally need to be. AddStmtChoice records this 50/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then 51/// the builder has an option not to add a subexpression as a 52/// block-level expression. 53/// 54class AddStmtChoice { 55public: 56 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 }; 57 58 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {} 59 60 bool alwaysAdd(CFGBuilder &builder, 61 const Stmt *stmt) const; 62 63 /// Return a copy of this object, except with the 'always-add' bit 64 /// set as specified. 65 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const { 66 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd); 67 } 68 69private: 70 Kind kind; 71}; 72 73/// LocalScope - Node in tree of local scopes created for C++ implicit 74/// destructor calls generation. It contains list of automatic variables 75/// declared in the scope and link to position in previous scope this scope 76/// began in. 77/// 78/// The process of creating local scopes is as follows: 79/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null), 80/// - Before processing statements in scope (e.g. CompoundStmt) create 81/// LocalScope object using CFGBuilder::ScopePos as link to previous scope 82/// and set CFGBuilder::ScopePos to the end of new scope, 83/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points 84/// at this VarDecl, 85/// - For every normal (without jump) end of scope add to CFGBlock destructors 86/// for objects in the current scope, 87/// - For every jump add to CFGBlock destructors for objects 88/// between CFGBuilder::ScopePos and local scope position saved for jump 89/// target. Thanks to C++ restrictions on goto jumps we can be sure that 90/// jump target position will be on the path to root from CFGBuilder::ScopePos 91/// (adding any variable that doesn't need constructor to be called to 92/// LocalScope can break this assumption), 93/// 94class LocalScope { 95public: 96 typedef BumpVector<VarDecl*> AutomaticVarsTy; 97 98 /// const_iterator - Iterates local scope backwards and jumps to previous 99 /// scope on reaching the beginning of currently iterated scope. 100 class const_iterator { 101 const LocalScope* Scope; 102 103 /// VarIter is guaranteed to be greater then 0 for every valid iterator. 104 /// Invalid iterator (with null Scope) has VarIter equal to 0. 105 unsigned VarIter; 106 107 public: 108 /// Create invalid iterator. Dereferencing invalid iterator is not allowed. 109 /// Incrementing invalid iterator is allowed and will result in invalid 110 /// iterator. 111 const_iterator() 112 : Scope(NULL), VarIter(0) {} 113 114 /// Create valid iterator. In case when S.Prev is an invalid iterator and 115 /// I is equal to 0, this will create invalid iterator. 116 const_iterator(const LocalScope& S, unsigned I) 117 : Scope(&S), VarIter(I) { 118 // Iterator to "end" of scope is not allowed. Handle it by going up 119 // in scopes tree possibly up to invalid iterator in the root. 120 if (VarIter == 0 && Scope) 121 *this = Scope->Prev; 122 } 123 124 VarDecl *const* operator->() const { 125 assert (Scope && "Dereferencing invalid iterator is not allowed"); 126 assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); 127 return &Scope->Vars[VarIter - 1]; 128 } 129 VarDecl *operator*() const { 130 return *this->operator->(); 131 } 132 133 const_iterator &operator++() { 134 if (!Scope) 135 return *this; 136 137 assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); 138 --VarIter; 139 if (VarIter == 0) 140 *this = Scope->Prev; 141 return *this; 142 } 143 const_iterator operator++(int) { 144 const_iterator P = *this; 145 ++*this; 146 return P; 147 } 148 149 bool operator==(const const_iterator &rhs) const { 150 return Scope == rhs.Scope && VarIter == rhs.VarIter; 151 } 152 bool operator!=(const const_iterator &rhs) const { 153 return !(*this == rhs); 154 } 155 156 operator bool() const { 157 return *this != const_iterator(); 158 } 159 160 int distance(const_iterator L); 161 }; 162 163 friend class const_iterator; 164 165private: 166 BumpVectorContext ctx; 167 168 /// Automatic variables in order of declaration. 169 AutomaticVarsTy Vars; 170 /// Iterator to variable in previous scope that was declared just before 171 /// begin of this scope. 172 const_iterator Prev; 173 174public: 175 /// Constructs empty scope linked to previous scope in specified place. 176 LocalScope(BumpVectorContext &ctx, const_iterator P) 177 : ctx(ctx), Vars(ctx, 4), Prev(P) {} 178 179 /// Begin of scope in direction of CFG building (backwards). 180 const_iterator begin() const { return const_iterator(*this, Vars.size()); } 181 182 void addVar(VarDecl *VD) { 183 Vars.push_back(VD, ctx); 184 } 185}; 186 187/// distance - Calculates distance from this to L. L must be reachable from this 188/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t. 189/// number of scopes between this and L. 190int LocalScope::const_iterator::distance(LocalScope::const_iterator L) { 191 int D = 0; 192 const_iterator F = *this; 193 while (F.Scope != L.Scope) { 194 assert (F != const_iterator() 195 && "L iterator is not reachable from F iterator."); 196 D += F.VarIter; 197 F = F.Scope->Prev; 198 } 199 D += F.VarIter - L.VarIter; 200 return D; 201} 202 203/// BlockScopePosPair - Structure for specifying position in CFG during its 204/// build process. It consists of CFGBlock that specifies position in CFG graph 205/// and LocalScope::const_iterator that specifies position in LocalScope graph. 206struct BlockScopePosPair { 207 BlockScopePosPair() : block(0) {} 208 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos) 209 : block(b), scopePosition(scopePos) {} 210 211 CFGBlock *block; 212 LocalScope::const_iterator scopePosition; 213}; 214 215/// TryResult - a class representing a variant over the values 216/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool, 217/// and is used by the CFGBuilder to decide if a branch condition 218/// can be decided up front during CFG construction. 219class TryResult { 220 int X; 221public: 222 TryResult(bool b) : X(b ? 1 : 0) {} 223 TryResult() : X(-1) {} 224 225 bool isTrue() const { return X == 1; } 226 bool isFalse() const { return X == 0; } 227 bool isKnown() const { return X >= 0; } 228 void negate() { 229 assert(isKnown()); 230 X ^= 0x1; 231 } 232}; 233 234/// CFGBuilder - This class implements CFG construction from an AST. 235/// The builder is stateful: an instance of the builder should be used to only 236/// construct a single CFG. 237/// 238/// Example usage: 239/// 240/// CFGBuilder builder; 241/// CFG* cfg = builder.BuildAST(stmt1); 242/// 243/// CFG construction is done via a recursive walk of an AST. We actually parse 244/// the AST in reverse order so that the successor of a basic block is 245/// constructed prior to its predecessor. This allows us to nicely capture 246/// implicit fall-throughs without extra basic blocks. 247/// 248class CFGBuilder { 249 typedef BlockScopePosPair JumpTarget; 250 typedef BlockScopePosPair JumpSource; 251 252 ASTContext *Context; 253 llvm::OwningPtr<CFG> cfg; 254 255 CFGBlock *Block; 256 CFGBlock *Succ; 257 JumpTarget ContinueJumpTarget; 258 JumpTarget BreakJumpTarget; 259 CFGBlock *SwitchTerminatedBlock; 260 CFGBlock *DefaultCaseBlock; 261 CFGBlock *TryTerminatedBlock; 262 263 // Current position in local scope. 264 LocalScope::const_iterator ScopePos; 265 266 // LabelMap records the mapping from Label expressions to their jump targets. 267 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy; 268 LabelMapTy LabelMap; 269 270 // A list of blocks that end with a "goto" that must be backpatched to their 271 // resolved targets upon completion of CFG construction. 272 typedef std::vector<JumpSource> BackpatchBlocksTy; 273 BackpatchBlocksTy BackpatchBlocks; 274 275 // A list of labels whose address has been taken (for indirect gotos). 276 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy; 277 LabelSetTy AddressTakenLabels; 278 279 bool badCFG; 280 const CFG::BuildOptions &BuildOpts; 281 282 // State to track for building switch statements. 283 bool switchExclusivelyCovered; 284 Expr::EvalResult *switchCond; 285 286 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry; 287 const Stmt *lastLookup; 288 289public: 290 explicit CFGBuilder(ASTContext *astContext, 291 const CFG::BuildOptions &buildOpts) 292 : Context(astContext), cfg(new CFG()), // crew a new CFG 293 Block(NULL), Succ(NULL), 294 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL), 295 TryTerminatedBlock(NULL), badCFG(false), BuildOpts(buildOpts), 296 switchExclusivelyCovered(false), switchCond(0), 297 cachedEntry(0), lastLookup(0) {} 298 299 // buildCFG - Used by external clients to construct the CFG. 300 CFG* buildCFG(const Decl *D, Stmt *Statement); 301 302 bool alwaysAdd(const Stmt *stmt); 303 304private: 305 // Visitors to walk an AST and construct the CFG. 306 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc); 307 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc); 308 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc); 309 CFGBlock *VisitBreakStmt(BreakStmt *B); 310 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S); 311 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, 312 AddStmtChoice asc); 313 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T); 314 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S); 315 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S); 316 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 317 AddStmtChoice asc); 318 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc); 319 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 320 AddStmtChoice asc); 321 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 322 AddStmtChoice asc); 323 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc); 324 CFGBlock *VisitCaseStmt(CaseStmt *C); 325 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc); 326 CFGBlock *VisitCompoundStmt(CompoundStmt *C); 327 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C, 328 AddStmtChoice asc); 329 CFGBlock *VisitContinueStmt(ContinueStmt *C); 330 CFGBlock *VisitDeclStmt(DeclStmt *DS); 331 CFGBlock *VisitDeclSubExpr(DeclStmt *DS); 332 CFGBlock *VisitDefaultStmt(DefaultStmt *D); 333 CFGBlock *VisitDoStmt(DoStmt *D); 334 CFGBlock *VisitForStmt(ForStmt *F); 335 CFGBlock *VisitGotoStmt(GotoStmt *G); 336 CFGBlock *VisitIfStmt(IfStmt *I); 337 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc); 338 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I); 339 CFGBlock *VisitLabelStmt(LabelStmt *L); 340 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc); 341 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 342 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 343 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 344 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); 345 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 346 CFGBlock *VisitReturnStmt(ReturnStmt *R); 347 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 348 AddStmtChoice asc); 349 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc); 350 CFGBlock *VisitSwitchStmt(SwitchStmt *S); 351 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc); 352 CFGBlock *VisitWhileStmt(WhileStmt *W); 353 354 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd); 355 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc); 356 CFGBlock *VisitChildren(Stmt *S); 357 358 // Visitors to walk an AST and generate destructors of temporaries in 359 // full expression. 360 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary = false); 361 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E); 362 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E); 363 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(CXXBindTemporaryExpr *E, 364 bool BindToTemporary); 365 CFGBlock * 366 VisitConditionalOperatorForTemporaryDtors(AbstractConditionalOperator *E, 367 bool BindToTemporary); 368 369 // NYS == Not Yet Supported 370 CFGBlock *NYS() { 371 badCFG = true; 372 return Block; 373 } 374 375 void autoCreateBlock() { if (!Block) Block = createBlock(); } 376 CFGBlock *createBlock(bool add_successor = true); 377 CFGBlock *createNoReturnBlock(); 378 379 CFGBlock *addStmt(Stmt *S) { 380 return Visit(S, AddStmtChoice::AlwaysAdd); 381 } 382 CFGBlock *addInitializer(CXXCtorInitializer *I); 383 void addAutomaticObjDtors(LocalScope::const_iterator B, 384 LocalScope::const_iterator E, Stmt *S); 385 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD); 386 387 // Local scopes creation. 388 LocalScope* createOrReuseLocalScope(LocalScope* Scope); 389 390 void addLocalScopeForStmt(Stmt *S); 391 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS, LocalScope* Scope = NULL); 392 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = NULL); 393 394 void addLocalScopeAndDtors(Stmt *S); 395 396 // Interface to CFGBlock - adding CFGElements. 397 void appendStmt(CFGBlock *B, const Stmt *S) { 398 if (alwaysAdd(S) && cachedEntry) 399 cachedEntry->second = B; 400 401 // All block-level expressions should have already been IgnoreParens()ed. 402 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S); 403 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext()); 404 } 405 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) { 406 B->appendInitializer(I, cfg->getBumpVectorContext()); 407 } 408 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) { 409 B->appendBaseDtor(BS, cfg->getBumpVectorContext()); 410 } 411 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) { 412 B->appendMemberDtor(FD, cfg->getBumpVectorContext()); 413 } 414 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) { 415 B->appendTemporaryDtor(E, cfg->getBumpVectorContext()); 416 } 417 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) { 418 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext()); 419 } 420 421 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 422 LocalScope::const_iterator B, LocalScope::const_iterator E); 423 424 void addSuccessor(CFGBlock *B, CFGBlock *S) { 425 B->addSuccessor(S, cfg->getBumpVectorContext()); 426 } 427 428 /// Try and evaluate an expression to an integer constant. 429 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) { 430 if (!BuildOpts.PruneTriviallyFalseEdges) 431 return false; 432 return !S->isTypeDependent() && 433 !S->isValueDependent() && 434 S->Evaluate(outResult, *Context); 435 } 436 437 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1 438 /// if we can evaluate to a known value, otherwise return -1. 439 TryResult tryEvaluateBool(Expr *S) { 440 Expr::EvalResult Result; 441 if (!tryEvaluate(S, Result)) 442 return TryResult(); 443 444 if (Result.Val.isInt()) 445 return Result.Val.getInt().getBoolValue(); 446 447 if (Result.Val.isLValue()) { 448 const Expr *e = Result.Val.getLValueBase(); 449 const CharUnits &c = Result.Val.getLValueOffset(); 450 if (!e && c.isZero()) 451 return false; 452 } 453 return TryResult(); 454 } 455 456}; 457 458inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder, 459 const Stmt *stmt) const { 460 return builder.alwaysAdd(stmt) || kind == AlwaysAdd; 461} 462 463bool CFGBuilder::alwaysAdd(const Stmt *stmt) { 464 bool shouldAdd = BuildOpts.alwaysAdd(stmt); 465 466 if (!BuildOpts.forcedBlkExprs) 467 return shouldAdd; 468 469 if (lastLookup == stmt) { 470 if (cachedEntry) { 471 assert(cachedEntry->first == stmt); 472 return true; 473 } 474 return shouldAdd; 475 } 476 477 lastLookup = stmt; 478 479 // Perform the lookup! 480 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs; 481 482 if (!fb) { 483 // No need to update 'cachedEntry', since it will always be null. 484 assert(cachedEntry == 0); 485 return shouldAdd; 486 } 487 488 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt); 489 if (itr == fb->end()) { 490 cachedEntry = 0; 491 return shouldAdd; 492 } 493 494 cachedEntry = &*itr; 495 return true; 496} 497 498// FIXME: Add support for dependent-sized array types in C++? 499// Does it even make sense to build a CFG for an uninstantiated template? 500static const VariableArrayType *FindVA(const Type *t) { 501 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) { 502 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt)) 503 if (vat->getSizeExpr()) 504 return vat; 505 506 t = vt->getElementType().getTypePtr(); 507 } 508 509 return 0; 510} 511 512/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an 513/// arbitrary statement. Examples include a single expression or a function 514/// body (compound statement). The ownership of the returned CFG is 515/// transferred to the caller. If CFG construction fails, this method returns 516/// NULL. 517CFG* CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) { 518 assert(cfg.get()); 519 if (!Statement) 520 return NULL; 521 522 // Create an empty block that will serve as the exit block for the CFG. Since 523 // this is the first block added to the CFG, it will be implicitly registered 524 // as the exit block. 525 Succ = createBlock(); 526 assert(Succ == &cfg->getExit()); 527 Block = NULL; // the EXIT block is empty. Create all other blocks lazily. 528 529 if (BuildOpts.AddImplicitDtors) 530 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D)) 531 addImplicitDtorsForDestructor(DD); 532 533 // Visit the statements and create the CFG. 534 CFGBlock *B = addStmt(Statement); 535 536 if (badCFG) 537 return NULL; 538 539 // For C++ constructor add initializers to CFG. 540 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) { 541 for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(), 542 E = CD->init_rend(); I != E; ++I) { 543 B = addInitializer(*I); 544 if (badCFG) 545 return NULL; 546 } 547 } 548 549 if (B) 550 Succ = B; 551 552 // Backpatch the gotos whose label -> block mappings we didn't know when we 553 // encountered them. 554 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(), 555 E = BackpatchBlocks.end(); I != E; ++I ) { 556 557 CFGBlock *B = I->block; 558 GotoStmt *G = cast<GotoStmt>(B->getTerminator()); 559 LabelMapTy::iterator LI = LabelMap.find(G->getLabel()); 560 561 // If there is no target for the goto, then we are looking at an 562 // incomplete AST. Handle this by not registering a successor. 563 if (LI == LabelMap.end()) continue; 564 565 JumpTarget JT = LI->second; 566 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition, 567 JT.scopePosition); 568 addSuccessor(B, JT.block); 569 } 570 571 // Add successors to the Indirect Goto Dispatch block (if we have one). 572 if (CFGBlock *B = cfg->getIndirectGotoBlock()) 573 for (LabelSetTy::iterator I = AddressTakenLabels.begin(), 574 E = AddressTakenLabels.end(); I != E; ++I ) { 575 576 // Lookup the target block. 577 LabelMapTy::iterator LI = LabelMap.find(*I); 578 579 // If there is no target block that contains label, then we are looking 580 // at an incomplete AST. Handle this by not registering a successor. 581 if (LI == LabelMap.end()) continue; 582 583 addSuccessor(B, LI->second.block); 584 } 585 586 // Create an empty entry block that has no predecessors. 587 cfg->setEntry(createBlock()); 588 589 return cfg.take(); 590} 591 592/// createBlock - Used to lazily create blocks that are connected 593/// to the current (global) succcessor. 594CFGBlock *CFGBuilder::createBlock(bool add_successor) { 595 CFGBlock *B = cfg->createBlock(); 596 if (add_successor && Succ) 597 addSuccessor(B, Succ); 598 return B; 599} 600 601/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the 602/// CFG. It is *not* connected to the current (global) successor, and instead 603/// directly tied to the exit block in order to be reachable. 604CFGBlock *CFGBuilder::createNoReturnBlock() { 605 CFGBlock *B = createBlock(false); 606 B->setHasNoReturnElement(); 607 addSuccessor(B, &cfg->getExit()); 608 return B; 609} 610 611/// addInitializer - Add C++ base or member initializer element to CFG. 612CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) { 613 if (!BuildOpts.AddInitializers) 614 return Block; 615 616 bool IsReference = false; 617 bool HasTemporaries = false; 618 619 // Destructors of temporaries in initialization expression should be called 620 // after initialization finishes. 621 Expr *Init = I->getInit(); 622 if (Init) { 623 if (FieldDecl *FD = I->getAnyMember()) 624 IsReference = FD->getType()->isReferenceType(); 625 HasTemporaries = isa<ExprWithCleanups>(Init); 626 627 if (BuildOpts.AddImplicitDtors && HasTemporaries) { 628 // Generate destructors for temporaries in initialization expression. 629 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 630 IsReference); 631 } 632 } 633 634 autoCreateBlock(); 635 appendInitializer(Block, I); 636 637 if (Init) { 638 if (HasTemporaries) { 639 // For expression with temporaries go directly to subexpression to omit 640 // generating destructors for the second time. 641 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr()); 642 } 643 return Visit(Init); 644 } 645 646 return Block; 647} 648 649/// addAutomaticObjDtors - Add to current block automatic objects destructors 650/// for objects in range of local scope positions. Use S as trigger statement 651/// for destructors. 652void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B, 653 LocalScope::const_iterator E, Stmt *S) { 654 if (!BuildOpts.AddImplicitDtors) 655 return; 656 657 if (B == E) 658 return; 659 660 CFGBlock::iterator InsertPos; 661 662 // We need to append the destructors in reverse order, but any one of them 663 // may be a no-return destructor which changes the CFG. As a result, buffer 664 // this sequence up and replay them in reverse order when appending onto the 665 // CFGBlock(s). 666 SmallVector<VarDecl*, 10> Decls; 667 Decls.reserve(B.distance(E)); 668 for (LocalScope::const_iterator I = B; I != E; ++I) 669 Decls.push_back(*I); 670 671 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(), 672 E = Decls.rend(); 673 I != E; ++I) { 674 // If this destructor is marked as a no-return destructor, we need to 675 // create a new block for the destructor which does not have as a successor 676 // anything built thus far: control won't flow out of this block. 677 QualType Ty = (*I)->getType().getNonReferenceType(); 678 if (const ArrayType *AT = Context->getAsArrayType(Ty)) 679 Ty = AT->getElementType(); 680 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor(); 681 if (cast<FunctionType>(Dtor->getType())->getNoReturnAttr()) 682 Block = createNoReturnBlock(); 683 else 684 autoCreateBlock(); 685 686 appendAutomaticObjDtor(Block, *I, S); 687 } 688} 689 690/// addImplicitDtorsForDestructor - Add implicit destructors generated for 691/// base and member objects in destructor. 692void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) { 693 assert (BuildOpts.AddImplicitDtors 694 && "Can be called only when dtors should be added"); 695 const CXXRecordDecl *RD = DD->getParent(); 696 697 // At the end destroy virtual base objects. 698 for (CXXRecordDecl::base_class_const_iterator VI = RD->vbases_begin(), 699 VE = RD->vbases_end(); VI != VE; ++VI) { 700 const CXXRecordDecl *CD = VI->getType()->getAsCXXRecordDecl(); 701 if (!CD->hasTrivialDestructor()) { 702 autoCreateBlock(); 703 appendBaseDtor(Block, VI); 704 } 705 } 706 707 // Before virtual bases destroy direct base objects. 708 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 709 BE = RD->bases_end(); BI != BE; ++BI) { 710 if (!BI->isVirtual()) { 711 const CXXRecordDecl *CD = BI->getType()->getAsCXXRecordDecl(); 712 if (!CD->hasTrivialDestructor()) { 713 autoCreateBlock(); 714 appendBaseDtor(Block, BI); 715 } 716 } 717 } 718 719 // First destroy member objects. 720 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 721 FE = RD->field_end(); FI != FE; ++FI) { 722 // Check for constant size array. Set type to array element type. 723 QualType QT = FI->getType(); 724 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 725 if (AT->getSize() == 0) 726 continue; 727 QT = AT->getElementType(); 728 } 729 730 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 731 if (!CD->hasTrivialDestructor()) { 732 autoCreateBlock(); 733 appendMemberDtor(Block, *FI); 734 } 735 } 736} 737 738/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either 739/// way return valid LocalScope object. 740LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) { 741 if (!Scope) { 742 llvm::BumpPtrAllocator &alloc = cfg->getAllocator(); 743 Scope = alloc.Allocate<LocalScope>(); 744 BumpVectorContext ctx(alloc); 745 new (Scope) LocalScope(ctx, ScopePos); 746 } 747 return Scope; 748} 749 750/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement 751/// that should create implicit scope (e.g. if/else substatements). 752void CFGBuilder::addLocalScopeForStmt(Stmt *S) { 753 if (!BuildOpts.AddImplicitDtors) 754 return; 755 756 LocalScope *Scope = 0; 757 758 // For compound statement we will be creating explicit scope. 759 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { 760 for (CompoundStmt::body_iterator BI = CS->body_begin(), BE = CS->body_end() 761 ; BI != BE; ++BI) { 762 Stmt *SI = (*BI)->stripLabelLikeStatements(); 763 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI)) 764 Scope = addLocalScopeForDeclStmt(DS, Scope); 765 } 766 return; 767 } 768 769 // For any other statement scope will be implicit and as such will be 770 // interesting only for DeclStmt. 771 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements())) 772 addLocalScopeForDeclStmt(DS); 773} 774 775/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will 776/// reuse Scope if not NULL. 777LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS, 778 LocalScope* Scope) { 779 if (!BuildOpts.AddImplicitDtors) 780 return Scope; 781 782 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end() 783 ; DI != DE; ++DI) { 784 if (VarDecl *VD = dyn_cast<VarDecl>(*DI)) 785 Scope = addLocalScopeForVarDecl(VD, Scope); 786 } 787 return Scope; 788} 789 790/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will 791/// create add scope for automatic objects and temporary objects bound to 792/// const reference. Will reuse Scope if not NULL. 793LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD, 794 LocalScope* Scope) { 795 if (!BuildOpts.AddImplicitDtors) 796 return Scope; 797 798 // Check if variable is local. 799 switch (VD->getStorageClass()) { 800 case SC_None: 801 case SC_Auto: 802 case SC_Register: 803 break; 804 default: return Scope; 805 } 806 807 // Check for const references bound to temporary. Set type to pointee. 808 QualType QT = VD->getType(); 809 if (const ReferenceType* RT = QT.getTypePtr()->getAs<ReferenceType>()) { 810 QT = RT->getPointeeType(); 811 if (!QT.isConstQualified()) 812 return Scope; 813 if (!VD->extendsLifetimeOfTemporary()) 814 return Scope; 815 } 816 817 // Check for constant size array. Set type to array element type. 818 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 819 if (AT->getSize() == 0) 820 return Scope; 821 QT = AT->getElementType(); 822 } 823 824 // Check if type is a C++ class with non-trivial destructor. 825 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 826 if (!CD->hasTrivialDestructor()) { 827 // Add the variable to scope 828 Scope = createOrReuseLocalScope(Scope); 829 Scope->addVar(VD); 830 ScopePos = Scope->begin(); 831 } 832 return Scope; 833} 834 835/// addLocalScopeAndDtors - For given statement add local scope for it and 836/// add destructors that will cleanup the scope. Will reuse Scope if not NULL. 837void CFGBuilder::addLocalScopeAndDtors(Stmt *S) { 838 if (!BuildOpts.AddImplicitDtors) 839 return; 840 841 LocalScope::const_iterator scopeBeginPos = ScopePos; 842 addLocalScopeForStmt(S); 843 addAutomaticObjDtors(ScopePos, scopeBeginPos, S); 844} 845 846/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for 847/// variables with automatic storage duration to CFGBlock's elements vector. 848/// Elements will be prepended to physical beginning of the vector which 849/// happens to be logical end. Use blocks terminator as statement that specifies 850/// destructors call site. 851/// FIXME: This mechanism for adding automatic destructors doesn't handle 852/// no-return destructors properly. 853void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 854 LocalScope::const_iterator B, LocalScope::const_iterator E) { 855 BumpVectorContext &C = cfg->getBumpVectorContext(); 856 CFGBlock::iterator InsertPos 857 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C); 858 for (LocalScope::const_iterator I = B; I != E; ++I) 859 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I, 860 Blk->getTerminator()); 861} 862 863/// Visit - Walk the subtree of a statement and add extra 864/// blocks for ternary operators, &&, and ||. We also process "," and 865/// DeclStmts (which may contain nested control-flow). 866CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) { 867 if (!S) { 868 badCFG = true; 869 return 0; 870 } 871 872 if (Expr *E = dyn_cast<Expr>(S)) 873 S = E->IgnoreParens(); 874 875 switch (S->getStmtClass()) { 876 default: 877 return VisitStmt(S, asc); 878 879 case Stmt::AddrLabelExprClass: 880 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc); 881 882 case Stmt::BinaryConditionalOperatorClass: 883 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc); 884 885 case Stmt::BinaryOperatorClass: 886 return VisitBinaryOperator(cast<BinaryOperator>(S), asc); 887 888 case Stmt::BlockExprClass: 889 return VisitBlockExpr(cast<BlockExpr>(S), asc); 890 891 case Stmt::BreakStmtClass: 892 return VisitBreakStmt(cast<BreakStmt>(S)); 893 894 case Stmt::CallExprClass: 895 case Stmt::CXXOperatorCallExprClass: 896 case Stmt::CXXMemberCallExprClass: 897 return VisitCallExpr(cast<CallExpr>(S), asc); 898 899 case Stmt::CaseStmtClass: 900 return VisitCaseStmt(cast<CaseStmt>(S)); 901 902 case Stmt::ChooseExprClass: 903 return VisitChooseExpr(cast<ChooseExpr>(S), asc); 904 905 case Stmt::CompoundStmtClass: 906 return VisitCompoundStmt(cast<CompoundStmt>(S)); 907 908 case Stmt::ConditionalOperatorClass: 909 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc); 910 911 case Stmt::ContinueStmtClass: 912 return VisitContinueStmt(cast<ContinueStmt>(S)); 913 914 case Stmt::CXXCatchStmtClass: 915 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S)); 916 917 case Stmt::ExprWithCleanupsClass: 918 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc); 919 920 case Stmt::CXXBindTemporaryExprClass: 921 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc); 922 923 case Stmt::CXXConstructExprClass: 924 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc); 925 926 case Stmt::CXXFunctionalCastExprClass: 927 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc); 928 929 case Stmt::CXXTemporaryObjectExprClass: 930 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc); 931 932 case Stmt::CXXThrowExprClass: 933 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S)); 934 935 case Stmt::CXXTryStmtClass: 936 return VisitCXXTryStmt(cast<CXXTryStmt>(S)); 937 938 case Stmt::CXXForRangeStmtClass: 939 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S)); 940 941 case Stmt::DeclStmtClass: 942 return VisitDeclStmt(cast<DeclStmt>(S)); 943 944 case Stmt::DefaultStmtClass: 945 return VisitDefaultStmt(cast<DefaultStmt>(S)); 946 947 case Stmt::DoStmtClass: 948 return VisitDoStmt(cast<DoStmt>(S)); 949 950 case Stmt::ForStmtClass: 951 return VisitForStmt(cast<ForStmt>(S)); 952 953 case Stmt::GotoStmtClass: 954 return VisitGotoStmt(cast<GotoStmt>(S)); 955 956 case Stmt::IfStmtClass: 957 return VisitIfStmt(cast<IfStmt>(S)); 958 959 case Stmt::ImplicitCastExprClass: 960 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc); 961 962 case Stmt::IndirectGotoStmtClass: 963 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S)); 964 965 case Stmt::LabelStmtClass: 966 return VisitLabelStmt(cast<LabelStmt>(S)); 967 968 case Stmt::MemberExprClass: 969 return VisitMemberExpr(cast<MemberExpr>(S), asc); 970 971 case Stmt::ObjCAtCatchStmtClass: 972 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S)); 973 974 case Stmt::ObjCAtSynchronizedStmtClass: 975 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S)); 976 977 case Stmt::ObjCAtThrowStmtClass: 978 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S)); 979 980 case Stmt::ObjCAtTryStmtClass: 981 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S)); 982 983 case Stmt::ObjCForCollectionStmtClass: 984 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); 985 986 case Stmt::NullStmtClass: 987 return Block; 988 989 case Stmt::ReturnStmtClass: 990 return VisitReturnStmt(cast<ReturnStmt>(S)); 991 992 case Stmt::UnaryExprOrTypeTraitExprClass: 993 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 994 asc); 995 996 case Stmt::StmtExprClass: 997 return VisitStmtExpr(cast<StmtExpr>(S), asc); 998 999 case Stmt::SwitchStmtClass: 1000 return VisitSwitchStmt(cast<SwitchStmt>(S)); 1001 1002 case Stmt::UnaryOperatorClass: 1003 return VisitUnaryOperator(cast<UnaryOperator>(S), asc); 1004 1005 case Stmt::WhileStmtClass: 1006 return VisitWhileStmt(cast<WhileStmt>(S)); 1007 } 1008} 1009 1010CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) { 1011 if (asc.alwaysAdd(*this, S)) { 1012 autoCreateBlock(); 1013 appendStmt(Block, S); 1014 } 1015 1016 return VisitChildren(S); 1017} 1018 1019/// VisitChildren - Visit the children of a Stmt. 1020CFGBlock *CFGBuilder::VisitChildren(Stmt *Terminator) { 1021 CFGBlock *lastBlock = Block; 1022 for (Stmt::child_range I = Terminator->children(); I; ++I) 1023 if (Stmt *child = *I) 1024 if (CFGBlock *b = Visit(child)) 1025 lastBlock = b; 1026 1027 return lastBlock; 1028} 1029 1030CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, 1031 AddStmtChoice asc) { 1032 AddressTakenLabels.insert(A->getLabel()); 1033 1034 if (asc.alwaysAdd(*this, A)) { 1035 autoCreateBlock(); 1036 appendStmt(Block, A); 1037 } 1038 1039 return Block; 1040} 1041 1042CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, 1043 AddStmtChoice asc) { 1044 if (asc.alwaysAdd(*this, U)) { 1045 autoCreateBlock(); 1046 appendStmt(Block, U); 1047 } 1048 1049 return Visit(U->getSubExpr(), AddStmtChoice()); 1050} 1051 1052CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, 1053 AddStmtChoice asc) { 1054 if (B->isLogicalOp()) { // && or || 1055 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 1056 appendStmt(ConfluenceBlock, B); 1057 1058 if (badCFG) 1059 return 0; 1060 1061 // create the block evaluating the LHS 1062 CFGBlock *LHSBlock = createBlock(false); 1063 LHSBlock->setTerminator(B); 1064 1065 // create the block evaluating the RHS 1066 Succ = ConfluenceBlock; 1067 Block = NULL; 1068 CFGBlock *RHSBlock = addStmt(B->getRHS()); 1069 1070 if (RHSBlock) { 1071 if (badCFG) 1072 return 0; 1073 } else { 1074 // Create an empty block for cases where the RHS doesn't require 1075 // any explicit statements in the CFG. 1076 RHSBlock = createBlock(); 1077 } 1078 1079 // See if this is a known constant. 1080 TryResult KnownVal = tryEvaluateBool(B->getLHS()); 1081 if (KnownVal.isKnown() && (B->getOpcode() == BO_LOr)) 1082 KnownVal.negate(); 1083 1084 // Now link the LHSBlock with RHSBlock. 1085 if (B->getOpcode() == BO_LOr) { 1086 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 1087 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 1088 } else { 1089 assert(B->getOpcode() == BO_LAnd); 1090 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 1091 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 1092 } 1093 1094 // Generate the blocks for evaluating the LHS. 1095 Block = LHSBlock; 1096 return addStmt(B->getLHS()); 1097 } 1098 1099 if (B->getOpcode() == BO_Comma) { // , 1100 autoCreateBlock(); 1101 appendStmt(Block, B); 1102 addStmt(B->getRHS()); 1103 return addStmt(B->getLHS()); 1104 } 1105 1106 if (B->isAssignmentOp()) { 1107 if (asc.alwaysAdd(*this, B)) { 1108 autoCreateBlock(); 1109 appendStmt(Block, B); 1110 } 1111 Visit(B->getLHS()); 1112 return Visit(B->getRHS()); 1113 } 1114 1115 if (asc.alwaysAdd(*this, B)) { 1116 autoCreateBlock(); 1117 appendStmt(Block, B); 1118 } 1119 1120 CFGBlock *RBlock = Visit(B->getRHS()); 1121 CFGBlock *LBlock = Visit(B->getLHS()); 1122 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr 1123 // containing a DoStmt, and the LHS doesn't create a new block, then we should 1124 // return RBlock. Otherwise we'll incorrectly return NULL. 1125 return (LBlock ? LBlock : RBlock); 1126} 1127 1128CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) { 1129 if (asc.alwaysAdd(*this, E)) { 1130 autoCreateBlock(); 1131 appendStmt(Block, E); 1132 } 1133 return Block; 1134} 1135 1136CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) { 1137 // "break" is a control-flow statement. Thus we stop processing the current 1138 // block. 1139 if (badCFG) 1140 return 0; 1141 1142 // Now create a new block that ends with the break statement. 1143 Block = createBlock(false); 1144 Block->setTerminator(B); 1145 1146 // If there is no target for the break, then we are looking at an incomplete 1147 // AST. This means that the CFG cannot be constructed. 1148 if (BreakJumpTarget.block) { 1149 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B); 1150 addSuccessor(Block, BreakJumpTarget.block); 1151 } else 1152 badCFG = true; 1153 1154 1155 return Block; 1156} 1157 1158static bool CanThrow(Expr *E, ASTContext &Ctx) { 1159 QualType Ty = E->getType(); 1160 if (Ty->isFunctionPointerType()) 1161 Ty = Ty->getAs<PointerType>()->getPointeeType(); 1162 else if (Ty->isBlockPointerType()) 1163 Ty = Ty->getAs<BlockPointerType>()->getPointeeType(); 1164 1165 const FunctionType *FT = Ty->getAs<FunctionType>(); 1166 if (FT) { 1167 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) 1168 if (Proto->isNothrow(Ctx)) 1169 return false; 1170 } 1171 return true; 1172} 1173 1174CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) { 1175 // Compute the callee type. 1176 QualType calleeType = C->getCallee()->getType(); 1177 if (calleeType == Context->BoundMemberTy) { 1178 QualType boundType = Expr::findBoundMemberType(C->getCallee()); 1179 1180 // We should only get a null bound type if processing a dependent 1181 // CFG. Recover by assuming nothing. 1182 if (!boundType.isNull()) calleeType = boundType; 1183 } 1184 1185 // If this is a call to a no-return function, this stops the block here. 1186 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn(); 1187 1188 bool AddEHEdge = false; 1189 1190 // Languages without exceptions are assumed to not throw. 1191 if (Context->getLangOptions().Exceptions) { 1192 if (BuildOpts.AddEHEdges) 1193 AddEHEdge = true; 1194 } 1195 1196 if (FunctionDecl *FD = C->getDirectCallee()) { 1197 if (FD->hasAttr<NoReturnAttr>()) 1198 NoReturn = true; 1199 if (FD->hasAttr<NoThrowAttr>()) 1200 AddEHEdge = false; 1201 } 1202 1203 if (!CanThrow(C->getCallee(), *Context)) 1204 AddEHEdge = false; 1205 1206 if (!NoReturn && !AddEHEdge) 1207 return VisitStmt(C, asc.withAlwaysAdd(true)); 1208 1209 if (Block) { 1210 Succ = Block; 1211 if (badCFG) 1212 return 0; 1213 } 1214 1215 if (NoReturn) 1216 Block = createNoReturnBlock(); 1217 else 1218 Block = createBlock(); 1219 1220 appendStmt(Block, C); 1221 1222 if (AddEHEdge) { 1223 // Add exceptional edges. 1224 if (TryTerminatedBlock) 1225 addSuccessor(Block, TryTerminatedBlock); 1226 else 1227 addSuccessor(Block, &cfg->getExit()); 1228 } 1229 1230 return VisitChildren(C); 1231} 1232 1233CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C, 1234 AddStmtChoice asc) { 1235 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 1236 appendStmt(ConfluenceBlock, C); 1237 if (badCFG) 1238 return 0; 1239 1240 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); 1241 Succ = ConfluenceBlock; 1242 Block = NULL; 1243 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd); 1244 if (badCFG) 1245 return 0; 1246 1247 Succ = ConfluenceBlock; 1248 Block = NULL; 1249 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd); 1250 if (badCFG) 1251 return 0; 1252 1253 Block = createBlock(false); 1254 // See if this is a known constant. 1255 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 1256 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 1257 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 1258 Block->setTerminator(C); 1259 return addStmt(C->getCond()); 1260} 1261 1262 1263CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) { 1264 addLocalScopeAndDtors(C); 1265 CFGBlock *LastBlock = Block; 1266 1267 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend(); 1268 I != E; ++I ) { 1269 // If we hit a segment of code just containing ';' (NullStmts), we can 1270 // get a null block back. In such cases, just use the LastBlock 1271 if (CFGBlock *newBlock = addStmt(*I)) 1272 LastBlock = newBlock; 1273 1274 if (badCFG) 1275 return NULL; 1276 } 1277 1278 return LastBlock; 1279} 1280 1281CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C, 1282 AddStmtChoice asc) { 1283 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C); 1284 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : NULL); 1285 1286 // Create the confluence block that will "merge" the results of the ternary 1287 // expression. 1288 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 1289 appendStmt(ConfluenceBlock, C); 1290 if (badCFG) 1291 return 0; 1292 1293 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); 1294 1295 // Create a block for the LHS expression if there is an LHS expression. A 1296 // GCC extension allows LHS to be NULL, causing the condition to be the 1297 // value that is returned instead. 1298 // e.g: x ?: y is shorthand for: x ? x : y; 1299 Succ = ConfluenceBlock; 1300 Block = NULL; 1301 CFGBlock *LHSBlock = 0; 1302 const Expr *trueExpr = C->getTrueExpr(); 1303 if (trueExpr != opaqueValue) { 1304 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd); 1305 if (badCFG) 1306 return 0; 1307 Block = NULL; 1308 } 1309 else 1310 LHSBlock = ConfluenceBlock; 1311 1312 // Create the block for the RHS expression. 1313 Succ = ConfluenceBlock; 1314 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd); 1315 if (badCFG) 1316 return 0; 1317 1318 // Create the block that will contain the condition. 1319 Block = createBlock(false); 1320 1321 // See if this is a known constant. 1322 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 1323 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 1324 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 1325 Block->setTerminator(C); 1326 Expr *condExpr = C->getCond(); 1327 1328 if (opaqueValue) { 1329 // Run the condition expression if it's not trivially expressed in 1330 // terms of the opaque value (or if there is no opaque value). 1331 if (condExpr != opaqueValue) 1332 addStmt(condExpr); 1333 1334 // Before that, run the common subexpression if there was one. 1335 // At least one of this or the above will be run. 1336 return addStmt(BCO->getCommon()); 1337 } 1338 1339 return addStmt(condExpr); 1340} 1341 1342CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { 1343 // Check if the Decl is for an __label__. If so, elide it from the 1344 // CFG entirely. 1345 if (isa<LabelDecl>(*DS->decl_begin())) 1346 return Block; 1347 1348 // This case also handles static_asserts. 1349 if (DS->isSingleDecl()) 1350 return VisitDeclSubExpr(DS); 1351 1352 CFGBlock *B = 0; 1353 1354 // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy. 1355 typedef SmallVector<Decl*,10> BufTy; 1356 BufTy Buf(DS->decl_begin(), DS->decl_end()); 1357 1358 for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) { 1359 // Get the alignment of the new DeclStmt, padding out to >=8 bytes. 1360 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8 1361 ? 8 : llvm::AlignOf<DeclStmt>::Alignment; 1362 1363 // Allocate the DeclStmt using the BumpPtrAllocator. It will get 1364 // automatically freed with the CFG. 1365 DeclGroupRef DG(*I); 1366 Decl *D = *I; 1367 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); 1368 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); 1369 1370 // Append the fake DeclStmt to block. 1371 B = VisitDeclSubExpr(DSNew); 1372 } 1373 1374 return B; 1375} 1376 1377/// VisitDeclSubExpr - Utility method to add block-level expressions for 1378/// DeclStmts and initializers in them. 1379CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) { 1380 assert(DS->isSingleDecl() && "Can handle single declarations only."); 1381 Decl *D = DS->getSingleDecl(); 1382 1383 if (isa<StaticAssertDecl>(D)) { 1384 // static_asserts aren't added to the CFG because they do not impact 1385 // runtime semantics. 1386 return Block; 1387 } 1388 1389 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); 1390 1391 if (!VD) { 1392 autoCreateBlock(); 1393 appendStmt(Block, DS); 1394 return Block; 1395 } 1396 1397 bool IsReference = false; 1398 bool HasTemporaries = false; 1399 1400 // Destructors of temporaries in initialization expression should be called 1401 // after initialization finishes. 1402 Expr *Init = VD->getInit(); 1403 if (Init) { 1404 IsReference = VD->getType()->isReferenceType(); 1405 HasTemporaries = isa<ExprWithCleanups>(Init); 1406 1407 if (BuildOpts.AddImplicitDtors && HasTemporaries) { 1408 // Generate destructors for temporaries in initialization expression. 1409 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 1410 IsReference); 1411 } 1412 } 1413 1414 autoCreateBlock(); 1415 appendStmt(Block, DS); 1416 1417 if (Init) { 1418 if (HasTemporaries) 1419 // For expression with temporaries go directly to subexpression to omit 1420 // generating destructors for the second time. 1421 Visit(cast<ExprWithCleanups>(Init)->getSubExpr()); 1422 else 1423 Visit(Init); 1424 } 1425 1426 // If the type of VD is a VLA, then we must process its size expressions. 1427 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); 1428 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 1429 Block = addStmt(VA->getSizeExpr()); 1430 1431 // Remove variable from local scope. 1432 if (ScopePos && VD == *ScopePos) 1433 ++ScopePos; 1434 1435 return Block; 1436} 1437 1438CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) { 1439 // We may see an if statement in the middle of a basic block, or it may be the 1440 // first statement we are processing. In either case, we create a new basic 1441 // block. First, we create the blocks for the then...else statements, and 1442 // then we create the block containing the if statement. If we were in the 1443 // middle of a block, we stop processing that block. That block is then the 1444 // implicit successor for the "then" and "else" clauses. 1445 1446 // Save local scope position because in case of condition variable ScopePos 1447 // won't be restored when traversing AST. 1448 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1449 1450 // Create local scope for possible condition variable. 1451 // Store scope position. Add implicit destructor. 1452 if (VarDecl *VD = I->getConditionVariable()) { 1453 LocalScope::const_iterator BeginScopePos = ScopePos; 1454 addLocalScopeForVarDecl(VD); 1455 addAutomaticObjDtors(ScopePos, BeginScopePos, I); 1456 } 1457 1458 // The block we were processing is now finished. Make it the successor 1459 // block. 1460 if (Block) { 1461 Succ = Block; 1462 if (badCFG) 1463 return 0; 1464 } 1465 1466 // Process the false branch. 1467 CFGBlock *ElseBlock = Succ; 1468 1469 if (Stmt *Else = I->getElse()) { 1470 SaveAndRestore<CFGBlock*> sv(Succ); 1471 1472 // NULL out Block so that the recursive call to Visit will 1473 // create a new basic block. 1474 Block = NULL; 1475 1476 // If branch is not a compound statement create implicit scope 1477 // and add destructors. 1478 if (!isa<CompoundStmt>(Else)) 1479 addLocalScopeAndDtors(Else); 1480 1481 ElseBlock = addStmt(Else); 1482 1483 if (!ElseBlock) // Can occur when the Else body has all NullStmts. 1484 ElseBlock = sv.get(); 1485 else if (Block) { 1486 if (badCFG) 1487 return 0; 1488 } 1489 } 1490 1491 // Process the true branch. 1492 CFGBlock *ThenBlock; 1493 { 1494 Stmt *Then = I->getThen(); 1495 assert(Then); 1496 SaveAndRestore<CFGBlock*> sv(Succ); 1497 Block = NULL; 1498 1499 // If branch is not a compound statement create implicit scope 1500 // and add destructors. 1501 if (!isa<CompoundStmt>(Then)) 1502 addLocalScopeAndDtors(Then); 1503 1504 ThenBlock = addStmt(Then); 1505 1506 if (!ThenBlock) { 1507 // We can reach here if the "then" body has all NullStmts. 1508 // Create an empty block so we can distinguish between true and false 1509 // branches in path-sensitive analyses. 1510 ThenBlock = createBlock(false); 1511 addSuccessor(ThenBlock, sv.get()); 1512 } else if (Block) { 1513 if (badCFG) 1514 return 0; 1515 } 1516 } 1517 1518 // Now create a new block containing the if statement. 1519 Block = createBlock(false); 1520 1521 // Set the terminator of the new block to the If statement. 1522 Block->setTerminator(I); 1523 1524 // See if this is a known constant. 1525 const TryResult &KnownVal = tryEvaluateBool(I->getCond()); 1526 1527 // Now add the successors. 1528 addSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock); 1529 addSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock); 1530 1531 // Add the condition as the last statement in the new block. This may create 1532 // new blocks as the condition may contain control-flow. Any newly created 1533 // blocks will be pointed to be "Block". 1534 Block = addStmt(I->getCond()); 1535 1536 // Finally, if the IfStmt contains a condition variable, add both the IfStmt 1537 // and the condition variable initialization to the CFG. 1538 if (VarDecl *VD = I->getConditionVariable()) { 1539 if (Expr *Init = VD->getInit()) { 1540 autoCreateBlock(); 1541 appendStmt(Block, I->getConditionVariableDeclStmt()); 1542 addStmt(Init); 1543 } 1544 } 1545 1546 return Block; 1547} 1548 1549 1550CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) { 1551 // If we were in the middle of a block we stop processing that block. 1552 // 1553 // NOTE: If a "return" appears in the middle of a block, this means that the 1554 // code afterwards is DEAD (unreachable). We still keep a basic block 1555 // for that code; a simple "mark-and-sweep" from the entry block will be 1556 // able to report such dead blocks. 1557 1558 // Create the new block. 1559 Block = createBlock(false); 1560 1561 // The Exit block is the only successor. 1562 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R); 1563 addSuccessor(Block, &cfg->getExit()); 1564 1565 // Add the return statement to the block. This may create new blocks if R 1566 // contains control-flow (short-circuit operations). 1567 return VisitStmt(R, AddStmtChoice::AlwaysAdd); 1568} 1569 1570CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) { 1571 // Get the block of the labeled statement. Add it to our map. 1572 addStmt(L->getSubStmt()); 1573 CFGBlock *LabelBlock = Block; 1574 1575 if (!LabelBlock) // This can happen when the body is empty, i.e. 1576 LabelBlock = createBlock(); // scopes that only contains NullStmts. 1577 1578 assert(LabelMap.find(L->getDecl()) == LabelMap.end() && 1579 "label already in map"); 1580 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos); 1581 1582 // Labels partition blocks, so this is the end of the basic block we were 1583 // processing (L is the block's label). Because this is label (and we have 1584 // already processed the substatement) there is no extra control-flow to worry 1585 // about. 1586 LabelBlock->setLabel(L); 1587 if (badCFG) 1588 return 0; 1589 1590 // We set Block to NULL to allow lazy creation of a new block (if necessary); 1591 Block = NULL; 1592 1593 // This block is now the implicit successor of other blocks. 1594 Succ = LabelBlock; 1595 1596 return LabelBlock; 1597} 1598 1599CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) { 1600 // Goto is a control-flow statement. Thus we stop processing the current 1601 // block and create a new one. 1602 1603 Block = createBlock(false); 1604 Block->setTerminator(G); 1605 1606 // If we already know the mapping to the label block add the successor now. 1607 LabelMapTy::iterator I = LabelMap.find(G->getLabel()); 1608 1609 if (I == LabelMap.end()) 1610 // We will need to backpatch this block later. 1611 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 1612 else { 1613 JumpTarget JT = I->second; 1614 addAutomaticObjDtors(ScopePos, JT.scopePosition, G); 1615 addSuccessor(Block, JT.block); 1616 } 1617 1618 return Block; 1619} 1620 1621CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { 1622 CFGBlock *LoopSuccessor = NULL; 1623 1624 // Save local scope position because in case of condition variable ScopePos 1625 // won't be restored when traversing AST. 1626 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1627 1628 // Create local scope for init statement and possible condition variable. 1629 // Add destructor for init statement and condition variable. 1630 // Store scope position for continue statement. 1631 if (Stmt *Init = F->getInit()) 1632 addLocalScopeForStmt(Init); 1633 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 1634 1635 if (VarDecl *VD = F->getConditionVariable()) 1636 addLocalScopeForVarDecl(VD); 1637 LocalScope::const_iterator ContinueScopePos = ScopePos; 1638 1639 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F); 1640 1641 // "for" is a control-flow statement. Thus we stop processing the current 1642 // block. 1643 if (Block) { 1644 if (badCFG) 1645 return 0; 1646 LoopSuccessor = Block; 1647 } else 1648 LoopSuccessor = Succ; 1649 1650 // Save the current value for the break targets. 1651 // All breaks should go to the code following the loop. 1652 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 1653 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1654 1655 // Because of short-circuit evaluation, the condition of the loop can span 1656 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1657 // evaluate the condition. 1658 CFGBlock *ExitConditionBlock = createBlock(false); 1659 CFGBlock *EntryConditionBlock = ExitConditionBlock; 1660 1661 // Set the terminator for the "exit" condition block. 1662 ExitConditionBlock->setTerminator(F); 1663 1664 // Now add the actual condition to the condition block. Because the condition 1665 // itself may contain control-flow, new blocks may be created. 1666 if (Stmt *C = F->getCond()) { 1667 Block = ExitConditionBlock; 1668 EntryConditionBlock = addStmt(C); 1669 if (badCFG) 1670 return 0; 1671 assert(Block == EntryConditionBlock || 1672 (Block == 0 && EntryConditionBlock == Succ)); 1673 1674 // If this block contains a condition variable, add both the condition 1675 // variable and initializer to the CFG. 1676 if (VarDecl *VD = F->getConditionVariable()) { 1677 if (Expr *Init = VD->getInit()) { 1678 autoCreateBlock(); 1679 appendStmt(Block, F->getConditionVariableDeclStmt()); 1680 EntryConditionBlock = addStmt(Init); 1681 assert(Block == EntryConditionBlock); 1682 } 1683 } 1684 1685 if (Block) { 1686 if (badCFG) 1687 return 0; 1688 } 1689 } 1690 1691 // The condition block is the implicit successor for the loop body as well as 1692 // any code above the loop. 1693 Succ = EntryConditionBlock; 1694 1695 // See if this is a known constant. 1696 TryResult KnownVal(true); 1697 1698 if (F->getCond()) 1699 KnownVal = tryEvaluateBool(F->getCond()); 1700 1701 // Now create the loop body. 1702 { 1703 assert(F->getBody()); 1704 1705 // Save the current values for Block, Succ, and continue targets. 1706 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 1707 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 1708 1709 // Create a new block to contain the (bottom) of the loop body. 1710 Block = NULL; 1711 1712 // Loop body should end with destructor of Condition variable (if any). 1713 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F); 1714 1715 if (Stmt *I = F->getInc()) { 1716 // Generate increment code in its own basic block. This is the target of 1717 // continue statements. 1718 Succ = addStmt(I); 1719 } else { 1720 // No increment code. Create a special, empty, block that is used as the 1721 // target block for "looping back" to the start of the loop. 1722 assert(Succ == EntryConditionBlock); 1723 Succ = Block ? Block : createBlock(); 1724 } 1725 1726 // Finish up the increment (or empty) block if it hasn't been already. 1727 if (Block) { 1728 assert(Block == Succ); 1729 if (badCFG) 1730 return 0; 1731 Block = 0; 1732 } 1733 1734 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 1735 1736 // The starting block for the loop increment is the block that should 1737 // represent the 'loop target' for looping back to the start of the loop. 1738 ContinueJumpTarget.block->setLoopTarget(F); 1739 1740 // If body is not a compound statement create implicit scope 1741 // and add destructors. 1742 if (!isa<CompoundStmt>(F->getBody())) 1743 addLocalScopeAndDtors(F->getBody()); 1744 1745 // Now populate the body block, and in the process create new blocks as we 1746 // walk the body of the loop. 1747 CFGBlock *BodyBlock = addStmt(F->getBody()); 1748 1749 if (!BodyBlock) 1750 BodyBlock = ContinueJumpTarget.block;//can happen for "for (...;...;...);" 1751 else if (badCFG) 1752 return 0; 1753 1754 // This new body block is a successor to our "exit" condition block. 1755 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 1756 } 1757 1758 // Link up the condition block with the code that follows the loop. (the 1759 // false branch). 1760 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 1761 1762 // If the loop contains initialization, create a new block for those 1763 // statements. This block can also contain statements that precede the loop. 1764 if (Stmt *I = F->getInit()) { 1765 Block = createBlock(); 1766 return addStmt(I); 1767 } 1768 1769 // There is no loop initialization. We are thus basically a while loop. 1770 // NULL out Block to force lazy block construction. 1771 Block = NULL; 1772 Succ = EntryConditionBlock; 1773 return EntryConditionBlock; 1774} 1775 1776CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) { 1777 if (asc.alwaysAdd(*this, M)) { 1778 autoCreateBlock(); 1779 appendStmt(Block, M); 1780 } 1781 return Visit(M->getBase()); 1782} 1783 1784CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { 1785 // Objective-C fast enumeration 'for' statements: 1786 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC 1787 // 1788 // for ( Type newVariable in collection_expression ) { statements } 1789 // 1790 // becomes: 1791 // 1792 // prologue: 1793 // 1. collection_expression 1794 // T. jump to loop_entry 1795 // loop_entry: 1796 // 1. side-effects of element expression 1797 // 1. ObjCForCollectionStmt [performs binding to newVariable] 1798 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] 1799 // TB: 1800 // statements 1801 // T. jump to loop_entry 1802 // FB: 1803 // what comes after 1804 // 1805 // and 1806 // 1807 // Type existingItem; 1808 // for ( existingItem in expression ) { statements } 1809 // 1810 // becomes: 1811 // 1812 // the same with newVariable replaced with existingItem; the binding works 1813 // the same except that for one ObjCForCollectionStmt::getElement() returns 1814 // a DeclStmt and the other returns a DeclRefExpr. 1815 // 1816 1817 CFGBlock *LoopSuccessor = 0; 1818 1819 if (Block) { 1820 if (badCFG) 1821 return 0; 1822 LoopSuccessor = Block; 1823 Block = 0; 1824 } else 1825 LoopSuccessor = Succ; 1826 1827 // Build the condition blocks. 1828 CFGBlock *ExitConditionBlock = createBlock(false); 1829 1830 // Set the terminator for the "exit" condition block. 1831 ExitConditionBlock->setTerminator(S); 1832 1833 // The last statement in the block should be the ObjCForCollectionStmt, which 1834 // performs the actual binding to 'element' and determines if there are any 1835 // more items in the collection. 1836 appendStmt(ExitConditionBlock, S); 1837 Block = ExitConditionBlock; 1838 1839 // Walk the 'element' expression to see if there are any side-effects. We 1840 // generate new blocks as necessary. We DON'T add the statement by default to 1841 // the CFG unless it contains control-flow. 1842 CFGBlock *EntryConditionBlock = Visit(S->getElement(), 1843 AddStmtChoice::NotAlwaysAdd); 1844 if (Block) { 1845 if (badCFG) 1846 return 0; 1847 Block = 0; 1848 } 1849 1850 // The condition block is the implicit successor for the loop body as well as 1851 // any code above the loop. 1852 Succ = EntryConditionBlock; 1853 1854 // Now create the true branch. 1855 { 1856 // Save the current values for Succ, continue and break targets. 1857 SaveAndRestore<CFGBlock*> save_Succ(Succ); 1858 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 1859 save_break(BreakJumpTarget); 1860 1861 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1862 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 1863 1864 CFGBlock *BodyBlock = addStmt(S->getBody()); 1865 1866 if (!BodyBlock) 1867 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;" 1868 else if (Block) { 1869 if (badCFG) 1870 return 0; 1871 } 1872 1873 // This new body block is a successor to our "exit" condition block. 1874 addSuccessor(ExitConditionBlock, BodyBlock); 1875 } 1876 1877 // Link up the condition block with the code that follows the loop. 1878 // (the false branch). 1879 addSuccessor(ExitConditionBlock, LoopSuccessor); 1880 1881 // Now create a prologue block to contain the collection expression. 1882 Block = createBlock(); 1883 return addStmt(S->getCollection()); 1884} 1885 1886CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) { 1887 // FIXME: Add locking 'primitives' to CFG for @synchronized. 1888 1889 // Inline the body. 1890 CFGBlock *SyncBlock = addStmt(S->getSynchBody()); 1891 1892 // The sync body starts its own basic block. This makes it a little easier 1893 // for diagnostic clients. 1894 if (SyncBlock) { 1895 if (badCFG) 1896 return 0; 1897 1898 Block = 0; 1899 Succ = SyncBlock; 1900 } 1901 1902 // Add the @synchronized to the CFG. 1903 autoCreateBlock(); 1904 appendStmt(Block, S); 1905 1906 // Inline the sync expression. 1907 return addStmt(S->getSynchExpr()); 1908} 1909 1910CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { 1911 // FIXME 1912 return NYS(); 1913} 1914 1915CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) { 1916 CFGBlock *LoopSuccessor = NULL; 1917 1918 // Save local scope position because in case of condition variable ScopePos 1919 // won't be restored when traversing AST. 1920 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1921 1922 // Create local scope for possible condition variable. 1923 // Store scope position for continue statement. 1924 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 1925 if (VarDecl *VD = W->getConditionVariable()) { 1926 addLocalScopeForVarDecl(VD); 1927 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); 1928 } 1929 1930 // "while" is a control-flow statement. Thus we stop processing the current 1931 // block. 1932 if (Block) { 1933 if (badCFG) 1934 return 0; 1935 LoopSuccessor = Block; 1936 Block = 0; 1937 } else 1938 LoopSuccessor = Succ; 1939 1940 // Because of short-circuit evaluation, the condition of the loop can span 1941 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1942 // evaluate the condition. 1943 CFGBlock *ExitConditionBlock = createBlock(false); 1944 CFGBlock *EntryConditionBlock = ExitConditionBlock; 1945 1946 // Set the terminator for the "exit" condition block. 1947 ExitConditionBlock->setTerminator(W); 1948 1949 // Now add the actual condition to the condition block. Because the condition 1950 // itself may contain control-flow, new blocks may be created. Thus we update 1951 // "Succ" after adding the condition. 1952 if (Stmt *C = W->getCond()) { 1953 Block = ExitConditionBlock; 1954 EntryConditionBlock = addStmt(C); 1955 // The condition might finish the current 'Block'. 1956 Block = EntryConditionBlock; 1957 1958 // If this block contains a condition variable, add both the condition 1959 // variable and initializer to the CFG. 1960 if (VarDecl *VD = W->getConditionVariable()) { 1961 if (Expr *Init = VD->getInit()) { 1962 autoCreateBlock(); 1963 appendStmt(Block, W->getConditionVariableDeclStmt()); 1964 EntryConditionBlock = addStmt(Init); 1965 assert(Block == EntryConditionBlock); 1966 } 1967 } 1968 1969 if (Block) { 1970 if (badCFG) 1971 return 0; 1972 } 1973 } 1974 1975 // The condition block is the implicit successor for the loop body as well as 1976 // any code above the loop. 1977 Succ = EntryConditionBlock; 1978 1979 // See if this is a known constant. 1980 const TryResult& KnownVal = tryEvaluateBool(W->getCond()); 1981 1982 // Process the loop body. 1983 { 1984 assert(W->getBody()); 1985 1986 // Save the current values for Block, Succ, and continue and break targets 1987 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 1988 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 1989 save_break(BreakJumpTarget); 1990 1991 // Create an empty block to represent the transition block for looping back 1992 // to the head of the loop. 1993 Block = 0; 1994 assert(Succ == EntryConditionBlock); 1995 Succ = createBlock(); 1996 Succ->setLoopTarget(W); 1997 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); 1998 1999 // All breaks should go to the code following the loop. 2000 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2001 2002 // NULL out Block to force lazy instantiation of blocks for the body. 2003 Block = NULL; 2004 2005 // Loop body should end with destructor of Condition variable (if any). 2006 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); 2007 2008 // If body is not a compound statement create implicit scope 2009 // and add destructors. 2010 if (!isa<CompoundStmt>(W->getBody())) 2011 addLocalScopeAndDtors(W->getBody()); 2012 2013 // Create the body. The returned block is the entry to the loop body. 2014 CFGBlock *BodyBlock = addStmt(W->getBody()); 2015 2016 if (!BodyBlock) 2017 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;" 2018 else if (Block) { 2019 if (badCFG) 2020 return 0; 2021 } 2022 2023 // Add the loop body entry as a successor to the condition. 2024 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 2025 } 2026 2027 // Link up the condition block with the code that follows the loop. (the 2028 // false branch). 2029 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 2030 2031 // There can be no more statements in the condition block since we loop back 2032 // to this block. NULL out Block to force lazy creation of another block. 2033 Block = NULL; 2034 2035 // Return the condition block, which is the dominating block for the loop. 2036 Succ = EntryConditionBlock; 2037 return EntryConditionBlock; 2038} 2039 2040 2041CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { 2042 // FIXME: For now we pretend that @catch and the code it contains does not 2043 // exit. 2044 return Block; 2045} 2046 2047CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { 2048 // FIXME: This isn't complete. We basically treat @throw like a return 2049 // statement. 2050 2051 // If we were in the middle of a block we stop processing that block. 2052 if (badCFG) 2053 return 0; 2054 2055 // Create the new block. 2056 Block = createBlock(false); 2057 2058 // The Exit block is the only successor. 2059 addSuccessor(Block, &cfg->getExit()); 2060 2061 // Add the statement to the block. This may create new blocks if S contains 2062 // control-flow (short-circuit operations). 2063 return VisitStmt(S, AddStmtChoice::AlwaysAdd); 2064} 2065 2066CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) { 2067 // If we were in the middle of a block we stop processing that block. 2068 if (badCFG) 2069 return 0; 2070 2071 // Create the new block. 2072 Block = createBlock(false); 2073 2074 if (TryTerminatedBlock) 2075 // The current try statement is the only successor. 2076 addSuccessor(Block, TryTerminatedBlock); 2077 else 2078 // otherwise the Exit block is the only successor. 2079 addSuccessor(Block, &cfg->getExit()); 2080 2081 // Add the statement to the block. This may create new blocks if S contains 2082 // control-flow (short-circuit operations). 2083 return VisitStmt(T, AddStmtChoice::AlwaysAdd); 2084} 2085 2086CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) { 2087 CFGBlock *LoopSuccessor = NULL; 2088 2089 // "do...while" is a control-flow statement. Thus we stop processing the 2090 // current block. 2091 if (Block) { 2092 if (badCFG) 2093 return 0; 2094 LoopSuccessor = Block; 2095 } else 2096 LoopSuccessor = Succ; 2097 2098 // Because of short-circuit evaluation, the condition of the loop can span 2099 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 2100 // evaluate the condition. 2101 CFGBlock *ExitConditionBlock = createBlock(false); 2102 CFGBlock *EntryConditionBlock = ExitConditionBlock; 2103 2104 // Set the terminator for the "exit" condition block. 2105 ExitConditionBlock->setTerminator(D); 2106 2107 // Now add the actual condition to the condition block. Because the condition 2108 // itself may contain control-flow, new blocks may be created. 2109 if (Stmt *C = D->getCond()) { 2110 Block = ExitConditionBlock; 2111 EntryConditionBlock = addStmt(C); 2112 if (Block) { 2113 if (badCFG) 2114 return 0; 2115 } 2116 } 2117 2118 // The condition block is the implicit successor for the loop body. 2119 Succ = EntryConditionBlock; 2120 2121 // See if this is a known constant. 2122 const TryResult &KnownVal = tryEvaluateBool(D->getCond()); 2123 2124 // Process the loop body. 2125 CFGBlock *BodyBlock = NULL; 2126 { 2127 assert(D->getBody()); 2128 2129 // Save the current values for Block, Succ, and continue and break targets 2130 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 2131 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 2132 save_break(BreakJumpTarget); 2133 2134 // All continues within this loop should go to the condition block 2135 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 2136 2137 // All breaks should go to the code following the loop. 2138 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2139 2140 // NULL out Block to force lazy instantiation of blocks for the body. 2141 Block = NULL; 2142 2143 // If body is not a compound statement create implicit scope 2144 // and add destructors. 2145 if (!isa<CompoundStmt>(D->getBody())) 2146 addLocalScopeAndDtors(D->getBody()); 2147 2148 // Create the body. The returned block is the entry to the loop body. 2149 BodyBlock = addStmt(D->getBody()); 2150 2151 if (!BodyBlock) 2152 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" 2153 else if (Block) { 2154 if (badCFG) 2155 return 0; 2156 } 2157 2158 if (!KnownVal.isFalse()) { 2159 // Add an intermediate block between the BodyBlock and the 2160 // ExitConditionBlock to represent the "loop back" transition. Create an 2161 // empty block to represent the transition block for looping back to the 2162 // head of the loop. 2163 // FIXME: Can we do this more efficiently without adding another block? 2164 Block = NULL; 2165 Succ = BodyBlock; 2166 CFGBlock *LoopBackBlock = createBlock(); 2167 LoopBackBlock->setLoopTarget(D); 2168 2169 // Add the loop body entry as a successor to the condition. 2170 addSuccessor(ExitConditionBlock, LoopBackBlock); 2171 } 2172 else 2173 addSuccessor(ExitConditionBlock, NULL); 2174 } 2175 2176 // Link up the condition block with the code that follows the loop. 2177 // (the false branch). 2178 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 2179 2180 // There can be no more statements in the body block(s) since we loop back to 2181 // the body. NULL out Block to force lazy creation of another block. 2182 Block = NULL; 2183 2184 // Return the loop body, which is the dominating block for the loop. 2185 Succ = BodyBlock; 2186 return BodyBlock; 2187} 2188 2189CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) { 2190 // "continue" is a control-flow statement. Thus we stop processing the 2191 // current block. 2192 if (badCFG) 2193 return 0; 2194 2195 // Now create a new block that ends with the continue statement. 2196 Block = createBlock(false); 2197 Block->setTerminator(C); 2198 2199 // If there is no target for the continue, then we are looking at an 2200 // incomplete AST. This means the CFG cannot be constructed. 2201 if (ContinueJumpTarget.block) { 2202 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C); 2203 addSuccessor(Block, ContinueJumpTarget.block); 2204 } else 2205 badCFG = true; 2206 2207 return Block; 2208} 2209 2210CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 2211 AddStmtChoice asc) { 2212 2213 if (asc.alwaysAdd(*this, E)) { 2214 autoCreateBlock(); 2215 appendStmt(Block, E); 2216 } 2217 2218 // VLA types have expressions that must be evaluated. 2219 CFGBlock *lastBlock = Block; 2220 2221 if (E->isArgumentType()) { 2222 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); 2223 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 2224 lastBlock = addStmt(VA->getSizeExpr()); 2225 } 2226 return lastBlock; 2227} 2228 2229/// VisitStmtExpr - Utility method to handle (nested) statement 2230/// expressions (a GCC extension). 2231CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) { 2232 if (asc.alwaysAdd(*this, SE)) { 2233 autoCreateBlock(); 2234 appendStmt(Block, SE); 2235 } 2236 return VisitCompoundStmt(SE->getSubStmt()); 2237} 2238 2239CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) { 2240 // "switch" is a control-flow statement. Thus we stop processing the current 2241 // block. 2242 CFGBlock *SwitchSuccessor = NULL; 2243 2244 // Save local scope position because in case of condition variable ScopePos 2245 // won't be restored when traversing AST. 2246 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2247 2248 // Create local scope for possible condition variable. 2249 // Store scope position. Add implicit destructor. 2250 if (VarDecl *VD = Terminator->getConditionVariable()) { 2251 LocalScope::const_iterator SwitchBeginScopePos = ScopePos; 2252 addLocalScopeForVarDecl(VD); 2253 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator); 2254 } 2255 2256 if (Block) { 2257 if (badCFG) 2258 return 0; 2259 SwitchSuccessor = Block; 2260 } else SwitchSuccessor = Succ; 2261 2262 // Save the current "switch" context. 2263 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), 2264 save_default(DefaultCaseBlock); 2265 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 2266 2267 // Set the "default" case to be the block after the switch statement. If the 2268 // switch statement contains a "default:", this value will be overwritten with 2269 // the block for that code. 2270 DefaultCaseBlock = SwitchSuccessor; 2271 2272 // Create a new block that will contain the switch statement. 2273 SwitchTerminatedBlock = createBlock(false); 2274 2275 // Now process the switch body. The code after the switch is the implicit 2276 // successor. 2277 Succ = SwitchSuccessor; 2278 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos); 2279 2280 // When visiting the body, the case statements should automatically get linked 2281 // up to the switch. We also don't keep a pointer to the body, since all 2282 // control-flow from the switch goes to case/default statements. 2283 assert(Terminator->getBody() && "switch must contain a non-NULL body"); 2284 Block = NULL; 2285 2286 // For pruning unreachable case statements, save the current state 2287 // for tracking the condition value. 2288 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered, 2289 false); 2290 2291 // Determine if the switch condition can be explicitly evaluated. 2292 assert(Terminator->getCond() && "switch condition must be non-NULL"); 2293 Expr::EvalResult result; 2294 bool b = tryEvaluate(Terminator->getCond(), result); 2295 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond, 2296 b ? &result : 0); 2297 2298 // If body is not a compound statement create implicit scope 2299 // and add destructors. 2300 if (!isa<CompoundStmt>(Terminator->getBody())) 2301 addLocalScopeAndDtors(Terminator->getBody()); 2302 2303 addStmt(Terminator->getBody()); 2304 if (Block) { 2305 if (badCFG) 2306 return 0; 2307 } 2308 2309 // If we have no "default:" case, the default transition is to the code 2310 // following the switch body. Moreover, take into account if all the 2311 // cases of a switch are covered (e.g., switching on an enum value). 2312 addSuccessor(SwitchTerminatedBlock, 2313 switchExclusivelyCovered || Terminator->isAllEnumCasesCovered() 2314 ? 0 : DefaultCaseBlock); 2315 2316 // Add the terminator and condition in the switch block. 2317 SwitchTerminatedBlock->setTerminator(Terminator); 2318 Block = SwitchTerminatedBlock; 2319 Block = addStmt(Terminator->getCond()); 2320 2321 // Finally, if the SwitchStmt contains a condition variable, add both the 2322 // SwitchStmt and the condition variable initialization to the CFG. 2323 if (VarDecl *VD = Terminator->getConditionVariable()) { 2324 if (Expr *Init = VD->getInit()) { 2325 autoCreateBlock(); 2326 appendStmt(Block, Terminator->getConditionVariableDeclStmt()); 2327 addStmt(Init); 2328 } 2329 } 2330 2331 return Block; 2332} 2333 2334static bool shouldAddCase(bool &switchExclusivelyCovered, 2335 const Expr::EvalResult *switchCond, 2336 const CaseStmt *CS, 2337 ASTContext &Ctx) { 2338 if (!switchCond) 2339 return true; 2340 2341 bool addCase = false; 2342 2343 if (!switchExclusivelyCovered) { 2344 if (switchCond->Val.isInt()) { 2345 // Evaluate the LHS of the case value. 2346 Expr::EvalResult V1; 2347 CS->getLHS()->Evaluate(V1, Ctx); 2348 assert(V1.Val.isInt()); 2349 const llvm::APSInt &condInt = switchCond->Val.getInt(); 2350 const llvm::APSInt &lhsInt = V1.Val.getInt(); 2351 2352 if (condInt == lhsInt) { 2353 addCase = true; 2354 switchExclusivelyCovered = true; 2355 } 2356 else if (condInt < lhsInt) { 2357 if (const Expr *RHS = CS->getRHS()) { 2358 // Evaluate the RHS of the case value. 2359 Expr::EvalResult V2; 2360 RHS->Evaluate(V2, Ctx); 2361 assert(V2.Val.isInt()); 2362 if (V2.Val.getInt() <= condInt) { 2363 addCase = true; 2364 switchExclusivelyCovered = true; 2365 } 2366 } 2367 } 2368 } 2369 else 2370 addCase = true; 2371 } 2372 return addCase; 2373} 2374 2375CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) { 2376 // CaseStmts are essentially labels, so they are the first statement in a 2377 // block. 2378 CFGBlock *TopBlock = 0, *LastBlock = 0; 2379 2380 if (Stmt *Sub = CS->getSubStmt()) { 2381 // For deeply nested chains of CaseStmts, instead of doing a recursion 2382 // (which can blow out the stack), manually unroll and create blocks 2383 // along the way. 2384 while (isa<CaseStmt>(Sub)) { 2385 CFGBlock *currentBlock = createBlock(false); 2386 currentBlock->setLabel(CS); 2387 2388 if (TopBlock) 2389 addSuccessor(LastBlock, currentBlock); 2390 else 2391 TopBlock = currentBlock; 2392 2393 addSuccessor(SwitchTerminatedBlock, 2394 shouldAddCase(switchExclusivelyCovered, switchCond, 2395 CS, *Context) 2396 ? currentBlock : 0); 2397 2398 LastBlock = currentBlock; 2399 CS = cast<CaseStmt>(Sub); 2400 Sub = CS->getSubStmt(); 2401 } 2402 2403 addStmt(Sub); 2404 } 2405 2406 CFGBlock *CaseBlock = Block; 2407 if (!CaseBlock) 2408 CaseBlock = createBlock(); 2409 2410 // Cases statements partition blocks, so this is the top of the basic block we 2411 // were processing (the "case XXX:" is the label). 2412 CaseBlock->setLabel(CS); 2413 2414 if (badCFG) 2415 return 0; 2416 2417 // Add this block to the list of successors for the block with the switch 2418 // statement. 2419 assert(SwitchTerminatedBlock); 2420 addSuccessor(SwitchTerminatedBlock, 2421 shouldAddCase(switchExclusivelyCovered, switchCond, 2422 CS, *Context) 2423 ? CaseBlock : 0); 2424 2425 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2426 Block = NULL; 2427 2428 if (TopBlock) { 2429 addSuccessor(LastBlock, CaseBlock); 2430 Succ = TopBlock; 2431 } else { 2432 // This block is now the implicit successor of other blocks. 2433 Succ = CaseBlock; 2434 } 2435 2436 return Succ; 2437} 2438 2439CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) { 2440 if (Terminator->getSubStmt()) 2441 addStmt(Terminator->getSubStmt()); 2442 2443 DefaultCaseBlock = Block; 2444 2445 if (!DefaultCaseBlock) 2446 DefaultCaseBlock = createBlock(); 2447 2448 // Default statements partition blocks, so this is the top of the basic block 2449 // we were processing (the "default:" is the label). 2450 DefaultCaseBlock->setLabel(Terminator); 2451 2452 if (badCFG) 2453 return 0; 2454 2455 // Unlike case statements, we don't add the default block to the successors 2456 // for the switch statement immediately. This is done when we finish 2457 // processing the switch statement. This allows for the default case 2458 // (including a fall-through to the code after the switch statement) to always 2459 // be the last successor of a switch-terminated block. 2460 2461 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2462 Block = NULL; 2463 2464 // This block is now the implicit successor of other blocks. 2465 Succ = DefaultCaseBlock; 2466 2467 return DefaultCaseBlock; 2468} 2469 2470CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { 2471 // "try"/"catch" is a control-flow statement. Thus we stop processing the 2472 // current block. 2473 CFGBlock *TrySuccessor = NULL; 2474 2475 if (Block) { 2476 if (badCFG) 2477 return 0; 2478 TrySuccessor = Block; 2479 } else TrySuccessor = Succ; 2480 2481 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 2482 2483 // Create a new block that will contain the try statement. 2484 CFGBlock *NewTryTerminatedBlock = createBlock(false); 2485 // Add the terminator in the try block. 2486 NewTryTerminatedBlock->setTerminator(Terminator); 2487 2488 bool HasCatchAll = false; 2489 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) { 2490 // The code after the try is the implicit successor. 2491 Succ = TrySuccessor; 2492 CXXCatchStmt *CS = Terminator->getHandler(h); 2493 if (CS->getExceptionDecl() == 0) { 2494 HasCatchAll = true; 2495 } 2496 Block = NULL; 2497 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); 2498 if (CatchBlock == 0) 2499 return 0; 2500 // Add this block to the list of successors for the block with the try 2501 // statement. 2502 addSuccessor(NewTryTerminatedBlock, CatchBlock); 2503 } 2504 if (!HasCatchAll) { 2505 if (PrevTryTerminatedBlock) 2506 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 2507 else 2508 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 2509 } 2510 2511 // The code after the try is the implicit successor. 2512 Succ = TrySuccessor; 2513 2514 // Save the current "try" context. 2515 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock); 2516 cfg->addTryDispatchBlock(TryTerminatedBlock); 2517 2518 assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); 2519 Block = NULL; 2520 Block = addStmt(Terminator->getTryBlock()); 2521 return Block; 2522} 2523 2524CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) { 2525 // CXXCatchStmt are treated like labels, so they are the first statement in a 2526 // block. 2527 2528 // Save local scope position because in case of exception variable ScopePos 2529 // won't be restored when traversing AST. 2530 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2531 2532 // Create local scope for possible exception variable. 2533 // Store scope position. Add implicit destructor. 2534 if (VarDecl *VD = CS->getExceptionDecl()) { 2535 LocalScope::const_iterator BeginScopePos = ScopePos; 2536 addLocalScopeForVarDecl(VD); 2537 addAutomaticObjDtors(ScopePos, BeginScopePos, CS); 2538 } 2539 2540 if (CS->getHandlerBlock()) 2541 addStmt(CS->getHandlerBlock()); 2542 2543 CFGBlock *CatchBlock = Block; 2544 if (!CatchBlock) 2545 CatchBlock = createBlock(); 2546 2547 CatchBlock->setLabel(CS); 2548 2549 if (badCFG) 2550 return 0; 2551 2552 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2553 Block = NULL; 2554 2555 return CatchBlock; 2556} 2557 2558CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) { 2559 // C++0x for-range statements are specified as [stmt.ranged]: 2560 // 2561 // { 2562 // auto && __range = range-init; 2563 // for ( auto __begin = begin-expr, 2564 // __end = end-expr; 2565 // __begin != __end; 2566 // ++__begin ) { 2567 // for-range-declaration = *__begin; 2568 // statement 2569 // } 2570 // } 2571 2572 // Save local scope position before the addition of the implicit variables. 2573 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2574 2575 // Create local scopes and destructors for range, begin and end variables. 2576 if (Stmt *Range = S->getRangeStmt()) 2577 addLocalScopeForStmt(Range); 2578 if (Stmt *BeginEnd = S->getBeginEndStmt()) 2579 addLocalScopeForStmt(BeginEnd); 2580 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S); 2581 2582 LocalScope::const_iterator ContinueScopePos = ScopePos; 2583 2584 // "for" is a control-flow statement. Thus we stop processing the current 2585 // block. 2586 CFGBlock *LoopSuccessor = NULL; 2587 if (Block) { 2588 if (badCFG) 2589 return 0; 2590 LoopSuccessor = Block; 2591 } else 2592 LoopSuccessor = Succ; 2593 2594 // Save the current value for the break targets. 2595 // All breaks should go to the code following the loop. 2596 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 2597 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2598 2599 // The block for the __begin != __end expression. 2600 CFGBlock *ConditionBlock = createBlock(false); 2601 ConditionBlock->setTerminator(S); 2602 2603 // Now add the actual condition to the condition block. 2604 if (Expr *C = S->getCond()) { 2605 Block = ConditionBlock; 2606 CFGBlock *BeginConditionBlock = addStmt(C); 2607 if (badCFG) 2608 return 0; 2609 assert(BeginConditionBlock == ConditionBlock && 2610 "condition block in for-range was unexpectedly complex"); 2611 (void)BeginConditionBlock; 2612 } 2613 2614 // The condition block is the implicit successor for the loop body as well as 2615 // any code above the loop. 2616 Succ = ConditionBlock; 2617 2618 // See if this is a known constant. 2619 TryResult KnownVal(true); 2620 2621 if (S->getCond()) 2622 KnownVal = tryEvaluateBool(S->getCond()); 2623 2624 // Now create the loop body. 2625 { 2626 assert(S->getBody()); 2627 2628 // Save the current values for Block, Succ, and continue targets. 2629 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 2630 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 2631 2632 // Generate increment code in its own basic block. This is the target of 2633 // continue statements. 2634 Block = 0; 2635 Succ = addStmt(S->getInc()); 2636 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 2637 2638 // The starting block for the loop increment is the block that should 2639 // represent the 'loop target' for looping back to the start of the loop. 2640 ContinueJumpTarget.block->setLoopTarget(S); 2641 2642 // Finish up the increment block and prepare to start the loop body. 2643 assert(Block); 2644 if (badCFG) 2645 return 0; 2646 Block = 0; 2647 2648 2649 // Add implicit scope and dtors for loop variable. 2650 addLocalScopeAndDtors(S->getLoopVarStmt()); 2651 2652 // Populate a new block to contain the loop body and loop variable. 2653 Block = addStmt(S->getBody()); 2654 if (badCFG) 2655 return 0; 2656 Block = addStmt(S->getLoopVarStmt()); 2657 if (badCFG) 2658 return 0; 2659 2660 // This new body block is a successor to our condition block. 2661 addSuccessor(ConditionBlock, KnownVal.isFalse() ? 0 : Block); 2662 } 2663 2664 // Link up the condition block with the code that follows the loop (the 2665 // false branch). 2666 addSuccessor(ConditionBlock, KnownVal.isTrue() ? 0 : LoopSuccessor); 2667 2668 // Add the initialization statements. 2669 Block = createBlock(); 2670 addStmt(S->getBeginEndStmt()); 2671 return addStmt(S->getRangeStmt()); 2672} 2673 2674CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E, 2675 AddStmtChoice asc) { 2676 if (BuildOpts.AddImplicitDtors) { 2677 // If adding implicit destructors visit the full expression for adding 2678 // destructors of temporaries. 2679 VisitForTemporaryDtors(E->getSubExpr()); 2680 2681 // Full expression has to be added as CFGStmt so it will be sequenced 2682 // before destructors of it's temporaries. 2683 asc = asc.withAlwaysAdd(true); 2684 } 2685 return Visit(E->getSubExpr(), asc); 2686} 2687 2688CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 2689 AddStmtChoice asc) { 2690 if (asc.alwaysAdd(*this, E)) { 2691 autoCreateBlock(); 2692 appendStmt(Block, E); 2693 2694 // We do not want to propagate the AlwaysAdd property. 2695 asc = asc.withAlwaysAdd(false); 2696 } 2697 return Visit(E->getSubExpr(), asc); 2698} 2699 2700CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, 2701 AddStmtChoice asc) { 2702 autoCreateBlock(); 2703 if (!C->isElidable()) 2704 appendStmt(Block, C); 2705 2706 return VisitChildren(C); 2707} 2708 2709CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 2710 AddStmtChoice asc) { 2711 if (asc.alwaysAdd(*this, E)) { 2712 autoCreateBlock(); 2713 appendStmt(Block, E); 2714 // We do not want to propagate the AlwaysAdd property. 2715 asc = asc.withAlwaysAdd(false); 2716 } 2717 return Visit(E->getSubExpr(), asc); 2718} 2719 2720CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 2721 AddStmtChoice asc) { 2722 autoCreateBlock(); 2723 appendStmt(Block, C); 2724 return VisitChildren(C); 2725} 2726 2727CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, 2728 AddStmtChoice asc) { 2729 if (asc.alwaysAdd(*this, E)) { 2730 autoCreateBlock(); 2731 appendStmt(Block, E); 2732 } 2733 return Visit(E->getSubExpr(), AddStmtChoice()); 2734} 2735 2736CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) { 2737 // Lazily create the indirect-goto dispatch block if there isn't one already. 2738 CFGBlock *IBlock = cfg->getIndirectGotoBlock(); 2739 2740 if (!IBlock) { 2741 IBlock = createBlock(false); 2742 cfg->setIndirectGotoBlock(IBlock); 2743 } 2744 2745 // IndirectGoto is a control-flow statement. Thus we stop processing the 2746 // current block and create a new one. 2747 if (badCFG) 2748 return 0; 2749 2750 Block = createBlock(false); 2751 Block->setTerminator(I); 2752 addSuccessor(Block, IBlock); 2753 return addStmt(I->getTarget()); 2754} 2755 2756CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) { 2757tryAgain: 2758 if (!E) { 2759 badCFG = true; 2760 return NULL; 2761 } 2762 switch (E->getStmtClass()) { 2763 default: 2764 return VisitChildrenForTemporaryDtors(E); 2765 2766 case Stmt::BinaryOperatorClass: 2767 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E)); 2768 2769 case Stmt::CXXBindTemporaryExprClass: 2770 return VisitCXXBindTemporaryExprForTemporaryDtors( 2771 cast<CXXBindTemporaryExpr>(E), BindToTemporary); 2772 2773 case Stmt::BinaryConditionalOperatorClass: 2774 case Stmt::ConditionalOperatorClass: 2775 return VisitConditionalOperatorForTemporaryDtors( 2776 cast<AbstractConditionalOperator>(E), BindToTemporary); 2777 2778 case Stmt::ImplicitCastExprClass: 2779 // For implicit cast we want BindToTemporary to be passed further. 2780 E = cast<CastExpr>(E)->getSubExpr(); 2781 goto tryAgain; 2782 2783 case Stmt::ParenExprClass: 2784 E = cast<ParenExpr>(E)->getSubExpr(); 2785 goto tryAgain; 2786 2787 case Stmt::MaterializeTemporaryExprClass: 2788 E = cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(); 2789 goto tryAgain; 2790 } 2791} 2792 2793CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) { 2794 // When visiting children for destructors we want to visit them in reverse 2795 // order. Because there's no reverse iterator for children must to reverse 2796 // them in helper vector. 2797 typedef SmallVector<Stmt *, 4> ChildrenVect; 2798 ChildrenVect ChildrenRev; 2799 for (Stmt::child_range I = E->children(); I; ++I) { 2800 if (*I) ChildrenRev.push_back(*I); 2801 } 2802 2803 CFGBlock *B = Block; 2804 for (ChildrenVect::reverse_iterator I = ChildrenRev.rbegin(), 2805 L = ChildrenRev.rend(); I != L; ++I) { 2806 if (CFGBlock *R = VisitForTemporaryDtors(*I)) 2807 B = R; 2808 } 2809 return B; 2810} 2811 2812CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) { 2813 if (E->isLogicalOp()) { 2814 // Destructors for temporaries in LHS expression should be called after 2815 // those for RHS expression. Even if this will unnecessarily create a block, 2816 // this block will be used at least by the full expression. 2817 autoCreateBlock(); 2818 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS()); 2819 if (badCFG) 2820 return NULL; 2821 2822 Succ = ConfluenceBlock; 2823 Block = NULL; 2824 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2825 2826 if (RHSBlock) { 2827 if (badCFG) 2828 return NULL; 2829 2830 // If RHS expression did produce destructors we need to connect created 2831 // blocks to CFG in same manner as for binary operator itself. 2832 CFGBlock *LHSBlock = createBlock(false); 2833 LHSBlock->setTerminator(CFGTerminator(E, true)); 2834 2835 // For binary operator LHS block is before RHS in list of predecessors 2836 // of ConfluenceBlock. 2837 std::reverse(ConfluenceBlock->pred_begin(), 2838 ConfluenceBlock->pred_end()); 2839 2840 // See if this is a known constant. 2841 TryResult KnownVal = tryEvaluateBool(E->getLHS()); 2842 if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr)) 2843 KnownVal.negate(); 2844 2845 // Link LHSBlock with RHSBlock exactly the same way as for binary operator 2846 // itself. 2847 if (E->getOpcode() == BO_LOr) { 2848 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2849 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2850 } else { 2851 assert (E->getOpcode() == BO_LAnd); 2852 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2853 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2854 } 2855 2856 Block = LHSBlock; 2857 return LHSBlock; 2858 } 2859 2860 Block = ConfluenceBlock; 2861 return ConfluenceBlock; 2862 } 2863 2864 if (E->isAssignmentOp()) { 2865 // For assignment operator (=) LHS expression is visited 2866 // before RHS expression. For destructors visit them in reverse order. 2867 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2868 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2869 return LHSBlock ? LHSBlock : RHSBlock; 2870 } 2871 2872 // For any other binary operator RHS expression is visited before 2873 // LHS expression (order of children). For destructors visit them in reverse 2874 // order. 2875 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2876 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2877 return RHSBlock ? RHSBlock : LHSBlock; 2878} 2879 2880CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( 2881 CXXBindTemporaryExpr *E, bool BindToTemporary) { 2882 // First add destructors for temporaries in subexpression. 2883 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr()); 2884 if (!BindToTemporary) { 2885 // If lifetime of temporary is not prolonged (by assigning to constant 2886 // reference) add destructor for it. 2887 2888 // If the destructor is marked as a no-return destructor, we need to create 2889 // a new block for the destructor which does not have as a successor 2890 // anything built thus far. Control won't flow out of this block. 2891 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor(); 2892 if (cast<FunctionType>(Dtor->getType())->getNoReturnAttr()) 2893 Block = createNoReturnBlock(); 2894 else 2895 autoCreateBlock(); 2896 2897 appendTemporaryDtor(Block, E); 2898 B = Block; 2899 } 2900 return B; 2901} 2902 2903CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( 2904 AbstractConditionalOperator *E, bool BindToTemporary) { 2905 // First add destructors for condition expression. Even if this will 2906 // unnecessarily create a block, this block will be used at least by the full 2907 // expression. 2908 autoCreateBlock(); 2909 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond()); 2910 if (badCFG) 2911 return NULL; 2912 if (BinaryConditionalOperator *BCO 2913 = dyn_cast<BinaryConditionalOperator>(E)) { 2914 ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon()); 2915 if (badCFG) 2916 return NULL; 2917 } 2918 2919 // Try to add block with destructors for LHS expression. 2920 CFGBlock *LHSBlock = NULL; 2921 Succ = ConfluenceBlock; 2922 Block = NULL; 2923 LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary); 2924 if (badCFG) 2925 return NULL; 2926 2927 // Try to add block with destructors for RHS expression; 2928 Succ = ConfluenceBlock; 2929 Block = NULL; 2930 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(), 2931 BindToTemporary); 2932 if (badCFG) 2933 return NULL; 2934 2935 if (!RHSBlock && !LHSBlock) { 2936 // If neither LHS nor RHS expression had temporaries to destroy don't create 2937 // more blocks. 2938 Block = ConfluenceBlock; 2939 return Block; 2940 } 2941 2942 Block = createBlock(false); 2943 Block->setTerminator(CFGTerminator(E, true)); 2944 2945 // See if this is a known constant. 2946 const TryResult &KnownVal = tryEvaluateBool(E->getCond()); 2947 2948 if (LHSBlock) { 2949 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 2950 } else if (KnownVal.isFalse()) { 2951 addSuccessor(Block, NULL); 2952 } else { 2953 addSuccessor(Block, ConfluenceBlock); 2954 std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end()); 2955 } 2956 2957 if (!RHSBlock) 2958 RHSBlock = ConfluenceBlock; 2959 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 2960 2961 return Block; 2962} 2963 2964} // end anonymous namespace 2965 2966/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 2967/// no successors or predecessors. If this is the first block created in the 2968/// CFG, it is automatically set to be the Entry and Exit of the CFG. 2969CFGBlock *CFG::createBlock() { 2970 bool first_block = begin() == end(); 2971 2972 // Create the block. 2973 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 2974 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC); 2975 Blocks.push_back(Mem, BlkBVC); 2976 2977 // If this is the first block, set it as the Entry and Exit. 2978 if (first_block) 2979 Entry = Exit = &back(); 2980 2981 // Return the block. 2982 return &back(); 2983} 2984 2985/// buildCFG - Constructs a CFG from an AST. Ownership of the returned 2986/// CFG is returned to the caller. 2987CFG* CFG::buildCFG(const Decl *D, Stmt *Statement, ASTContext *C, 2988 const BuildOptions &BO) { 2989 CFGBuilder Builder(C, BO); 2990 return Builder.buildCFG(D, Statement); 2991} 2992 2993const CXXDestructorDecl * 2994CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { 2995 switch (getKind()) { 2996 case CFGElement::Invalid: 2997 case CFGElement::Statement: 2998 case CFGElement::Initializer: 2999 llvm_unreachable("getDestructorDecl should only be used with " 3000 "ImplicitDtors"); 3001 case CFGElement::AutomaticObjectDtor: { 3002 const VarDecl *var = cast<CFGAutomaticObjDtor>(this)->getVarDecl(); 3003 QualType ty = var->getType(); 3004 ty = ty.getNonReferenceType(); 3005 if (const ArrayType *arrayType = astContext.getAsArrayType(ty)) { 3006 ty = arrayType->getElementType(); 3007 } 3008 const RecordType *recordType = ty->getAs<RecordType>(); 3009 const CXXRecordDecl *classDecl = 3010 cast<CXXRecordDecl>(recordType->getDecl()); 3011 return classDecl->getDestructor(); 3012 } 3013 case CFGElement::TemporaryDtor: { 3014 const CXXBindTemporaryExpr *bindExpr = 3015 cast<CFGTemporaryDtor>(this)->getBindTemporaryExpr(); 3016 const CXXTemporary *temp = bindExpr->getTemporary(); 3017 return temp->getDestructor(); 3018 } 3019 case CFGElement::BaseDtor: 3020 case CFGElement::MemberDtor: 3021 3022 // Not yet supported. 3023 return 0; 3024 } 3025 llvm_unreachable("getKind() returned bogus value"); 3026 return 0; 3027} 3028 3029bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const { 3030 if (const CXXDestructorDecl *cdecl = getDestructorDecl(astContext)) { 3031 QualType ty = cdecl->getType(); 3032 return cast<FunctionType>(ty)->getNoReturnAttr(); 3033 } 3034 return false; 3035} 3036 3037//===----------------------------------------------------------------------===// 3038// CFG: Queries for BlkExprs. 3039//===----------------------------------------------------------------------===// 3040 3041namespace { 3042 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy; 3043} 3044 3045static void FindSubExprAssignments(const Stmt *S, 3046 llvm::SmallPtrSet<const Expr*,50>& Set) { 3047 if (!S) 3048 return; 3049 3050 for (Stmt::const_child_range I = S->children(); I; ++I) { 3051 const Stmt *child = *I; 3052 if (!child) 3053 continue; 3054 3055 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(child)) 3056 if (B->isAssignmentOp()) Set.insert(B); 3057 3058 FindSubExprAssignments(child, Set); 3059 } 3060} 3061 3062static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) { 3063 BlkExprMapTy* M = new BlkExprMapTy(); 3064 3065 // Look for assignments that are used as subexpressions. These are the only 3066 // assignments that we want to *possibly* register as a block-level 3067 // expression. Basically, if an assignment occurs both in a subexpression and 3068 // at the block-level, it is a block-level expression. 3069 llvm::SmallPtrSet<const Expr*,50> SubExprAssignments; 3070 3071 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) 3072 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) 3073 if (const CFGStmt *S = BI->getAs<CFGStmt>()) 3074 FindSubExprAssignments(S->getStmt(), SubExprAssignments); 3075 3076 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) { 3077 3078 // Iterate over the statements again on identify the Expr* and Stmt* at the 3079 // block-level that are block-level expressions. 3080 3081 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) { 3082 const CFGStmt *CS = BI->getAs<CFGStmt>(); 3083 if (!CS) 3084 continue; 3085 if (const Expr *Exp = dyn_cast<Expr>(CS->getStmt())) { 3086 assert((Exp->IgnoreParens() == Exp) && "No parens on block-level exps"); 3087 3088 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) { 3089 // Assignment expressions that are not nested within another 3090 // expression are really "statements" whose value is never used by 3091 // another expression. 3092 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp)) 3093 continue; 3094 } else if (const StmtExpr *SE = dyn_cast<StmtExpr>(Exp)) { 3095 // Special handling for statement expressions. The last statement in 3096 // the statement expression is also a block-level expr. 3097 const CompoundStmt *C = SE->getSubStmt(); 3098 if (!C->body_empty()) { 3099 const Stmt *Last = C->body_back(); 3100 if (const Expr *LastEx = dyn_cast<Expr>(Last)) 3101 Last = LastEx->IgnoreParens(); 3102 unsigned x = M->size(); 3103 (*M)[Last] = x; 3104 } 3105 } 3106 3107 unsigned x = M->size(); 3108 (*M)[Exp] = x; 3109 } 3110 } 3111 3112 // Look at terminators. The condition is a block-level expression. 3113 3114 Stmt *S = (*I)->getTerminatorCondition(); 3115 3116 if (S && M->find(S) == M->end()) { 3117 unsigned x = M->size(); 3118 (*M)[S] = x; 3119 } 3120 } 3121 3122 return M; 3123} 3124 3125CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt *S) { 3126 assert(S != NULL); 3127 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); } 3128 3129 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap); 3130 BlkExprMapTy::iterator I = M->find(S); 3131 return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second); 3132} 3133 3134unsigned CFG::getNumBlkExprs() { 3135 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap)) 3136 return M->size(); 3137 3138 // We assume callers interested in the number of BlkExprs will want 3139 // the map constructed if it doesn't already exist. 3140 BlkExprMap = (void*) PopulateBlkExprMap(*this); 3141 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size(); 3142} 3143 3144//===----------------------------------------------------------------------===// 3145// Filtered walking of the CFG. 3146//===----------------------------------------------------------------------===// 3147 3148bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 3149 const CFGBlock *From, const CFGBlock *To) { 3150 3151 if (To && F.IgnoreDefaultsWithCoveredEnums) { 3152 // If the 'To' has no label or is labeled but the label isn't a 3153 // CaseStmt then filter this edge. 3154 if (const SwitchStmt *S = 3155 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) { 3156 if (S->isAllEnumCasesCovered()) { 3157 const Stmt *L = To->getLabel(); 3158 if (!L || !isa<CaseStmt>(L)) 3159 return true; 3160 } 3161 } 3162 } 3163 3164 return false; 3165} 3166 3167//===----------------------------------------------------------------------===// 3168// Cleanup: CFG dstor. 3169//===----------------------------------------------------------------------===// 3170 3171CFG::~CFG() { 3172 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap); 3173} 3174 3175//===----------------------------------------------------------------------===// 3176// CFG pretty printing 3177//===----------------------------------------------------------------------===// 3178 3179namespace { 3180 3181class StmtPrinterHelper : public PrinterHelper { 3182 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; 3183 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy; 3184 StmtMapTy StmtMap; 3185 DeclMapTy DeclMap; 3186 signed currentBlock; 3187 unsigned currentStmt; 3188 const LangOptions &LangOpts; 3189public: 3190 3191 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 3192 : currentBlock(0), currentStmt(0), LangOpts(LO) 3193 { 3194 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 3195 unsigned j = 1; 3196 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 3197 BI != BEnd; ++BI, ++j ) { 3198 if (const CFGStmt *SE = BI->getAs<CFGStmt>()) { 3199 const Stmt *stmt= SE->getStmt(); 3200 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 3201 StmtMap[stmt] = P; 3202 3203 switch (stmt->getStmtClass()) { 3204 case Stmt::DeclStmtClass: 3205 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P; 3206 break; 3207 case Stmt::IfStmtClass: { 3208 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable(); 3209 if (var) 3210 DeclMap[var] = P; 3211 break; 3212 } 3213 case Stmt::ForStmtClass: { 3214 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable(); 3215 if (var) 3216 DeclMap[var] = P; 3217 break; 3218 } 3219 case Stmt::WhileStmtClass: { 3220 const VarDecl *var = 3221 cast<WhileStmt>(stmt)->getConditionVariable(); 3222 if (var) 3223 DeclMap[var] = P; 3224 break; 3225 } 3226 case Stmt::SwitchStmtClass: { 3227 const VarDecl *var = 3228 cast<SwitchStmt>(stmt)->getConditionVariable(); 3229 if (var) 3230 DeclMap[var] = P; 3231 break; 3232 } 3233 case Stmt::CXXCatchStmtClass: { 3234 const VarDecl *var = 3235 cast<CXXCatchStmt>(stmt)->getExceptionDecl(); 3236 if (var) 3237 DeclMap[var] = P; 3238 break; 3239 } 3240 default: 3241 break; 3242 } 3243 } 3244 } 3245 } 3246 } 3247 3248 3249 virtual ~StmtPrinterHelper() {} 3250 3251 const LangOptions &getLangOpts() const { return LangOpts; } 3252 void setBlockID(signed i) { currentBlock = i; } 3253 void setStmtID(unsigned i) { currentStmt = i; } 3254 3255 virtual bool handledStmt(Stmt *S, raw_ostream &OS) { 3256 StmtMapTy::iterator I = StmtMap.find(S); 3257 3258 if (I == StmtMap.end()) 3259 return false; 3260 3261 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 3262 && I->second.second == currentStmt) { 3263 return false; 3264 } 3265 3266 OS << "[B" << I->second.first << "." << I->second.second << "]"; 3267 return true; 3268 } 3269 3270 bool handleDecl(const Decl *D, raw_ostream &OS) { 3271 DeclMapTy::iterator I = DeclMap.find(D); 3272 3273 if (I == DeclMap.end()) 3274 return false; 3275 3276 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 3277 && I->second.second == currentStmt) { 3278 return false; 3279 } 3280 3281 OS << "[B" << I->second.first << "." << I->second.second << "]"; 3282 return true; 3283 } 3284}; 3285} // end anonymous namespace 3286 3287 3288namespace { 3289class CFGBlockTerminatorPrint 3290 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 3291 3292 raw_ostream &OS; 3293 StmtPrinterHelper* Helper; 3294 PrintingPolicy Policy; 3295public: 3296 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper, 3297 const PrintingPolicy &Policy) 3298 : OS(os), Helper(helper), Policy(Policy) {} 3299 3300 void VisitIfStmt(IfStmt *I) { 3301 OS << "if "; 3302 I->getCond()->printPretty(OS,Helper,Policy); 3303 } 3304 3305 // Default case. 3306 void VisitStmt(Stmt *Terminator) { 3307 Terminator->printPretty(OS, Helper, Policy); 3308 } 3309 3310 void VisitForStmt(ForStmt *F) { 3311 OS << "for (" ; 3312 if (F->getInit()) 3313 OS << "..."; 3314 OS << "; "; 3315 if (Stmt *C = F->getCond()) 3316 C->printPretty(OS, Helper, Policy); 3317 OS << "; "; 3318 if (F->getInc()) 3319 OS << "..."; 3320 OS << ")"; 3321 } 3322 3323 void VisitWhileStmt(WhileStmt *W) { 3324 OS << "while " ; 3325 if (Stmt *C = W->getCond()) 3326 C->printPretty(OS, Helper, Policy); 3327 } 3328 3329 void VisitDoStmt(DoStmt *D) { 3330 OS << "do ... while "; 3331 if (Stmt *C = D->getCond()) 3332 C->printPretty(OS, Helper, Policy); 3333 } 3334 3335 void VisitSwitchStmt(SwitchStmt *Terminator) { 3336 OS << "switch "; 3337 Terminator->getCond()->printPretty(OS, Helper, Policy); 3338 } 3339 3340 void VisitCXXTryStmt(CXXTryStmt *CS) { 3341 OS << "try ..."; 3342 } 3343 3344 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) { 3345 C->getCond()->printPretty(OS, Helper, Policy); 3346 OS << " ? ... : ..."; 3347 } 3348 3349 void VisitChooseExpr(ChooseExpr *C) { 3350 OS << "__builtin_choose_expr( "; 3351 C->getCond()->printPretty(OS, Helper, Policy); 3352 OS << " )"; 3353 } 3354 3355 void VisitIndirectGotoStmt(IndirectGotoStmt *I) { 3356 OS << "goto *"; 3357 I->getTarget()->printPretty(OS, Helper, Policy); 3358 } 3359 3360 void VisitBinaryOperator(BinaryOperator* B) { 3361 if (!B->isLogicalOp()) { 3362 VisitExpr(B); 3363 return; 3364 } 3365 3366 B->getLHS()->printPretty(OS, Helper, Policy); 3367 3368 switch (B->getOpcode()) { 3369 case BO_LOr: 3370 OS << " || ..."; 3371 return; 3372 case BO_LAnd: 3373 OS << " && ..."; 3374 return; 3375 default: 3376 llvm_unreachable("Invalid logical operator."); 3377 } 3378 } 3379 3380 void VisitExpr(Expr *E) { 3381 E->printPretty(OS, Helper, Policy); 3382 } 3383}; 3384} // end anonymous namespace 3385 3386static void print_elem(raw_ostream &OS, StmtPrinterHelper* Helper, 3387 const CFGElement &E) { 3388 if (const CFGStmt *CS = E.getAs<CFGStmt>()) { 3389 const Stmt *S = CS->getStmt(); 3390 3391 if (Helper) { 3392 3393 // special printing for statement-expressions. 3394 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) { 3395 const CompoundStmt *Sub = SE->getSubStmt(); 3396 3397 if (Sub->children()) { 3398 OS << "({ ... ; "; 3399 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 3400 OS << " })\n"; 3401 return; 3402 } 3403 } 3404 // special printing for comma expressions. 3405 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 3406 if (B->getOpcode() == BO_Comma) { 3407 OS << "... , "; 3408 Helper->handledStmt(B->getRHS(),OS); 3409 OS << '\n'; 3410 return; 3411 } 3412 } 3413 } 3414 S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3415 3416 if (isa<CXXOperatorCallExpr>(S)) { 3417 OS << " (OperatorCall)"; 3418 } else if (isa<CXXBindTemporaryExpr>(S)) { 3419 OS << " (BindTemporary)"; 3420 } 3421 3422 // Expressions need a newline. 3423 if (isa<Expr>(S)) 3424 OS << '\n'; 3425 3426 } else if (const CFGInitializer *IE = E.getAs<CFGInitializer>()) { 3427 const CXXCtorInitializer *I = IE->getInitializer(); 3428 if (I->isBaseInitializer()) 3429 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 3430 else OS << I->getAnyMember()->getName(); 3431 3432 OS << "("; 3433 if (Expr *IE = I->getInit()) 3434 IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3435 OS << ")"; 3436 3437 if (I->isBaseInitializer()) 3438 OS << " (Base initializer)\n"; 3439 else OS << " (Member initializer)\n"; 3440 3441 } else if (const CFGAutomaticObjDtor *DE = E.getAs<CFGAutomaticObjDtor>()){ 3442 const VarDecl *VD = DE->getVarDecl(); 3443 Helper->handleDecl(VD, OS); 3444 3445 const Type* T = VD->getType().getTypePtr(); 3446 if (const ReferenceType* RT = T->getAs<ReferenceType>()) 3447 T = RT->getPointeeType().getTypePtr(); 3448 else if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3449 T = ET; 3450 3451 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()"; 3452 OS << " (Implicit destructor)\n"; 3453 3454 } else if (const CFGBaseDtor *BE = E.getAs<CFGBaseDtor>()) { 3455 const CXXBaseSpecifier *BS = BE->getBaseSpecifier(); 3456 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; 3457 OS << " (Base object destructor)\n"; 3458 3459 } else if (const CFGMemberDtor *ME = E.getAs<CFGMemberDtor>()) { 3460 const FieldDecl *FD = ME->getFieldDecl(); 3461 3462 const Type *T = FD->getType().getTypePtr(); 3463 if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3464 T = ET; 3465 3466 OS << "this->" << FD->getName(); 3467 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; 3468 OS << " (Member object destructor)\n"; 3469 3470 } else if (const CFGTemporaryDtor *TE = E.getAs<CFGTemporaryDtor>()) { 3471 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr(); 3472 OS << "~" << BT->getType()->getAsCXXRecordDecl()->getName() << "()"; 3473 OS << " (Temporary object destructor)\n"; 3474 } 3475} 3476 3477static void print_block(raw_ostream &OS, const CFG* cfg, 3478 const CFGBlock &B, 3479 StmtPrinterHelper* Helper, bool print_edges) { 3480 3481 if (Helper) Helper->setBlockID(B.getBlockID()); 3482 3483 // Print the header. 3484 OS << "\n [ B" << B.getBlockID(); 3485 3486 if (&B == &cfg->getEntry()) 3487 OS << " (ENTRY) ]\n"; 3488 else if (&B == &cfg->getExit()) 3489 OS << " (EXIT) ]\n"; 3490 else if (&B == cfg->getIndirectGotoBlock()) 3491 OS << " (INDIRECT GOTO DISPATCH) ]\n"; 3492 else 3493 OS << " ]\n"; 3494 3495 // Print the label of this block. 3496 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) { 3497 3498 if (print_edges) 3499 OS << " "; 3500 3501 if (LabelStmt *L = dyn_cast<LabelStmt>(Label)) 3502 OS << L->getName(); 3503 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 3504 OS << "case "; 3505 C->getLHS()->printPretty(OS, Helper, 3506 PrintingPolicy(Helper->getLangOpts())); 3507 if (C->getRHS()) { 3508 OS << " ... "; 3509 C->getRHS()->printPretty(OS, Helper, 3510 PrintingPolicy(Helper->getLangOpts())); 3511 } 3512 } else if (isa<DefaultStmt>(Label)) 3513 OS << "default"; 3514 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 3515 OS << "catch ("; 3516 if (CS->getExceptionDecl()) 3517 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()), 3518 0); 3519 else 3520 OS << "..."; 3521 OS << ")"; 3522 3523 } else 3524 llvm_unreachable("Invalid label statement in CFGBlock."); 3525 3526 OS << ":\n"; 3527 } 3528 3529 // Iterate through the statements in the block and print them. 3530 unsigned j = 1; 3531 3532 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 3533 I != E ; ++I, ++j ) { 3534 3535 // Print the statement # in the basic block and the statement itself. 3536 if (print_edges) 3537 OS << " "; 3538 3539 OS << llvm::format("%3d", j) << ": "; 3540 3541 if (Helper) 3542 Helper->setStmtID(j); 3543 3544 print_elem(OS,Helper,*I); 3545 } 3546 3547 // Print the terminator of this block. 3548 if (B.getTerminator()) { 3549 if (print_edges) 3550 OS << " "; 3551 3552 OS << " T: "; 3553 3554 if (Helper) Helper->setBlockID(-1); 3555 3556 CFGBlockTerminatorPrint TPrinter(OS, Helper, 3557 PrintingPolicy(Helper->getLangOpts())); 3558 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt())); 3559 OS << '\n'; 3560 } 3561 3562 if (print_edges) { 3563 // Print the predecessors of this block. 3564 OS << " Predecessors (" << B.pred_size() << "):"; 3565 unsigned i = 0; 3566 3567 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 3568 I != E; ++I, ++i) { 3569 3570 if (i == 8 || (i-8) == 0) 3571 OS << "\n "; 3572 3573 OS << " B" << (*I)->getBlockID(); 3574 } 3575 3576 OS << '\n'; 3577 3578 // Print the successors of this block. 3579 OS << " Successors (" << B.succ_size() << "):"; 3580 i = 0; 3581 3582 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 3583 I != E; ++I, ++i) { 3584 3585 if (i == 8 || (i-8) % 10 == 0) 3586 OS << "\n "; 3587 3588 if (*I) 3589 OS << " B" << (*I)->getBlockID(); 3590 else 3591 OS << " NULL"; 3592 } 3593 3594 OS << '\n'; 3595 } 3596} 3597 3598 3599/// dump - A simple pretty printer of a CFG that outputs to stderr. 3600void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); } 3601 3602/// print - A simple pretty printer of a CFG that outputs to an ostream. 3603void CFG::print(raw_ostream &OS, const LangOptions &LO) const { 3604 StmtPrinterHelper Helper(this, LO); 3605 3606 // Print the entry block. 3607 print_block(OS, this, getEntry(), &Helper, true); 3608 3609 // Iterate through the CFGBlocks and print them one by one. 3610 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 3611 // Skip the entry block, because we already printed it. 3612 if (&(**I) == &getEntry() || &(**I) == &getExit()) 3613 continue; 3614 3615 print_block(OS, this, **I, &Helper, true); 3616 } 3617 3618 // Print the exit block. 3619 print_block(OS, this, getExit(), &Helper, true); 3620 OS.flush(); 3621} 3622 3623/// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 3624void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const { 3625 print(llvm::errs(), cfg, LO); 3626} 3627 3628/// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 3629/// Generally this will only be called from CFG::print. 3630void CFGBlock::print(raw_ostream &OS, const CFG* cfg, 3631 const LangOptions &LO) const { 3632 StmtPrinterHelper Helper(cfg, LO); 3633 print_block(OS, cfg, *this, &Helper, true); 3634} 3635 3636/// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 3637void CFGBlock::printTerminator(raw_ostream &OS, 3638 const LangOptions &LO) const { 3639 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO)); 3640 TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt())); 3641} 3642 3643Stmt *CFGBlock::getTerminatorCondition() { 3644 Stmt *Terminator = this->Terminator; 3645 if (!Terminator) 3646 return NULL; 3647 3648 Expr *E = NULL; 3649 3650 switch (Terminator->getStmtClass()) { 3651 default: 3652 break; 3653 3654 case Stmt::ForStmtClass: 3655 E = cast<ForStmt>(Terminator)->getCond(); 3656 break; 3657 3658 case Stmt::WhileStmtClass: 3659 E = cast<WhileStmt>(Terminator)->getCond(); 3660 break; 3661 3662 case Stmt::DoStmtClass: 3663 E = cast<DoStmt>(Terminator)->getCond(); 3664 break; 3665 3666 case Stmt::IfStmtClass: 3667 E = cast<IfStmt>(Terminator)->getCond(); 3668 break; 3669 3670 case Stmt::ChooseExprClass: 3671 E = cast<ChooseExpr>(Terminator)->getCond(); 3672 break; 3673 3674 case Stmt::IndirectGotoStmtClass: 3675 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 3676 break; 3677 3678 case Stmt::SwitchStmtClass: 3679 E = cast<SwitchStmt>(Terminator)->getCond(); 3680 break; 3681 3682 case Stmt::BinaryConditionalOperatorClass: 3683 E = cast<BinaryConditionalOperator>(Terminator)->getCond(); 3684 break; 3685 3686 case Stmt::ConditionalOperatorClass: 3687 E = cast<ConditionalOperator>(Terminator)->getCond(); 3688 break; 3689 3690 case Stmt::BinaryOperatorClass: // '&&' and '||' 3691 E = cast<BinaryOperator>(Terminator)->getLHS(); 3692 break; 3693 3694 case Stmt::ObjCForCollectionStmtClass: 3695 return Terminator; 3696 } 3697 3698 return E ? E->IgnoreParens() : NULL; 3699} 3700 3701//===----------------------------------------------------------------------===// 3702// CFG Graphviz Visualization 3703//===----------------------------------------------------------------------===// 3704 3705 3706#ifndef NDEBUG 3707static StmtPrinterHelper* GraphHelper; 3708#endif 3709 3710void CFG::viewCFG(const LangOptions &LO) const { 3711#ifndef NDEBUG 3712 StmtPrinterHelper H(this, LO); 3713 GraphHelper = &H; 3714 llvm::ViewGraph(this,"CFG"); 3715 GraphHelper = NULL; 3716#endif 3717} 3718 3719namespace llvm { 3720template<> 3721struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 3722 3723 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 3724 3725 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) { 3726 3727#ifndef NDEBUG 3728 std::string OutSStr; 3729 llvm::raw_string_ostream Out(OutSStr); 3730 print_block(Out,Graph, *Node, GraphHelper, false); 3731 std::string& OutStr = Out.str(); 3732 3733 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 3734 3735 // Process string output to make it nicer... 3736 for (unsigned i = 0; i != OutStr.length(); ++i) 3737 if (OutStr[i] == '\n') { // Left justify 3738 OutStr[i] = '\\'; 3739 OutStr.insert(OutStr.begin()+i+1, 'l'); 3740 } 3741 3742 return OutStr; 3743#else 3744 return ""; 3745#endif 3746 } 3747}; 3748} // end namespace llvm 3749