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