1 //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the CFG and CFGBuilder classes for representing and 11 // building Control-Flow Graphs (CFGs) from ASTs. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Analysis/CFG.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/PrettyPrinter.h" 21 #include "clang/AST/StmtVisitor.h" 22 #include "clang/Basic/Builtins.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include <memory> 25 #include "llvm/ADT/SmallPtrSet.h" 26 #include "llvm/Support/Allocator.h" 27 #include "llvm/Support/Format.h" 28 #include "llvm/Support/GraphWriter.h" 29 #include "llvm/Support/SaveAndRestore.h" 30 31 using namespace clang; 32 33 namespace { 34 35 static SourceLocation GetEndLoc(Decl *D) { 36 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 37 if (Expr *Ex = VD->getInit()) 38 return Ex->getSourceRange().getEnd(); 39 return D->getLocation(); 40 } 41 42 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral 43 /// or EnumConstantDecl from the given Expr. If it fails, returns nullptr. 44 const Expr *tryTransformToIntOrEnumConstant(const Expr *E) { 45 E = E->IgnoreParens(); 46 if (isa<IntegerLiteral>(E)) 47 return E; 48 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 49 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr; 50 return nullptr; 51 } 52 53 /// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is 54 /// an integer literal or an enum constant. 55 /// 56 /// If this fails, at least one of the returned DeclRefExpr or Expr will be 57 /// null. 58 static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *> 59 tryNormalizeBinaryOperator(const BinaryOperator *B) { 60 BinaryOperatorKind Op = B->getOpcode(); 61 62 const Expr *MaybeDecl = B->getLHS(); 63 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS()); 64 // Expr looked like `0 == Foo` instead of `Foo == 0` 65 if (Constant == nullptr) { 66 // Flip the operator 67 if (Op == BO_GT) 68 Op = BO_LT; 69 else if (Op == BO_GE) 70 Op = BO_LE; 71 else if (Op == BO_LT) 72 Op = BO_GT; 73 else if (Op == BO_LE) 74 Op = BO_GE; 75 76 MaybeDecl = B->getRHS(); 77 Constant = tryTransformToIntOrEnumConstant(B->getLHS()); 78 } 79 80 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts()); 81 return std::make_tuple(D, Op, Constant); 82 } 83 84 /// For an expression `x == Foo && x == Bar`, this determines whether the 85 /// `Foo` and `Bar` are either of the same enumeration type, or both integer 86 /// literals. 87 /// 88 /// It's an error to pass this arguments that are not either IntegerLiterals 89 /// or DeclRefExprs (that have decls of type EnumConstantDecl) 90 static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) { 91 // User intent isn't clear if they're mixing int literals with enum 92 // constants. 93 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2)) 94 return false; 95 96 // Integer literal comparisons, regardless of literal type, are acceptable. 97 if (isa<IntegerLiteral>(E1)) 98 return true; 99 100 // IntegerLiterals are handled above and only EnumConstantDecls are expected 101 // beyond this point 102 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2)); 103 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl(); 104 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl(); 105 106 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2)); 107 const DeclContext *DC1 = Decl1->getDeclContext(); 108 const DeclContext *DC2 = Decl2->getDeclContext(); 109 110 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2)); 111 return DC1 == DC2; 112 } 113 114 class CFGBuilder; 115 116 /// The CFG builder uses a recursive algorithm to build the CFG. When 117 /// we process an expression, sometimes we know that we must add the 118 /// subexpressions as block-level expressions. For example: 119 /// 120 /// exp1 || exp2 121 /// 122 /// When processing the '||' expression, we know that exp1 and exp2 123 /// need to be added as block-level expressions, even though they 124 /// might not normally need to be. AddStmtChoice records this 125 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then 126 /// the builder has an option not to add a subexpression as a 127 /// block-level expression. 128 /// 129 class AddStmtChoice { 130 public: 131 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 }; 132 133 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {} 134 135 bool alwaysAdd(CFGBuilder &builder, 136 const Stmt *stmt) const; 137 138 /// Return a copy of this object, except with the 'always-add' bit 139 /// set as specified. 140 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const { 141 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd); 142 } 143 144 private: 145 Kind kind; 146 }; 147 148 /// LocalScope - Node in tree of local scopes created for C++ implicit 149 /// destructor calls generation. It contains list of automatic variables 150 /// declared in the scope and link to position in previous scope this scope 151 /// began in. 152 /// 153 /// The process of creating local scopes is as follows: 154 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null), 155 /// - Before processing statements in scope (e.g. CompoundStmt) create 156 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope 157 /// and set CFGBuilder::ScopePos to the end of new scope, 158 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points 159 /// at this VarDecl, 160 /// - For every normal (without jump) end of scope add to CFGBlock destructors 161 /// for objects in the current scope, 162 /// - For every jump add to CFGBlock destructors for objects 163 /// between CFGBuilder::ScopePos and local scope position saved for jump 164 /// target. Thanks to C++ restrictions on goto jumps we can be sure that 165 /// jump target position will be on the path to root from CFGBuilder::ScopePos 166 /// (adding any variable that doesn't need constructor to be called to 167 /// LocalScope can break this assumption), 168 /// 169 class LocalScope { 170 public: 171 typedef BumpVector<VarDecl*> AutomaticVarsTy; 172 173 /// const_iterator - Iterates local scope backwards and jumps to previous 174 /// scope on reaching the beginning of currently iterated scope. 175 class const_iterator { 176 const LocalScope* Scope; 177 178 /// VarIter is guaranteed to be greater then 0 for every valid iterator. 179 /// Invalid iterator (with null Scope) has VarIter equal to 0. 180 unsigned VarIter; 181 182 public: 183 /// Create invalid iterator. Dereferencing invalid iterator is not allowed. 184 /// Incrementing invalid iterator is allowed and will result in invalid 185 /// iterator. 186 const_iterator() 187 : Scope(nullptr), VarIter(0) {} 188 189 /// Create valid iterator. In case when S.Prev is an invalid iterator and 190 /// I is equal to 0, this will create invalid iterator. 191 const_iterator(const LocalScope& S, unsigned I) 192 : Scope(&S), VarIter(I) { 193 // Iterator to "end" of scope is not allowed. Handle it by going up 194 // in scopes tree possibly up to invalid iterator in the root. 195 if (VarIter == 0 && Scope) 196 *this = Scope->Prev; 197 } 198 199 VarDecl *const* operator->() const { 200 assert (Scope && "Dereferencing invalid iterator is not allowed"); 201 assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); 202 return &Scope->Vars[VarIter - 1]; 203 } 204 VarDecl *operator*() const { 205 return *this->operator->(); 206 } 207 208 const_iterator &operator++() { 209 if (!Scope) 210 return *this; 211 212 assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); 213 --VarIter; 214 if (VarIter == 0) 215 *this = Scope->Prev; 216 return *this; 217 } 218 const_iterator operator++(int) { 219 const_iterator P = *this; 220 ++*this; 221 return P; 222 } 223 224 bool operator==(const const_iterator &rhs) const { 225 return Scope == rhs.Scope && VarIter == rhs.VarIter; 226 } 227 bool operator!=(const const_iterator &rhs) const { 228 return !(*this == rhs); 229 } 230 231 explicit operator bool() const { 232 return *this != const_iterator(); 233 } 234 235 int distance(const_iterator L); 236 const_iterator shared_parent(const_iterator L); 237 }; 238 239 friend class const_iterator; 240 241 private: 242 BumpVectorContext ctx; 243 244 /// Automatic variables in order of declaration. 245 AutomaticVarsTy Vars; 246 /// Iterator to variable in previous scope that was declared just before 247 /// begin of this scope. 248 const_iterator Prev; 249 250 public: 251 /// Constructs empty scope linked to previous scope in specified place. 252 LocalScope(BumpVectorContext ctx, const_iterator P) 253 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {} 254 255 /// Begin of scope in direction of CFG building (backwards). 256 const_iterator begin() const { return const_iterator(*this, Vars.size()); } 257 258 void addVar(VarDecl *VD) { 259 Vars.push_back(VD, ctx); 260 } 261 }; 262 263 /// distance - Calculates distance from this to L. L must be reachable from this 264 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t. 265 /// number of scopes between this and L. 266 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) { 267 int D = 0; 268 const_iterator F = *this; 269 while (F.Scope != L.Scope) { 270 assert (F != const_iterator() 271 && "L iterator is not reachable from F iterator."); 272 D += F.VarIter; 273 F = F.Scope->Prev; 274 } 275 D += F.VarIter - L.VarIter; 276 return D; 277 } 278 279 /// Calculates the closest parent of this iterator 280 /// that is in a scope reachable through the parents of L. 281 /// I.e. when using 'goto' from this to L, the lifetime of all variables 282 /// between this and shared_parent(L) end. 283 LocalScope::const_iterator 284 LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) { 285 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL; 286 while (true) { 287 ScopesOfL.insert(L.Scope); 288 if (L == const_iterator()) 289 break; 290 L = L.Scope->Prev; 291 } 292 293 const_iterator F = *this; 294 while (true) { 295 if (ScopesOfL.count(F.Scope)) 296 return F; 297 assert(F != const_iterator() && 298 "L iterator is not reachable from F iterator."); 299 F = F.Scope->Prev; 300 } 301 } 302 303 /// Structure for specifying position in CFG during its build process. It 304 /// consists of CFGBlock that specifies position in CFG and 305 /// LocalScope::const_iterator that specifies position in LocalScope graph. 306 struct BlockScopePosPair { 307 BlockScopePosPair() : block(nullptr) {} 308 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos) 309 : block(b), scopePosition(scopePos) {} 310 311 CFGBlock *block; 312 LocalScope::const_iterator scopePosition; 313 }; 314 315 /// TryResult - a class representing a variant over the values 316 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool, 317 /// and is used by the CFGBuilder to decide if a branch condition 318 /// can be decided up front during CFG construction. 319 class TryResult { 320 int X; 321 public: 322 TryResult(bool b) : X(b ? 1 : 0) {} 323 TryResult() : X(-1) {} 324 325 bool isTrue() const { return X == 1; } 326 bool isFalse() const { return X == 0; } 327 bool isKnown() const { return X >= 0; } 328 void negate() { 329 assert(isKnown()); 330 X ^= 0x1; 331 } 332 }; 333 334 TryResult bothKnownTrue(TryResult R1, TryResult R2) { 335 if (!R1.isKnown() || !R2.isKnown()) 336 return TryResult(); 337 return TryResult(R1.isTrue() && R2.isTrue()); 338 } 339 340 class reverse_children { 341 llvm::SmallVector<Stmt *, 12> childrenBuf; 342 ArrayRef<Stmt*> children; 343 public: 344 reverse_children(Stmt *S); 345 346 typedef ArrayRef<Stmt*>::reverse_iterator iterator; 347 iterator begin() const { return children.rbegin(); } 348 iterator end() const { return children.rend(); } 349 }; 350 351 352 reverse_children::reverse_children(Stmt *S) { 353 if (CallExpr *CE = dyn_cast<CallExpr>(S)) { 354 children = CE->getRawSubExprs(); 355 return; 356 } 357 switch (S->getStmtClass()) { 358 // Note: Fill in this switch with more cases we want to optimize. 359 case Stmt::InitListExprClass: { 360 InitListExpr *IE = cast<InitListExpr>(S); 361 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()), 362 IE->getNumInits()); 363 return; 364 } 365 default: 366 break; 367 } 368 369 // Default case for all other statements. 370 for (Stmt *SubStmt : S->children()) 371 childrenBuf.push_back(SubStmt); 372 373 // This needs to be done *after* childrenBuf has been populated. 374 children = childrenBuf; 375 } 376 377 /// CFGBuilder - This class implements CFG construction from an AST. 378 /// The builder is stateful: an instance of the builder should be used to only 379 /// construct a single CFG. 380 /// 381 /// Example usage: 382 /// 383 /// CFGBuilder builder; 384 /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1); 385 /// 386 /// CFG construction is done via a recursive walk of an AST. We actually parse 387 /// the AST in reverse order so that the successor of a basic block is 388 /// constructed prior to its predecessor. This allows us to nicely capture 389 /// implicit fall-throughs without extra basic blocks. 390 /// 391 class CFGBuilder { 392 typedef BlockScopePosPair JumpTarget; 393 typedef BlockScopePosPair JumpSource; 394 395 ASTContext *Context; 396 std::unique_ptr<CFG> cfg; 397 398 CFGBlock *Block; // Current block. 399 CFGBlock *Succ; // Block after the current block. 400 JumpTarget ContinueJumpTarget; 401 JumpTarget BreakJumpTarget; 402 JumpTarget SEHLeaveJumpTarget; 403 CFGBlock *SwitchTerminatedBlock; 404 CFGBlock *DefaultCaseBlock; 405 406 // This can point either to a try or a __try block. The frontend forbids 407 // mixing both kinds in one function, so having one for both is enough. 408 CFGBlock *TryTerminatedBlock; 409 410 // Current position in local scope. 411 LocalScope::const_iterator ScopePos; 412 413 // LabelMap records the mapping from Label expressions to their jump targets. 414 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy; 415 LabelMapTy LabelMap; 416 417 // A list of blocks that end with a "goto" that must be backpatched to their 418 // resolved targets upon completion of CFG construction. 419 typedef std::vector<JumpSource> BackpatchBlocksTy; 420 BackpatchBlocksTy BackpatchBlocks; 421 422 // A list of labels whose address has been taken (for indirect gotos). 423 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy; 424 LabelSetTy AddressTakenLabels; 425 426 bool badCFG; 427 const CFG::BuildOptions &BuildOpts; 428 429 // State to track for building switch statements. 430 bool switchExclusivelyCovered; 431 Expr::EvalResult *switchCond; 432 433 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry; 434 const Stmt *lastLookup; 435 436 // Caches boolean evaluations of expressions to avoid multiple re-evaluations 437 // during construction of branches for chained logical operators. 438 typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy; 439 CachedBoolEvalsTy CachedBoolEvals; 440 441 public: 442 explicit CFGBuilder(ASTContext *astContext, 443 const CFG::BuildOptions &buildOpts) 444 : Context(astContext), cfg(new CFG()), // crew a new CFG 445 Block(nullptr), Succ(nullptr), SwitchTerminatedBlock(nullptr), 446 DefaultCaseBlock(nullptr), TryTerminatedBlock(nullptr), badCFG(false), 447 BuildOpts(buildOpts), switchExclusivelyCovered(false), 448 switchCond(nullptr), cachedEntry(nullptr), lastLookup(nullptr) {} 449 450 // buildCFG - Used by external clients to construct the CFG. 451 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement); 452 453 bool alwaysAdd(const Stmt *stmt); 454 455 private: 456 // Visitors to walk an AST and construct the CFG. 457 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc); 458 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc); 459 CFGBlock *VisitBreakStmt(BreakStmt *B); 460 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc); 461 CFGBlock *VisitCaseStmt(CaseStmt *C); 462 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc); 463 CFGBlock *VisitCompoundStmt(CompoundStmt *C); 464 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C, 465 AddStmtChoice asc); 466 CFGBlock *VisitContinueStmt(ContinueStmt *C); 467 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 468 AddStmtChoice asc); 469 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S); 470 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc); 471 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc); 472 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc); 473 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S); 474 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 475 AddStmtChoice asc); 476 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 477 AddStmtChoice asc); 478 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T); 479 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S); 480 CFGBlock *VisitDeclStmt(DeclStmt *DS); 481 CFGBlock *VisitDeclSubExpr(DeclStmt *DS); 482 CFGBlock *VisitDefaultStmt(DefaultStmt *D); 483 CFGBlock *VisitDoStmt(DoStmt *D); 484 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc); 485 CFGBlock *VisitForStmt(ForStmt *F); 486 CFGBlock *VisitGotoStmt(GotoStmt *G); 487 CFGBlock *VisitIfStmt(IfStmt *I); 488 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc); 489 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I); 490 CFGBlock *VisitLabelStmt(LabelStmt *L); 491 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc); 492 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc); 493 CFGBlock *VisitLogicalOperator(BinaryOperator *B); 494 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B, 495 Stmt *Term, 496 CFGBlock *TrueBlock, 497 CFGBlock *FalseBlock); 498 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc); 499 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 500 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 501 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 502 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); 503 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); 504 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 505 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E); 506 CFGBlock *VisitReturnStmt(ReturnStmt *R); 507 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S); 508 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S); 509 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S); 510 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S); 511 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc); 512 CFGBlock *VisitSwitchStmt(SwitchStmt *S); 513 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 514 AddStmtChoice asc); 515 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc); 516 CFGBlock *VisitWhileStmt(WhileStmt *W); 517 518 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd); 519 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc); 520 CFGBlock *VisitChildren(Stmt *S); 521 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc); 522 523 /// When creating the CFG for temporary destructors, we want to mirror the 524 /// branch structure of the corresponding constructor calls. 525 /// Thus, while visiting a statement for temporary destructors, we keep a 526 /// context to keep track of the following information: 527 /// - whether a subexpression is executed unconditionally 528 /// - if a subexpression is executed conditionally, the first 529 /// CXXBindTemporaryExpr we encounter in that subexpression (which 530 /// corresponds to the last temporary destructor we have to call for this 531 /// subexpression) and the CFG block at that point (which will become the 532 /// successor block when inserting the decision point). 533 /// 534 /// That way, we can build the branch structure for temporary destructors as 535 /// follows: 536 /// 1. If a subexpression is executed unconditionally, we add the temporary 537 /// destructor calls to the current block. 538 /// 2. If a subexpression is executed conditionally, when we encounter a 539 /// CXXBindTemporaryExpr: 540 /// a) If it is the first temporary destructor call in the subexpression, 541 /// we remember the CXXBindTemporaryExpr and the current block in the 542 /// TempDtorContext; we start a new block, and insert the temporary 543 /// destructor call. 544 /// b) Otherwise, add the temporary destructor call to the current block. 545 /// 3. When we finished visiting a conditionally executed subexpression, 546 /// and we found at least one temporary constructor during the visitation 547 /// (2.a has executed), we insert a decision block that uses the 548 /// CXXBindTemporaryExpr as terminator, and branches to the current block 549 /// if the CXXBindTemporaryExpr was marked executed, and otherwise 550 /// branches to the stored successor. 551 struct TempDtorContext { 552 TempDtorContext() 553 : IsConditional(false), KnownExecuted(true), Succ(nullptr), 554 TerminatorExpr(nullptr) {} 555 556 TempDtorContext(TryResult KnownExecuted) 557 : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr), 558 TerminatorExpr(nullptr) {} 559 560 /// Returns whether we need to start a new branch for a temporary destructor 561 /// call. This is the case when the temporary destructor is 562 /// conditionally executed, and it is the first one we encounter while 563 /// visiting a subexpression - other temporary destructors at the same level 564 /// will be added to the same block and are executed under the same 565 /// condition. 566 bool needsTempDtorBranch() const { 567 return IsConditional && !TerminatorExpr; 568 } 569 570 /// Remember the successor S of a temporary destructor decision branch for 571 /// the corresponding CXXBindTemporaryExpr E. 572 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) { 573 Succ = S; 574 TerminatorExpr = E; 575 } 576 577 const bool IsConditional; 578 const TryResult KnownExecuted; 579 CFGBlock *Succ; 580 CXXBindTemporaryExpr *TerminatorExpr; 581 }; 582 583 // Visitors to walk an AST and generate destructors of temporaries in 584 // full expression. 585 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary, 586 TempDtorContext &Context); 587 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context); 588 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E, 589 TempDtorContext &Context); 590 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors( 591 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context); 592 CFGBlock *VisitConditionalOperatorForTemporaryDtors( 593 AbstractConditionalOperator *E, bool BindToTemporary, 594 TempDtorContext &Context); 595 void InsertTempDtorDecisionBlock(const TempDtorContext &Context, 596 CFGBlock *FalseSucc = nullptr); 597 598 // NYS == Not Yet Supported 599 CFGBlock *NYS() { 600 badCFG = true; 601 return Block; 602 } 603 604 void autoCreateBlock() { if (!Block) Block = createBlock(); } 605 CFGBlock *createBlock(bool add_successor = true); 606 CFGBlock *createNoReturnBlock(); 607 608 CFGBlock *addStmt(Stmt *S) { 609 return Visit(S, AddStmtChoice::AlwaysAdd); 610 } 611 CFGBlock *addInitializer(CXXCtorInitializer *I); 612 void addLoopExit(const Stmt *LoopStmt); 613 void addAutomaticObjDtors(LocalScope::const_iterator B, 614 LocalScope::const_iterator E, Stmt *S); 615 void addLifetimeEnds(LocalScope::const_iterator B, 616 LocalScope::const_iterator E, Stmt *S); 617 void addAutomaticObjHandling(LocalScope::const_iterator B, 618 LocalScope::const_iterator E, Stmt *S); 619 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD); 620 621 // Local scopes creation. 622 LocalScope* createOrReuseLocalScope(LocalScope* Scope); 623 624 void addLocalScopeForStmt(Stmt *S); 625 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS, 626 LocalScope* Scope = nullptr); 627 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr); 628 629 void addLocalScopeAndDtors(Stmt *S); 630 631 // Interface to CFGBlock - adding CFGElements. 632 void appendStmt(CFGBlock *B, const Stmt *S) { 633 if (alwaysAdd(S) && cachedEntry) 634 cachedEntry->second = B; 635 636 // All block-level expressions should have already been IgnoreParens()ed. 637 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S); 638 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext()); 639 } 640 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) { 641 B->appendInitializer(I, cfg->getBumpVectorContext()); 642 } 643 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) { 644 B->appendNewAllocator(NE, cfg->getBumpVectorContext()); 645 } 646 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) { 647 B->appendBaseDtor(BS, cfg->getBumpVectorContext()); 648 } 649 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) { 650 B->appendMemberDtor(FD, cfg->getBumpVectorContext()); 651 } 652 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) { 653 B->appendTemporaryDtor(E, cfg->getBumpVectorContext()); 654 } 655 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) { 656 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext()); 657 } 658 659 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) { 660 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext()); 661 } 662 663 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) { 664 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext()); 665 } 666 667 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) { 668 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext()); 669 } 670 671 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 672 LocalScope::const_iterator B, LocalScope::const_iterator E); 673 674 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk, 675 LocalScope::const_iterator B, 676 LocalScope::const_iterator E); 677 678 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) { 679 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable), 680 cfg->getBumpVectorContext()); 681 } 682 683 /// Add a reachable successor to a block, with the alternate variant that is 684 /// unreachable. 685 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) { 686 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock), 687 cfg->getBumpVectorContext()); 688 } 689 690 /// \brief Find a relational comparison with an expression evaluating to a 691 /// boolean and a constant other than 0 and 1. 692 /// e.g. if ((x < y) == 10) 693 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) { 694 const Expr *LHSExpr = B->getLHS()->IgnoreParens(); 695 const Expr *RHSExpr = B->getRHS()->IgnoreParens(); 696 697 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr); 698 const Expr *BoolExpr = RHSExpr; 699 bool IntFirst = true; 700 if (!IntLiteral) { 701 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr); 702 BoolExpr = LHSExpr; 703 IntFirst = false; 704 } 705 706 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue()) 707 return TryResult(); 708 709 llvm::APInt IntValue = IntLiteral->getValue(); 710 if ((IntValue == 1) || (IntValue == 0)) 711 return TryResult(); 712 713 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() || 714 !IntValue.isNegative(); 715 716 BinaryOperatorKind Bok = B->getOpcode(); 717 if (Bok == BO_GT || Bok == BO_GE) { 718 // Always true for 10 > bool and bool > -1 719 // Always false for -1 > bool and bool > 10 720 return TryResult(IntFirst == IntLarger); 721 } else { 722 // Always true for -1 < bool and bool < 10 723 // Always false for 10 < bool and bool < -1 724 return TryResult(IntFirst != IntLarger); 725 } 726 } 727 728 /// Find an incorrect equality comparison. Either with an expression 729 /// evaluating to a boolean and a constant other than 0 and 1. 730 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to 731 /// true/false e.q. (x & 8) == 4. 732 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) { 733 const Expr *LHSExpr = B->getLHS()->IgnoreParens(); 734 const Expr *RHSExpr = B->getRHS()->IgnoreParens(); 735 736 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr); 737 const Expr *BoolExpr = RHSExpr; 738 739 if (!IntLiteral) { 740 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr); 741 BoolExpr = LHSExpr; 742 } 743 744 if (!IntLiteral) 745 return TryResult(); 746 747 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr); 748 if (BitOp && (BitOp->getOpcode() == BO_And || 749 BitOp->getOpcode() == BO_Or)) { 750 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens(); 751 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens(); 752 753 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2); 754 755 if (!IntLiteral2) 756 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2); 757 758 if (!IntLiteral2) 759 return TryResult(); 760 761 llvm::APInt L1 = IntLiteral->getValue(); 762 llvm::APInt L2 = IntLiteral2->getValue(); 763 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) || 764 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) { 765 if (BuildOpts.Observer) 766 BuildOpts.Observer->compareBitwiseEquality(B, 767 B->getOpcode() != BO_EQ); 768 TryResult(B->getOpcode() != BO_EQ); 769 } 770 } else if (BoolExpr->isKnownToHaveBooleanValue()) { 771 llvm::APInt IntValue = IntLiteral->getValue(); 772 if ((IntValue == 1) || (IntValue == 0)) { 773 return TryResult(); 774 } 775 return TryResult(B->getOpcode() != BO_EQ); 776 } 777 778 return TryResult(); 779 } 780 781 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation, 782 const llvm::APSInt &Value1, 783 const llvm::APSInt &Value2) { 784 assert(Value1.isSigned() == Value2.isSigned()); 785 switch (Relation) { 786 default: 787 return TryResult(); 788 case BO_EQ: 789 return TryResult(Value1 == Value2); 790 case BO_NE: 791 return TryResult(Value1 != Value2); 792 case BO_LT: 793 return TryResult(Value1 < Value2); 794 case BO_LE: 795 return TryResult(Value1 <= Value2); 796 case BO_GT: 797 return TryResult(Value1 > Value2); 798 case BO_GE: 799 return TryResult(Value1 >= Value2); 800 } 801 } 802 803 /// \brief Find a pair of comparison expressions with or without parentheses 804 /// with a shared variable and constants and a logical operator between them 805 /// that always evaluates to either true or false. 806 /// e.g. if (x != 3 || x != 4) 807 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) { 808 assert(B->isLogicalOp()); 809 const BinaryOperator *LHS = 810 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens()); 811 const BinaryOperator *RHS = 812 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens()); 813 if (!LHS || !RHS) 814 return TryResult(); 815 816 if (!LHS->isComparisonOp() || !RHS->isComparisonOp()) 817 return TryResult(); 818 819 const DeclRefExpr *Decl1; 820 const Expr *Expr1; 821 BinaryOperatorKind BO1; 822 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS); 823 824 if (!Decl1 || !Expr1) 825 return TryResult(); 826 827 const DeclRefExpr *Decl2; 828 const Expr *Expr2; 829 BinaryOperatorKind BO2; 830 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS); 831 832 if (!Decl2 || !Expr2) 833 return TryResult(); 834 835 // Check that it is the same variable on both sides. 836 if (Decl1->getDecl() != Decl2->getDecl()) 837 return TryResult(); 838 839 // Make sure the user's intent is clear (e.g. they're comparing against two 840 // int literals, or two things from the same enum) 841 if (!areExprTypesCompatible(Expr1, Expr2)) 842 return TryResult(); 843 844 llvm::APSInt L1, L2; 845 846 if (!Expr1->EvaluateAsInt(L1, *Context) || 847 !Expr2->EvaluateAsInt(L2, *Context)) 848 return TryResult(); 849 850 // Can't compare signed with unsigned or with different bit width. 851 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth()) 852 return TryResult(); 853 854 // Values that will be used to determine if result of logical 855 // operator is always true/false 856 const llvm::APSInt Values[] = { 857 // Value less than both Value1 and Value2 858 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()), 859 // L1 860 L1, 861 // Value between Value1 and Value2 862 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1), 863 L1.isUnsigned()), 864 // L2 865 L2, 866 // Value greater than both Value1 and Value2 867 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()), 868 }; 869 870 // Check whether expression is always true/false by evaluating the following 871 // * variable x is less than the smallest literal. 872 // * variable x is equal to the smallest literal. 873 // * Variable x is between smallest and largest literal. 874 // * Variable x is equal to the largest literal. 875 // * Variable x is greater than largest literal. 876 bool AlwaysTrue = true, AlwaysFalse = true; 877 for (const llvm::APSInt &Value : Values) { 878 TryResult Res1, Res2; 879 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1); 880 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2); 881 882 if (!Res1.isKnown() || !Res2.isKnown()) 883 return TryResult(); 884 885 if (B->getOpcode() == BO_LAnd) { 886 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue()); 887 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue()); 888 } else { 889 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue()); 890 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue()); 891 } 892 } 893 894 if (AlwaysTrue || AlwaysFalse) { 895 if (BuildOpts.Observer) 896 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue); 897 return TryResult(AlwaysTrue); 898 } 899 return TryResult(); 900 } 901 902 /// Try and evaluate an expression to an integer constant. 903 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) { 904 if (!BuildOpts.PruneTriviallyFalseEdges) 905 return false; 906 return !S->isTypeDependent() && 907 !S->isValueDependent() && 908 S->EvaluateAsRValue(outResult, *Context); 909 } 910 911 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1 912 /// if we can evaluate to a known value, otherwise return -1. 913 TryResult tryEvaluateBool(Expr *S) { 914 if (!BuildOpts.PruneTriviallyFalseEdges || 915 S->isTypeDependent() || S->isValueDependent()) 916 return TryResult(); 917 918 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) { 919 if (Bop->isLogicalOp()) { 920 // Check the cache first. 921 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S); 922 if (I != CachedBoolEvals.end()) 923 return I->second; // already in map; 924 925 // Retrieve result at first, or the map might be updated. 926 TryResult Result = evaluateAsBooleanConditionNoCache(S); 927 CachedBoolEvals[S] = Result; // update or insert 928 return Result; 929 } 930 else { 931 switch (Bop->getOpcode()) { 932 default: break; 933 // For 'x & 0' and 'x * 0', we can determine that 934 // the value is always false. 935 case BO_Mul: 936 case BO_And: { 937 // If either operand is zero, we know the value 938 // must be false. 939 llvm::APSInt IntVal; 940 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) { 941 if (!IntVal.getBoolValue()) { 942 return TryResult(false); 943 } 944 } 945 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) { 946 if (!IntVal.getBoolValue()) { 947 return TryResult(false); 948 } 949 } 950 } 951 break; 952 } 953 } 954 } 955 956 return evaluateAsBooleanConditionNoCache(S); 957 } 958 959 /// \brief Evaluate as boolean \param E without using the cache. 960 TryResult evaluateAsBooleanConditionNoCache(Expr *E) { 961 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) { 962 if (Bop->isLogicalOp()) { 963 TryResult LHS = tryEvaluateBool(Bop->getLHS()); 964 if (LHS.isKnown()) { 965 // We were able to evaluate the LHS, see if we can get away with not 966 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 967 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr)) 968 return LHS.isTrue(); 969 970 TryResult RHS = tryEvaluateBool(Bop->getRHS()); 971 if (RHS.isKnown()) { 972 if (Bop->getOpcode() == BO_LOr) 973 return LHS.isTrue() || RHS.isTrue(); 974 else 975 return LHS.isTrue() && RHS.isTrue(); 976 } 977 } else { 978 TryResult RHS = tryEvaluateBool(Bop->getRHS()); 979 if (RHS.isKnown()) { 980 // We can't evaluate the LHS; however, sometimes the result 981 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 982 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr)) 983 return RHS.isTrue(); 984 } else { 985 TryResult BopRes = checkIncorrectLogicOperator(Bop); 986 if (BopRes.isKnown()) 987 return BopRes.isTrue(); 988 } 989 } 990 991 return TryResult(); 992 } else if (Bop->isEqualityOp()) { 993 TryResult BopRes = checkIncorrectEqualityOperator(Bop); 994 if (BopRes.isKnown()) 995 return BopRes.isTrue(); 996 } else if (Bop->isRelationalOp()) { 997 TryResult BopRes = checkIncorrectRelationalOperator(Bop); 998 if (BopRes.isKnown()) 999 return BopRes.isTrue(); 1000 } 1001 } 1002 1003 bool Result; 1004 if (E->EvaluateAsBooleanCondition(Result, *Context)) 1005 return Result; 1006 1007 return TryResult(); 1008 } 1009 1010 bool hasTrivialDestructor(VarDecl *VD); 1011 }; 1012 1013 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder, 1014 const Stmt *stmt) const { 1015 return builder.alwaysAdd(stmt) || kind == AlwaysAdd; 1016 } 1017 1018 bool CFGBuilder::alwaysAdd(const Stmt *stmt) { 1019 bool shouldAdd = BuildOpts.alwaysAdd(stmt); 1020 1021 if (!BuildOpts.forcedBlkExprs) 1022 return shouldAdd; 1023 1024 if (lastLookup == stmt) { 1025 if (cachedEntry) { 1026 assert(cachedEntry->first == stmt); 1027 return true; 1028 } 1029 return shouldAdd; 1030 } 1031 1032 lastLookup = stmt; 1033 1034 // Perform the lookup! 1035 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs; 1036 1037 if (!fb) { 1038 // No need to update 'cachedEntry', since it will always be null. 1039 assert(!cachedEntry); 1040 return shouldAdd; 1041 } 1042 1043 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt); 1044 if (itr == fb->end()) { 1045 cachedEntry = nullptr; 1046 return shouldAdd; 1047 } 1048 1049 cachedEntry = &*itr; 1050 return true; 1051 } 1052 1053 // FIXME: Add support for dependent-sized array types in C++? 1054 // Does it even make sense to build a CFG for an uninstantiated template? 1055 static const VariableArrayType *FindVA(const Type *t) { 1056 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) { 1057 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt)) 1058 if (vat->getSizeExpr()) 1059 return vat; 1060 1061 t = vt->getElementType().getTypePtr(); 1062 } 1063 1064 return nullptr; 1065 } 1066 1067 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an 1068 /// arbitrary statement. Examples include a single expression or a function 1069 /// body (compound statement). The ownership of the returned CFG is 1070 /// transferred to the caller. If CFG construction fails, this method returns 1071 /// NULL. 1072 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) { 1073 assert(cfg.get()); 1074 if (!Statement) 1075 return nullptr; 1076 1077 // Create an empty block that will serve as the exit block for the CFG. Since 1078 // this is the first block added to the CFG, it will be implicitly registered 1079 // as the exit block. 1080 Succ = createBlock(); 1081 assert(Succ == &cfg->getExit()); 1082 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily. 1083 1084 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) && 1085 "AddImplicitDtors and AddLifetime cannot be used at the same time"); 1086 1087 if (BuildOpts.AddImplicitDtors) 1088 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D)) 1089 addImplicitDtorsForDestructor(DD); 1090 1091 // Visit the statements and create the CFG. 1092 CFGBlock *B = addStmt(Statement); 1093 1094 if (badCFG) 1095 return nullptr; 1096 1097 // For C++ constructor add initializers to CFG. 1098 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) { 1099 for (auto *I : llvm::reverse(CD->inits())) { 1100 B = addInitializer(I); 1101 if (badCFG) 1102 return nullptr; 1103 } 1104 } 1105 1106 if (B) 1107 Succ = B; 1108 1109 // Backpatch the gotos whose label -> block mappings we didn't know when we 1110 // encountered them. 1111 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(), 1112 E = BackpatchBlocks.end(); I != E; ++I ) { 1113 1114 CFGBlock *B = I->block; 1115 const GotoStmt *G = cast<GotoStmt>(B->getTerminator()); 1116 LabelMapTy::iterator LI = LabelMap.find(G->getLabel()); 1117 1118 // If there is no target for the goto, then we are looking at an 1119 // incomplete AST. Handle this by not registering a successor. 1120 if (LI == LabelMap.end()) continue; 1121 1122 JumpTarget JT = LI->second; 1123 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition, 1124 JT.scopePosition); 1125 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition, 1126 JT.scopePosition); 1127 addSuccessor(B, JT.block); 1128 } 1129 1130 // Add successors to the Indirect Goto Dispatch block (if we have one). 1131 if (CFGBlock *B = cfg->getIndirectGotoBlock()) 1132 for (LabelSetTy::iterator I = AddressTakenLabels.begin(), 1133 E = AddressTakenLabels.end(); I != E; ++I ) { 1134 1135 // Lookup the target block. 1136 LabelMapTy::iterator LI = LabelMap.find(*I); 1137 1138 // If there is no target block that contains label, then we are looking 1139 // at an incomplete AST. Handle this by not registering a successor. 1140 if (LI == LabelMap.end()) continue; 1141 1142 addSuccessor(B, LI->second.block); 1143 } 1144 1145 // Create an empty entry block that has no predecessors. 1146 cfg->setEntry(createBlock()); 1147 1148 return std::move(cfg); 1149 } 1150 1151 /// createBlock - Used to lazily create blocks that are connected 1152 /// to the current (global) succcessor. 1153 CFGBlock *CFGBuilder::createBlock(bool add_successor) { 1154 CFGBlock *B = cfg->createBlock(); 1155 if (add_successor && Succ) 1156 addSuccessor(B, Succ); 1157 return B; 1158 } 1159 1160 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the 1161 /// CFG. It is *not* connected to the current (global) successor, and instead 1162 /// directly tied to the exit block in order to be reachable. 1163 CFGBlock *CFGBuilder::createNoReturnBlock() { 1164 CFGBlock *B = createBlock(false); 1165 B->setHasNoReturnElement(); 1166 addSuccessor(B, &cfg->getExit(), Succ); 1167 return B; 1168 } 1169 1170 /// addInitializer - Add C++ base or member initializer element to CFG. 1171 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) { 1172 if (!BuildOpts.AddInitializers) 1173 return Block; 1174 1175 bool HasTemporaries = false; 1176 1177 // Destructors of temporaries in initialization expression should be called 1178 // after initialization finishes. 1179 Expr *Init = I->getInit(); 1180 if (Init) { 1181 HasTemporaries = isa<ExprWithCleanups>(Init); 1182 1183 if (BuildOpts.AddTemporaryDtors && HasTemporaries) { 1184 // Generate destructors for temporaries in initialization expression. 1185 TempDtorContext Context; 1186 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 1187 /*BindToTemporary=*/false, Context); 1188 } 1189 } 1190 1191 autoCreateBlock(); 1192 appendInitializer(Block, I); 1193 1194 if (Init) { 1195 if (HasTemporaries) { 1196 // For expression with temporaries go directly to subexpression to omit 1197 // generating destructors for the second time. 1198 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr()); 1199 } 1200 if (BuildOpts.AddCXXDefaultInitExprInCtors) { 1201 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) { 1202 // In general, appending the expression wrapped by a CXXDefaultInitExpr 1203 // may cause the same Expr to appear more than once in the CFG. Doing it 1204 // here is safe because there's only one initializer per field. 1205 autoCreateBlock(); 1206 appendStmt(Block, Default); 1207 if (Stmt *Child = Default->getExpr()) 1208 if (CFGBlock *R = Visit(Child)) 1209 Block = R; 1210 return Block; 1211 } 1212 } 1213 return Visit(Init); 1214 } 1215 1216 return Block; 1217 } 1218 1219 /// \brief Retrieve the type of the temporary object whose lifetime was 1220 /// extended by a local reference with the given initializer. 1221 static QualType getReferenceInitTemporaryType(ASTContext &Context, 1222 const Expr *Init, 1223 bool *FoundMTE = nullptr) { 1224 while (true) { 1225 // Skip parentheses. 1226 Init = Init->IgnoreParens(); 1227 1228 // Skip through cleanups. 1229 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) { 1230 Init = EWC->getSubExpr(); 1231 continue; 1232 } 1233 1234 // Skip through the temporary-materialization expression. 1235 if (const MaterializeTemporaryExpr *MTE 1236 = dyn_cast<MaterializeTemporaryExpr>(Init)) { 1237 Init = MTE->GetTemporaryExpr(); 1238 if (FoundMTE) 1239 *FoundMTE = true; 1240 continue; 1241 } 1242 1243 // Skip derived-to-base and no-op casts. 1244 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) { 1245 if ((CE->getCastKind() == CK_DerivedToBase || 1246 CE->getCastKind() == CK_UncheckedDerivedToBase || 1247 CE->getCastKind() == CK_NoOp) && 1248 Init->getType()->isRecordType()) { 1249 Init = CE->getSubExpr(); 1250 continue; 1251 } 1252 } 1253 1254 // Skip member accesses into rvalues. 1255 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) { 1256 if (!ME->isArrow() && ME->getBase()->isRValue()) { 1257 Init = ME->getBase(); 1258 continue; 1259 } 1260 } 1261 1262 break; 1263 } 1264 1265 return Init->getType(); 1266 } 1267 1268 1269 // TODO: Support adding LoopExit element to the CFG in case where the loop is 1270 // ended by ReturnStmt, GotoStmt or ThrowExpr. 1271 void CFGBuilder::addLoopExit(const Stmt *LoopStmt){ 1272 if(!BuildOpts.AddLoopExit) 1273 return; 1274 autoCreateBlock(); 1275 appendLoopExit(Block, LoopStmt); 1276 } 1277 1278 void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B, 1279 LocalScope::const_iterator E, 1280 Stmt *S) { 1281 if (BuildOpts.AddImplicitDtors) 1282 addAutomaticObjDtors(B, E, S); 1283 if (BuildOpts.AddLifetime) 1284 addLifetimeEnds(B, E, S); 1285 } 1286 1287 /// Add to current block automatic objects that leave the scope. 1288 void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B, 1289 LocalScope::const_iterator E, Stmt *S) { 1290 if (!BuildOpts.AddLifetime) 1291 return; 1292 1293 if (B == E) 1294 return; 1295 1296 // To go from B to E, one first goes up the scopes from B to P 1297 // then sideways in one scope from P to P' and then down 1298 // the scopes from P' to E. 1299 // The lifetime of all objects between B and P end. 1300 LocalScope::const_iterator P = B.shared_parent(E); 1301 int dist = B.distance(P); 1302 if (dist <= 0) 1303 return; 1304 1305 // We need to perform the scope leaving in reverse order 1306 SmallVector<VarDecl *, 10> DeclsTrivial; 1307 SmallVector<VarDecl *, 10> DeclsNonTrivial; 1308 DeclsTrivial.reserve(dist); 1309 DeclsNonTrivial.reserve(dist); 1310 1311 for (LocalScope::const_iterator I = B; I != P; ++I) 1312 if (hasTrivialDestructor(*I)) 1313 DeclsTrivial.push_back(*I); 1314 else 1315 DeclsNonTrivial.push_back(*I); 1316 1317 autoCreateBlock(); 1318 // object with trivial destructor end their lifetime last (when storage 1319 // duration ends) 1320 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(), 1321 E = DeclsTrivial.rend(); 1322 I != E; ++I) 1323 appendLifetimeEnds(Block, *I, S); 1324 1325 for (SmallVectorImpl<VarDecl *>::reverse_iterator 1326 I = DeclsNonTrivial.rbegin(), 1327 E = DeclsNonTrivial.rend(); 1328 I != E; ++I) 1329 appendLifetimeEnds(Block, *I, S); 1330 } 1331 1332 /// addAutomaticObjDtors - Add to current block automatic objects destructors 1333 /// for objects in range of local scope positions. Use S as trigger statement 1334 /// for destructors. 1335 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B, 1336 LocalScope::const_iterator E, Stmt *S) { 1337 if (!BuildOpts.AddImplicitDtors) 1338 return; 1339 1340 if (B == E) 1341 return; 1342 1343 // We need to append the destructors in reverse order, but any one of them 1344 // may be a no-return destructor which changes the CFG. As a result, buffer 1345 // this sequence up and replay them in reverse order when appending onto the 1346 // CFGBlock(s). 1347 SmallVector<VarDecl*, 10> Decls; 1348 Decls.reserve(B.distance(E)); 1349 for (LocalScope::const_iterator I = B; I != E; ++I) 1350 Decls.push_back(*I); 1351 1352 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(), 1353 E = Decls.rend(); 1354 I != E; ++I) { 1355 // If this destructor is marked as a no-return destructor, we need to 1356 // create a new block for the destructor which does not have as a successor 1357 // anything built thus far: control won't flow out of this block. 1358 QualType Ty = (*I)->getType(); 1359 if (Ty->isReferenceType()) { 1360 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit()); 1361 } 1362 Ty = Context->getBaseElementType(Ty); 1363 1364 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn()) 1365 Block = createNoReturnBlock(); 1366 else 1367 autoCreateBlock(); 1368 1369 appendAutomaticObjDtor(Block, *I, S); 1370 } 1371 } 1372 1373 /// addImplicitDtorsForDestructor - Add implicit destructors generated for 1374 /// base and member objects in destructor. 1375 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) { 1376 assert (BuildOpts.AddImplicitDtors 1377 && "Can be called only when dtors should be added"); 1378 const CXXRecordDecl *RD = DD->getParent(); 1379 1380 // At the end destroy virtual base objects. 1381 for (const auto &VI : RD->vbases()) { 1382 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl(); 1383 if (!CD->hasTrivialDestructor()) { 1384 autoCreateBlock(); 1385 appendBaseDtor(Block, &VI); 1386 } 1387 } 1388 1389 // Before virtual bases destroy direct base objects. 1390 for (const auto &BI : RD->bases()) { 1391 if (!BI.isVirtual()) { 1392 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl(); 1393 if (!CD->hasTrivialDestructor()) { 1394 autoCreateBlock(); 1395 appendBaseDtor(Block, &BI); 1396 } 1397 } 1398 } 1399 1400 // First destroy member objects. 1401 for (auto *FI : RD->fields()) { 1402 // Check for constant size array. Set type to array element type. 1403 QualType QT = FI->getType(); 1404 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 1405 if (AT->getSize() == 0) 1406 continue; 1407 QT = AT->getElementType(); 1408 } 1409 1410 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 1411 if (!CD->hasTrivialDestructor()) { 1412 autoCreateBlock(); 1413 appendMemberDtor(Block, FI); 1414 } 1415 } 1416 } 1417 1418 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either 1419 /// way return valid LocalScope object. 1420 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) { 1421 if (Scope) 1422 return Scope; 1423 llvm::BumpPtrAllocator &alloc = cfg->getAllocator(); 1424 return new (alloc.Allocate<LocalScope>()) 1425 LocalScope(BumpVectorContext(alloc), ScopePos); 1426 } 1427 1428 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement 1429 /// that should create implicit scope (e.g. if/else substatements). 1430 void CFGBuilder::addLocalScopeForStmt(Stmt *S) { 1431 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime) 1432 return; 1433 1434 LocalScope *Scope = nullptr; 1435 1436 // For compound statement we will be creating explicit scope. 1437 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { 1438 for (auto *BI : CS->body()) { 1439 Stmt *SI = BI->stripLabelLikeStatements(); 1440 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI)) 1441 Scope = addLocalScopeForDeclStmt(DS, Scope); 1442 } 1443 return; 1444 } 1445 1446 // For any other statement scope will be implicit and as such will be 1447 // interesting only for DeclStmt. 1448 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements())) 1449 addLocalScopeForDeclStmt(DS); 1450 } 1451 1452 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will 1453 /// reuse Scope if not NULL. 1454 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS, 1455 LocalScope* Scope) { 1456 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime) 1457 return Scope; 1458 1459 for (auto *DI : DS->decls()) 1460 if (VarDecl *VD = dyn_cast<VarDecl>(DI)) 1461 Scope = addLocalScopeForVarDecl(VD, Scope); 1462 return Scope; 1463 } 1464 1465 bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) { 1466 // Check for const references bound to temporary. Set type to pointee. 1467 QualType QT = VD->getType(); 1468 if (QT.getTypePtr()->isReferenceType()) { 1469 // Attempt to determine whether this declaration lifetime-extends a 1470 // temporary. 1471 // 1472 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend 1473 // temporaries, and a single declaration can extend multiple temporaries. 1474 // We should look at the storage duration on each nested 1475 // MaterializeTemporaryExpr instead. 1476 1477 const Expr *Init = VD->getInit(); 1478 if (!Init) 1479 return true; 1480 1481 // Lifetime-extending a temporary. 1482 bool FoundMTE = false; 1483 QT = getReferenceInitTemporaryType(*Context, Init, &FoundMTE); 1484 if (!FoundMTE) 1485 return true; 1486 } 1487 1488 // Check for constant size array. Set type to array element type. 1489 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 1490 if (AT->getSize() == 0) 1491 return true; 1492 QT = AT->getElementType(); 1493 } 1494 1495 // Check if type is a C++ class with non-trivial destructor. 1496 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 1497 return !CD->hasDefinition() || CD->hasTrivialDestructor(); 1498 return true; 1499 } 1500 1501 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will 1502 /// create add scope for automatic objects and temporary objects bound to 1503 /// const reference. Will reuse Scope if not NULL. 1504 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD, 1505 LocalScope* Scope) { 1506 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) && 1507 "AddImplicitDtors and AddLifetime cannot be used at the same time"); 1508 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime) 1509 return Scope; 1510 1511 // Check if variable is local. 1512 switch (VD->getStorageClass()) { 1513 case SC_None: 1514 case SC_Auto: 1515 case SC_Register: 1516 break; 1517 default: return Scope; 1518 } 1519 1520 if (BuildOpts.AddImplicitDtors) { 1521 if (!hasTrivialDestructor(VD)) { 1522 // Add the variable to scope 1523 Scope = createOrReuseLocalScope(Scope); 1524 Scope->addVar(VD); 1525 ScopePos = Scope->begin(); 1526 } 1527 return Scope; 1528 } 1529 1530 assert(BuildOpts.AddLifetime); 1531 // Add the variable to scope 1532 Scope = createOrReuseLocalScope(Scope); 1533 Scope->addVar(VD); 1534 ScopePos = Scope->begin(); 1535 return Scope; 1536 } 1537 1538 /// addLocalScopeAndDtors - For given statement add local scope for it and 1539 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL. 1540 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) { 1541 LocalScope::const_iterator scopeBeginPos = ScopePos; 1542 addLocalScopeForStmt(S); 1543 addAutomaticObjHandling(ScopePos, scopeBeginPos, S); 1544 } 1545 1546 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for 1547 /// variables with automatic storage duration to CFGBlock's elements vector. 1548 /// Elements will be prepended to physical beginning of the vector which 1549 /// happens to be logical end. Use blocks terminator as statement that specifies 1550 /// destructors call site. 1551 /// FIXME: This mechanism for adding automatic destructors doesn't handle 1552 /// no-return destructors properly. 1553 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 1554 LocalScope::const_iterator B, LocalScope::const_iterator E) { 1555 if (!BuildOpts.AddImplicitDtors) 1556 return; 1557 BumpVectorContext &C = cfg->getBumpVectorContext(); 1558 CFGBlock::iterator InsertPos 1559 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C); 1560 for (LocalScope::const_iterator I = B; I != E; ++I) 1561 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I, 1562 Blk->getTerminator()); 1563 } 1564 1565 /// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for 1566 /// variables with automatic storage duration to CFGBlock's elements vector. 1567 /// Elements will be prepended to physical beginning of the vector which 1568 /// happens to be logical end. Use blocks terminator as statement that specifies 1569 /// where lifetime ends. 1570 void CFGBuilder::prependAutomaticObjLifetimeWithTerminator( 1571 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) { 1572 if (!BuildOpts.AddLifetime) 1573 return; 1574 BumpVectorContext &C = cfg->getBumpVectorContext(); 1575 CFGBlock::iterator InsertPos = 1576 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C); 1577 for (LocalScope::const_iterator I = B; I != E; ++I) 1578 InsertPos = Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminator()); 1579 } 1580 /// Visit - Walk the subtree of a statement and add extra 1581 /// blocks for ternary operators, &&, and ||. We also process "," and 1582 /// DeclStmts (which may contain nested control-flow). 1583 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) { 1584 if (!S) { 1585 badCFG = true; 1586 return nullptr; 1587 } 1588 1589 if (Expr *E = dyn_cast<Expr>(S)) 1590 S = E->IgnoreParens(); 1591 1592 switch (S->getStmtClass()) { 1593 default: 1594 return VisitStmt(S, asc); 1595 1596 case Stmt::AddrLabelExprClass: 1597 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc); 1598 1599 case Stmt::BinaryConditionalOperatorClass: 1600 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc); 1601 1602 case Stmt::BinaryOperatorClass: 1603 return VisitBinaryOperator(cast<BinaryOperator>(S), asc); 1604 1605 case Stmt::BlockExprClass: 1606 return VisitBlockExpr(cast<BlockExpr>(S), asc); 1607 1608 case Stmt::BreakStmtClass: 1609 return VisitBreakStmt(cast<BreakStmt>(S)); 1610 1611 case Stmt::CallExprClass: 1612 case Stmt::CXXOperatorCallExprClass: 1613 case Stmt::CXXMemberCallExprClass: 1614 case Stmt::UserDefinedLiteralClass: 1615 return VisitCallExpr(cast<CallExpr>(S), asc); 1616 1617 case Stmt::CaseStmtClass: 1618 return VisitCaseStmt(cast<CaseStmt>(S)); 1619 1620 case Stmt::ChooseExprClass: 1621 return VisitChooseExpr(cast<ChooseExpr>(S), asc); 1622 1623 case Stmt::CompoundStmtClass: 1624 return VisitCompoundStmt(cast<CompoundStmt>(S)); 1625 1626 case Stmt::ConditionalOperatorClass: 1627 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc); 1628 1629 case Stmt::ContinueStmtClass: 1630 return VisitContinueStmt(cast<ContinueStmt>(S)); 1631 1632 case Stmt::CXXCatchStmtClass: 1633 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S)); 1634 1635 case Stmt::ExprWithCleanupsClass: 1636 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc); 1637 1638 case Stmt::CXXDefaultArgExprClass: 1639 case Stmt::CXXDefaultInitExprClass: 1640 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the 1641 // called function's declaration, not by the caller. If we simply add 1642 // this expression to the CFG, we could end up with the same Expr 1643 // appearing multiple times. 1644 // PR13385 / <rdar://problem/12156507> 1645 // 1646 // It's likewise possible for multiple CXXDefaultInitExprs for the same 1647 // expression to be used in the same function (through aggregate 1648 // initialization). 1649 return VisitStmt(S, asc); 1650 1651 case Stmt::CXXBindTemporaryExprClass: 1652 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc); 1653 1654 case Stmt::CXXConstructExprClass: 1655 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc); 1656 1657 case Stmt::CXXNewExprClass: 1658 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc); 1659 1660 case Stmt::CXXDeleteExprClass: 1661 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc); 1662 1663 case Stmt::CXXFunctionalCastExprClass: 1664 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc); 1665 1666 case Stmt::CXXTemporaryObjectExprClass: 1667 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc); 1668 1669 case Stmt::CXXThrowExprClass: 1670 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S)); 1671 1672 case Stmt::CXXTryStmtClass: 1673 return VisitCXXTryStmt(cast<CXXTryStmt>(S)); 1674 1675 case Stmt::CXXForRangeStmtClass: 1676 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S)); 1677 1678 case Stmt::DeclStmtClass: 1679 return VisitDeclStmt(cast<DeclStmt>(S)); 1680 1681 case Stmt::DefaultStmtClass: 1682 return VisitDefaultStmt(cast<DefaultStmt>(S)); 1683 1684 case Stmt::DoStmtClass: 1685 return VisitDoStmt(cast<DoStmt>(S)); 1686 1687 case Stmt::ForStmtClass: 1688 return VisitForStmt(cast<ForStmt>(S)); 1689 1690 case Stmt::GotoStmtClass: 1691 return VisitGotoStmt(cast<GotoStmt>(S)); 1692 1693 case Stmt::IfStmtClass: 1694 return VisitIfStmt(cast<IfStmt>(S)); 1695 1696 case Stmt::ImplicitCastExprClass: 1697 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc); 1698 1699 case Stmt::IndirectGotoStmtClass: 1700 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S)); 1701 1702 case Stmt::LabelStmtClass: 1703 return VisitLabelStmt(cast<LabelStmt>(S)); 1704 1705 case Stmt::LambdaExprClass: 1706 return VisitLambdaExpr(cast<LambdaExpr>(S), asc); 1707 1708 case Stmt::MemberExprClass: 1709 return VisitMemberExpr(cast<MemberExpr>(S), asc); 1710 1711 case Stmt::NullStmtClass: 1712 return Block; 1713 1714 case Stmt::ObjCAtCatchStmtClass: 1715 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S)); 1716 1717 case Stmt::ObjCAutoreleasePoolStmtClass: 1718 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S)); 1719 1720 case Stmt::ObjCAtSynchronizedStmtClass: 1721 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S)); 1722 1723 case Stmt::ObjCAtThrowStmtClass: 1724 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S)); 1725 1726 case Stmt::ObjCAtTryStmtClass: 1727 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S)); 1728 1729 case Stmt::ObjCForCollectionStmtClass: 1730 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); 1731 1732 case Stmt::OpaqueValueExprClass: 1733 return Block; 1734 1735 case Stmt::PseudoObjectExprClass: 1736 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S)); 1737 1738 case Stmt::ReturnStmtClass: 1739 return VisitReturnStmt(cast<ReturnStmt>(S)); 1740 1741 case Stmt::SEHExceptStmtClass: 1742 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S)); 1743 1744 case Stmt::SEHFinallyStmtClass: 1745 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S)); 1746 1747 case Stmt::SEHLeaveStmtClass: 1748 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S)); 1749 1750 case Stmt::SEHTryStmtClass: 1751 return VisitSEHTryStmt(cast<SEHTryStmt>(S)); 1752 1753 case Stmt::UnaryExprOrTypeTraitExprClass: 1754 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 1755 asc); 1756 1757 case Stmt::StmtExprClass: 1758 return VisitStmtExpr(cast<StmtExpr>(S), asc); 1759 1760 case Stmt::SwitchStmtClass: 1761 return VisitSwitchStmt(cast<SwitchStmt>(S)); 1762 1763 case Stmt::UnaryOperatorClass: 1764 return VisitUnaryOperator(cast<UnaryOperator>(S), asc); 1765 1766 case Stmt::WhileStmtClass: 1767 return VisitWhileStmt(cast<WhileStmt>(S)); 1768 } 1769 } 1770 1771 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) { 1772 if (asc.alwaysAdd(*this, S)) { 1773 autoCreateBlock(); 1774 appendStmt(Block, S); 1775 } 1776 1777 return VisitChildren(S); 1778 } 1779 1780 /// VisitChildren - Visit the children of a Stmt. 1781 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) { 1782 CFGBlock *B = Block; 1783 1784 // Visit the children in their reverse order so that they appear in 1785 // left-to-right (natural) order in the CFG. 1786 reverse_children RChildren(S); 1787 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end(); 1788 I != E; ++I) { 1789 if (Stmt *Child = *I) 1790 if (CFGBlock *R = Visit(Child)) 1791 B = R; 1792 } 1793 return B; 1794 } 1795 1796 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, 1797 AddStmtChoice asc) { 1798 AddressTakenLabels.insert(A->getLabel()); 1799 1800 if (asc.alwaysAdd(*this, A)) { 1801 autoCreateBlock(); 1802 appendStmt(Block, A); 1803 } 1804 1805 return Block; 1806 } 1807 1808 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, 1809 AddStmtChoice asc) { 1810 if (asc.alwaysAdd(*this, U)) { 1811 autoCreateBlock(); 1812 appendStmt(Block, U); 1813 } 1814 1815 return Visit(U->getSubExpr(), AddStmtChoice()); 1816 } 1817 1818 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) { 1819 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 1820 appendStmt(ConfluenceBlock, B); 1821 1822 if (badCFG) 1823 return nullptr; 1824 1825 return VisitLogicalOperator(B, nullptr, ConfluenceBlock, 1826 ConfluenceBlock).first; 1827 } 1828 1829 std::pair<CFGBlock*, CFGBlock*> 1830 CFGBuilder::VisitLogicalOperator(BinaryOperator *B, 1831 Stmt *Term, 1832 CFGBlock *TrueBlock, 1833 CFGBlock *FalseBlock) { 1834 1835 // Introspect the RHS. If it is a nested logical operation, we recursively 1836 // build the CFG using this function. Otherwise, resort to default 1837 // CFG construction behavior. 1838 Expr *RHS = B->getRHS()->IgnoreParens(); 1839 CFGBlock *RHSBlock, *ExitBlock; 1840 1841 do { 1842 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS)) 1843 if (B_RHS->isLogicalOp()) { 1844 std::tie(RHSBlock, ExitBlock) = 1845 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock); 1846 break; 1847 } 1848 1849 // The RHS is not a nested logical operation. Don't push the terminator 1850 // down further, but instead visit RHS and construct the respective 1851 // pieces of the CFG, and link up the RHSBlock with the terminator 1852 // we have been provided. 1853 ExitBlock = RHSBlock = createBlock(false); 1854 1855 // Even though KnownVal is only used in the else branch of the next 1856 // conditional, tryEvaluateBool performs additional checking on the 1857 // Expr, so it should be called unconditionally. 1858 TryResult KnownVal = tryEvaluateBool(RHS); 1859 if (!KnownVal.isKnown()) 1860 KnownVal = tryEvaluateBool(B); 1861 1862 if (!Term) { 1863 assert(TrueBlock == FalseBlock); 1864 addSuccessor(RHSBlock, TrueBlock); 1865 } 1866 else { 1867 RHSBlock->setTerminator(Term); 1868 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse()); 1869 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue()); 1870 } 1871 1872 Block = RHSBlock; 1873 RHSBlock = addStmt(RHS); 1874 } 1875 while (false); 1876 1877 if (badCFG) 1878 return std::make_pair(nullptr, nullptr); 1879 1880 // Generate the blocks for evaluating the LHS. 1881 Expr *LHS = B->getLHS()->IgnoreParens(); 1882 1883 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS)) 1884 if (B_LHS->isLogicalOp()) { 1885 if (B->getOpcode() == BO_LOr) 1886 FalseBlock = RHSBlock; 1887 else 1888 TrueBlock = RHSBlock; 1889 1890 // For the LHS, treat 'B' as the terminator that we want to sink 1891 // into the nested branch. The RHS always gets the top-most 1892 // terminator. 1893 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock); 1894 } 1895 1896 // Create the block evaluating the LHS. 1897 // This contains the '&&' or '||' as the terminator. 1898 CFGBlock *LHSBlock = createBlock(false); 1899 LHSBlock->setTerminator(B); 1900 1901 Block = LHSBlock; 1902 CFGBlock *EntryLHSBlock = addStmt(LHS); 1903 1904 if (badCFG) 1905 return std::make_pair(nullptr, nullptr); 1906 1907 // See if this is a known constant. 1908 TryResult KnownVal = tryEvaluateBool(LHS); 1909 1910 // Now link the LHSBlock with RHSBlock. 1911 if (B->getOpcode() == BO_LOr) { 1912 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse()); 1913 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue()); 1914 } else { 1915 assert(B->getOpcode() == BO_LAnd); 1916 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse()); 1917 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue()); 1918 } 1919 1920 return std::make_pair(EntryLHSBlock, ExitBlock); 1921 } 1922 1923 1924 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, 1925 AddStmtChoice asc) { 1926 // && or || 1927 if (B->isLogicalOp()) 1928 return VisitLogicalOperator(B); 1929 1930 if (B->getOpcode() == BO_Comma) { // , 1931 autoCreateBlock(); 1932 appendStmt(Block, B); 1933 addStmt(B->getRHS()); 1934 return addStmt(B->getLHS()); 1935 } 1936 1937 if (B->isAssignmentOp()) { 1938 if (asc.alwaysAdd(*this, B)) { 1939 autoCreateBlock(); 1940 appendStmt(Block, B); 1941 } 1942 Visit(B->getLHS()); 1943 return Visit(B->getRHS()); 1944 } 1945 1946 if (asc.alwaysAdd(*this, B)) { 1947 autoCreateBlock(); 1948 appendStmt(Block, B); 1949 } 1950 1951 CFGBlock *RBlock = Visit(B->getRHS()); 1952 CFGBlock *LBlock = Visit(B->getLHS()); 1953 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr 1954 // containing a DoStmt, and the LHS doesn't create a new block, then we should 1955 // return RBlock. Otherwise we'll incorrectly return NULL. 1956 return (LBlock ? LBlock : RBlock); 1957 } 1958 1959 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) { 1960 if (asc.alwaysAdd(*this, E)) { 1961 autoCreateBlock(); 1962 appendStmt(Block, E); 1963 } 1964 return Block; 1965 } 1966 1967 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) { 1968 // "break" is a control-flow statement. Thus we stop processing the current 1969 // block. 1970 if (badCFG) 1971 return nullptr; 1972 1973 // Now create a new block that ends with the break statement. 1974 Block = createBlock(false); 1975 Block->setTerminator(B); 1976 1977 // If there is no target for the break, then we are looking at an incomplete 1978 // AST. This means that the CFG cannot be constructed. 1979 if (BreakJumpTarget.block) { 1980 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B); 1981 addSuccessor(Block, BreakJumpTarget.block); 1982 } else 1983 badCFG = true; 1984 1985 1986 return Block; 1987 } 1988 1989 static bool CanThrow(Expr *E, ASTContext &Ctx) { 1990 QualType Ty = E->getType(); 1991 if (Ty->isFunctionPointerType()) 1992 Ty = Ty->getAs<PointerType>()->getPointeeType(); 1993 else if (Ty->isBlockPointerType()) 1994 Ty = Ty->getAs<BlockPointerType>()->getPointeeType(); 1995 1996 const FunctionType *FT = Ty->getAs<FunctionType>(); 1997 if (FT) { 1998 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) 1999 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) && 2000 Proto->isNothrow(Ctx)) 2001 return false; 2002 } 2003 return true; 2004 } 2005 2006 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) { 2007 // Compute the callee type. 2008 QualType calleeType = C->getCallee()->getType(); 2009 if (calleeType == Context->BoundMemberTy) { 2010 QualType boundType = Expr::findBoundMemberType(C->getCallee()); 2011 2012 // We should only get a null bound type if processing a dependent 2013 // CFG. Recover by assuming nothing. 2014 if (!boundType.isNull()) calleeType = boundType; 2015 } 2016 2017 // If this is a call to a no-return function, this stops the block here. 2018 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn(); 2019 2020 bool AddEHEdge = false; 2021 2022 // Languages without exceptions are assumed to not throw. 2023 if (Context->getLangOpts().Exceptions) { 2024 if (BuildOpts.AddEHEdges) 2025 AddEHEdge = true; 2026 } 2027 2028 // If this is a call to a builtin function, it might not actually evaluate 2029 // its arguments. Don't add them to the CFG if this is the case. 2030 bool OmitArguments = false; 2031 2032 if (FunctionDecl *FD = C->getDirectCallee()) { 2033 if (FD->isNoReturn()) 2034 NoReturn = true; 2035 if (FD->hasAttr<NoThrowAttr>()) 2036 AddEHEdge = false; 2037 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size) 2038 OmitArguments = true; 2039 } 2040 2041 if (!CanThrow(C->getCallee(), *Context)) 2042 AddEHEdge = false; 2043 2044 if (OmitArguments) { 2045 assert(!NoReturn && "noreturn calls with unevaluated args not implemented"); 2046 assert(!AddEHEdge && "EH calls with unevaluated args not implemented"); 2047 autoCreateBlock(); 2048 appendStmt(Block, C); 2049 return Visit(C->getCallee()); 2050 } 2051 2052 if (!NoReturn && !AddEHEdge) { 2053 return VisitStmt(C, asc.withAlwaysAdd(true)); 2054 } 2055 2056 if (Block) { 2057 Succ = Block; 2058 if (badCFG) 2059 return nullptr; 2060 } 2061 2062 if (NoReturn) 2063 Block = createNoReturnBlock(); 2064 else 2065 Block = createBlock(); 2066 2067 appendStmt(Block, C); 2068 2069 if (AddEHEdge) { 2070 // Add exceptional edges. 2071 if (TryTerminatedBlock) 2072 addSuccessor(Block, TryTerminatedBlock); 2073 else 2074 addSuccessor(Block, &cfg->getExit()); 2075 } 2076 2077 return VisitChildren(C); 2078 } 2079 2080 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C, 2081 AddStmtChoice asc) { 2082 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 2083 appendStmt(ConfluenceBlock, C); 2084 if (badCFG) 2085 return nullptr; 2086 2087 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); 2088 Succ = ConfluenceBlock; 2089 Block = nullptr; 2090 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd); 2091 if (badCFG) 2092 return nullptr; 2093 2094 Succ = ConfluenceBlock; 2095 Block = nullptr; 2096 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd); 2097 if (badCFG) 2098 return nullptr; 2099 2100 Block = createBlock(false); 2101 // See if this is a known constant. 2102 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 2103 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock); 2104 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock); 2105 Block->setTerminator(C); 2106 return addStmt(C->getCond()); 2107 } 2108 2109 2110 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) { 2111 LocalScope::const_iterator scopeBeginPos = ScopePos; 2112 addLocalScopeForStmt(C); 2113 2114 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) { 2115 // If the body ends with a ReturnStmt, the dtors will be added in 2116 // VisitReturnStmt. 2117 addAutomaticObjHandling(ScopePos, scopeBeginPos, C); 2118 } 2119 2120 CFGBlock *LastBlock = Block; 2121 2122 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend(); 2123 I != E; ++I ) { 2124 // If we hit a segment of code just containing ';' (NullStmts), we can 2125 // get a null block back. In such cases, just use the LastBlock 2126 if (CFGBlock *newBlock = addStmt(*I)) 2127 LastBlock = newBlock; 2128 2129 if (badCFG) 2130 return nullptr; 2131 } 2132 2133 return LastBlock; 2134 } 2135 2136 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C, 2137 AddStmtChoice asc) { 2138 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C); 2139 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr); 2140 2141 // Create the confluence block that will "merge" the results of the ternary 2142 // expression. 2143 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 2144 appendStmt(ConfluenceBlock, C); 2145 if (badCFG) 2146 return nullptr; 2147 2148 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); 2149 2150 // Create a block for the LHS expression if there is an LHS expression. A 2151 // GCC extension allows LHS to be NULL, causing the condition to be the 2152 // value that is returned instead. 2153 // e.g: x ?: y is shorthand for: x ? x : y; 2154 Succ = ConfluenceBlock; 2155 Block = nullptr; 2156 CFGBlock *LHSBlock = nullptr; 2157 const Expr *trueExpr = C->getTrueExpr(); 2158 if (trueExpr != opaqueValue) { 2159 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd); 2160 if (badCFG) 2161 return nullptr; 2162 Block = nullptr; 2163 } 2164 else 2165 LHSBlock = ConfluenceBlock; 2166 2167 // Create the block for the RHS expression. 2168 Succ = ConfluenceBlock; 2169 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd); 2170 if (badCFG) 2171 return nullptr; 2172 2173 // If the condition is a logical '&&' or '||', build a more accurate CFG. 2174 if (BinaryOperator *Cond = 2175 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens())) 2176 if (Cond->isLogicalOp()) 2177 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first; 2178 2179 // Create the block that will contain the condition. 2180 Block = createBlock(false); 2181 2182 // See if this is a known constant. 2183 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 2184 addSuccessor(Block, LHSBlock, !KnownVal.isFalse()); 2185 addSuccessor(Block, RHSBlock, !KnownVal.isTrue()); 2186 Block->setTerminator(C); 2187 Expr *condExpr = C->getCond(); 2188 2189 if (opaqueValue) { 2190 // Run the condition expression if it's not trivially expressed in 2191 // terms of the opaque value (or if there is no opaque value). 2192 if (condExpr != opaqueValue) 2193 addStmt(condExpr); 2194 2195 // Before that, run the common subexpression if there was one. 2196 // At least one of this or the above will be run. 2197 return addStmt(BCO->getCommon()); 2198 } 2199 2200 return addStmt(condExpr); 2201 } 2202 2203 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { 2204 // Check if the Decl is for an __label__. If so, elide it from the 2205 // CFG entirely. 2206 if (isa<LabelDecl>(*DS->decl_begin())) 2207 return Block; 2208 2209 // This case also handles static_asserts. 2210 if (DS->isSingleDecl()) 2211 return VisitDeclSubExpr(DS); 2212 2213 CFGBlock *B = nullptr; 2214 2215 // Build an individual DeclStmt for each decl. 2216 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(), 2217 E = DS->decl_rend(); 2218 I != E; ++I) { 2219 // Get the alignment of the new DeclStmt, padding out to >=8 bytes. 2220 unsigned A = alignof(DeclStmt) < 8 ? 8 : alignof(DeclStmt); 2221 2222 // Allocate the DeclStmt using the BumpPtrAllocator. It will get 2223 // automatically freed with the CFG. 2224 DeclGroupRef DG(*I); 2225 Decl *D = *I; 2226 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); 2227 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); 2228 cfg->addSyntheticDeclStmt(DSNew, DS); 2229 2230 // Append the fake DeclStmt to block. 2231 B = VisitDeclSubExpr(DSNew); 2232 } 2233 2234 return B; 2235 } 2236 2237 /// VisitDeclSubExpr - Utility method to add block-level expressions for 2238 /// DeclStmts and initializers in them. 2239 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) { 2240 assert(DS->isSingleDecl() && "Can handle single declarations only."); 2241 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); 2242 2243 if (!VD) { 2244 // Of everything that can be declared in a DeclStmt, only VarDecls impact 2245 // runtime semantics. 2246 return Block; 2247 } 2248 2249 bool HasTemporaries = false; 2250 2251 // Guard static initializers under a branch. 2252 CFGBlock *blockAfterStaticInit = nullptr; 2253 2254 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) { 2255 // For static variables, we need to create a branch to track 2256 // whether or not they are initialized. 2257 if (Block) { 2258 Succ = Block; 2259 Block = nullptr; 2260 if (badCFG) 2261 return nullptr; 2262 } 2263 blockAfterStaticInit = Succ; 2264 } 2265 2266 // Destructors of temporaries in initialization expression should be called 2267 // after initialization finishes. 2268 Expr *Init = VD->getInit(); 2269 if (Init) { 2270 HasTemporaries = isa<ExprWithCleanups>(Init); 2271 2272 if (BuildOpts.AddTemporaryDtors && HasTemporaries) { 2273 // Generate destructors for temporaries in initialization expression. 2274 TempDtorContext Context; 2275 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 2276 /*BindToTemporary=*/false, Context); 2277 } 2278 } 2279 2280 autoCreateBlock(); 2281 appendStmt(Block, DS); 2282 2283 // Keep track of the last non-null block, as 'Block' can be nulled out 2284 // if the initializer expression is something like a 'while' in a 2285 // statement-expression. 2286 CFGBlock *LastBlock = Block; 2287 2288 if (Init) { 2289 if (HasTemporaries) { 2290 // For expression with temporaries go directly to subexpression to omit 2291 // generating destructors for the second time. 2292 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init); 2293 if (CFGBlock *newBlock = Visit(EC->getSubExpr())) 2294 LastBlock = newBlock; 2295 } 2296 else { 2297 if (CFGBlock *newBlock = Visit(Init)) 2298 LastBlock = newBlock; 2299 } 2300 } 2301 2302 // If the type of VD is a VLA, then we must process its size expressions. 2303 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); 2304 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) { 2305 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr())) 2306 LastBlock = newBlock; 2307 } 2308 2309 // Remove variable from local scope. 2310 if (ScopePos && VD == *ScopePos) 2311 ++ScopePos; 2312 2313 CFGBlock *B = LastBlock; 2314 if (blockAfterStaticInit) { 2315 Succ = B; 2316 Block = createBlock(false); 2317 Block->setTerminator(DS); 2318 addSuccessor(Block, blockAfterStaticInit); 2319 addSuccessor(Block, B); 2320 B = Block; 2321 } 2322 2323 return B; 2324 } 2325 2326 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) { 2327 // We may see an if statement in the middle of a basic block, or it may be the 2328 // first statement we are processing. In either case, we create a new basic 2329 // block. First, we create the blocks for the then...else statements, and 2330 // then we create the block containing the if statement. If we were in the 2331 // middle of a block, we stop processing that block. That block is then the 2332 // implicit successor for the "then" and "else" clauses. 2333 2334 // Save local scope position because in case of condition variable ScopePos 2335 // won't be restored when traversing AST. 2336 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2337 2338 // Create local scope for C++17 if init-stmt if one exists. 2339 if (Stmt *Init = I->getInit()) 2340 addLocalScopeForStmt(Init); 2341 2342 // Create local scope for possible condition variable. 2343 // Store scope position. Add implicit destructor. 2344 if (VarDecl *VD = I->getConditionVariable()) 2345 addLocalScopeForVarDecl(VD); 2346 2347 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I); 2348 2349 // The block we were processing is now finished. Make it the successor 2350 // block. 2351 if (Block) { 2352 Succ = Block; 2353 if (badCFG) 2354 return nullptr; 2355 } 2356 2357 // Process the false branch. 2358 CFGBlock *ElseBlock = Succ; 2359 2360 if (Stmt *Else = I->getElse()) { 2361 SaveAndRestore<CFGBlock*> sv(Succ); 2362 2363 // NULL out Block so that the recursive call to Visit will 2364 // create a new basic block. 2365 Block = nullptr; 2366 2367 // If branch is not a compound statement create implicit scope 2368 // and add destructors. 2369 if (!isa<CompoundStmt>(Else)) 2370 addLocalScopeAndDtors(Else); 2371 2372 ElseBlock = addStmt(Else); 2373 2374 if (!ElseBlock) // Can occur when the Else body has all NullStmts. 2375 ElseBlock = sv.get(); 2376 else if (Block) { 2377 if (badCFG) 2378 return nullptr; 2379 } 2380 } 2381 2382 // Process the true branch. 2383 CFGBlock *ThenBlock; 2384 { 2385 Stmt *Then = I->getThen(); 2386 assert(Then); 2387 SaveAndRestore<CFGBlock*> sv(Succ); 2388 Block = nullptr; 2389 2390 // If branch is not a compound statement create implicit scope 2391 // and add destructors. 2392 if (!isa<CompoundStmt>(Then)) 2393 addLocalScopeAndDtors(Then); 2394 2395 ThenBlock = addStmt(Then); 2396 2397 if (!ThenBlock) { 2398 // We can reach here if the "then" body has all NullStmts. 2399 // Create an empty block so we can distinguish between true and false 2400 // branches in path-sensitive analyses. 2401 ThenBlock = createBlock(false); 2402 addSuccessor(ThenBlock, sv.get()); 2403 } else if (Block) { 2404 if (badCFG) 2405 return nullptr; 2406 } 2407 } 2408 2409 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by 2410 // having these handle the actual control-flow jump. Note that 2411 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)" 2412 // we resort to the old control-flow behavior. This special handling 2413 // removes infeasible paths from the control-flow graph by having the 2414 // control-flow transfer of '&&' or '||' go directly into the then/else 2415 // blocks directly. 2416 BinaryOperator *Cond = 2417 I->getConditionVariable() 2418 ? nullptr 2419 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()); 2420 CFGBlock *LastBlock; 2421 if (Cond && Cond->isLogicalOp()) 2422 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first; 2423 else { 2424 // Now create a new block containing the if statement. 2425 Block = createBlock(false); 2426 2427 // Set the terminator of the new block to the If statement. 2428 Block->setTerminator(I); 2429 2430 // See if this is a known constant. 2431 const TryResult &KnownVal = tryEvaluateBool(I->getCond()); 2432 2433 // Add the successors. If we know that specific branches are 2434 // unreachable, inform addSuccessor() of that knowledge. 2435 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse()); 2436 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue()); 2437 2438 // Add the condition as the last statement in the new block. This may 2439 // create new blocks as the condition may contain control-flow. Any newly 2440 // created blocks will be pointed to be "Block". 2441 LastBlock = addStmt(I->getCond()); 2442 2443 // If the IfStmt contains a condition variable, add it and its 2444 // initializer to the CFG. 2445 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) { 2446 autoCreateBlock(); 2447 LastBlock = addStmt(const_cast<DeclStmt *>(DS)); 2448 } 2449 } 2450 2451 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG. 2452 if (Stmt *Init = I->getInit()) { 2453 autoCreateBlock(); 2454 LastBlock = addStmt(Init); 2455 } 2456 2457 return LastBlock; 2458 } 2459 2460 2461 CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) { 2462 // If we were in the middle of a block we stop processing that block. 2463 // 2464 // NOTE: If a "return" appears in the middle of a block, this means that the 2465 // code afterwards is DEAD (unreachable). We still keep a basic block 2466 // for that code; a simple "mark-and-sweep" from the entry block will be 2467 // able to report such dead blocks. 2468 2469 // Create the new block. 2470 Block = createBlock(false); 2471 2472 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), R); 2473 2474 // If the one of the destructors does not return, we already have the Exit 2475 // block as a successor. 2476 if (!Block->hasNoReturnElement()) 2477 addSuccessor(Block, &cfg->getExit()); 2478 2479 // Add the return statement to the block. This may create new blocks if R 2480 // contains control-flow (short-circuit operations). 2481 return VisitStmt(R, AddStmtChoice::AlwaysAdd); 2482 } 2483 2484 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) { 2485 // SEHExceptStmt are treated like labels, so they are the first statement in a 2486 // block. 2487 2488 // Save local scope position because in case of exception variable ScopePos 2489 // won't be restored when traversing AST. 2490 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2491 2492 addStmt(ES->getBlock()); 2493 CFGBlock *SEHExceptBlock = Block; 2494 if (!SEHExceptBlock) 2495 SEHExceptBlock = createBlock(); 2496 2497 appendStmt(SEHExceptBlock, ES); 2498 2499 // Also add the SEHExceptBlock as a label, like with regular labels. 2500 SEHExceptBlock->setLabel(ES); 2501 2502 // Bail out if the CFG is bad. 2503 if (badCFG) 2504 return nullptr; 2505 2506 // We set Block to NULL to allow lazy creation of a new block (if necessary). 2507 Block = nullptr; 2508 2509 return SEHExceptBlock; 2510 } 2511 2512 CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) { 2513 return VisitCompoundStmt(FS->getBlock()); 2514 } 2515 2516 CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) { 2517 // "__leave" is a control-flow statement. Thus we stop processing the current 2518 // block. 2519 if (badCFG) 2520 return nullptr; 2521 2522 // Now create a new block that ends with the __leave statement. 2523 Block = createBlock(false); 2524 Block->setTerminator(LS); 2525 2526 // If there is no target for the __leave, then we are looking at an incomplete 2527 // AST. This means that the CFG cannot be constructed. 2528 if (SEHLeaveJumpTarget.block) { 2529 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS); 2530 addSuccessor(Block, SEHLeaveJumpTarget.block); 2531 } else 2532 badCFG = true; 2533 2534 return Block; 2535 } 2536 2537 CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) { 2538 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop 2539 // processing the current block. 2540 CFGBlock *SEHTrySuccessor = nullptr; 2541 2542 if (Block) { 2543 if (badCFG) 2544 return nullptr; 2545 SEHTrySuccessor = Block; 2546 } else SEHTrySuccessor = Succ; 2547 2548 // FIXME: Implement __finally support. 2549 if (Terminator->getFinallyHandler()) 2550 return NYS(); 2551 2552 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock; 2553 2554 // Create a new block that will contain the __try statement. 2555 CFGBlock *NewTryTerminatedBlock = createBlock(false); 2556 2557 // Add the terminator in the __try block. 2558 NewTryTerminatedBlock->setTerminator(Terminator); 2559 2560 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) { 2561 // The code after the try is the implicit successor if there's an __except. 2562 Succ = SEHTrySuccessor; 2563 Block = nullptr; 2564 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except); 2565 if (!ExceptBlock) 2566 return nullptr; 2567 // Add this block to the list of successors for the block with the try 2568 // statement. 2569 addSuccessor(NewTryTerminatedBlock, ExceptBlock); 2570 } 2571 if (PrevSEHTryTerminatedBlock) 2572 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock); 2573 else 2574 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 2575 2576 // The code after the try is the implicit successor. 2577 Succ = SEHTrySuccessor; 2578 2579 // Save the current "__try" context. 2580 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock, 2581 NewTryTerminatedBlock); 2582 cfg->addTryDispatchBlock(TryTerminatedBlock); 2583 2584 // Save the current value for the __leave target. 2585 // All __leaves should go to the code following the __try 2586 // (FIXME: or if the __try has a __finally, to the __finally.) 2587 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget); 2588 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos); 2589 2590 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body"); 2591 Block = nullptr; 2592 return addStmt(Terminator->getTryBlock()); 2593 } 2594 2595 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) { 2596 // Get the block of the labeled statement. Add it to our map. 2597 addStmt(L->getSubStmt()); 2598 CFGBlock *LabelBlock = Block; 2599 2600 if (!LabelBlock) // This can happen when the body is empty, i.e. 2601 LabelBlock = createBlock(); // scopes that only contains NullStmts. 2602 2603 assert(LabelMap.find(L->getDecl()) == LabelMap.end() && 2604 "label already in map"); 2605 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos); 2606 2607 // Labels partition blocks, so this is the end of the basic block we were 2608 // processing (L is the block's label). Because this is label (and we have 2609 // already processed the substatement) there is no extra control-flow to worry 2610 // about. 2611 LabelBlock->setLabel(L); 2612 if (badCFG) 2613 return nullptr; 2614 2615 // We set Block to NULL to allow lazy creation of a new block (if necessary); 2616 Block = nullptr; 2617 2618 // This block is now the implicit successor of other blocks. 2619 Succ = LabelBlock; 2620 2621 return LabelBlock; 2622 } 2623 2624 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) { 2625 CFGBlock *LastBlock = VisitNoRecurse(E, asc); 2626 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) { 2627 if (Expr *CopyExpr = CI.getCopyExpr()) { 2628 CFGBlock *Tmp = Visit(CopyExpr); 2629 if (Tmp) 2630 LastBlock = Tmp; 2631 } 2632 } 2633 return LastBlock; 2634 } 2635 2636 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) { 2637 CFGBlock *LastBlock = VisitNoRecurse(E, asc); 2638 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(), 2639 et = E->capture_init_end(); it != et; ++it) { 2640 if (Expr *Init = *it) { 2641 CFGBlock *Tmp = Visit(Init); 2642 if (Tmp) 2643 LastBlock = Tmp; 2644 } 2645 } 2646 return LastBlock; 2647 } 2648 2649 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) { 2650 // Goto is a control-flow statement. Thus we stop processing the current 2651 // block and create a new one. 2652 2653 Block = createBlock(false); 2654 Block->setTerminator(G); 2655 2656 // If we already know the mapping to the label block add the successor now. 2657 LabelMapTy::iterator I = LabelMap.find(G->getLabel()); 2658 2659 if (I == LabelMap.end()) 2660 // We will need to backpatch this block later. 2661 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 2662 else { 2663 JumpTarget JT = I->second; 2664 addAutomaticObjHandling(ScopePos, JT.scopePosition, G); 2665 addSuccessor(Block, JT.block); 2666 } 2667 2668 return Block; 2669 } 2670 2671 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { 2672 CFGBlock *LoopSuccessor = nullptr; 2673 2674 // Save local scope position because in case of condition variable ScopePos 2675 // won't be restored when traversing AST. 2676 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2677 2678 // Create local scope for init statement and possible condition variable. 2679 // Add destructor for init statement and condition variable. 2680 // Store scope position for continue statement. 2681 if (Stmt *Init = F->getInit()) 2682 addLocalScopeForStmt(Init); 2683 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 2684 2685 if (VarDecl *VD = F->getConditionVariable()) 2686 addLocalScopeForVarDecl(VD); 2687 LocalScope::const_iterator ContinueScopePos = ScopePos; 2688 2689 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F); 2690 2691 addLoopExit(F); 2692 2693 // "for" is a control-flow statement. Thus we stop processing the current 2694 // block. 2695 if (Block) { 2696 if (badCFG) 2697 return nullptr; 2698 LoopSuccessor = Block; 2699 } else 2700 LoopSuccessor = Succ; 2701 2702 // Save the current value for the break targets. 2703 // All breaks should go to the code following the loop. 2704 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 2705 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2706 2707 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr; 2708 2709 // Now create the loop body. 2710 { 2711 assert(F->getBody()); 2712 2713 // Save the current values for Block, Succ, continue and break targets. 2714 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 2715 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 2716 2717 // Create an empty block to represent the transition block for looping back 2718 // to the head of the loop. If we have increment code, it will 2719 // go in this block as well. 2720 Block = Succ = TransitionBlock = createBlock(false); 2721 TransitionBlock->setLoopTarget(F); 2722 2723 if (Stmt *I = F->getInc()) { 2724 // Generate increment code in its own basic block. This is the target of 2725 // continue statements. 2726 Succ = addStmt(I); 2727 } 2728 2729 // Finish up the increment (or empty) block if it hasn't been already. 2730 if (Block) { 2731 assert(Block == Succ); 2732 if (badCFG) 2733 return nullptr; 2734 Block = nullptr; 2735 } 2736 2737 // The starting block for the loop increment is the block that should 2738 // represent the 'loop target' for looping back to the start of the loop. 2739 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 2740 ContinueJumpTarget.block->setLoopTarget(F); 2741 2742 // Loop body should end with destructor of Condition variable (if any). 2743 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F); 2744 2745 // If body is not a compound statement create implicit scope 2746 // and add destructors. 2747 if (!isa<CompoundStmt>(F->getBody())) 2748 addLocalScopeAndDtors(F->getBody()); 2749 2750 // Now populate the body block, and in the process create new blocks as we 2751 // walk the body of the loop. 2752 BodyBlock = addStmt(F->getBody()); 2753 2754 if (!BodyBlock) { 2755 // In the case of "for (...;...;...);" we can have a null BodyBlock. 2756 // Use the continue jump target as the proxy for the body. 2757 BodyBlock = ContinueJumpTarget.block; 2758 } 2759 else if (badCFG) 2760 return nullptr; 2761 } 2762 2763 // Because of short-circuit evaluation, the condition of the loop can span 2764 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 2765 // evaluate the condition. 2766 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr; 2767 2768 do { 2769 Expr *C = F->getCond(); 2770 2771 // Specially handle logical operators, which have a slightly 2772 // more optimal CFG representation. 2773 if (BinaryOperator *Cond = 2774 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr)) 2775 if (Cond->isLogicalOp()) { 2776 std::tie(EntryConditionBlock, ExitConditionBlock) = 2777 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor); 2778 break; 2779 } 2780 2781 // The default case when not handling logical operators. 2782 EntryConditionBlock = ExitConditionBlock = createBlock(false); 2783 ExitConditionBlock->setTerminator(F); 2784 2785 // See if this is a known constant. 2786 TryResult KnownVal(true); 2787 2788 if (C) { 2789 // Now add the actual condition to the condition block. 2790 // Because the condition itself may contain control-flow, new blocks may 2791 // be created. Thus we update "Succ" after adding the condition. 2792 Block = ExitConditionBlock; 2793 EntryConditionBlock = addStmt(C); 2794 2795 // If this block contains a condition variable, add both the condition 2796 // variable and initializer to the CFG. 2797 if (VarDecl *VD = F->getConditionVariable()) { 2798 if (Expr *Init = VD->getInit()) { 2799 autoCreateBlock(); 2800 appendStmt(Block, F->getConditionVariableDeclStmt()); 2801 EntryConditionBlock = addStmt(Init); 2802 assert(Block == EntryConditionBlock); 2803 } 2804 } 2805 2806 if (Block && badCFG) 2807 return nullptr; 2808 2809 KnownVal = tryEvaluateBool(C); 2810 } 2811 2812 // Add the loop body entry as a successor to the condition. 2813 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock); 2814 // Link up the condition block with the code that follows the loop. (the 2815 // false branch). 2816 addSuccessor(ExitConditionBlock, 2817 KnownVal.isTrue() ? nullptr : LoopSuccessor); 2818 2819 } while (false); 2820 2821 // Link up the loop-back block to the entry condition block. 2822 addSuccessor(TransitionBlock, EntryConditionBlock); 2823 2824 // The condition block is the implicit successor for any code above the loop. 2825 Succ = EntryConditionBlock; 2826 2827 // If the loop contains initialization, create a new block for those 2828 // statements. This block can also contain statements that precede the loop. 2829 if (Stmt *I = F->getInit()) { 2830 Block = createBlock(); 2831 return addStmt(I); 2832 } 2833 2834 // There is no loop initialization. We are thus basically a while loop. 2835 // NULL out Block to force lazy block construction. 2836 Block = nullptr; 2837 Succ = EntryConditionBlock; 2838 return EntryConditionBlock; 2839 } 2840 2841 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) { 2842 if (asc.alwaysAdd(*this, M)) { 2843 autoCreateBlock(); 2844 appendStmt(Block, M); 2845 } 2846 return Visit(M->getBase()); 2847 } 2848 2849 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { 2850 // Objective-C fast enumeration 'for' statements: 2851 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC 2852 // 2853 // for ( Type newVariable in collection_expression ) { statements } 2854 // 2855 // becomes: 2856 // 2857 // prologue: 2858 // 1. collection_expression 2859 // T. jump to loop_entry 2860 // loop_entry: 2861 // 1. side-effects of element expression 2862 // 1. ObjCForCollectionStmt [performs binding to newVariable] 2863 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] 2864 // TB: 2865 // statements 2866 // T. jump to loop_entry 2867 // FB: 2868 // what comes after 2869 // 2870 // and 2871 // 2872 // Type existingItem; 2873 // for ( existingItem in expression ) { statements } 2874 // 2875 // becomes: 2876 // 2877 // the same with newVariable replaced with existingItem; the binding works 2878 // the same except that for one ObjCForCollectionStmt::getElement() returns 2879 // a DeclStmt and the other returns a DeclRefExpr. 2880 // 2881 2882 CFGBlock *LoopSuccessor = nullptr; 2883 2884 if (Block) { 2885 if (badCFG) 2886 return nullptr; 2887 LoopSuccessor = Block; 2888 Block = nullptr; 2889 } else 2890 LoopSuccessor = Succ; 2891 2892 // Build the condition blocks. 2893 CFGBlock *ExitConditionBlock = createBlock(false); 2894 2895 // Set the terminator for the "exit" condition block. 2896 ExitConditionBlock->setTerminator(S); 2897 2898 // The last statement in the block should be the ObjCForCollectionStmt, which 2899 // performs the actual binding to 'element' and determines if there are any 2900 // more items in the collection. 2901 appendStmt(ExitConditionBlock, S); 2902 Block = ExitConditionBlock; 2903 2904 // Walk the 'element' expression to see if there are any side-effects. We 2905 // generate new blocks as necessary. We DON'T add the statement by default to 2906 // the CFG unless it contains control-flow. 2907 CFGBlock *EntryConditionBlock = Visit(S->getElement(), 2908 AddStmtChoice::NotAlwaysAdd); 2909 if (Block) { 2910 if (badCFG) 2911 return nullptr; 2912 Block = nullptr; 2913 } 2914 2915 // The condition block is the implicit successor for the loop body as well as 2916 // any code above the loop. 2917 Succ = EntryConditionBlock; 2918 2919 // Now create the true branch. 2920 { 2921 // Save the current values for Succ, continue and break targets. 2922 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 2923 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 2924 save_break(BreakJumpTarget); 2925 2926 // Add an intermediate block between the BodyBlock and the 2927 // EntryConditionBlock to represent the "loop back" transition, for looping 2928 // back to the head of the loop. 2929 CFGBlock *LoopBackBlock = nullptr; 2930 Succ = LoopBackBlock = createBlock(); 2931 LoopBackBlock->setLoopTarget(S); 2932 2933 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2934 ContinueJumpTarget = JumpTarget(Succ, ScopePos); 2935 2936 CFGBlock *BodyBlock = addStmt(S->getBody()); 2937 2938 if (!BodyBlock) 2939 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;" 2940 else if (Block) { 2941 if (badCFG) 2942 return nullptr; 2943 } 2944 2945 // This new body block is a successor to our "exit" condition block. 2946 addSuccessor(ExitConditionBlock, BodyBlock); 2947 } 2948 2949 // Link up the condition block with the code that follows the loop. 2950 // (the false branch). 2951 addSuccessor(ExitConditionBlock, LoopSuccessor); 2952 2953 // Now create a prologue block to contain the collection expression. 2954 Block = createBlock(); 2955 return addStmt(S->getCollection()); 2956 } 2957 2958 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { 2959 // Inline the body. 2960 return addStmt(S->getSubStmt()); 2961 // TODO: consider adding cleanups for the end of @autoreleasepool scope. 2962 } 2963 2964 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) { 2965 // FIXME: Add locking 'primitives' to CFG for @synchronized. 2966 2967 // Inline the body. 2968 CFGBlock *SyncBlock = addStmt(S->getSynchBody()); 2969 2970 // The sync body starts its own basic block. This makes it a little easier 2971 // for diagnostic clients. 2972 if (SyncBlock) { 2973 if (badCFG) 2974 return nullptr; 2975 2976 Block = nullptr; 2977 Succ = SyncBlock; 2978 } 2979 2980 // Add the @synchronized to the CFG. 2981 autoCreateBlock(); 2982 appendStmt(Block, S); 2983 2984 // Inline the sync expression. 2985 return addStmt(S->getSynchExpr()); 2986 } 2987 2988 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { 2989 // FIXME 2990 return NYS(); 2991 } 2992 2993 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) { 2994 autoCreateBlock(); 2995 2996 // Add the PseudoObject as the last thing. 2997 appendStmt(Block, E); 2998 2999 CFGBlock *lastBlock = Block; 3000 3001 // Before that, evaluate all of the semantics in order. In 3002 // CFG-land, that means appending them in reverse order. 3003 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) { 3004 Expr *Semantic = E->getSemanticExpr(--i); 3005 3006 // If the semantic is an opaque value, we're being asked to bind 3007 // it to its source expression. 3008 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) 3009 Semantic = OVE->getSourceExpr(); 3010 3011 if (CFGBlock *B = Visit(Semantic)) 3012 lastBlock = B; 3013 } 3014 3015 return lastBlock; 3016 } 3017 3018 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) { 3019 CFGBlock *LoopSuccessor = nullptr; 3020 3021 // Save local scope position because in case of condition variable ScopePos 3022 // won't be restored when traversing AST. 3023 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3024 3025 // Create local scope for possible condition variable. 3026 // Store scope position for continue statement. 3027 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 3028 if (VarDecl *VD = W->getConditionVariable()) { 3029 addLocalScopeForVarDecl(VD); 3030 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W); 3031 } 3032 addLoopExit(W); 3033 3034 // "while" is a control-flow statement. Thus we stop processing the current 3035 // block. 3036 if (Block) { 3037 if (badCFG) 3038 return nullptr; 3039 LoopSuccessor = Block; 3040 Block = nullptr; 3041 } else { 3042 LoopSuccessor = Succ; 3043 } 3044 3045 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr; 3046 3047 // Process the loop body. 3048 { 3049 assert(W->getBody()); 3050 3051 // Save the current values for Block, Succ, continue and break targets. 3052 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 3053 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 3054 save_break(BreakJumpTarget); 3055 3056 // Create an empty block to represent the transition block for looping back 3057 // to the head of the loop. 3058 Succ = TransitionBlock = createBlock(false); 3059 TransitionBlock->setLoopTarget(W); 3060 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); 3061 3062 // All breaks should go to the code following the loop. 3063 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 3064 3065 // Loop body should end with destructor of Condition variable (if any). 3066 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W); 3067 3068 // If body is not a compound statement create implicit scope 3069 // and add destructors. 3070 if (!isa<CompoundStmt>(W->getBody())) 3071 addLocalScopeAndDtors(W->getBody()); 3072 3073 // Create the body. The returned block is the entry to the loop body. 3074 BodyBlock = addStmt(W->getBody()); 3075 3076 if (!BodyBlock) 3077 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;" 3078 else if (Block && badCFG) 3079 return nullptr; 3080 } 3081 3082 // Because of short-circuit evaluation, the condition of the loop can span 3083 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 3084 // evaluate the condition. 3085 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr; 3086 3087 do { 3088 Expr *C = W->getCond(); 3089 3090 // Specially handle logical operators, which have a slightly 3091 // more optimal CFG representation. 3092 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens())) 3093 if (Cond->isLogicalOp()) { 3094 std::tie(EntryConditionBlock, ExitConditionBlock) = 3095 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor); 3096 break; 3097 } 3098 3099 // The default case when not handling logical operators. 3100 ExitConditionBlock = createBlock(false); 3101 ExitConditionBlock->setTerminator(W); 3102 3103 // Now add the actual condition to the condition block. 3104 // Because the condition itself may contain control-flow, new blocks may 3105 // be created. Thus we update "Succ" after adding the condition. 3106 Block = ExitConditionBlock; 3107 Block = EntryConditionBlock = addStmt(C); 3108 3109 // If this block contains a condition variable, add both the condition 3110 // variable and initializer to the CFG. 3111 if (VarDecl *VD = W->getConditionVariable()) { 3112 if (Expr *Init = VD->getInit()) { 3113 autoCreateBlock(); 3114 appendStmt(Block, W->getConditionVariableDeclStmt()); 3115 EntryConditionBlock = addStmt(Init); 3116 assert(Block == EntryConditionBlock); 3117 } 3118 } 3119 3120 if (Block && badCFG) 3121 return nullptr; 3122 3123 // See if this is a known constant. 3124 const TryResult& KnownVal = tryEvaluateBool(C); 3125 3126 // Add the loop body entry as a successor to the condition. 3127 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock); 3128 // Link up the condition block with the code that follows the loop. (the 3129 // false branch). 3130 addSuccessor(ExitConditionBlock, 3131 KnownVal.isTrue() ? nullptr : LoopSuccessor); 3132 3133 } while(false); 3134 3135 // Link up the loop-back block to the entry condition block. 3136 addSuccessor(TransitionBlock, EntryConditionBlock); 3137 3138 // There can be no more statements in the condition block since we loop back 3139 // to this block. NULL out Block to force lazy creation of another block. 3140 Block = nullptr; 3141 3142 // Return the condition block, which is the dominating block for the loop. 3143 Succ = EntryConditionBlock; 3144 return EntryConditionBlock; 3145 } 3146 3147 3148 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { 3149 // FIXME: For now we pretend that @catch and the code it contains does not 3150 // exit. 3151 return Block; 3152 } 3153 3154 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { 3155 // FIXME: This isn't complete. We basically treat @throw like a return 3156 // statement. 3157 3158 // If we were in the middle of a block we stop processing that block. 3159 if (badCFG) 3160 return nullptr; 3161 3162 // Create the new block. 3163 Block = createBlock(false); 3164 3165 // The Exit block is the only successor. 3166 addSuccessor(Block, &cfg->getExit()); 3167 3168 // Add the statement to the block. This may create new blocks if S contains 3169 // control-flow (short-circuit operations). 3170 return VisitStmt(S, AddStmtChoice::AlwaysAdd); 3171 } 3172 3173 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) { 3174 // If we were in the middle of a block we stop processing that block. 3175 if (badCFG) 3176 return nullptr; 3177 3178 // Create the new block. 3179 Block = createBlock(false); 3180 3181 if (TryTerminatedBlock) 3182 // The current try statement is the only successor. 3183 addSuccessor(Block, TryTerminatedBlock); 3184 else 3185 // otherwise the Exit block is the only successor. 3186 addSuccessor(Block, &cfg->getExit()); 3187 3188 // Add the statement to the block. This may create new blocks if S contains 3189 // control-flow (short-circuit operations). 3190 return VisitStmt(T, AddStmtChoice::AlwaysAdd); 3191 } 3192 3193 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) { 3194 CFGBlock *LoopSuccessor = nullptr; 3195 3196 addLoopExit(D); 3197 3198 // "do...while" is a control-flow statement. Thus we stop processing the 3199 // current block. 3200 if (Block) { 3201 if (badCFG) 3202 return nullptr; 3203 LoopSuccessor = Block; 3204 } else 3205 LoopSuccessor = Succ; 3206 3207 // Because of short-circuit evaluation, the condition of the loop can span 3208 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 3209 // evaluate the condition. 3210 CFGBlock *ExitConditionBlock = createBlock(false); 3211 CFGBlock *EntryConditionBlock = ExitConditionBlock; 3212 3213 // Set the terminator for the "exit" condition block. 3214 ExitConditionBlock->setTerminator(D); 3215 3216 // Now add the actual condition to the condition block. Because the condition 3217 // itself may contain control-flow, new blocks may be created. 3218 if (Stmt *C = D->getCond()) { 3219 Block = ExitConditionBlock; 3220 EntryConditionBlock = addStmt(C); 3221 if (Block) { 3222 if (badCFG) 3223 return nullptr; 3224 } 3225 } 3226 3227 // The condition block is the implicit successor for the loop body. 3228 Succ = EntryConditionBlock; 3229 3230 // See if this is a known constant. 3231 const TryResult &KnownVal = tryEvaluateBool(D->getCond()); 3232 3233 // Process the loop body. 3234 CFGBlock *BodyBlock = nullptr; 3235 { 3236 assert(D->getBody()); 3237 3238 // Save the current values for Block, Succ, and continue and break targets 3239 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 3240 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 3241 save_break(BreakJumpTarget); 3242 3243 // All continues within this loop should go to the condition block 3244 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 3245 3246 // All breaks should go to the code following the loop. 3247 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 3248 3249 // NULL out Block to force lazy instantiation of blocks for the body. 3250 Block = nullptr; 3251 3252 // If body is not a compound statement create implicit scope 3253 // and add destructors. 3254 if (!isa<CompoundStmt>(D->getBody())) 3255 addLocalScopeAndDtors(D->getBody()); 3256 3257 // Create the body. The returned block is the entry to the loop body. 3258 BodyBlock = addStmt(D->getBody()); 3259 3260 if (!BodyBlock) 3261 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" 3262 else if (Block) { 3263 if (badCFG) 3264 return nullptr; 3265 } 3266 3267 // Add an intermediate block between the BodyBlock and the 3268 // ExitConditionBlock to represent the "loop back" transition. Create an 3269 // empty block to represent the transition block for looping back to the 3270 // head of the loop. 3271 // FIXME: Can we do this more efficiently without adding another block? 3272 Block = nullptr; 3273 Succ = BodyBlock; 3274 CFGBlock *LoopBackBlock = createBlock(); 3275 LoopBackBlock->setLoopTarget(D); 3276 3277 if (!KnownVal.isFalse()) 3278 // Add the loop body entry as a successor to the condition. 3279 addSuccessor(ExitConditionBlock, LoopBackBlock); 3280 else 3281 addSuccessor(ExitConditionBlock, nullptr); 3282 } 3283 3284 // Link up the condition block with the code that follows the loop. 3285 // (the false branch). 3286 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor); 3287 3288 // There can be no more statements in the body block(s) since we loop back to 3289 // the body. NULL out Block to force lazy creation of another block. 3290 Block = nullptr; 3291 3292 // Return the loop body, which is the dominating block for the loop. 3293 Succ = BodyBlock; 3294 return BodyBlock; 3295 } 3296 3297 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) { 3298 // "continue" is a control-flow statement. Thus we stop processing the 3299 // current block. 3300 if (badCFG) 3301 return nullptr; 3302 3303 // Now create a new block that ends with the continue statement. 3304 Block = createBlock(false); 3305 Block->setTerminator(C); 3306 3307 // If there is no target for the continue, then we are looking at an 3308 // incomplete AST. This means the CFG cannot be constructed. 3309 if (ContinueJumpTarget.block) { 3310 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C); 3311 addSuccessor(Block, ContinueJumpTarget.block); 3312 } else 3313 badCFG = true; 3314 3315 return Block; 3316 } 3317 3318 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 3319 AddStmtChoice asc) { 3320 3321 if (asc.alwaysAdd(*this, E)) { 3322 autoCreateBlock(); 3323 appendStmt(Block, E); 3324 } 3325 3326 // VLA types have expressions that must be evaluated. 3327 CFGBlock *lastBlock = Block; 3328 3329 if (E->isArgumentType()) { 3330 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); 3331 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) 3332 lastBlock = addStmt(VA->getSizeExpr()); 3333 } 3334 return lastBlock; 3335 } 3336 3337 /// VisitStmtExpr - Utility method to handle (nested) statement 3338 /// expressions (a GCC extension). 3339 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) { 3340 if (asc.alwaysAdd(*this, SE)) { 3341 autoCreateBlock(); 3342 appendStmt(Block, SE); 3343 } 3344 return VisitCompoundStmt(SE->getSubStmt()); 3345 } 3346 3347 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) { 3348 // "switch" is a control-flow statement. Thus we stop processing the current 3349 // block. 3350 CFGBlock *SwitchSuccessor = nullptr; 3351 3352 // Save local scope position because in case of condition variable ScopePos 3353 // won't be restored when traversing AST. 3354 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3355 3356 // Create local scope for C++17 switch init-stmt if one exists. 3357 if (Stmt *Init = Terminator->getInit()) 3358 addLocalScopeForStmt(Init); 3359 3360 // Create local scope for possible condition variable. 3361 // Store scope position. Add implicit destructor. 3362 if (VarDecl *VD = Terminator->getConditionVariable()) 3363 addLocalScopeForVarDecl(VD); 3364 3365 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator); 3366 3367 if (Block) { 3368 if (badCFG) 3369 return nullptr; 3370 SwitchSuccessor = Block; 3371 } else SwitchSuccessor = Succ; 3372 3373 // Save the current "switch" context. 3374 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), 3375 save_default(DefaultCaseBlock); 3376 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 3377 3378 // Set the "default" case to be the block after the switch statement. If the 3379 // switch statement contains a "default:", this value will be overwritten with 3380 // the block for that code. 3381 DefaultCaseBlock = SwitchSuccessor; 3382 3383 // Create a new block that will contain the switch statement. 3384 SwitchTerminatedBlock = createBlock(false); 3385 3386 // Now process the switch body. The code after the switch is the implicit 3387 // successor. 3388 Succ = SwitchSuccessor; 3389 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos); 3390 3391 // When visiting the body, the case statements should automatically get linked 3392 // up to the switch. We also don't keep a pointer to the body, since all 3393 // control-flow from the switch goes to case/default statements. 3394 assert(Terminator->getBody() && "switch must contain a non-NULL body"); 3395 Block = nullptr; 3396 3397 // For pruning unreachable case statements, save the current state 3398 // for tracking the condition value. 3399 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered, 3400 false); 3401 3402 // Determine if the switch condition can be explicitly evaluated. 3403 assert(Terminator->getCond() && "switch condition must be non-NULL"); 3404 Expr::EvalResult result; 3405 bool b = tryEvaluate(Terminator->getCond(), result); 3406 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond, 3407 b ? &result : nullptr); 3408 3409 // If body is not a compound statement create implicit scope 3410 // and add destructors. 3411 if (!isa<CompoundStmt>(Terminator->getBody())) 3412 addLocalScopeAndDtors(Terminator->getBody()); 3413 3414 addStmt(Terminator->getBody()); 3415 if (Block) { 3416 if (badCFG) 3417 return nullptr; 3418 } 3419 3420 // If we have no "default:" case, the default transition is to the code 3421 // following the switch body. Moreover, take into account if all the 3422 // cases of a switch are covered (e.g., switching on an enum value). 3423 // 3424 // Note: We add a successor to a switch that is considered covered yet has no 3425 // case statements if the enumeration has no enumerators. 3426 bool SwitchAlwaysHasSuccessor = false; 3427 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered; 3428 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() && 3429 Terminator->getSwitchCaseList(); 3430 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock, 3431 !SwitchAlwaysHasSuccessor); 3432 3433 // Add the terminator and condition in the switch block. 3434 SwitchTerminatedBlock->setTerminator(Terminator); 3435 Block = SwitchTerminatedBlock; 3436 CFGBlock *LastBlock = addStmt(Terminator->getCond()); 3437 3438 // If the SwitchStmt contains a condition variable, add both the 3439 // SwitchStmt and the condition variable initialization to the CFG. 3440 if (VarDecl *VD = Terminator->getConditionVariable()) { 3441 if (Expr *Init = VD->getInit()) { 3442 autoCreateBlock(); 3443 appendStmt(Block, Terminator->getConditionVariableDeclStmt()); 3444 LastBlock = addStmt(Init); 3445 } 3446 } 3447 3448 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG. 3449 if (Stmt *Init = Terminator->getInit()) { 3450 autoCreateBlock(); 3451 LastBlock = addStmt(Init); 3452 } 3453 3454 return LastBlock; 3455 } 3456 3457 static bool shouldAddCase(bool &switchExclusivelyCovered, 3458 const Expr::EvalResult *switchCond, 3459 const CaseStmt *CS, 3460 ASTContext &Ctx) { 3461 if (!switchCond) 3462 return true; 3463 3464 bool addCase = false; 3465 3466 if (!switchExclusivelyCovered) { 3467 if (switchCond->Val.isInt()) { 3468 // Evaluate the LHS of the case value. 3469 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx); 3470 const llvm::APSInt &condInt = switchCond->Val.getInt(); 3471 3472 if (condInt == lhsInt) { 3473 addCase = true; 3474 switchExclusivelyCovered = true; 3475 } 3476 else if (condInt > lhsInt) { 3477 if (const Expr *RHS = CS->getRHS()) { 3478 // Evaluate the RHS of the case value. 3479 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx); 3480 if (V2 >= condInt) { 3481 addCase = true; 3482 switchExclusivelyCovered = true; 3483 } 3484 } 3485 } 3486 } 3487 else 3488 addCase = true; 3489 } 3490 return addCase; 3491 } 3492 3493 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) { 3494 // CaseStmts are essentially labels, so they are the first statement in a 3495 // block. 3496 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr; 3497 3498 if (Stmt *Sub = CS->getSubStmt()) { 3499 // For deeply nested chains of CaseStmts, instead of doing a recursion 3500 // (which can blow out the stack), manually unroll and create blocks 3501 // along the way. 3502 while (isa<CaseStmt>(Sub)) { 3503 CFGBlock *currentBlock = createBlock(false); 3504 currentBlock->setLabel(CS); 3505 3506 if (TopBlock) 3507 addSuccessor(LastBlock, currentBlock); 3508 else 3509 TopBlock = currentBlock; 3510 3511 addSuccessor(SwitchTerminatedBlock, 3512 shouldAddCase(switchExclusivelyCovered, switchCond, 3513 CS, *Context) 3514 ? currentBlock : nullptr); 3515 3516 LastBlock = currentBlock; 3517 CS = cast<CaseStmt>(Sub); 3518 Sub = CS->getSubStmt(); 3519 } 3520 3521 addStmt(Sub); 3522 } 3523 3524 CFGBlock *CaseBlock = Block; 3525 if (!CaseBlock) 3526 CaseBlock = createBlock(); 3527 3528 // Cases statements partition blocks, so this is the top of the basic block we 3529 // were processing (the "case XXX:" is the label). 3530 CaseBlock->setLabel(CS); 3531 3532 if (badCFG) 3533 return nullptr; 3534 3535 // Add this block to the list of successors for the block with the switch 3536 // statement. 3537 assert(SwitchTerminatedBlock); 3538 addSuccessor(SwitchTerminatedBlock, CaseBlock, 3539 shouldAddCase(switchExclusivelyCovered, switchCond, 3540 CS, *Context)); 3541 3542 // We set Block to NULL to allow lazy creation of a new block (if necessary) 3543 Block = nullptr; 3544 3545 if (TopBlock) { 3546 addSuccessor(LastBlock, CaseBlock); 3547 Succ = TopBlock; 3548 } else { 3549 // This block is now the implicit successor of other blocks. 3550 Succ = CaseBlock; 3551 } 3552 3553 return Succ; 3554 } 3555 3556 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) { 3557 if (Terminator->getSubStmt()) 3558 addStmt(Terminator->getSubStmt()); 3559 3560 DefaultCaseBlock = Block; 3561 3562 if (!DefaultCaseBlock) 3563 DefaultCaseBlock = createBlock(); 3564 3565 // Default statements partition blocks, so this is the top of the basic block 3566 // we were processing (the "default:" is the label). 3567 DefaultCaseBlock->setLabel(Terminator); 3568 3569 if (badCFG) 3570 return nullptr; 3571 3572 // Unlike case statements, we don't add the default block to the successors 3573 // for the switch statement immediately. This is done when we finish 3574 // processing the switch statement. This allows for the default case 3575 // (including a fall-through to the code after the switch statement) to always 3576 // be the last successor of a switch-terminated block. 3577 3578 // We set Block to NULL to allow lazy creation of a new block (if necessary) 3579 Block = nullptr; 3580 3581 // This block is now the implicit successor of other blocks. 3582 Succ = DefaultCaseBlock; 3583 3584 return DefaultCaseBlock; 3585 } 3586 3587 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { 3588 // "try"/"catch" is a control-flow statement. Thus we stop processing the 3589 // current block. 3590 CFGBlock *TrySuccessor = nullptr; 3591 3592 if (Block) { 3593 if (badCFG) 3594 return nullptr; 3595 TrySuccessor = Block; 3596 } else TrySuccessor = Succ; 3597 3598 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 3599 3600 // Create a new block that will contain the try statement. 3601 CFGBlock *NewTryTerminatedBlock = createBlock(false); 3602 // Add the terminator in the try block. 3603 NewTryTerminatedBlock->setTerminator(Terminator); 3604 3605 bool HasCatchAll = false; 3606 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) { 3607 // The code after the try is the implicit successor. 3608 Succ = TrySuccessor; 3609 CXXCatchStmt *CS = Terminator->getHandler(h); 3610 if (CS->getExceptionDecl() == nullptr) { 3611 HasCatchAll = true; 3612 } 3613 Block = nullptr; 3614 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); 3615 if (!CatchBlock) 3616 return nullptr; 3617 // Add this block to the list of successors for the block with the try 3618 // statement. 3619 addSuccessor(NewTryTerminatedBlock, CatchBlock); 3620 } 3621 if (!HasCatchAll) { 3622 if (PrevTryTerminatedBlock) 3623 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 3624 else 3625 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 3626 } 3627 3628 // The code after the try is the implicit successor. 3629 Succ = TrySuccessor; 3630 3631 // Save the current "try" context. 3632 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock); 3633 cfg->addTryDispatchBlock(TryTerminatedBlock); 3634 3635 assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); 3636 Block = nullptr; 3637 return addStmt(Terminator->getTryBlock()); 3638 } 3639 3640 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) { 3641 // CXXCatchStmt are treated like labels, so they are the first statement in a 3642 // block. 3643 3644 // Save local scope position because in case of exception variable ScopePos 3645 // won't be restored when traversing AST. 3646 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3647 3648 // Create local scope for possible exception variable. 3649 // Store scope position. Add implicit destructor. 3650 if (VarDecl *VD = CS->getExceptionDecl()) { 3651 LocalScope::const_iterator BeginScopePos = ScopePos; 3652 addLocalScopeForVarDecl(VD); 3653 addAutomaticObjHandling(ScopePos, BeginScopePos, CS); 3654 } 3655 3656 if (CS->getHandlerBlock()) 3657 addStmt(CS->getHandlerBlock()); 3658 3659 CFGBlock *CatchBlock = Block; 3660 if (!CatchBlock) 3661 CatchBlock = createBlock(); 3662 3663 // CXXCatchStmt is more than just a label. They have semantic meaning 3664 // as well, as they implicitly "initialize" the catch variable. Add 3665 // it to the CFG as a CFGElement so that the control-flow of these 3666 // semantics gets captured. 3667 appendStmt(CatchBlock, CS); 3668 3669 // Also add the CXXCatchStmt as a label, to mirror handling of regular 3670 // labels. 3671 CatchBlock->setLabel(CS); 3672 3673 // Bail out if the CFG is bad. 3674 if (badCFG) 3675 return nullptr; 3676 3677 // We set Block to NULL to allow lazy creation of a new block (if necessary) 3678 Block = nullptr; 3679 3680 return CatchBlock; 3681 } 3682 3683 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) { 3684 // C++0x for-range statements are specified as [stmt.ranged]: 3685 // 3686 // { 3687 // auto && __range = range-init; 3688 // for ( auto __begin = begin-expr, 3689 // __end = end-expr; 3690 // __begin != __end; 3691 // ++__begin ) { 3692 // for-range-declaration = *__begin; 3693 // statement 3694 // } 3695 // } 3696 3697 // Save local scope position before the addition of the implicit variables. 3698 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3699 3700 // Create local scopes and destructors for range, begin and end variables. 3701 if (Stmt *Range = S->getRangeStmt()) 3702 addLocalScopeForStmt(Range); 3703 if (Stmt *Begin = S->getBeginStmt()) 3704 addLocalScopeForStmt(Begin); 3705 if (Stmt *End = S->getEndStmt()) 3706 addLocalScopeForStmt(End); 3707 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S); 3708 3709 LocalScope::const_iterator ContinueScopePos = ScopePos; 3710 3711 // "for" is a control-flow statement. Thus we stop processing the current 3712 // block. 3713 CFGBlock *LoopSuccessor = nullptr; 3714 if (Block) { 3715 if (badCFG) 3716 return nullptr; 3717 LoopSuccessor = Block; 3718 } else 3719 LoopSuccessor = Succ; 3720 3721 // Save the current value for the break targets. 3722 // All breaks should go to the code following the loop. 3723 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 3724 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 3725 3726 // The block for the __begin != __end expression. 3727 CFGBlock *ConditionBlock = createBlock(false); 3728 ConditionBlock->setTerminator(S); 3729 3730 // Now add the actual condition to the condition block. 3731 if (Expr *C = S->getCond()) { 3732 Block = ConditionBlock; 3733 CFGBlock *BeginConditionBlock = addStmt(C); 3734 if (badCFG) 3735 return nullptr; 3736 assert(BeginConditionBlock == ConditionBlock && 3737 "condition block in for-range was unexpectedly complex"); 3738 (void)BeginConditionBlock; 3739 } 3740 3741 // The condition block is the implicit successor for the loop body as well as 3742 // any code above the loop. 3743 Succ = ConditionBlock; 3744 3745 // See if this is a known constant. 3746 TryResult KnownVal(true); 3747 3748 if (S->getCond()) 3749 KnownVal = tryEvaluateBool(S->getCond()); 3750 3751 // Now create the loop body. 3752 { 3753 assert(S->getBody()); 3754 3755 // Save the current values for Block, Succ, and continue targets. 3756 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 3757 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 3758 3759 // Generate increment code in its own basic block. This is the target of 3760 // continue statements. 3761 Block = nullptr; 3762 Succ = addStmt(S->getInc()); 3763 if (badCFG) 3764 return nullptr; 3765 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 3766 3767 // The starting block for the loop increment is the block that should 3768 // represent the 'loop target' for looping back to the start of the loop. 3769 ContinueJumpTarget.block->setLoopTarget(S); 3770 3771 // Finish up the increment block and prepare to start the loop body. 3772 assert(Block); 3773 if (badCFG) 3774 return nullptr; 3775 Block = nullptr; 3776 3777 // Add implicit scope and dtors for loop variable. 3778 addLocalScopeAndDtors(S->getLoopVarStmt()); 3779 3780 // Populate a new block to contain the loop body and loop variable. 3781 addStmt(S->getBody()); 3782 if (badCFG) 3783 return nullptr; 3784 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt()); 3785 if (badCFG) 3786 return nullptr; 3787 3788 // This new body block is a successor to our condition block. 3789 addSuccessor(ConditionBlock, 3790 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock); 3791 } 3792 3793 // Link up the condition block with the code that follows the loop (the 3794 // false branch). 3795 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor); 3796 3797 // Add the initialization statements. 3798 Block = createBlock(); 3799 addStmt(S->getBeginStmt()); 3800 addStmt(S->getEndStmt()); 3801 return addStmt(S->getRangeStmt()); 3802 } 3803 3804 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E, 3805 AddStmtChoice asc) { 3806 if (BuildOpts.AddTemporaryDtors) { 3807 // If adding implicit destructors visit the full expression for adding 3808 // destructors of temporaries. 3809 TempDtorContext Context; 3810 VisitForTemporaryDtors(E->getSubExpr(), false, Context); 3811 3812 // Full expression has to be added as CFGStmt so it will be sequenced 3813 // before destructors of it's temporaries. 3814 asc = asc.withAlwaysAdd(true); 3815 } 3816 return Visit(E->getSubExpr(), asc); 3817 } 3818 3819 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 3820 AddStmtChoice asc) { 3821 if (asc.alwaysAdd(*this, E)) { 3822 autoCreateBlock(); 3823 appendStmt(Block, E); 3824 3825 // We do not want to propagate the AlwaysAdd property. 3826 asc = asc.withAlwaysAdd(false); 3827 } 3828 return Visit(E->getSubExpr(), asc); 3829 } 3830 3831 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, 3832 AddStmtChoice asc) { 3833 autoCreateBlock(); 3834 appendStmt(Block, C); 3835 3836 return VisitChildren(C); 3837 } 3838 3839 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE, 3840 AddStmtChoice asc) { 3841 3842 autoCreateBlock(); 3843 appendStmt(Block, NE); 3844 3845 if (NE->getInitializer()) 3846 Block = Visit(NE->getInitializer()); 3847 if (BuildOpts.AddCXXNewAllocator) 3848 appendNewAllocator(Block, NE); 3849 if (NE->isArray()) 3850 Block = Visit(NE->getArraySize()); 3851 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(), 3852 E = NE->placement_arg_end(); I != E; ++I) 3853 Block = Visit(*I); 3854 return Block; 3855 } 3856 3857 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE, 3858 AddStmtChoice asc) { 3859 autoCreateBlock(); 3860 appendStmt(Block, DE); 3861 QualType DTy = DE->getDestroyedType(); 3862 if (!DTy.isNull()) { 3863 DTy = DTy.getNonReferenceType(); 3864 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl(); 3865 if (RD) { 3866 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor()) 3867 appendDeleteDtor(Block, RD, DE); 3868 } 3869 } 3870 3871 return VisitChildren(DE); 3872 } 3873 3874 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 3875 AddStmtChoice asc) { 3876 if (asc.alwaysAdd(*this, E)) { 3877 autoCreateBlock(); 3878 appendStmt(Block, E); 3879 // We do not want to propagate the AlwaysAdd property. 3880 asc = asc.withAlwaysAdd(false); 3881 } 3882 return Visit(E->getSubExpr(), asc); 3883 } 3884 3885 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 3886 AddStmtChoice asc) { 3887 autoCreateBlock(); 3888 appendStmt(Block, C); 3889 return VisitChildren(C); 3890 } 3891 3892 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, 3893 AddStmtChoice asc) { 3894 if (asc.alwaysAdd(*this, E)) { 3895 autoCreateBlock(); 3896 appendStmt(Block, E); 3897 } 3898 return Visit(E->getSubExpr(), AddStmtChoice()); 3899 } 3900 3901 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) { 3902 // Lazily create the indirect-goto dispatch block if there isn't one already. 3903 CFGBlock *IBlock = cfg->getIndirectGotoBlock(); 3904 3905 if (!IBlock) { 3906 IBlock = createBlock(false); 3907 cfg->setIndirectGotoBlock(IBlock); 3908 } 3909 3910 // IndirectGoto is a control-flow statement. Thus we stop processing the 3911 // current block and create a new one. 3912 if (badCFG) 3913 return nullptr; 3914 3915 Block = createBlock(false); 3916 Block->setTerminator(I); 3917 addSuccessor(Block, IBlock); 3918 return addStmt(I->getTarget()); 3919 } 3920 3921 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary, 3922 TempDtorContext &Context) { 3923 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors); 3924 3925 tryAgain: 3926 if (!E) { 3927 badCFG = true; 3928 return nullptr; 3929 } 3930 switch (E->getStmtClass()) { 3931 default: 3932 return VisitChildrenForTemporaryDtors(E, Context); 3933 3934 case Stmt::BinaryOperatorClass: 3935 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E), 3936 Context); 3937 3938 case Stmt::CXXBindTemporaryExprClass: 3939 return VisitCXXBindTemporaryExprForTemporaryDtors( 3940 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context); 3941 3942 case Stmt::BinaryConditionalOperatorClass: 3943 case Stmt::ConditionalOperatorClass: 3944 return VisitConditionalOperatorForTemporaryDtors( 3945 cast<AbstractConditionalOperator>(E), BindToTemporary, Context); 3946 3947 case Stmt::ImplicitCastExprClass: 3948 // For implicit cast we want BindToTemporary to be passed further. 3949 E = cast<CastExpr>(E)->getSubExpr(); 3950 goto tryAgain; 3951 3952 case Stmt::CXXFunctionalCastExprClass: 3953 // For functional cast we want BindToTemporary to be passed further. 3954 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr(); 3955 goto tryAgain; 3956 3957 case Stmt::ParenExprClass: 3958 E = cast<ParenExpr>(E)->getSubExpr(); 3959 goto tryAgain; 3960 3961 case Stmt::MaterializeTemporaryExprClass: { 3962 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E); 3963 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression); 3964 SmallVector<const Expr *, 2> CommaLHSs; 3965 SmallVector<SubobjectAdjustment, 2> Adjustments; 3966 // Find the expression whose lifetime needs to be extended. 3967 E = const_cast<Expr *>( 3968 cast<MaterializeTemporaryExpr>(E) 3969 ->GetTemporaryExpr() 3970 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments)); 3971 // Visit the skipped comma operator left-hand sides for other temporaries. 3972 for (const Expr *CommaLHS : CommaLHSs) { 3973 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS), 3974 /*BindToTemporary=*/false, Context); 3975 } 3976 goto tryAgain; 3977 } 3978 3979 case Stmt::BlockExprClass: 3980 // Don't recurse into blocks; their subexpressions don't get evaluated 3981 // here. 3982 return Block; 3983 3984 case Stmt::LambdaExprClass: { 3985 // For lambda expressions, only recurse into the capture initializers, 3986 // and not the body. 3987 auto *LE = cast<LambdaExpr>(E); 3988 CFGBlock *B = Block; 3989 for (Expr *Init : LE->capture_inits()) { 3990 if (CFGBlock *R = VisitForTemporaryDtors( 3991 Init, /*BindToTemporary=*/false, Context)) 3992 B = R; 3993 } 3994 return B; 3995 } 3996 3997 case Stmt::CXXDefaultArgExprClass: 3998 E = cast<CXXDefaultArgExpr>(E)->getExpr(); 3999 goto tryAgain; 4000 4001 case Stmt::CXXDefaultInitExprClass: 4002 E = cast<CXXDefaultInitExpr>(E)->getExpr(); 4003 goto tryAgain; 4004 } 4005 } 4006 4007 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E, 4008 TempDtorContext &Context) { 4009 if (isa<LambdaExpr>(E)) { 4010 // Do not visit the children of lambdas; they have their own CFGs. 4011 return Block; 4012 } 4013 4014 // When visiting children for destructors we want to visit them in reverse 4015 // order that they will appear in the CFG. Because the CFG is built 4016 // bottom-up, this means we visit them in their natural order, which 4017 // reverses them in the CFG. 4018 CFGBlock *B = Block; 4019 for (Stmt *Child : E->children()) 4020 if (Child) 4021 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context)) 4022 B = R; 4023 4024 return B; 4025 } 4026 4027 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors( 4028 BinaryOperator *E, TempDtorContext &Context) { 4029 if (E->isLogicalOp()) { 4030 VisitForTemporaryDtors(E->getLHS(), false, Context); 4031 TryResult RHSExecuted = tryEvaluateBool(E->getLHS()); 4032 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr) 4033 RHSExecuted.negate(); 4034 4035 // We do not know at CFG-construction time whether the right-hand-side was 4036 // executed, thus we add a branch node that depends on the temporary 4037 // constructor call. 4038 TempDtorContext RHSContext( 4039 bothKnownTrue(Context.KnownExecuted, RHSExecuted)); 4040 VisitForTemporaryDtors(E->getRHS(), false, RHSContext); 4041 InsertTempDtorDecisionBlock(RHSContext); 4042 4043 return Block; 4044 } 4045 4046 if (E->isAssignmentOp()) { 4047 // For assignment operator (=) LHS expression is visited 4048 // before RHS expression. For destructors visit them in reverse order. 4049 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context); 4050 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context); 4051 return LHSBlock ? LHSBlock : RHSBlock; 4052 } 4053 4054 // For any other binary operator RHS expression is visited before 4055 // LHS expression (order of children). For destructors visit them in reverse 4056 // order. 4057 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context); 4058 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context); 4059 return RHSBlock ? RHSBlock : LHSBlock; 4060 } 4061 4062 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( 4063 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) { 4064 // First add destructors for temporaries in subexpression. 4065 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context); 4066 if (!BindToTemporary) { 4067 // If lifetime of temporary is not prolonged (by assigning to constant 4068 // reference) add destructor for it. 4069 4070 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor(); 4071 4072 if (Dtor->getParent()->isAnyDestructorNoReturn()) { 4073 // If the destructor is marked as a no-return destructor, we need to 4074 // create a new block for the destructor which does not have as a 4075 // successor anything built thus far. Control won't flow out of this 4076 // block. 4077 if (B) Succ = B; 4078 Block = createNoReturnBlock(); 4079 } else if (Context.needsTempDtorBranch()) { 4080 // If we need to introduce a branch, we add a new block that we will hook 4081 // up to a decision block later. 4082 if (B) Succ = B; 4083 Block = createBlock(); 4084 } else { 4085 autoCreateBlock(); 4086 } 4087 if (Context.needsTempDtorBranch()) { 4088 Context.setDecisionPoint(Succ, E); 4089 } 4090 appendTemporaryDtor(Block, E); 4091 4092 B = Block; 4093 } 4094 return B; 4095 } 4096 4097 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context, 4098 CFGBlock *FalseSucc) { 4099 if (!Context.TerminatorExpr) { 4100 // If no temporary was found, we do not need to insert a decision point. 4101 return; 4102 } 4103 assert(Context.TerminatorExpr); 4104 CFGBlock *Decision = createBlock(false); 4105 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true)); 4106 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse()); 4107 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ, 4108 !Context.KnownExecuted.isTrue()); 4109 Block = Decision; 4110 } 4111 4112 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( 4113 AbstractConditionalOperator *E, bool BindToTemporary, 4114 TempDtorContext &Context) { 4115 VisitForTemporaryDtors(E->getCond(), false, Context); 4116 CFGBlock *ConditionBlock = Block; 4117 CFGBlock *ConditionSucc = Succ; 4118 TryResult ConditionVal = tryEvaluateBool(E->getCond()); 4119 TryResult NegatedVal = ConditionVal; 4120 if (NegatedVal.isKnown()) NegatedVal.negate(); 4121 4122 TempDtorContext TrueContext( 4123 bothKnownTrue(Context.KnownExecuted, ConditionVal)); 4124 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext); 4125 CFGBlock *TrueBlock = Block; 4126 4127 Block = ConditionBlock; 4128 Succ = ConditionSucc; 4129 TempDtorContext FalseContext( 4130 bothKnownTrue(Context.KnownExecuted, NegatedVal)); 4131 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext); 4132 4133 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) { 4134 InsertTempDtorDecisionBlock(FalseContext, TrueBlock); 4135 } else if (TrueContext.TerminatorExpr) { 4136 Block = TrueBlock; 4137 InsertTempDtorDecisionBlock(TrueContext); 4138 } else { 4139 InsertTempDtorDecisionBlock(FalseContext); 4140 } 4141 return Block; 4142 } 4143 4144 } // end anonymous namespace 4145 4146 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 4147 /// no successors or predecessors. If this is the first block created in the 4148 /// CFG, it is automatically set to be the Entry and Exit of the CFG. 4149 CFGBlock *CFG::createBlock() { 4150 bool first_block = begin() == end(); 4151 4152 // Create the block. 4153 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 4154 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this); 4155 Blocks.push_back(Mem, BlkBVC); 4156 4157 // If this is the first block, set it as the Entry and Exit. 4158 if (first_block) 4159 Entry = Exit = &back(); 4160 4161 // Return the block. 4162 return &back(); 4163 } 4164 4165 /// buildCFG - Constructs a CFG from an AST. 4166 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement, 4167 ASTContext *C, const BuildOptions &BO) { 4168 CFGBuilder Builder(C, BO); 4169 return Builder.buildCFG(D, Statement); 4170 } 4171 4172 const CXXDestructorDecl * 4173 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { 4174 switch (getKind()) { 4175 case CFGElement::Statement: 4176 case CFGElement::Initializer: 4177 case CFGElement::NewAllocator: 4178 case CFGElement::LoopExit: 4179 case CFGElement::LifetimeEnds: 4180 llvm_unreachable("getDestructorDecl should only be used with " 4181 "ImplicitDtors"); 4182 case CFGElement::AutomaticObjectDtor: { 4183 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl(); 4184 QualType ty = var->getType(); 4185 4186 // FIXME: See CFGBuilder::addLocalScopeForVarDecl. 4187 // 4188 // Lifetime-extending constructs are handled here. This works for a single 4189 // temporary in an initializer expression. 4190 if (ty->isReferenceType()) { 4191 if (const Expr *Init = var->getInit()) { 4192 ty = getReferenceInitTemporaryType(astContext, Init); 4193 } 4194 } 4195 4196 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) { 4197 ty = arrayType->getElementType(); 4198 } 4199 const RecordType *recordType = ty->getAs<RecordType>(); 4200 const CXXRecordDecl *classDecl = 4201 cast<CXXRecordDecl>(recordType->getDecl()); 4202 return classDecl->getDestructor(); 4203 } 4204 case CFGElement::DeleteDtor: { 4205 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr(); 4206 QualType DTy = DE->getDestroyedType(); 4207 DTy = DTy.getNonReferenceType(); 4208 const CXXRecordDecl *classDecl = 4209 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl(); 4210 return classDecl->getDestructor(); 4211 } 4212 case CFGElement::TemporaryDtor: { 4213 const CXXBindTemporaryExpr *bindExpr = 4214 castAs<CFGTemporaryDtor>().getBindTemporaryExpr(); 4215 const CXXTemporary *temp = bindExpr->getTemporary(); 4216 return temp->getDestructor(); 4217 } 4218 case CFGElement::BaseDtor: 4219 case CFGElement::MemberDtor: 4220 4221 // Not yet supported. 4222 return nullptr; 4223 } 4224 llvm_unreachable("getKind() returned bogus value"); 4225 } 4226 4227 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const { 4228 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext)) 4229 return DD->isNoReturn(); 4230 return false; 4231 } 4232 4233 //===----------------------------------------------------------------------===// 4234 // CFGBlock operations. 4235 //===----------------------------------------------------------------------===// 4236 4237 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable) 4238 : ReachableBlock(IsReachable ? B : nullptr), 4239 UnreachableBlock(!IsReachable ? B : nullptr, 4240 B && IsReachable ? AB_Normal : AB_Unreachable) {} 4241 4242 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock) 4243 : ReachableBlock(B), 4244 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock, 4245 B == AlternateBlock ? AB_Alternate : AB_Normal) {} 4246 4247 void CFGBlock::addSuccessor(AdjacentBlock Succ, 4248 BumpVectorContext &C) { 4249 if (CFGBlock *B = Succ.getReachableBlock()) 4250 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C); 4251 4252 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock()) 4253 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C); 4254 4255 Succs.push_back(Succ, C); 4256 } 4257 4258 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 4259 const CFGBlock *From, const CFGBlock *To) { 4260 4261 if (F.IgnoreNullPredecessors && !From) 4262 return true; 4263 4264 if (To && From && F.IgnoreDefaultsWithCoveredEnums) { 4265 // If the 'To' has no label or is labeled but the label isn't a 4266 // CaseStmt then filter this edge. 4267 if (const SwitchStmt *S = 4268 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) { 4269 if (S->isAllEnumCasesCovered()) { 4270 const Stmt *L = To->getLabel(); 4271 if (!L || !isa<CaseStmt>(L)) 4272 return true; 4273 } 4274 } 4275 } 4276 4277 return false; 4278 } 4279 4280 //===----------------------------------------------------------------------===// 4281 // CFG pretty printing 4282 //===----------------------------------------------------------------------===// 4283 4284 namespace { 4285 4286 class StmtPrinterHelper : public PrinterHelper { 4287 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; 4288 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy; 4289 StmtMapTy StmtMap; 4290 DeclMapTy DeclMap; 4291 signed currentBlock; 4292 unsigned currStmt; 4293 const LangOptions &LangOpts; 4294 public: 4295 4296 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 4297 : currentBlock(0), currStmt(0), LangOpts(LO) 4298 { 4299 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 4300 unsigned j = 1; 4301 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 4302 BI != BEnd; ++BI, ++j ) { 4303 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) { 4304 const Stmt *stmt= SE->getStmt(); 4305 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 4306 StmtMap[stmt] = P; 4307 4308 switch (stmt->getStmtClass()) { 4309 case Stmt::DeclStmtClass: 4310 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P; 4311 break; 4312 case Stmt::IfStmtClass: { 4313 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable(); 4314 if (var) 4315 DeclMap[var] = P; 4316 break; 4317 } 4318 case Stmt::ForStmtClass: { 4319 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable(); 4320 if (var) 4321 DeclMap[var] = P; 4322 break; 4323 } 4324 case Stmt::WhileStmtClass: { 4325 const VarDecl *var = 4326 cast<WhileStmt>(stmt)->getConditionVariable(); 4327 if (var) 4328 DeclMap[var] = P; 4329 break; 4330 } 4331 case Stmt::SwitchStmtClass: { 4332 const VarDecl *var = 4333 cast<SwitchStmt>(stmt)->getConditionVariable(); 4334 if (var) 4335 DeclMap[var] = P; 4336 break; 4337 } 4338 case Stmt::CXXCatchStmtClass: { 4339 const VarDecl *var = 4340 cast<CXXCatchStmt>(stmt)->getExceptionDecl(); 4341 if (var) 4342 DeclMap[var] = P; 4343 break; 4344 } 4345 default: 4346 break; 4347 } 4348 } 4349 } 4350 } 4351 } 4352 4353 ~StmtPrinterHelper() override {} 4354 4355 const LangOptions &getLangOpts() const { return LangOpts; } 4356 void setBlockID(signed i) { currentBlock = i; } 4357 void setStmtID(unsigned i) { currStmt = i; } 4358 4359 bool handledStmt(Stmt *S, raw_ostream &OS) override { 4360 StmtMapTy::iterator I = StmtMap.find(S); 4361 4362 if (I == StmtMap.end()) 4363 return false; 4364 4365 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 4366 && I->second.second == currStmt) { 4367 return false; 4368 } 4369 4370 OS << "[B" << I->second.first << "." << I->second.second << "]"; 4371 return true; 4372 } 4373 4374 bool handleDecl(const Decl *D, raw_ostream &OS) { 4375 DeclMapTy::iterator I = DeclMap.find(D); 4376 4377 if (I == DeclMap.end()) 4378 return false; 4379 4380 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 4381 && I->second.second == currStmt) { 4382 return false; 4383 } 4384 4385 OS << "[B" << I->second.first << "." << I->second.second << "]"; 4386 return true; 4387 } 4388 }; 4389 } // end anonymous namespace 4390 4391 4392 namespace { 4393 class CFGBlockTerminatorPrint 4394 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 4395 4396 raw_ostream &OS; 4397 StmtPrinterHelper* Helper; 4398 PrintingPolicy Policy; 4399 public: 4400 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper, 4401 const PrintingPolicy &Policy) 4402 : OS(os), Helper(helper), Policy(Policy) { 4403 this->Policy.IncludeNewlines = false; 4404 } 4405 4406 void VisitIfStmt(IfStmt *I) { 4407 OS << "if "; 4408 if (Stmt *C = I->getCond()) 4409 C->printPretty(OS, Helper, Policy); 4410 } 4411 4412 // Default case. 4413 void VisitStmt(Stmt *Terminator) { 4414 Terminator->printPretty(OS, Helper, Policy); 4415 } 4416 4417 void VisitDeclStmt(DeclStmt *DS) { 4418 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 4419 OS << "static init " << VD->getName(); 4420 } 4421 4422 void VisitForStmt(ForStmt *F) { 4423 OS << "for (" ; 4424 if (F->getInit()) 4425 OS << "..."; 4426 OS << "; "; 4427 if (Stmt *C = F->getCond()) 4428 C->printPretty(OS, Helper, Policy); 4429 OS << "; "; 4430 if (F->getInc()) 4431 OS << "..."; 4432 OS << ")"; 4433 } 4434 4435 void VisitWhileStmt(WhileStmt *W) { 4436 OS << "while " ; 4437 if (Stmt *C = W->getCond()) 4438 C->printPretty(OS, Helper, Policy); 4439 } 4440 4441 void VisitDoStmt(DoStmt *D) { 4442 OS << "do ... while "; 4443 if (Stmt *C = D->getCond()) 4444 C->printPretty(OS, Helper, Policy); 4445 } 4446 4447 void VisitSwitchStmt(SwitchStmt *Terminator) { 4448 OS << "switch "; 4449 Terminator->getCond()->printPretty(OS, Helper, Policy); 4450 } 4451 4452 void VisitCXXTryStmt(CXXTryStmt *CS) { 4453 OS << "try ..."; 4454 } 4455 4456 void VisitSEHTryStmt(SEHTryStmt *CS) { 4457 OS << "__try ..."; 4458 } 4459 4460 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) { 4461 if (Stmt *Cond = C->getCond()) 4462 Cond->printPretty(OS, Helper, Policy); 4463 OS << " ? ... : ..."; 4464 } 4465 4466 void VisitChooseExpr(ChooseExpr *C) { 4467 OS << "__builtin_choose_expr( "; 4468 if (Stmt *Cond = C->getCond()) 4469 Cond->printPretty(OS, Helper, Policy); 4470 OS << " )"; 4471 } 4472 4473 void VisitIndirectGotoStmt(IndirectGotoStmt *I) { 4474 OS << "goto *"; 4475 if (Stmt *T = I->getTarget()) 4476 T->printPretty(OS, Helper, Policy); 4477 } 4478 4479 void VisitBinaryOperator(BinaryOperator* B) { 4480 if (!B->isLogicalOp()) { 4481 VisitExpr(B); 4482 return; 4483 } 4484 4485 if (B->getLHS()) 4486 B->getLHS()->printPretty(OS, Helper, Policy); 4487 4488 switch (B->getOpcode()) { 4489 case BO_LOr: 4490 OS << " || ..."; 4491 return; 4492 case BO_LAnd: 4493 OS << " && ..."; 4494 return; 4495 default: 4496 llvm_unreachable("Invalid logical operator."); 4497 } 4498 } 4499 4500 void VisitExpr(Expr *E) { 4501 E->printPretty(OS, Helper, Policy); 4502 } 4503 4504 public: 4505 void print(CFGTerminator T) { 4506 if (T.isTemporaryDtorsBranch()) 4507 OS << "(Temp Dtor) "; 4508 Visit(T.getStmt()); 4509 } 4510 }; 4511 } // end anonymous namespace 4512 4513 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper, 4514 const CFGElement &E) { 4515 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) { 4516 const Stmt *S = CS->getStmt(); 4517 assert(S != nullptr && "Expecting non-null Stmt"); 4518 4519 // special printing for statement-expressions. 4520 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) { 4521 const CompoundStmt *Sub = SE->getSubStmt(); 4522 4523 auto Children = Sub->children(); 4524 if (Children.begin() != Children.end()) { 4525 OS << "({ ... ; "; 4526 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 4527 OS << " })\n"; 4528 return; 4529 } 4530 } 4531 // special printing for comma expressions. 4532 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 4533 if (B->getOpcode() == BO_Comma) { 4534 OS << "... , "; 4535 Helper.handledStmt(B->getRHS(),OS); 4536 OS << '\n'; 4537 return; 4538 } 4539 } 4540 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); 4541 4542 if (isa<CXXOperatorCallExpr>(S)) { 4543 OS << " (OperatorCall)"; 4544 } 4545 else if (isa<CXXBindTemporaryExpr>(S)) { 4546 OS << " (BindTemporary)"; 4547 } 4548 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) { 4549 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")"; 4550 } 4551 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) { 4552 OS << " (" << CE->getStmtClassName() << ", " 4553 << CE->getCastKindName() 4554 << ", " << CE->getType().getAsString() 4555 << ")"; 4556 } 4557 4558 // Expressions need a newline. 4559 if (isa<Expr>(S)) 4560 OS << '\n'; 4561 4562 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) { 4563 const CXXCtorInitializer *I = IE->getInitializer(); 4564 if (I->isBaseInitializer()) 4565 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 4566 else if (I->isDelegatingInitializer()) 4567 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName(); 4568 else OS << I->getAnyMember()->getName(); 4569 4570 OS << "("; 4571 if (Expr *IE = I->getInit()) 4572 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); 4573 OS << ")"; 4574 4575 if (I->isBaseInitializer()) 4576 OS << " (Base initializer)\n"; 4577 else if (I->isDelegatingInitializer()) 4578 OS << " (Delegating initializer)\n"; 4579 else OS << " (Member initializer)\n"; 4580 4581 } else if (Optional<CFGAutomaticObjDtor> DE = 4582 E.getAs<CFGAutomaticObjDtor>()) { 4583 const VarDecl *VD = DE->getVarDecl(); 4584 Helper.handleDecl(VD, OS); 4585 4586 const Type* T = VD->getType().getTypePtr(); 4587 if (const ReferenceType* RT = T->getAs<ReferenceType>()) 4588 T = RT->getPointeeType().getTypePtr(); 4589 T = T->getBaseElementTypeUnsafe(); 4590 4591 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()"; 4592 OS << " (Implicit destructor)\n"; 4593 4594 } else if (Optional<CFGLifetimeEnds> DE = E.getAs<CFGLifetimeEnds>()) { 4595 const VarDecl *VD = DE->getVarDecl(); 4596 Helper.handleDecl(VD, OS); 4597 4598 OS << " (Lifetime ends)\n"; 4599 4600 } else if (Optional<CFGLoopExit> LE = E.getAs<CFGLoopExit>()) { 4601 const Stmt *LoopStmt = LE->getLoopStmt(); 4602 OS << LoopStmt->getStmtClassName() << " (LoopExit)\n"; 4603 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) { 4604 OS << "CFGNewAllocator("; 4605 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr()) 4606 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts())); 4607 OS << ")\n"; 4608 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) { 4609 const CXXRecordDecl *RD = DE->getCXXRecordDecl(); 4610 if (!RD) 4611 return; 4612 CXXDeleteExpr *DelExpr = 4613 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr()); 4614 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS); 4615 OS << "->~" << RD->getName().str() << "()"; 4616 OS << " (Implicit destructor)\n"; 4617 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) { 4618 const CXXBaseSpecifier *BS = BE->getBaseSpecifier(); 4619 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; 4620 OS << " (Base object destructor)\n"; 4621 4622 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) { 4623 const FieldDecl *FD = ME->getFieldDecl(); 4624 const Type *T = FD->getType()->getBaseElementTypeUnsafe(); 4625 OS << "this->" << FD->getName(); 4626 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; 4627 OS << " (Member object destructor)\n"; 4628 4629 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) { 4630 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr(); 4631 OS << "~"; 4632 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts())); 4633 OS << "() (Temporary object destructor)\n"; 4634 } 4635 } 4636 4637 static void print_block(raw_ostream &OS, const CFG* cfg, 4638 const CFGBlock &B, 4639 StmtPrinterHelper &Helper, bool print_edges, 4640 bool ShowColors) { 4641 4642 Helper.setBlockID(B.getBlockID()); 4643 4644 // Print the header. 4645 if (ShowColors) 4646 OS.changeColor(raw_ostream::YELLOW, true); 4647 4648 OS << "\n [B" << B.getBlockID(); 4649 4650 if (&B == &cfg->getEntry()) 4651 OS << " (ENTRY)]\n"; 4652 else if (&B == &cfg->getExit()) 4653 OS << " (EXIT)]\n"; 4654 else if (&B == cfg->getIndirectGotoBlock()) 4655 OS << " (INDIRECT GOTO DISPATCH)]\n"; 4656 else if (B.hasNoReturnElement()) 4657 OS << " (NORETURN)]\n"; 4658 else 4659 OS << "]\n"; 4660 4661 if (ShowColors) 4662 OS.resetColor(); 4663 4664 // Print the label of this block. 4665 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) { 4666 4667 if (print_edges) 4668 OS << " "; 4669 4670 if (LabelStmt *L = dyn_cast<LabelStmt>(Label)) 4671 OS << L->getName(); 4672 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 4673 OS << "case "; 4674 if (C->getLHS()) 4675 C->getLHS()->printPretty(OS, &Helper, 4676 PrintingPolicy(Helper.getLangOpts())); 4677 if (C->getRHS()) { 4678 OS << " ... "; 4679 C->getRHS()->printPretty(OS, &Helper, 4680 PrintingPolicy(Helper.getLangOpts())); 4681 } 4682 } else if (isa<DefaultStmt>(Label)) 4683 OS << "default"; 4684 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 4685 OS << "catch ("; 4686 if (CS->getExceptionDecl()) 4687 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()), 4688 0); 4689 else 4690 OS << "..."; 4691 OS << ")"; 4692 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) { 4693 OS << "__except ("; 4694 ES->getFilterExpr()->printPretty(OS, &Helper, 4695 PrintingPolicy(Helper.getLangOpts()), 0); 4696 OS << ")"; 4697 } else 4698 llvm_unreachable("Invalid label statement in CFGBlock."); 4699 4700 OS << ":\n"; 4701 } 4702 4703 // Iterate through the statements in the block and print them. 4704 unsigned j = 1; 4705 4706 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 4707 I != E ; ++I, ++j ) { 4708 4709 // Print the statement # in the basic block and the statement itself. 4710 if (print_edges) 4711 OS << " "; 4712 4713 OS << llvm::format("%3d", j) << ": "; 4714 4715 Helper.setStmtID(j); 4716 4717 print_elem(OS, Helper, *I); 4718 } 4719 4720 // Print the terminator of this block. 4721 if (B.getTerminator()) { 4722 if (ShowColors) 4723 OS.changeColor(raw_ostream::GREEN); 4724 4725 OS << " T: "; 4726 4727 Helper.setBlockID(-1); 4728 4729 PrintingPolicy PP(Helper.getLangOpts()); 4730 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP); 4731 TPrinter.print(B.getTerminator()); 4732 OS << '\n'; 4733 4734 if (ShowColors) 4735 OS.resetColor(); 4736 } 4737 4738 if (print_edges) { 4739 // Print the predecessors of this block. 4740 if (!B.pred_empty()) { 4741 const raw_ostream::Colors Color = raw_ostream::BLUE; 4742 if (ShowColors) 4743 OS.changeColor(Color); 4744 OS << " Preds " ; 4745 if (ShowColors) 4746 OS.resetColor(); 4747 OS << '(' << B.pred_size() << "):"; 4748 unsigned i = 0; 4749 4750 if (ShowColors) 4751 OS.changeColor(Color); 4752 4753 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 4754 I != E; ++I, ++i) { 4755 4756 if (i % 10 == 8) 4757 OS << "\n "; 4758 4759 CFGBlock *B = *I; 4760 bool Reachable = true; 4761 if (!B) { 4762 Reachable = false; 4763 B = I->getPossiblyUnreachableBlock(); 4764 } 4765 4766 OS << " B" << B->getBlockID(); 4767 if (!Reachable) 4768 OS << "(Unreachable)"; 4769 } 4770 4771 if (ShowColors) 4772 OS.resetColor(); 4773 4774 OS << '\n'; 4775 } 4776 4777 // Print the successors of this block. 4778 if (!B.succ_empty()) { 4779 const raw_ostream::Colors Color = raw_ostream::MAGENTA; 4780 if (ShowColors) 4781 OS.changeColor(Color); 4782 OS << " Succs "; 4783 if (ShowColors) 4784 OS.resetColor(); 4785 OS << '(' << B.succ_size() << "):"; 4786 unsigned i = 0; 4787 4788 if (ShowColors) 4789 OS.changeColor(Color); 4790 4791 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 4792 I != E; ++I, ++i) { 4793 4794 if (i % 10 == 8) 4795 OS << "\n "; 4796 4797 CFGBlock *B = *I; 4798 4799 bool Reachable = true; 4800 if (!B) { 4801 Reachable = false; 4802 B = I->getPossiblyUnreachableBlock(); 4803 } 4804 4805 if (B) { 4806 OS << " B" << B->getBlockID(); 4807 if (!Reachable) 4808 OS << "(Unreachable)"; 4809 } 4810 else { 4811 OS << " NULL"; 4812 } 4813 } 4814 4815 if (ShowColors) 4816 OS.resetColor(); 4817 OS << '\n'; 4818 } 4819 } 4820 } 4821 4822 4823 /// dump - A simple pretty printer of a CFG that outputs to stderr. 4824 void CFG::dump(const LangOptions &LO, bool ShowColors) const { 4825 print(llvm::errs(), LO, ShowColors); 4826 } 4827 4828 /// print - A simple pretty printer of a CFG that outputs to an ostream. 4829 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const { 4830 StmtPrinterHelper Helper(this, LO); 4831 4832 // Print the entry block. 4833 print_block(OS, this, getEntry(), Helper, true, ShowColors); 4834 4835 // Iterate through the CFGBlocks and print them one by one. 4836 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 4837 // Skip the entry block, because we already printed it. 4838 if (&(**I) == &getEntry() || &(**I) == &getExit()) 4839 continue; 4840 4841 print_block(OS, this, **I, Helper, true, ShowColors); 4842 } 4843 4844 // Print the exit block. 4845 print_block(OS, this, getExit(), Helper, true, ShowColors); 4846 OS << '\n'; 4847 OS.flush(); 4848 } 4849 4850 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 4851 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO, 4852 bool ShowColors) const { 4853 print(llvm::errs(), cfg, LO, ShowColors); 4854 } 4855 4856 LLVM_DUMP_METHOD void CFGBlock::dump() const { 4857 dump(getParent(), LangOptions(), false); 4858 } 4859 4860 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 4861 /// Generally this will only be called from CFG::print. 4862 void CFGBlock::print(raw_ostream &OS, const CFG* cfg, 4863 const LangOptions &LO, bool ShowColors) const { 4864 StmtPrinterHelper Helper(cfg, LO); 4865 print_block(OS, cfg, *this, Helper, true, ShowColors); 4866 OS << '\n'; 4867 } 4868 4869 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 4870 void CFGBlock::printTerminator(raw_ostream &OS, 4871 const LangOptions &LO) const { 4872 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO)); 4873 TPrinter.print(getTerminator()); 4874 } 4875 4876 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) { 4877 Stmt *Terminator = this->Terminator; 4878 if (!Terminator) 4879 return nullptr; 4880 4881 Expr *E = nullptr; 4882 4883 switch (Terminator->getStmtClass()) { 4884 default: 4885 break; 4886 4887 case Stmt::CXXForRangeStmtClass: 4888 E = cast<CXXForRangeStmt>(Terminator)->getCond(); 4889 break; 4890 4891 case Stmt::ForStmtClass: 4892 E = cast<ForStmt>(Terminator)->getCond(); 4893 break; 4894 4895 case Stmt::WhileStmtClass: 4896 E = cast<WhileStmt>(Terminator)->getCond(); 4897 break; 4898 4899 case Stmt::DoStmtClass: 4900 E = cast<DoStmt>(Terminator)->getCond(); 4901 break; 4902 4903 case Stmt::IfStmtClass: 4904 E = cast<IfStmt>(Terminator)->getCond(); 4905 break; 4906 4907 case Stmt::ChooseExprClass: 4908 E = cast<ChooseExpr>(Terminator)->getCond(); 4909 break; 4910 4911 case Stmt::IndirectGotoStmtClass: 4912 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 4913 break; 4914 4915 case Stmt::SwitchStmtClass: 4916 E = cast<SwitchStmt>(Terminator)->getCond(); 4917 break; 4918 4919 case Stmt::BinaryConditionalOperatorClass: 4920 E = cast<BinaryConditionalOperator>(Terminator)->getCond(); 4921 break; 4922 4923 case Stmt::ConditionalOperatorClass: 4924 E = cast<ConditionalOperator>(Terminator)->getCond(); 4925 break; 4926 4927 case Stmt::BinaryOperatorClass: // '&&' and '||' 4928 E = cast<BinaryOperator>(Terminator)->getLHS(); 4929 break; 4930 4931 case Stmt::ObjCForCollectionStmtClass: 4932 return Terminator; 4933 } 4934 4935 if (!StripParens) 4936 return E; 4937 4938 return E ? E->IgnoreParens() : nullptr; 4939 } 4940 4941 //===----------------------------------------------------------------------===// 4942 // CFG Graphviz Visualization 4943 //===----------------------------------------------------------------------===// 4944 4945 4946 #ifndef NDEBUG 4947 static StmtPrinterHelper* GraphHelper; 4948 #endif 4949 4950 void CFG::viewCFG(const LangOptions &LO) const { 4951 #ifndef NDEBUG 4952 StmtPrinterHelper H(this, LO); 4953 GraphHelper = &H; 4954 llvm::ViewGraph(this,"CFG"); 4955 GraphHelper = nullptr; 4956 #endif 4957 } 4958 4959 namespace llvm { 4960 template<> 4961 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 4962 4963 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 4964 4965 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) { 4966 4967 #ifndef NDEBUG 4968 std::string OutSStr; 4969 llvm::raw_string_ostream Out(OutSStr); 4970 print_block(Out,Graph, *Node, *GraphHelper, false, false); 4971 std::string& OutStr = Out.str(); 4972 4973 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 4974 4975 // Process string output to make it nicer... 4976 for (unsigned i = 0; i != OutStr.length(); ++i) 4977 if (OutStr[i] == '\n') { // Left justify 4978 OutStr[i] = '\\'; 4979 OutStr.insert(OutStr.begin()+i+1, 'l'); 4980 } 4981 4982 return OutStr; 4983 #else 4984 return ""; 4985 #endif 4986 } 4987 }; 4988 } // end namespace llvm 4989