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