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