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