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