CFG.cpp revision 60618fa7f88d5162bb5b40988b6b38d4d75d6fc6
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) { 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()) 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())) 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 tryEvaluate(Terminator->getCond(), result); 2237 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond, &result); 2238 2239 // If body is not a compound statement create implicit scope 2240 // and add destructors. 2241 if (!isa<CompoundStmt>(Terminator->getBody())) 2242 addLocalScopeAndDtors(Terminator->getBody()); 2243 2244 addStmt(Terminator->getBody()); 2245 if (Block) { 2246 if (badCFG) 2247 return 0; 2248 } 2249 2250 // If we have no "default:" case, the default transition is to the code 2251 // following the switch body. 2252 addSuccessor(SwitchTerminatedBlock, 2253 switchExclusivelyCovered ? 0 : DefaultCaseBlock); 2254 2255 // Add the terminator and condition in the switch block. 2256 SwitchTerminatedBlock->setTerminator(Terminator); 2257 Block = SwitchTerminatedBlock; 2258 Block = addStmt(Terminator->getCond()); 2259 2260 // Finally, if the SwitchStmt contains a condition variable, add both the 2261 // SwitchStmt and the condition variable initialization to the CFG. 2262 if (VarDecl *VD = Terminator->getConditionVariable()) { 2263 if (Expr *Init = VD->getInit()) { 2264 autoCreateBlock(); 2265 appendStmt(Block, Terminator); 2266 addStmt(Init); 2267 } 2268 } 2269 2270 return Block; 2271} 2272 2273static bool shouldAddCase(bool &switchExclusivelyCovered, 2274 const Expr::EvalResult &switchCond, 2275 const CaseStmt *CS, 2276 ASTContext &Ctx) { 2277 bool addCase = false; 2278 2279 if (!switchExclusivelyCovered) { 2280 if (switchCond.Val.isInt()) { 2281 // Evaluate the LHS of the case value. 2282 Expr::EvalResult V1; 2283 CS->getLHS()->Evaluate(V1, Ctx); 2284 assert(V1.Val.isInt()); 2285 const llvm::APSInt &condInt = switchCond.Val.getInt(); 2286 const llvm::APSInt &lhsInt = V1.Val.getInt(); 2287 2288 if (condInt == lhsInt) { 2289 addCase = true; 2290 switchExclusivelyCovered = true; 2291 } 2292 else if (condInt < lhsInt) { 2293 if (const Expr *RHS = CS->getRHS()) { 2294 // Evaluate the RHS of the case value. 2295 Expr::EvalResult V2; 2296 RHS->Evaluate(V2, Ctx); 2297 assert(V2.Val.isInt()); 2298 if (V2.Val.getInt() <= condInt) { 2299 addCase = true; 2300 switchExclusivelyCovered = true; 2301 } 2302 } 2303 } 2304 } 2305 else 2306 addCase = true; 2307 } 2308 return addCase; 2309} 2310 2311CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) { 2312 // CaseStmts are essentially labels, so they are the first statement in a 2313 // block. 2314 CFGBlock *TopBlock = 0, *LastBlock = 0; 2315 assert(switchCond); 2316 2317 if (Stmt *Sub = CS->getSubStmt()) { 2318 // For deeply nested chains of CaseStmts, instead of doing a recursion 2319 // (which can blow out the stack), manually unroll and create blocks 2320 // along the way. 2321 while (isa<CaseStmt>(Sub)) { 2322 CFGBlock *currentBlock = createBlock(false); 2323 currentBlock->setLabel(CS); 2324 2325 if (TopBlock) 2326 addSuccessor(LastBlock, currentBlock); 2327 else 2328 TopBlock = currentBlock; 2329 2330 addSuccessor(SwitchTerminatedBlock, 2331 shouldAddCase(switchExclusivelyCovered, *switchCond, 2332 CS, *Context) 2333 ? currentBlock : 0); 2334 2335 LastBlock = currentBlock; 2336 CS = cast<CaseStmt>(Sub); 2337 Sub = CS->getSubStmt(); 2338 } 2339 2340 addStmt(Sub); 2341 } 2342 2343 CFGBlock* CaseBlock = Block; 2344 if (!CaseBlock) 2345 CaseBlock = createBlock(); 2346 2347 // Cases statements partition blocks, so this is the top of the basic block we 2348 // were processing (the "case XXX:" is the label). 2349 CaseBlock->setLabel(CS); 2350 2351 if (badCFG) 2352 return 0; 2353 2354 // Add this block to the list of successors for the block with the switch 2355 // statement. 2356 assert(SwitchTerminatedBlock); 2357 addSuccessor(SwitchTerminatedBlock, 2358 shouldAddCase(switchExclusivelyCovered, *switchCond, 2359 CS, *Context) 2360 ? CaseBlock : 0); 2361 2362 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2363 Block = NULL; 2364 2365 if (TopBlock) { 2366 addSuccessor(LastBlock, CaseBlock); 2367 Succ = TopBlock; 2368 } else { 2369 // This block is now the implicit successor of other blocks. 2370 Succ = CaseBlock; 2371 } 2372 2373 return Succ; 2374} 2375 2376CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) { 2377 if (Terminator->getSubStmt()) 2378 addStmt(Terminator->getSubStmt()); 2379 2380 DefaultCaseBlock = Block; 2381 2382 if (!DefaultCaseBlock) 2383 DefaultCaseBlock = createBlock(); 2384 2385 // Default statements partition blocks, so this is the top of the basic block 2386 // we were processing (the "default:" is the label). 2387 DefaultCaseBlock->setLabel(Terminator); 2388 2389 if (badCFG) 2390 return 0; 2391 2392 // Unlike case statements, we don't add the default block to the successors 2393 // for the switch statement immediately. This is done when we finish 2394 // processing the switch statement. This allows for the default case 2395 // (including a fall-through to the code after the switch statement) to always 2396 // be the last successor of a switch-terminated block. 2397 2398 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2399 Block = NULL; 2400 2401 // This block is now the implicit successor of other blocks. 2402 Succ = DefaultCaseBlock; 2403 2404 return DefaultCaseBlock; 2405} 2406 2407CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { 2408 // "try"/"catch" is a control-flow statement. Thus we stop processing the 2409 // current block. 2410 CFGBlock* TrySuccessor = NULL; 2411 2412 if (Block) { 2413 if (badCFG) 2414 return 0; 2415 TrySuccessor = Block; 2416 } else TrySuccessor = Succ; 2417 2418 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 2419 2420 // Create a new block that will contain the try statement. 2421 CFGBlock *NewTryTerminatedBlock = createBlock(false); 2422 // Add the terminator in the try block. 2423 NewTryTerminatedBlock->setTerminator(Terminator); 2424 2425 bool HasCatchAll = false; 2426 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) { 2427 // The code after the try is the implicit successor. 2428 Succ = TrySuccessor; 2429 CXXCatchStmt *CS = Terminator->getHandler(h); 2430 if (CS->getExceptionDecl() == 0) { 2431 HasCatchAll = true; 2432 } 2433 Block = NULL; 2434 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); 2435 if (CatchBlock == 0) 2436 return 0; 2437 // Add this block to the list of successors for the block with the try 2438 // statement. 2439 addSuccessor(NewTryTerminatedBlock, CatchBlock); 2440 } 2441 if (!HasCatchAll) { 2442 if (PrevTryTerminatedBlock) 2443 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 2444 else 2445 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 2446 } 2447 2448 // The code after the try is the implicit successor. 2449 Succ = TrySuccessor; 2450 2451 // Save the current "try" context. 2452 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock); 2453 TryTerminatedBlock = NewTryTerminatedBlock; 2454 2455 assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); 2456 Block = NULL; 2457 Block = addStmt(Terminator->getTryBlock()); 2458 return Block; 2459} 2460 2461CFGBlock* CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt* CS) { 2462 // CXXCatchStmt are treated like labels, so they are the first statement in a 2463 // block. 2464 2465 // Save local scope position because in case of exception variable ScopePos 2466 // won't be restored when traversing AST. 2467 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2468 2469 // Create local scope for possible exception variable. 2470 // Store scope position. Add implicit destructor. 2471 if (VarDecl* VD = CS->getExceptionDecl()) { 2472 LocalScope::const_iterator BeginScopePos = ScopePos; 2473 addLocalScopeForVarDecl(VD); 2474 addAutomaticObjDtors(ScopePos, BeginScopePos, CS); 2475 } 2476 2477 if (CS->getHandlerBlock()) 2478 addStmt(CS->getHandlerBlock()); 2479 2480 CFGBlock* CatchBlock = Block; 2481 if (!CatchBlock) 2482 CatchBlock = createBlock(); 2483 2484 CatchBlock->setLabel(CS); 2485 2486 if (badCFG) 2487 return 0; 2488 2489 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2490 Block = NULL; 2491 2492 return CatchBlock; 2493} 2494 2495CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E, 2496 AddStmtChoice asc) { 2497 if (BuildOpts.AddImplicitDtors) { 2498 // If adding implicit destructors visit the full expression for adding 2499 // destructors of temporaries. 2500 VisitForTemporaryDtors(E->getSubExpr()); 2501 2502 // Full expression has to be added as CFGStmt so it will be sequenced 2503 // before destructors of it's temporaries. 2504 asc = asc.withAlwaysAdd(true); 2505 } 2506 return Visit(E->getSubExpr(), asc); 2507} 2508 2509CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 2510 AddStmtChoice asc) { 2511 if (asc.alwaysAdd(*this, E)) { 2512 autoCreateBlock(); 2513 appendStmt(Block, E); 2514 2515 // We do not want to propagate the AlwaysAdd property. 2516 asc = asc.withAlwaysAdd(false); 2517 } 2518 return Visit(E->getSubExpr(), asc); 2519} 2520 2521CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, 2522 AddStmtChoice asc) { 2523 autoCreateBlock(); 2524 if (!C->isElidable()) 2525 appendStmt(Block, C); 2526 2527 return VisitChildren(C); 2528} 2529 2530CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 2531 AddStmtChoice asc) { 2532 if (asc.alwaysAdd(*this, E)) { 2533 autoCreateBlock(); 2534 appendStmt(Block, E); 2535 // We do not want to propagate the AlwaysAdd property. 2536 asc = asc.withAlwaysAdd(false); 2537 } 2538 return Visit(E->getSubExpr(), asc); 2539} 2540 2541CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 2542 AddStmtChoice asc) { 2543 autoCreateBlock(); 2544 appendStmt(Block, C); 2545 return VisitChildren(C); 2546} 2547 2548CFGBlock *CFGBuilder::VisitCXXMemberCallExpr(CXXMemberCallExpr *C, 2549 AddStmtChoice asc) { 2550 autoCreateBlock(); 2551 appendStmt(Block, C); 2552 return VisitChildren(C); 2553} 2554 2555CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, 2556 AddStmtChoice asc) { 2557 if (asc.alwaysAdd(*this, E)) { 2558 autoCreateBlock(); 2559 appendStmt(Block, E); 2560 } 2561 return Visit(E->getSubExpr(), AddStmtChoice()); 2562} 2563 2564CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) { 2565 // Lazily create the indirect-goto dispatch block if there isn't one already. 2566 CFGBlock* IBlock = cfg->getIndirectGotoBlock(); 2567 2568 if (!IBlock) { 2569 IBlock = createBlock(false); 2570 cfg->setIndirectGotoBlock(IBlock); 2571 } 2572 2573 // IndirectGoto is a control-flow statement. Thus we stop processing the 2574 // current block and create a new one. 2575 if (badCFG) 2576 return 0; 2577 2578 Block = createBlock(false); 2579 Block->setTerminator(I); 2580 addSuccessor(Block, IBlock); 2581 return addStmt(I->getTarget()); 2582} 2583 2584CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) { 2585tryAgain: 2586 if (!E) { 2587 badCFG = true; 2588 return NULL; 2589 } 2590 switch (E->getStmtClass()) { 2591 default: 2592 return VisitChildrenForTemporaryDtors(E); 2593 2594 case Stmt::BinaryOperatorClass: 2595 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E)); 2596 2597 case Stmt::CXXBindTemporaryExprClass: 2598 return VisitCXXBindTemporaryExprForTemporaryDtors( 2599 cast<CXXBindTemporaryExpr>(E), BindToTemporary); 2600 2601 case Stmt::BinaryConditionalOperatorClass: 2602 case Stmt::ConditionalOperatorClass: 2603 return VisitConditionalOperatorForTemporaryDtors( 2604 cast<AbstractConditionalOperator>(E), BindToTemporary); 2605 2606 case Stmt::ImplicitCastExprClass: 2607 // For implicit cast we want BindToTemporary to be passed further. 2608 E = cast<CastExpr>(E)->getSubExpr(); 2609 goto tryAgain; 2610 2611 case Stmt::ParenExprClass: 2612 E = cast<ParenExpr>(E)->getSubExpr(); 2613 goto tryAgain; 2614 } 2615} 2616 2617CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) { 2618 // When visiting children for destructors we want to visit them in reverse 2619 // order. Because there's no reverse iterator for children must to reverse 2620 // them in helper vector. 2621 typedef llvm::SmallVector<Stmt *, 4> ChildrenVect; 2622 ChildrenVect ChildrenRev; 2623 for (Stmt::child_range I = E->children(); I; ++I) { 2624 if (*I) ChildrenRev.push_back(*I); 2625 } 2626 2627 CFGBlock *B = Block; 2628 for (ChildrenVect::reverse_iterator I = ChildrenRev.rbegin(), 2629 L = ChildrenRev.rend(); I != L; ++I) { 2630 if (CFGBlock *R = VisitForTemporaryDtors(*I)) 2631 B = R; 2632 } 2633 return B; 2634} 2635 2636CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) { 2637 if (E->isLogicalOp()) { 2638 // Destructors for temporaries in LHS expression should be called after 2639 // those for RHS expression. Even if this will unnecessarily create a block, 2640 // this block will be used at least by the full expression. 2641 autoCreateBlock(); 2642 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS()); 2643 if (badCFG) 2644 return NULL; 2645 2646 Succ = ConfluenceBlock; 2647 Block = NULL; 2648 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2649 2650 if (RHSBlock) { 2651 if (badCFG) 2652 return NULL; 2653 2654 // If RHS expression did produce destructors we need to connect created 2655 // blocks to CFG in same manner as for binary operator itself. 2656 CFGBlock *LHSBlock = createBlock(false); 2657 LHSBlock->setTerminator(CFGTerminator(E, true)); 2658 2659 // For binary operator LHS block is before RHS in list of predecessors 2660 // of ConfluenceBlock. 2661 std::reverse(ConfluenceBlock->pred_begin(), 2662 ConfluenceBlock->pred_end()); 2663 2664 // See if this is a known constant. 2665 TryResult KnownVal = tryEvaluateBool(E->getLHS()); 2666 if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr)) 2667 KnownVal.negate(); 2668 2669 // Link LHSBlock with RHSBlock exactly the same way as for binary operator 2670 // itself. 2671 if (E->getOpcode() == BO_LOr) { 2672 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2673 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2674 } else { 2675 assert (E->getOpcode() == BO_LAnd); 2676 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2677 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2678 } 2679 2680 Block = LHSBlock; 2681 return LHSBlock; 2682 } 2683 2684 Block = ConfluenceBlock; 2685 return ConfluenceBlock; 2686 } 2687 2688 if (E->isAssignmentOp()) { 2689 // For assignment operator (=) LHS expression is visited 2690 // before RHS expression. For destructors visit them in reverse order. 2691 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2692 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2693 return LHSBlock ? LHSBlock : RHSBlock; 2694 } 2695 2696 // For any other binary operator RHS expression is visited before 2697 // LHS expression (order of children). For destructors visit them in reverse 2698 // order. 2699 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2700 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2701 return RHSBlock ? RHSBlock : LHSBlock; 2702} 2703 2704CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( 2705 CXXBindTemporaryExpr *E, bool BindToTemporary) { 2706 // First add destructors for temporaries in subexpression. 2707 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr()); 2708 if (!BindToTemporary) { 2709 // If lifetime of temporary is not prolonged (by assigning to constant 2710 // reference) add destructor for it. 2711 autoCreateBlock(); 2712 appendTemporaryDtor(Block, E); 2713 B = Block; 2714 } 2715 return B; 2716} 2717 2718CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( 2719 AbstractConditionalOperator *E, bool BindToTemporary) { 2720 // First add destructors for condition expression. Even if this will 2721 // unnecessarily create a block, this block will be used at least by the full 2722 // expression. 2723 autoCreateBlock(); 2724 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond()); 2725 if (badCFG) 2726 return NULL; 2727 if (BinaryConditionalOperator *BCO 2728 = dyn_cast<BinaryConditionalOperator>(E)) { 2729 ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon()); 2730 if (badCFG) 2731 return NULL; 2732 } 2733 2734 // Try to add block with destructors for LHS expression. 2735 CFGBlock *LHSBlock = NULL; 2736 Succ = ConfluenceBlock; 2737 Block = NULL; 2738 LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary); 2739 if (badCFG) 2740 return NULL; 2741 2742 // Try to add block with destructors for RHS expression; 2743 Succ = ConfluenceBlock; 2744 Block = NULL; 2745 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(), 2746 BindToTemporary); 2747 if (badCFG) 2748 return NULL; 2749 2750 if (!RHSBlock && !LHSBlock) { 2751 // If neither LHS nor RHS expression had temporaries to destroy don't create 2752 // more blocks. 2753 Block = ConfluenceBlock; 2754 return Block; 2755 } 2756 2757 Block = createBlock(false); 2758 Block->setTerminator(CFGTerminator(E, true)); 2759 2760 // See if this is a known constant. 2761 const TryResult &KnownVal = tryEvaluateBool(E->getCond()); 2762 2763 if (LHSBlock) { 2764 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 2765 } else if (KnownVal.isFalse()) { 2766 addSuccessor(Block, NULL); 2767 } else { 2768 addSuccessor(Block, ConfluenceBlock); 2769 std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end()); 2770 } 2771 2772 if (!RHSBlock) 2773 RHSBlock = ConfluenceBlock; 2774 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 2775 2776 return Block; 2777} 2778 2779} // end anonymous namespace 2780 2781/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 2782/// no successors or predecessors. If this is the first block created in the 2783/// CFG, it is automatically set to be the Entry and Exit of the CFG. 2784CFGBlock* CFG::createBlock() { 2785 bool first_block = begin() == end(); 2786 2787 // Create the block. 2788 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 2789 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC); 2790 Blocks.push_back(Mem, BlkBVC); 2791 2792 // If this is the first block, set it as the Entry and Exit. 2793 if (first_block) 2794 Entry = Exit = &back(); 2795 2796 // Return the block. 2797 return &back(); 2798} 2799 2800/// buildCFG - Constructs a CFG from an AST. Ownership of the returned 2801/// CFG is returned to the caller. 2802CFG* CFG::buildCFG(const Decl *D, Stmt* Statement, ASTContext *C, 2803 const BuildOptions &BO) { 2804 CFGBuilder Builder(C, BO); 2805 return Builder.buildCFG(D, Statement); 2806} 2807 2808const CXXDestructorDecl * 2809CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { 2810 switch (getKind()) { 2811 case CFGElement::Invalid: 2812 case CFGElement::Statement: 2813 case CFGElement::Initializer: 2814 llvm_unreachable("getDestructorDecl should only be used with " 2815 "ImplicitDtors"); 2816 case CFGElement::AutomaticObjectDtor: { 2817 const VarDecl *var = cast<CFGAutomaticObjDtor>(this)->getVarDecl(); 2818 QualType ty = var->getType(); 2819 ty = ty.getNonReferenceType(); 2820 if (const ArrayType *arrayType = astContext.getAsArrayType(ty)) { 2821 ty = arrayType->getElementType(); 2822 } 2823 const RecordType *recordType = ty->getAs<RecordType>(); 2824 const CXXRecordDecl *classDecl = 2825 cast<CXXRecordDecl>(recordType->getDecl()); 2826 return classDecl->getDestructor(); 2827 } 2828 case CFGElement::TemporaryDtor: { 2829 const CXXBindTemporaryExpr *bindExpr = 2830 cast<CFGTemporaryDtor>(this)->getBindTemporaryExpr(); 2831 const CXXTemporary *temp = bindExpr->getTemporary(); 2832 return temp->getDestructor(); 2833 } 2834 case CFGElement::BaseDtor: 2835 case CFGElement::MemberDtor: 2836 2837 // Not yet supported. 2838 return 0; 2839 } 2840 llvm_unreachable("getKind() returned bogus value"); 2841 return 0; 2842} 2843 2844bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const { 2845 if (const CXXDestructorDecl *cdecl = getDestructorDecl(astContext)) { 2846 QualType ty = cdecl->getType(); 2847 return cast<FunctionType>(ty)->getNoReturnAttr(); 2848 } 2849 return false; 2850} 2851 2852//===----------------------------------------------------------------------===// 2853// CFG: Queries for BlkExprs. 2854//===----------------------------------------------------------------------===// 2855 2856namespace { 2857 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy; 2858} 2859 2860static void FindSubExprAssignments(Stmt *S, 2861 llvm::SmallPtrSet<Expr*,50>& Set) { 2862 if (!S) 2863 return; 2864 2865 for (Stmt::child_range I = S->children(); I; ++I) { 2866 Stmt *child = *I; 2867 if (!child) 2868 continue; 2869 2870 if (BinaryOperator* B = dyn_cast<BinaryOperator>(child)) 2871 if (B->isAssignmentOp()) Set.insert(B); 2872 2873 FindSubExprAssignments(child, Set); 2874 } 2875} 2876 2877static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) { 2878 BlkExprMapTy* M = new BlkExprMapTy(); 2879 2880 // Look for assignments that are used as subexpressions. These are the only 2881 // assignments that we want to *possibly* register as a block-level 2882 // expression. Basically, if an assignment occurs both in a subexpression and 2883 // at the block-level, it is a block-level expression. 2884 llvm::SmallPtrSet<Expr*,50> SubExprAssignments; 2885 2886 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) 2887 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) 2888 if (const CFGStmt *S = BI->getAs<CFGStmt>()) 2889 FindSubExprAssignments(S->getStmt(), SubExprAssignments); 2890 2891 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) { 2892 2893 // Iterate over the statements again on identify the Expr* and Stmt* at the 2894 // block-level that are block-level expressions. 2895 2896 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) { 2897 const CFGStmt *CS = BI->getAs<CFGStmt>(); 2898 if (!CS) 2899 continue; 2900 if (Expr* Exp = dyn_cast<Expr>(CS->getStmt())) { 2901 2902 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) { 2903 // Assignment expressions that are not nested within another 2904 // expression are really "statements" whose value is never used by 2905 // another expression. 2906 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp)) 2907 continue; 2908 } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) { 2909 // Special handling for statement expressions. The last statement in 2910 // the statement expression is also a block-level expr. 2911 const CompoundStmt* C = Terminator->getSubStmt(); 2912 if (!C->body_empty()) { 2913 unsigned x = M->size(); 2914 (*M)[C->body_back()] = x; 2915 } 2916 } 2917 2918 unsigned x = M->size(); 2919 (*M)[Exp] = x; 2920 } 2921 } 2922 2923 // Look at terminators. The condition is a block-level expression. 2924 2925 Stmt* S = (*I)->getTerminatorCondition(); 2926 2927 if (S && M->find(S) == M->end()) { 2928 unsigned x = M->size(); 2929 (*M)[S] = x; 2930 } 2931 } 2932 2933 return M; 2934} 2935 2936CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) { 2937 assert(S != NULL); 2938 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); } 2939 2940 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap); 2941 BlkExprMapTy::iterator I = M->find(S); 2942 return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second); 2943} 2944 2945unsigned CFG::getNumBlkExprs() { 2946 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap)) 2947 return M->size(); 2948 2949 // We assume callers interested in the number of BlkExprs will want 2950 // the map constructed if it doesn't already exist. 2951 BlkExprMap = (void*) PopulateBlkExprMap(*this); 2952 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size(); 2953} 2954 2955//===----------------------------------------------------------------------===// 2956// Filtered walking of the CFG. 2957//===----------------------------------------------------------------------===// 2958 2959bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 2960 const CFGBlock *From, const CFGBlock *To) { 2961 2962 if (To && F.IgnoreDefaultsWithCoveredEnums) { 2963 // If the 'To' has no label or is labeled but the label isn't a 2964 // CaseStmt then filter this edge. 2965 if (const SwitchStmt *S = 2966 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) { 2967 if (S->isAllEnumCasesCovered()) { 2968 const Stmt *L = To->getLabel(); 2969 if (!L || !isa<CaseStmt>(L)) 2970 return true; 2971 } 2972 } 2973 } 2974 2975 return false; 2976} 2977 2978//===----------------------------------------------------------------------===// 2979// Cleanup: CFG dstor. 2980//===----------------------------------------------------------------------===// 2981 2982CFG::~CFG() { 2983 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap); 2984} 2985 2986//===----------------------------------------------------------------------===// 2987// CFG pretty printing 2988//===----------------------------------------------------------------------===// 2989 2990namespace { 2991 2992class StmtPrinterHelper : public PrinterHelper { 2993 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; 2994 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy; 2995 StmtMapTy StmtMap; 2996 DeclMapTy DeclMap; 2997 signed currentBlock; 2998 unsigned currentStmt; 2999 const LangOptions &LangOpts; 3000public: 3001 3002 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 3003 : currentBlock(0), currentStmt(0), LangOpts(LO) 3004 { 3005 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 3006 unsigned j = 1; 3007 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 3008 BI != BEnd; ++BI, ++j ) { 3009 if (const CFGStmt *SE = BI->getAs<CFGStmt>()) { 3010 const Stmt *stmt= SE->getStmt(); 3011 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 3012 StmtMap[stmt] = P; 3013 3014 switch (stmt->getStmtClass()) { 3015 case Stmt::DeclStmtClass: 3016 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P; 3017 break; 3018 case Stmt::IfStmtClass: { 3019 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable(); 3020 if (var) 3021 DeclMap[var] = P; 3022 break; 3023 } 3024 case Stmt::ForStmtClass: { 3025 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable(); 3026 if (var) 3027 DeclMap[var] = P; 3028 break; 3029 } 3030 case Stmt::WhileStmtClass: { 3031 const VarDecl *var = 3032 cast<WhileStmt>(stmt)->getConditionVariable(); 3033 if (var) 3034 DeclMap[var] = P; 3035 break; 3036 } 3037 case Stmt::SwitchStmtClass: { 3038 const VarDecl *var = 3039 cast<SwitchStmt>(stmt)->getConditionVariable(); 3040 if (var) 3041 DeclMap[var] = P; 3042 break; 3043 } 3044 case Stmt::CXXCatchStmtClass: { 3045 const VarDecl *var = 3046 cast<CXXCatchStmt>(stmt)->getExceptionDecl(); 3047 if (var) 3048 DeclMap[var] = P; 3049 break; 3050 } 3051 default: 3052 break; 3053 } 3054 } 3055 } 3056 } 3057 } 3058 3059 3060 virtual ~StmtPrinterHelper() {} 3061 3062 const LangOptions &getLangOpts() const { return LangOpts; } 3063 void setBlockID(signed i) { currentBlock = i; } 3064 void setStmtID(unsigned i) { currentStmt = i; } 3065 3066 virtual bool handledStmt(Stmt* S, llvm::raw_ostream& OS) { 3067 StmtMapTy::iterator I = StmtMap.find(S); 3068 3069 if (I == StmtMap.end()) 3070 return false; 3071 3072 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 3073 && I->second.second == currentStmt) { 3074 return false; 3075 } 3076 3077 OS << "[B" << I->second.first << "." << I->second.second << "]"; 3078 return true; 3079 } 3080 3081 bool handleDecl(const Decl* D, llvm::raw_ostream& OS) { 3082 DeclMapTy::iterator I = DeclMap.find(D); 3083 3084 if (I == DeclMap.end()) 3085 return false; 3086 3087 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 3088 && I->second.second == currentStmt) { 3089 return false; 3090 } 3091 3092 OS << "[B" << I->second.first << "." << I->second.second << "]"; 3093 return true; 3094 } 3095}; 3096} // end anonymous namespace 3097 3098 3099namespace { 3100class CFGBlockTerminatorPrint 3101 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 3102 3103 llvm::raw_ostream& OS; 3104 StmtPrinterHelper* Helper; 3105 PrintingPolicy Policy; 3106public: 3107 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper, 3108 const PrintingPolicy &Policy) 3109 : OS(os), Helper(helper), Policy(Policy) {} 3110 3111 void VisitIfStmt(IfStmt* I) { 3112 OS << "if "; 3113 I->getCond()->printPretty(OS,Helper,Policy); 3114 } 3115 3116 // Default case. 3117 void VisitStmt(Stmt* Terminator) { 3118 Terminator->printPretty(OS, Helper, Policy); 3119 } 3120 3121 void VisitForStmt(ForStmt* F) { 3122 OS << "for (" ; 3123 if (F->getInit()) 3124 OS << "..."; 3125 OS << "; "; 3126 if (Stmt* C = F->getCond()) 3127 C->printPretty(OS, Helper, Policy); 3128 OS << "; "; 3129 if (F->getInc()) 3130 OS << "..."; 3131 OS << ")"; 3132 } 3133 3134 void VisitWhileStmt(WhileStmt* W) { 3135 OS << "while " ; 3136 if (Stmt* C = W->getCond()) 3137 C->printPretty(OS, Helper, Policy); 3138 } 3139 3140 void VisitDoStmt(DoStmt* D) { 3141 OS << "do ... while "; 3142 if (Stmt* C = D->getCond()) 3143 C->printPretty(OS, Helper, Policy); 3144 } 3145 3146 void VisitSwitchStmt(SwitchStmt* Terminator) { 3147 OS << "switch "; 3148 Terminator->getCond()->printPretty(OS, Helper, Policy); 3149 } 3150 3151 void VisitCXXTryStmt(CXXTryStmt* CS) { 3152 OS << "try ..."; 3153 } 3154 3155 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) { 3156 C->getCond()->printPretty(OS, Helper, Policy); 3157 OS << " ? ... : ..."; 3158 } 3159 3160 void VisitChooseExpr(ChooseExpr* C) { 3161 OS << "__builtin_choose_expr( "; 3162 C->getCond()->printPretty(OS, Helper, Policy); 3163 OS << " )"; 3164 } 3165 3166 void VisitIndirectGotoStmt(IndirectGotoStmt* I) { 3167 OS << "goto *"; 3168 I->getTarget()->printPretty(OS, Helper, Policy); 3169 } 3170 3171 void VisitBinaryOperator(BinaryOperator* B) { 3172 if (!B->isLogicalOp()) { 3173 VisitExpr(B); 3174 return; 3175 } 3176 3177 B->getLHS()->printPretty(OS, Helper, Policy); 3178 3179 switch (B->getOpcode()) { 3180 case BO_LOr: 3181 OS << " || ..."; 3182 return; 3183 case BO_LAnd: 3184 OS << " && ..."; 3185 return; 3186 default: 3187 assert(false && "Invalid logical operator."); 3188 } 3189 } 3190 3191 void VisitExpr(Expr* E) { 3192 E->printPretty(OS, Helper, Policy); 3193 } 3194}; 3195} // end anonymous namespace 3196 3197static void print_elem(llvm::raw_ostream &OS, StmtPrinterHelper* Helper, 3198 const CFGElement &E) { 3199 if (const CFGStmt *CS = E.getAs<CFGStmt>()) { 3200 Stmt *S = CS->getStmt(); 3201 3202 if (Helper) { 3203 3204 // special printing for statement-expressions. 3205 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) { 3206 CompoundStmt* Sub = SE->getSubStmt(); 3207 3208 if (Sub->children()) { 3209 OS << "({ ... ; "; 3210 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 3211 OS << " })\n"; 3212 return; 3213 } 3214 } 3215 // special printing for comma expressions. 3216 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 3217 if (B->getOpcode() == BO_Comma) { 3218 OS << "... , "; 3219 Helper->handledStmt(B->getRHS(),OS); 3220 OS << '\n'; 3221 return; 3222 } 3223 } 3224 } 3225 S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3226 3227 if (isa<CXXOperatorCallExpr>(S)) { 3228 OS << " (OperatorCall)"; 3229 } else if (isa<CXXBindTemporaryExpr>(S)) { 3230 OS << " (BindTemporary)"; 3231 } 3232 3233 // Expressions need a newline. 3234 if (isa<Expr>(S)) 3235 OS << '\n'; 3236 3237 } else if (const CFGInitializer *IE = E.getAs<CFGInitializer>()) { 3238 const CXXCtorInitializer *I = IE->getInitializer(); 3239 if (I->isBaseInitializer()) 3240 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 3241 else OS << I->getAnyMember()->getName(); 3242 3243 OS << "("; 3244 if (Expr* IE = I->getInit()) 3245 IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3246 OS << ")"; 3247 3248 if (I->isBaseInitializer()) 3249 OS << " (Base initializer)\n"; 3250 else OS << " (Member initializer)\n"; 3251 3252 } else if (const CFGAutomaticObjDtor *DE = E.getAs<CFGAutomaticObjDtor>()){ 3253 const VarDecl* VD = DE->getVarDecl(); 3254 Helper->handleDecl(VD, OS); 3255 3256 const Type* T = VD->getType().getTypePtr(); 3257 if (const ReferenceType* RT = T->getAs<ReferenceType>()) 3258 T = RT->getPointeeType().getTypePtr(); 3259 else if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3260 T = ET; 3261 3262 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()"; 3263 OS << " (Implicit destructor)\n"; 3264 3265 } else if (const CFGBaseDtor *BE = E.getAs<CFGBaseDtor>()) { 3266 const CXXBaseSpecifier *BS = BE->getBaseSpecifier(); 3267 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; 3268 OS << " (Base object destructor)\n"; 3269 3270 } else if (const CFGMemberDtor *ME = E.getAs<CFGMemberDtor>()) { 3271 const FieldDecl *FD = ME->getFieldDecl(); 3272 3273 const Type *T = FD->getType().getTypePtr(); 3274 if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3275 T = ET; 3276 3277 OS << "this->" << FD->getName(); 3278 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; 3279 OS << " (Member object destructor)\n"; 3280 3281 } else if (const CFGTemporaryDtor *TE = E.getAs<CFGTemporaryDtor>()) { 3282 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr(); 3283 OS << "~" << BT->getType()->getAsCXXRecordDecl()->getName() << "()"; 3284 OS << " (Temporary object destructor)\n"; 3285 } 3286} 3287 3288static void print_block(llvm::raw_ostream& OS, const CFG* cfg, 3289 const CFGBlock& B, 3290 StmtPrinterHelper* Helper, bool print_edges) { 3291 3292 if (Helper) Helper->setBlockID(B.getBlockID()); 3293 3294 // Print the header. 3295 OS << "\n [ B" << B.getBlockID(); 3296 3297 if (&B == &cfg->getEntry()) 3298 OS << " (ENTRY) ]\n"; 3299 else if (&B == &cfg->getExit()) 3300 OS << " (EXIT) ]\n"; 3301 else if (&B == cfg->getIndirectGotoBlock()) 3302 OS << " (INDIRECT GOTO DISPATCH) ]\n"; 3303 else 3304 OS << " ]\n"; 3305 3306 // Print the label of this block. 3307 if (Stmt* Label = const_cast<Stmt*>(B.getLabel())) { 3308 3309 if (print_edges) 3310 OS << " "; 3311 3312 if (LabelStmt* L = dyn_cast<LabelStmt>(Label)) 3313 OS << L->getName(); 3314 else if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) { 3315 OS << "case "; 3316 C->getLHS()->printPretty(OS, Helper, 3317 PrintingPolicy(Helper->getLangOpts())); 3318 if (C->getRHS()) { 3319 OS << " ... "; 3320 C->getRHS()->printPretty(OS, Helper, 3321 PrintingPolicy(Helper->getLangOpts())); 3322 } 3323 } else if (isa<DefaultStmt>(Label)) 3324 OS << "default"; 3325 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 3326 OS << "catch ("; 3327 if (CS->getExceptionDecl()) 3328 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()), 3329 0); 3330 else 3331 OS << "..."; 3332 OS << ")"; 3333 3334 } else 3335 assert(false && "Invalid label statement in CFGBlock."); 3336 3337 OS << ":\n"; 3338 } 3339 3340 // Iterate through the statements in the block and print them. 3341 unsigned j = 1; 3342 3343 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 3344 I != E ; ++I, ++j ) { 3345 3346 // Print the statement # in the basic block and the statement itself. 3347 if (print_edges) 3348 OS << " "; 3349 3350 OS << llvm::format("%3d", j) << ": "; 3351 3352 if (Helper) 3353 Helper->setStmtID(j); 3354 3355 print_elem(OS,Helper,*I); 3356 } 3357 3358 // Print the terminator of this block. 3359 if (B.getTerminator()) { 3360 if (print_edges) 3361 OS << " "; 3362 3363 OS << " T: "; 3364 3365 if (Helper) Helper->setBlockID(-1); 3366 3367 CFGBlockTerminatorPrint TPrinter(OS, Helper, 3368 PrintingPolicy(Helper->getLangOpts())); 3369 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt())); 3370 OS << '\n'; 3371 } 3372 3373 if (print_edges) { 3374 // Print the predecessors of this block. 3375 OS << " Predecessors (" << B.pred_size() << "):"; 3376 unsigned i = 0; 3377 3378 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 3379 I != E; ++I, ++i) { 3380 3381 if (i == 8 || (i-8) == 0) 3382 OS << "\n "; 3383 3384 OS << " B" << (*I)->getBlockID(); 3385 } 3386 3387 OS << '\n'; 3388 3389 // Print the successors of this block. 3390 OS << " Successors (" << B.succ_size() << "):"; 3391 i = 0; 3392 3393 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 3394 I != E; ++I, ++i) { 3395 3396 if (i == 8 || (i-8) % 10 == 0) 3397 OS << "\n "; 3398 3399 if (*I) 3400 OS << " B" << (*I)->getBlockID(); 3401 else 3402 OS << " NULL"; 3403 } 3404 3405 OS << '\n'; 3406 } 3407} 3408 3409 3410/// dump - A simple pretty printer of a CFG that outputs to stderr. 3411void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); } 3412 3413/// print - A simple pretty printer of a CFG that outputs to an ostream. 3414void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const { 3415 StmtPrinterHelper Helper(this, LO); 3416 3417 // Print the entry block. 3418 print_block(OS, this, getEntry(), &Helper, true); 3419 3420 // Iterate through the CFGBlocks and print them one by one. 3421 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 3422 // Skip the entry block, because we already printed it. 3423 if (&(**I) == &getEntry() || &(**I) == &getExit()) 3424 continue; 3425 3426 print_block(OS, this, **I, &Helper, true); 3427 } 3428 3429 // Print the exit block. 3430 print_block(OS, this, getExit(), &Helper, true); 3431 OS.flush(); 3432} 3433 3434/// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 3435void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const { 3436 print(llvm::errs(), cfg, LO); 3437} 3438 3439/// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 3440/// Generally this will only be called from CFG::print. 3441void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg, 3442 const LangOptions &LO) const { 3443 StmtPrinterHelper Helper(cfg, LO); 3444 print_block(OS, cfg, *this, &Helper, true); 3445} 3446 3447/// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 3448void CFGBlock::printTerminator(llvm::raw_ostream &OS, 3449 const LangOptions &LO) const { 3450 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO)); 3451 TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt())); 3452} 3453 3454Stmt* CFGBlock::getTerminatorCondition() { 3455 Stmt *Terminator = this->Terminator; 3456 if (!Terminator) 3457 return NULL; 3458 3459 Expr* E = NULL; 3460 3461 switch (Terminator->getStmtClass()) { 3462 default: 3463 break; 3464 3465 case Stmt::ForStmtClass: 3466 E = cast<ForStmt>(Terminator)->getCond(); 3467 break; 3468 3469 case Stmt::WhileStmtClass: 3470 E = cast<WhileStmt>(Terminator)->getCond(); 3471 break; 3472 3473 case Stmt::DoStmtClass: 3474 E = cast<DoStmt>(Terminator)->getCond(); 3475 break; 3476 3477 case Stmt::IfStmtClass: 3478 E = cast<IfStmt>(Terminator)->getCond(); 3479 break; 3480 3481 case Stmt::ChooseExprClass: 3482 E = cast<ChooseExpr>(Terminator)->getCond(); 3483 break; 3484 3485 case Stmt::IndirectGotoStmtClass: 3486 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 3487 break; 3488 3489 case Stmt::SwitchStmtClass: 3490 E = cast<SwitchStmt>(Terminator)->getCond(); 3491 break; 3492 3493 case Stmt::BinaryConditionalOperatorClass: 3494 E = cast<BinaryConditionalOperator>(Terminator)->getCond(); 3495 break; 3496 3497 case Stmt::ConditionalOperatorClass: 3498 E = cast<ConditionalOperator>(Terminator)->getCond(); 3499 break; 3500 3501 case Stmt::BinaryOperatorClass: // '&&' and '||' 3502 E = cast<BinaryOperator>(Terminator)->getLHS(); 3503 break; 3504 3505 case Stmt::ObjCForCollectionStmtClass: 3506 return Terminator; 3507 } 3508 3509 return E ? E->IgnoreParens() : NULL; 3510} 3511 3512bool CFGBlock::hasBinaryBranchTerminator() const { 3513 const Stmt *Terminator = this->Terminator; 3514 if (!Terminator) 3515 return false; 3516 3517 Expr* E = NULL; 3518 3519 switch (Terminator->getStmtClass()) { 3520 default: 3521 return false; 3522 3523 case Stmt::ForStmtClass: 3524 case Stmt::WhileStmtClass: 3525 case Stmt::DoStmtClass: 3526 case Stmt::IfStmtClass: 3527 case Stmt::ChooseExprClass: 3528 case Stmt::BinaryConditionalOperatorClass: 3529 case Stmt::ConditionalOperatorClass: 3530 case Stmt::BinaryOperatorClass: 3531 return true; 3532 } 3533 3534 return E ? E->IgnoreParens() : NULL; 3535} 3536 3537 3538//===----------------------------------------------------------------------===// 3539// CFG Graphviz Visualization 3540//===----------------------------------------------------------------------===// 3541 3542 3543#ifndef NDEBUG 3544static StmtPrinterHelper* GraphHelper; 3545#endif 3546 3547void CFG::viewCFG(const LangOptions &LO) const { 3548#ifndef NDEBUG 3549 StmtPrinterHelper H(this, LO); 3550 GraphHelper = &H; 3551 llvm::ViewGraph(this,"CFG"); 3552 GraphHelper = NULL; 3553#endif 3554} 3555 3556namespace llvm { 3557template<> 3558struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 3559 3560 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 3561 3562 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) { 3563 3564#ifndef NDEBUG 3565 std::string OutSStr; 3566 llvm::raw_string_ostream Out(OutSStr); 3567 print_block(Out,Graph, *Node, GraphHelper, false); 3568 std::string& OutStr = Out.str(); 3569 3570 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 3571 3572 // Process string output to make it nicer... 3573 for (unsigned i = 0; i != OutStr.length(); ++i) 3574 if (OutStr[i] == '\n') { // Left justify 3575 OutStr[i] = '\\'; 3576 OutStr.insert(OutStr.begin()+i+1, 'l'); 3577 } 3578 3579 return OutStr; 3580#else 3581 return ""; 3582#endif 3583 } 3584}; 3585} // end namespace llvm 3586