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 llvm::append_range(childrenBuf, S->children()); 445 446 // This needs to be done *after* childrenBuf has been populated. 447 children = childrenBuf; 448 } 449 450 namespace { 451 452 /// CFGBuilder - This class implements CFG construction from an AST. 453 /// The builder is stateful: an instance of the builder should be used to only 454 /// construct a single CFG. 455 /// 456 /// Example usage: 457 /// 458 /// CFGBuilder builder; 459 /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1); 460 /// 461 /// CFG construction is done via a recursive walk of an AST. We actually parse 462 /// the AST in reverse order so that the successor of a basic block is 463 /// constructed prior to its predecessor. This allows us to nicely capture 464 /// implicit fall-throughs without extra basic blocks. 465 class CFGBuilder { 466 using JumpTarget = BlockScopePosPair; 467 using JumpSource = BlockScopePosPair; 468 469 ASTContext *Context; 470 std::unique_ptr<CFG> cfg; 471 472 // Current block. 473 CFGBlock *Block = nullptr; 474 475 // Block after the current block. 476 CFGBlock *Succ = nullptr; 477 478 JumpTarget ContinueJumpTarget; 479 JumpTarget BreakJumpTarget; 480 JumpTarget SEHLeaveJumpTarget; 481 CFGBlock *SwitchTerminatedBlock = nullptr; 482 CFGBlock *DefaultCaseBlock = nullptr; 483 484 // This can point to either a C++ try, an Objective-C @try, or an SEH __try. 485 // try and @try can be mixed and generally work the same. 486 // The frontend forbids mixing SEH __try with either try or @try. 487 // So having one for all three is enough. 488 CFGBlock *TryTerminatedBlock = nullptr; 489 490 // Current position in local scope. 491 LocalScope::const_iterator ScopePos; 492 493 // LabelMap records the mapping from Label expressions to their jump targets. 494 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>; 495 LabelMapTy LabelMap; 496 497 // A list of blocks that end with a "goto" that must be backpatched to their 498 // resolved targets upon completion of CFG construction. 499 using BackpatchBlocksTy = std::vector<JumpSource>; 500 BackpatchBlocksTy BackpatchBlocks; 501 502 // A list of labels whose address has been taken (for indirect gotos). 503 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>; 504 LabelSetTy AddressTakenLabels; 505 506 // Information about the currently visited C++ object construction site. 507 // This is set in the construction trigger and read when the constructor 508 // or a function that returns an object by value is being visited. 509 llvm::DenseMap<Expr *, const ConstructionContextLayer *> 510 ConstructionContextMap; 511 512 using DeclsWithEndedScopeSetTy = llvm::SmallSetVector<VarDecl *, 16>; 513 DeclsWithEndedScopeSetTy DeclsWithEndedScope; 514 515 bool badCFG = false; 516 const CFG::BuildOptions &BuildOpts; 517 518 // State to track for building switch statements. 519 bool switchExclusivelyCovered = false; 520 Expr::EvalResult *switchCond = nullptr; 521 522 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr; 523 const Stmt *lastLookup = nullptr; 524 525 // Caches boolean evaluations of expressions to avoid multiple re-evaluations 526 // during construction of branches for chained logical operators. 527 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>; 528 CachedBoolEvalsTy CachedBoolEvals; 529 530 public: 531 explicit CFGBuilder(ASTContext *astContext, 532 const CFG::BuildOptions &buildOpts) 533 : Context(astContext), cfg(new CFG()), BuildOpts(buildOpts) {} 534 535 // buildCFG - Used by external clients to construct the CFG. 536 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement); 537 538 bool alwaysAdd(const Stmt *stmt); 539 540 private: 541 // Visitors to walk an AST and construct the CFG. 542 CFGBlock *VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc); 543 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc); 544 CFGBlock *VisitAttributedStmt(AttributedStmt *A, AddStmtChoice asc); 545 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc); 546 CFGBlock *VisitBreakStmt(BreakStmt *B); 547 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc); 548 CFGBlock *VisitCaseStmt(CaseStmt *C); 549 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc); 550 CFGBlock *VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed); 551 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C, 552 AddStmtChoice asc); 553 CFGBlock *VisitContinueStmt(ContinueStmt *C); 554 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 555 AddStmtChoice asc); 556 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S); 557 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc); 558 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc); 559 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc); 560 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S); 561 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 562 AddStmtChoice asc); 563 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 564 AddStmtChoice asc); 565 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T); 566 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S); 567 CFGBlock *VisitDeclStmt(DeclStmt *DS); 568 CFGBlock *VisitDeclSubExpr(DeclStmt *DS); 569 CFGBlock *VisitDefaultStmt(DefaultStmt *D); 570 CFGBlock *VisitDoStmt(DoStmt *D); 571 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, 572 AddStmtChoice asc, bool ExternallyDestructed); 573 CFGBlock *VisitForStmt(ForStmt *F); 574 CFGBlock *VisitGotoStmt(GotoStmt *G); 575 CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc); 576 CFGBlock *VisitIfStmt(IfStmt *I); 577 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc); 578 CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc); 579 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I); 580 CFGBlock *VisitLabelStmt(LabelStmt *L); 581 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc); 582 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc); 583 CFGBlock *VisitLogicalOperator(BinaryOperator *B); 584 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B, 585 Stmt *Term, 586 CFGBlock *TrueBlock, 587 CFGBlock *FalseBlock); 588 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE, 589 AddStmtChoice asc); 590 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc); 591 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 592 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 593 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 594 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); 595 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); 596 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 597 CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc); 598 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E); 599 CFGBlock *VisitReturnStmt(Stmt *S); 600 CFGBlock *VisitCoroutineSuspendExpr(CoroutineSuspendExpr *S, 601 AddStmtChoice asc); 602 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S); 603 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S); 604 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S); 605 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S); 606 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc); 607 CFGBlock *VisitSwitchStmt(SwitchStmt *S); 608 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 609 AddStmtChoice asc); 610 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc); 611 CFGBlock *VisitWhileStmt(WhileStmt *W); 612 CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc); 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 1825 /// addAutomaticObjDtors - Add to current block automatic objects destructors 1826 /// for objects in range of local scope positions. Use S as trigger statement 1827 /// for destructors. 1828 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B, 1829 LocalScope::const_iterator E, Stmt *S) { 1830 if (!BuildOpts.AddImplicitDtors) 1831 return; 1832 1833 if (B == E) 1834 return; 1835 1836 // We need to append the destructors in reverse order, but any one of them 1837 // may be a no-return destructor which changes the CFG. As a result, buffer 1838 // this sequence up and replay them in reverse order when appending onto the 1839 // CFGBlock(s). 1840 SmallVector<VarDecl*, 10> Decls; 1841 Decls.reserve(B.distance(E)); 1842 for (LocalScope::const_iterator I = B; I != E; ++I) 1843 Decls.push_back(*I); 1844 1845 for (VarDecl *VD : llvm::reverse(Decls)) { 1846 if (hasTrivialDestructor(VD)) { 1847 // If AddScopes is enabled and *I is a first variable in a scope, add a 1848 // ScopeEnd marker in a Block. 1849 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD)) { 1850 autoCreateBlock(); 1851 appendScopeEnd(Block, VD, S); 1852 } 1853 continue; 1854 } 1855 // If this destructor is marked as a no-return destructor, we need to 1856 // create a new block for the destructor which does not have as a successor 1857 // anything built thus far: control won't flow out of this block. 1858 QualType Ty = VD->getType(); 1859 if (Ty->isReferenceType()) { 1860 Ty = getReferenceInitTemporaryType(VD->getInit()); 1861 } 1862 Ty = Context->getBaseElementType(Ty); 1863 1864 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn()) 1865 Block = createNoReturnBlock(); 1866 else 1867 autoCreateBlock(); 1868 1869 // Add ScopeEnd just after automatic obj destructor. 1870 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD)) 1871 appendScopeEnd(Block, VD, S); 1872 appendAutomaticObjDtor(Block, VD, S); 1873 } 1874 } 1875 1876 /// addImplicitDtorsForDestructor - Add implicit destructors generated for 1877 /// base and member objects in destructor. 1878 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) { 1879 assert(BuildOpts.AddImplicitDtors && 1880 "Can be called only when dtors should be added"); 1881 const CXXRecordDecl *RD = DD->getParent(); 1882 1883 // At the end destroy virtual base objects. 1884 for (const auto &VI : RD->vbases()) { 1885 // TODO: Add a VirtualBaseBranch to see if the most derived class 1886 // (which is different from the current class) is responsible for 1887 // destroying them. 1888 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl(); 1889 if (!CD->hasTrivialDestructor()) { 1890 autoCreateBlock(); 1891 appendBaseDtor(Block, &VI); 1892 } 1893 } 1894 1895 // Before virtual bases destroy direct base objects. 1896 for (const auto &BI : RD->bases()) { 1897 if (!BI.isVirtual()) { 1898 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl(); 1899 if (!CD->hasTrivialDestructor()) { 1900 autoCreateBlock(); 1901 appendBaseDtor(Block, &BI); 1902 } 1903 } 1904 } 1905 1906 // First destroy member objects. 1907 for (auto *FI : RD->fields()) { 1908 // Check for constant size array. Set type to array element type. 1909 QualType QT = FI->getType(); 1910 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 1911 if (AT->getSize() == 0) 1912 continue; 1913 QT = AT->getElementType(); 1914 } 1915 1916 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 1917 if (!CD->hasTrivialDestructor()) { 1918 autoCreateBlock(); 1919 appendMemberDtor(Block, FI); 1920 } 1921 } 1922 } 1923 1924 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either 1925 /// way return valid LocalScope object. 1926 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) { 1927 if (Scope) 1928 return Scope; 1929 llvm::BumpPtrAllocator &alloc = cfg->getAllocator(); 1930 return new (alloc.Allocate<LocalScope>()) 1931 LocalScope(BumpVectorContext(alloc), ScopePos); 1932 } 1933 1934 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement 1935 /// that should create implicit scope (e.g. if/else substatements). 1936 void CFGBuilder::addLocalScopeForStmt(Stmt *S) { 1937 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime && 1938 !BuildOpts.AddScopes) 1939 return; 1940 1941 LocalScope *Scope = nullptr; 1942 1943 // For compound statement we will be creating explicit scope. 1944 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { 1945 for (auto *BI : CS->body()) { 1946 Stmt *SI = BI->stripLabelLikeStatements(); 1947 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI)) 1948 Scope = addLocalScopeForDeclStmt(DS, Scope); 1949 } 1950 return; 1951 } 1952 1953 // For any other statement scope will be implicit and as such will be 1954 // interesting only for DeclStmt. 1955 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements())) 1956 addLocalScopeForDeclStmt(DS); 1957 } 1958 1959 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will 1960 /// reuse Scope if not NULL. 1961 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS, 1962 LocalScope* Scope) { 1963 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime && 1964 !BuildOpts.AddScopes) 1965 return Scope; 1966 1967 for (auto *DI : DS->decls()) 1968 if (VarDecl *VD = dyn_cast<VarDecl>(DI)) 1969 Scope = addLocalScopeForVarDecl(VD, Scope); 1970 return Scope; 1971 } 1972 1973 bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) { 1974 // Check for const references bound to temporary. Set type to pointee. 1975 QualType QT = VD->getType(); 1976 if (QT->isReferenceType()) { 1977 // Attempt to determine whether this declaration lifetime-extends a 1978 // temporary. 1979 // 1980 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend 1981 // temporaries, and a single declaration can extend multiple temporaries. 1982 // We should look at the storage duration on each nested 1983 // MaterializeTemporaryExpr instead. 1984 1985 const Expr *Init = VD->getInit(); 1986 if (!Init) { 1987 // Probably an exception catch-by-reference variable. 1988 // FIXME: It doesn't really mean that the object has a trivial destructor. 1989 // Also are there other cases? 1990 return true; 1991 } 1992 1993 // Lifetime-extending a temporary? 1994 bool FoundMTE = false; 1995 QT = getReferenceInitTemporaryType(Init, &FoundMTE); 1996 if (!FoundMTE) 1997 return true; 1998 } 1999 2000 // Check for constant size array. Set type to array element type. 2001 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 2002 if (AT->getSize() == 0) 2003 return true; 2004 QT = AT->getElementType(); 2005 } 2006 2007 // Check if type is a C++ class with non-trivial destructor. 2008 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 2009 return !CD->hasDefinition() || CD->hasTrivialDestructor(); 2010 return true; 2011 } 2012 2013 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will 2014 /// create add scope for automatic objects and temporary objects bound to 2015 /// const reference. Will reuse Scope if not NULL. 2016 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD, 2017 LocalScope* Scope) { 2018 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) && 2019 "AddImplicitDtors and AddLifetime cannot be used at the same time"); 2020 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime && 2021 !BuildOpts.AddScopes) 2022 return Scope; 2023 2024 // Check if variable is local. 2025 if (!VD->hasLocalStorage()) 2026 return Scope; 2027 2028 if (BuildOpts.AddImplicitDtors) { 2029 if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) { 2030 // Add the variable to scope 2031 Scope = createOrReuseLocalScope(Scope); 2032 Scope->addVar(VD); 2033 ScopePos = Scope->begin(); 2034 } 2035 return Scope; 2036 } 2037 2038 assert(BuildOpts.AddLifetime); 2039 // Add the variable to scope 2040 Scope = createOrReuseLocalScope(Scope); 2041 Scope->addVar(VD); 2042 ScopePos = Scope->begin(); 2043 return Scope; 2044 } 2045 2046 /// addLocalScopeAndDtors - For given statement add local scope for it and 2047 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL. 2048 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) { 2049 LocalScope::const_iterator scopeBeginPos = ScopePos; 2050 addLocalScopeForStmt(S); 2051 addAutomaticObjHandling(ScopePos, scopeBeginPos, S); 2052 } 2053 2054 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for 2055 /// variables with automatic storage duration to CFGBlock's elements vector. 2056 /// Elements will be prepended to physical beginning of the vector which 2057 /// happens to be logical end. Use blocks terminator as statement that specifies 2058 /// destructors call site. 2059 /// FIXME: This mechanism for adding automatic destructors doesn't handle 2060 /// no-return destructors properly. 2061 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 2062 LocalScope::const_iterator B, LocalScope::const_iterator E) { 2063 if (!BuildOpts.AddImplicitDtors) 2064 return; 2065 BumpVectorContext &C = cfg->getBumpVectorContext(); 2066 CFGBlock::iterator InsertPos 2067 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C); 2068 for (LocalScope::const_iterator I = B; I != E; ++I) 2069 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I, 2070 Blk->getTerminatorStmt()); 2071 } 2072 2073 /// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for 2074 /// variables with automatic storage duration to CFGBlock's elements vector. 2075 /// Elements will be prepended to physical beginning of the vector which 2076 /// happens to be logical end. Use blocks terminator as statement that specifies 2077 /// where lifetime ends. 2078 void CFGBuilder::prependAutomaticObjLifetimeWithTerminator( 2079 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) { 2080 if (!BuildOpts.AddLifetime) 2081 return; 2082 BumpVectorContext &C = cfg->getBumpVectorContext(); 2083 CFGBlock::iterator InsertPos = 2084 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C); 2085 for (LocalScope::const_iterator I = B; I != E; ++I) { 2086 InsertPos = 2087 Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminatorStmt()); 2088 } 2089 } 2090 2091 /// prependAutomaticObjScopeEndWithTerminator - Prepend scope end CFGElements for 2092 /// variables with automatic storage duration to CFGBlock's elements vector. 2093 /// Elements will be prepended to physical beginning of the vector which 2094 /// happens to be logical end. Use blocks terminator as statement that specifies 2095 /// where scope ends. 2096 const VarDecl * 2097 CFGBuilder::prependAutomaticObjScopeEndWithTerminator( 2098 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) { 2099 if (!BuildOpts.AddScopes) 2100 return nullptr; 2101 BumpVectorContext &C = cfg->getBumpVectorContext(); 2102 CFGBlock::iterator InsertPos = 2103 Blk->beginScopeEndInsert(Blk->end(), 1, C); 2104 LocalScope::const_iterator PlaceToInsert = B; 2105 for (LocalScope::const_iterator I = B; I != E; ++I) 2106 PlaceToInsert = I; 2107 Blk->insertScopeEnd(InsertPos, *PlaceToInsert, Blk->getTerminatorStmt()); 2108 return *PlaceToInsert; 2109 } 2110 2111 /// Visit - Walk the subtree of a statement and add extra 2112 /// blocks for ternary operators, &&, and ||. We also process "," and 2113 /// DeclStmts (which may contain nested control-flow). 2114 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc, 2115 bool ExternallyDestructed) { 2116 if (!S) { 2117 badCFG = true; 2118 return nullptr; 2119 } 2120 2121 if (Expr *E = dyn_cast<Expr>(S)) 2122 S = E->IgnoreParens(); 2123 2124 if (Context->getLangOpts().OpenMP) 2125 if (auto *D = dyn_cast<OMPExecutableDirective>(S)) 2126 return VisitOMPExecutableDirective(D, asc); 2127 2128 switch (S->getStmtClass()) { 2129 default: 2130 return VisitStmt(S, asc); 2131 2132 case Stmt::ImplicitValueInitExprClass: 2133 if (BuildOpts.OmitImplicitValueInitializers) 2134 return Block; 2135 return VisitStmt(S, asc); 2136 2137 case Stmt::InitListExprClass: 2138 return VisitInitListExpr(cast<InitListExpr>(S), asc); 2139 2140 case Stmt::AttributedStmtClass: 2141 return VisitAttributedStmt(cast<AttributedStmt>(S), asc); 2142 2143 case Stmt::AddrLabelExprClass: 2144 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc); 2145 2146 case Stmt::BinaryConditionalOperatorClass: 2147 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc); 2148 2149 case Stmt::BinaryOperatorClass: 2150 return VisitBinaryOperator(cast<BinaryOperator>(S), asc); 2151 2152 case Stmt::BlockExprClass: 2153 return VisitBlockExpr(cast<BlockExpr>(S), asc); 2154 2155 case Stmt::BreakStmtClass: 2156 return VisitBreakStmt(cast<BreakStmt>(S)); 2157 2158 case Stmt::CallExprClass: 2159 case Stmt::CXXOperatorCallExprClass: 2160 case Stmt::CXXMemberCallExprClass: 2161 case Stmt::UserDefinedLiteralClass: 2162 return VisitCallExpr(cast<CallExpr>(S), asc); 2163 2164 case Stmt::CaseStmtClass: 2165 return VisitCaseStmt(cast<CaseStmt>(S)); 2166 2167 case Stmt::ChooseExprClass: 2168 return VisitChooseExpr(cast<ChooseExpr>(S), asc); 2169 2170 case Stmt::CompoundStmtClass: 2171 return VisitCompoundStmt(cast<CompoundStmt>(S), ExternallyDestructed); 2172 2173 case Stmt::ConditionalOperatorClass: 2174 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc); 2175 2176 case Stmt::ContinueStmtClass: 2177 return VisitContinueStmt(cast<ContinueStmt>(S)); 2178 2179 case Stmt::CXXCatchStmtClass: 2180 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S)); 2181 2182 case Stmt::ExprWithCleanupsClass: 2183 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), 2184 asc, ExternallyDestructed); 2185 2186 case Stmt::CXXDefaultArgExprClass: 2187 case Stmt::CXXDefaultInitExprClass: 2188 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the 2189 // called function's declaration, not by the caller. If we simply add 2190 // this expression to the CFG, we could end up with the same Expr 2191 // appearing multiple times. 2192 // PR13385 / <rdar://problem/12156507> 2193 // 2194 // It's likewise possible for multiple CXXDefaultInitExprs for the same 2195 // expression to be used in the same function (through aggregate 2196 // initialization). 2197 return VisitStmt(S, asc); 2198 2199 case Stmt::CXXBindTemporaryExprClass: 2200 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc); 2201 2202 case Stmt::CXXConstructExprClass: 2203 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc); 2204 2205 case Stmt::CXXNewExprClass: 2206 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc); 2207 2208 case Stmt::CXXDeleteExprClass: 2209 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc); 2210 2211 case Stmt::CXXFunctionalCastExprClass: 2212 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc); 2213 2214 case Stmt::CXXTemporaryObjectExprClass: 2215 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc); 2216 2217 case Stmt::CXXThrowExprClass: 2218 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S)); 2219 2220 case Stmt::CXXTryStmtClass: 2221 return VisitCXXTryStmt(cast<CXXTryStmt>(S)); 2222 2223 case Stmt::CXXForRangeStmtClass: 2224 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S)); 2225 2226 case Stmt::DeclStmtClass: 2227 return VisitDeclStmt(cast<DeclStmt>(S)); 2228 2229 case Stmt::DefaultStmtClass: 2230 return VisitDefaultStmt(cast<DefaultStmt>(S)); 2231 2232 case Stmt::DoStmtClass: 2233 return VisitDoStmt(cast<DoStmt>(S)); 2234 2235 case Stmt::ForStmtClass: 2236 return VisitForStmt(cast<ForStmt>(S)); 2237 2238 case Stmt::GotoStmtClass: 2239 return VisitGotoStmt(cast<GotoStmt>(S)); 2240 2241 case Stmt::GCCAsmStmtClass: 2242 return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc); 2243 2244 case Stmt::IfStmtClass: 2245 return VisitIfStmt(cast<IfStmt>(S)); 2246 2247 case Stmt::ImplicitCastExprClass: 2248 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc); 2249 2250 case Stmt::ConstantExprClass: 2251 return VisitConstantExpr(cast<ConstantExpr>(S), asc); 2252 2253 case Stmt::IndirectGotoStmtClass: 2254 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S)); 2255 2256 case Stmt::LabelStmtClass: 2257 return VisitLabelStmt(cast<LabelStmt>(S)); 2258 2259 case Stmt::LambdaExprClass: 2260 return VisitLambdaExpr(cast<LambdaExpr>(S), asc); 2261 2262 case Stmt::MaterializeTemporaryExprClass: 2263 return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S), 2264 asc); 2265 2266 case Stmt::MemberExprClass: 2267 return VisitMemberExpr(cast<MemberExpr>(S), asc); 2268 2269 case Stmt::NullStmtClass: 2270 return Block; 2271 2272 case Stmt::ObjCAtCatchStmtClass: 2273 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S)); 2274 2275 case Stmt::ObjCAutoreleasePoolStmtClass: 2276 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S)); 2277 2278 case Stmt::ObjCAtSynchronizedStmtClass: 2279 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S)); 2280 2281 case Stmt::ObjCAtThrowStmtClass: 2282 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S)); 2283 2284 case Stmt::ObjCAtTryStmtClass: 2285 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S)); 2286 2287 case Stmt::ObjCForCollectionStmtClass: 2288 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); 2289 2290 case Stmt::ObjCMessageExprClass: 2291 return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc); 2292 2293 case Stmt::OpaqueValueExprClass: 2294 return Block; 2295 2296 case Stmt::PseudoObjectExprClass: 2297 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S)); 2298 2299 case Stmt::ReturnStmtClass: 2300 case Stmt::CoreturnStmtClass: 2301 return VisitReturnStmt(S); 2302 2303 case Stmt::CoyieldExprClass: 2304 case Stmt::CoawaitExprClass: 2305 return VisitCoroutineSuspendExpr(cast<CoroutineSuspendExpr>(S), asc); 2306 2307 case Stmt::SEHExceptStmtClass: 2308 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S)); 2309 2310 case Stmt::SEHFinallyStmtClass: 2311 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S)); 2312 2313 case Stmt::SEHLeaveStmtClass: 2314 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S)); 2315 2316 case Stmt::SEHTryStmtClass: 2317 return VisitSEHTryStmt(cast<SEHTryStmt>(S)); 2318 2319 case Stmt::UnaryExprOrTypeTraitExprClass: 2320 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 2321 asc); 2322 2323 case Stmt::StmtExprClass: 2324 return VisitStmtExpr(cast<StmtExpr>(S), asc); 2325 2326 case Stmt::SwitchStmtClass: 2327 return VisitSwitchStmt(cast<SwitchStmt>(S)); 2328 2329 case Stmt::UnaryOperatorClass: 2330 return VisitUnaryOperator(cast<UnaryOperator>(S), asc); 2331 2332 case Stmt::WhileStmtClass: 2333 return VisitWhileStmt(cast<WhileStmt>(S)); 2334 2335 case Stmt::ArrayInitLoopExprClass: 2336 return VisitArrayInitLoopExpr(cast<ArrayInitLoopExpr>(S), asc); 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 3151 CoreturnStmt *CRS = cast<CoreturnStmt>(S); 3152 auto *B = Block; 3153 if (CFGBlock *R = Visit(CRS->getPromiseCall())) 3154 B = R; 3155 3156 if (Expr *RV = CRS->getOperand()) 3157 if (RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) 3158 // A non-initlist void expression. 3159 if (CFGBlock *R = Visit(RV)) 3160 B = R; 3161 3162 return B; 3163 } 3164 3165 CFGBlock *CFGBuilder::VisitCoroutineSuspendExpr(CoroutineSuspendExpr *E, 3166 AddStmtChoice asc) { 3167 // We're modelling the pre-coro-xform CFG. Thus just evalate the various 3168 // active components of the co_await or co_yield. Note we do not model the 3169 // edge from the builtin_suspend to the exit node. 3170 if (asc.alwaysAdd(*this, E)) { 3171 autoCreateBlock(); 3172 appendStmt(Block, E); 3173 } 3174 CFGBlock *B = Block; 3175 if (auto *R = Visit(E->getResumeExpr())) 3176 B = R; 3177 if (auto *R = Visit(E->getSuspendExpr())) 3178 B = R; 3179 if (auto *R = Visit(E->getReadyExpr())) 3180 B = R; 3181 if (auto *R = Visit(E->getCommonExpr())) 3182 B = R; 3183 return B; 3184 } 3185 3186 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) { 3187 // SEHExceptStmt are treated like labels, so they are the first statement in a 3188 // block. 3189 3190 // Save local scope position because in case of exception variable ScopePos 3191 // won't be restored when traversing AST. 3192 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3193 3194 addStmt(ES->getBlock()); 3195 CFGBlock *SEHExceptBlock = Block; 3196 if (!SEHExceptBlock) 3197 SEHExceptBlock = createBlock(); 3198 3199 appendStmt(SEHExceptBlock, ES); 3200 3201 // Also add the SEHExceptBlock as a label, like with regular labels. 3202 SEHExceptBlock->setLabel(ES); 3203 3204 // Bail out if the CFG is bad. 3205 if (badCFG) 3206 return nullptr; 3207 3208 // We set Block to NULL to allow lazy creation of a new block (if necessary). 3209 Block = nullptr; 3210 3211 return SEHExceptBlock; 3212 } 3213 3214 CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) { 3215 return VisitCompoundStmt(FS->getBlock(), /*ExternallyDestructed=*/false); 3216 } 3217 3218 CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) { 3219 // "__leave" is a control-flow statement. Thus we stop processing the current 3220 // block. 3221 if (badCFG) 3222 return nullptr; 3223 3224 // Now create a new block that ends with the __leave statement. 3225 Block = createBlock(false); 3226 Block->setTerminator(LS); 3227 3228 // If there is no target for the __leave, then we are looking at an incomplete 3229 // AST. This means that the CFG cannot be constructed. 3230 if (SEHLeaveJumpTarget.block) { 3231 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS); 3232 addSuccessor(Block, SEHLeaveJumpTarget.block); 3233 } else 3234 badCFG = true; 3235 3236 return Block; 3237 } 3238 3239 CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) { 3240 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop 3241 // processing the current block. 3242 CFGBlock *SEHTrySuccessor = nullptr; 3243 3244 if (Block) { 3245 if (badCFG) 3246 return nullptr; 3247 SEHTrySuccessor = Block; 3248 } else SEHTrySuccessor = Succ; 3249 3250 // FIXME: Implement __finally support. 3251 if (Terminator->getFinallyHandler()) 3252 return NYS(); 3253 3254 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock; 3255 3256 // Create a new block that will contain the __try statement. 3257 CFGBlock *NewTryTerminatedBlock = createBlock(false); 3258 3259 // Add the terminator in the __try block. 3260 NewTryTerminatedBlock->setTerminator(Terminator); 3261 3262 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) { 3263 // The code after the try is the implicit successor if there's an __except. 3264 Succ = SEHTrySuccessor; 3265 Block = nullptr; 3266 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except); 3267 if (!ExceptBlock) 3268 return nullptr; 3269 // Add this block to the list of successors for the block with the try 3270 // statement. 3271 addSuccessor(NewTryTerminatedBlock, ExceptBlock); 3272 } 3273 if (PrevSEHTryTerminatedBlock) 3274 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock); 3275 else 3276 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 3277 3278 // The code after the try is the implicit successor. 3279 Succ = SEHTrySuccessor; 3280 3281 // Save the current "__try" context. 3282 SaveAndRestore<CFGBlock *> SaveTry(TryTerminatedBlock, NewTryTerminatedBlock); 3283 cfg->addTryDispatchBlock(TryTerminatedBlock); 3284 3285 // Save the current value for the __leave target. 3286 // All __leaves should go to the code following the __try 3287 // (FIXME: or if the __try has a __finally, to the __finally.) 3288 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget); 3289 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos); 3290 3291 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body"); 3292 Block = nullptr; 3293 return addStmt(Terminator->getTryBlock()); 3294 } 3295 3296 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) { 3297 // Get the block of the labeled statement. Add it to our map. 3298 addStmt(L->getSubStmt()); 3299 CFGBlock *LabelBlock = Block; 3300 3301 if (!LabelBlock) // This can happen when the body is empty, i.e. 3302 LabelBlock = createBlock(); // scopes that only contains NullStmts. 3303 3304 assert(LabelMap.find(L->getDecl()) == LabelMap.end() && 3305 "label already in map"); 3306 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos); 3307 3308 // Labels partition blocks, so this is the end of the basic block we were 3309 // processing (L is the block's label). Because this is label (and we have 3310 // already processed the substatement) there is no extra control-flow to worry 3311 // about. 3312 LabelBlock->setLabel(L); 3313 if (badCFG) 3314 return nullptr; 3315 3316 // We set Block to NULL to allow lazy creation of a new block (if necessary). 3317 Block = nullptr; 3318 3319 // This block is now the implicit successor of other blocks. 3320 Succ = LabelBlock; 3321 3322 return LabelBlock; 3323 } 3324 3325 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) { 3326 CFGBlock *LastBlock = VisitNoRecurse(E, asc); 3327 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) { 3328 if (Expr *CopyExpr = CI.getCopyExpr()) { 3329 CFGBlock *Tmp = Visit(CopyExpr); 3330 if (Tmp) 3331 LastBlock = Tmp; 3332 } 3333 } 3334 return LastBlock; 3335 } 3336 3337 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) { 3338 CFGBlock *LastBlock = VisitNoRecurse(E, asc); 3339 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(), 3340 et = E->capture_init_end(); it != et; ++it) { 3341 if (Expr *Init = *it) { 3342 CFGBlock *Tmp = Visit(Init); 3343 if (Tmp) 3344 LastBlock = Tmp; 3345 } 3346 } 3347 return LastBlock; 3348 } 3349 3350 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) { 3351 // Goto is a control-flow statement. Thus we stop processing the current 3352 // block and create a new one. 3353 3354 Block = createBlock(false); 3355 Block->setTerminator(G); 3356 3357 // If we already know the mapping to the label block add the successor now. 3358 LabelMapTy::iterator I = LabelMap.find(G->getLabel()); 3359 3360 if (I == LabelMap.end()) 3361 // We will need to backpatch this block later. 3362 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 3363 else { 3364 JumpTarget JT = I->second; 3365 addAutomaticObjHandling(ScopePos, JT.scopePosition, G); 3366 addSuccessor(Block, JT.block); 3367 } 3368 3369 return Block; 3370 } 3371 3372 CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) { 3373 // Goto is a control-flow statement. Thus we stop processing the current 3374 // block and create a new one. 3375 3376 if (!G->isAsmGoto()) 3377 return VisitStmt(G, asc); 3378 3379 if (Block) { 3380 Succ = Block; 3381 if (badCFG) 3382 return nullptr; 3383 } 3384 Block = createBlock(); 3385 Block->setTerminator(G); 3386 // We will backpatch this block later for all the labels. 3387 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 3388 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is 3389 // used to avoid adding "Succ" again. 3390 BackpatchBlocks.push_back(JumpSource(Succ, ScopePos)); 3391 return VisitChildren(G); 3392 } 3393 3394 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { 3395 CFGBlock *LoopSuccessor = nullptr; 3396 3397 // Save local scope position because in case of condition variable ScopePos 3398 // won't be restored when traversing AST. 3399 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3400 3401 // Create local scope for init statement and possible condition variable. 3402 // Add destructor for init statement and condition variable. 3403 // Store scope position for continue statement. 3404 if (Stmt *Init = F->getInit()) 3405 addLocalScopeForStmt(Init); 3406 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 3407 3408 if (VarDecl *VD = F->getConditionVariable()) 3409 addLocalScopeForVarDecl(VD); 3410 LocalScope::const_iterator ContinueScopePos = ScopePos; 3411 3412 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F); 3413 3414 addLoopExit(F); 3415 3416 // "for" is a control-flow statement. Thus we stop processing the current 3417 // block. 3418 if (Block) { 3419 if (badCFG) 3420 return nullptr; 3421 LoopSuccessor = Block; 3422 } else 3423 LoopSuccessor = Succ; 3424 3425 // Save the current value for the break targets. 3426 // All breaks should go to the code following the loop. 3427 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 3428 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 3429 3430 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr; 3431 3432 // Now create the loop body. 3433 { 3434 assert(F->getBody()); 3435 3436 // Save the current values for Block, Succ, continue and break targets. 3437 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 3438 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 3439 3440 // Create an empty block to represent the transition block for looping back 3441 // to the head of the loop. If we have increment code, it will 3442 // go in this block as well. 3443 Block = Succ = TransitionBlock = createBlock(false); 3444 TransitionBlock->setLoopTarget(F); 3445 3446 if (Stmt *I = F->getInc()) { 3447 // Generate increment code in its own basic block. This is the target of 3448 // continue statements. 3449 Succ = addStmt(I); 3450 } 3451 3452 // Finish up the increment (or empty) block if it hasn't been already. 3453 if (Block) { 3454 assert(Block == Succ); 3455 if (badCFG) 3456 return nullptr; 3457 Block = nullptr; 3458 } 3459 3460 // The starting block for the loop increment is the block that should 3461 // represent the 'loop target' for looping back to the start of the loop. 3462 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 3463 ContinueJumpTarget.block->setLoopTarget(F); 3464 3465 // Loop body should end with destructor of Condition variable (if any). 3466 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F); 3467 3468 // If body is not a compound statement create implicit scope 3469 // and add destructors. 3470 if (!isa<CompoundStmt>(F->getBody())) 3471 addLocalScopeAndDtors(F->getBody()); 3472 3473 // Now populate the body block, and in the process create new blocks as we 3474 // walk the body of the loop. 3475 BodyBlock = addStmt(F->getBody()); 3476 3477 if (!BodyBlock) { 3478 // In the case of "for (...;...;...);" we can have a null BodyBlock. 3479 // Use the continue jump target as the proxy for the body. 3480 BodyBlock = ContinueJumpTarget.block; 3481 } 3482 else if (badCFG) 3483 return nullptr; 3484 } 3485 3486 // Because of short-circuit evaluation, the condition of the loop can span 3487 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 3488 // evaluate the condition. 3489 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr; 3490 3491 do { 3492 Expr *C = F->getCond(); 3493 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3494 3495 // Specially handle logical operators, which have a slightly 3496 // more optimal CFG representation. 3497 if (BinaryOperator *Cond = 3498 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr)) 3499 if (Cond->isLogicalOp()) { 3500 std::tie(EntryConditionBlock, ExitConditionBlock) = 3501 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor); 3502 break; 3503 } 3504 3505 // The default case when not handling logical operators. 3506 EntryConditionBlock = ExitConditionBlock = createBlock(false); 3507 ExitConditionBlock->setTerminator(F); 3508 3509 // See if this is a known constant. 3510 TryResult KnownVal(true); 3511 3512 if (C) { 3513 // Now add the actual condition to the condition block. 3514 // Because the condition itself may contain control-flow, new blocks may 3515 // be created. Thus we update "Succ" after adding the condition. 3516 Block = ExitConditionBlock; 3517 EntryConditionBlock = addStmt(C); 3518 3519 // If this block contains a condition variable, add both the condition 3520 // variable and initializer to the CFG. 3521 if (VarDecl *VD = F->getConditionVariable()) { 3522 if (Expr *Init = VD->getInit()) { 3523 autoCreateBlock(); 3524 const DeclStmt *DS = F->getConditionVariableDeclStmt(); 3525 assert(DS->isSingleDecl()); 3526 findConstructionContexts( 3527 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS), 3528 Init); 3529 appendStmt(Block, DS); 3530 EntryConditionBlock = addStmt(Init); 3531 assert(Block == EntryConditionBlock); 3532 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C); 3533 } 3534 } 3535 3536 if (Block && badCFG) 3537 return nullptr; 3538 3539 KnownVal = tryEvaluateBool(C); 3540 } 3541 3542 // Add the loop body entry as a successor to the condition. 3543 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock); 3544 // Link up the condition block with the code that follows the loop. (the 3545 // false branch). 3546 addSuccessor(ExitConditionBlock, 3547 KnownVal.isTrue() ? nullptr : LoopSuccessor); 3548 } while (false); 3549 3550 // Link up the loop-back block to the entry condition block. 3551 addSuccessor(TransitionBlock, EntryConditionBlock); 3552 3553 // The condition block is the implicit successor for any code above the loop. 3554 Succ = EntryConditionBlock; 3555 3556 // If the loop contains initialization, create a new block for those 3557 // statements. This block can also contain statements that precede the loop. 3558 if (Stmt *I = F->getInit()) { 3559 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3560 ScopePos = LoopBeginScopePos; 3561 Block = createBlock(); 3562 return addStmt(I); 3563 } 3564 3565 // There is no loop initialization. We are thus basically a while loop. 3566 // NULL out Block to force lazy block construction. 3567 Block = nullptr; 3568 Succ = EntryConditionBlock; 3569 return EntryConditionBlock; 3570 } 3571 3572 CFGBlock * 3573 CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE, 3574 AddStmtChoice asc) { 3575 findConstructionContexts( 3576 ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE), 3577 MTE->getSubExpr()); 3578 3579 return VisitStmt(MTE, asc); 3580 } 3581 3582 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) { 3583 if (asc.alwaysAdd(*this, M)) { 3584 autoCreateBlock(); 3585 appendStmt(Block, M); 3586 } 3587 return Visit(M->getBase()); 3588 } 3589 3590 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { 3591 // Objective-C fast enumeration 'for' statements: 3592 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC 3593 // 3594 // for ( Type newVariable in collection_expression ) { statements } 3595 // 3596 // becomes: 3597 // 3598 // prologue: 3599 // 1. collection_expression 3600 // T. jump to loop_entry 3601 // loop_entry: 3602 // 1. side-effects of element expression 3603 // 1. ObjCForCollectionStmt [performs binding to newVariable] 3604 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] 3605 // TB: 3606 // statements 3607 // T. jump to loop_entry 3608 // FB: 3609 // what comes after 3610 // 3611 // and 3612 // 3613 // Type existingItem; 3614 // for ( existingItem in expression ) { statements } 3615 // 3616 // becomes: 3617 // 3618 // the same with newVariable replaced with existingItem; the binding works 3619 // the same except that for one ObjCForCollectionStmt::getElement() returns 3620 // a DeclStmt and the other returns a DeclRefExpr. 3621 3622 CFGBlock *LoopSuccessor = nullptr; 3623 3624 if (Block) { 3625 if (badCFG) 3626 return nullptr; 3627 LoopSuccessor = Block; 3628 Block = nullptr; 3629 } else 3630 LoopSuccessor = Succ; 3631 3632 // Build the condition blocks. 3633 CFGBlock *ExitConditionBlock = createBlock(false); 3634 3635 // Set the terminator for the "exit" condition block. 3636 ExitConditionBlock->setTerminator(S); 3637 3638 // The last statement in the block should be the ObjCForCollectionStmt, which 3639 // performs the actual binding to 'element' and determines if there are any 3640 // more items in the collection. 3641 appendStmt(ExitConditionBlock, S); 3642 Block = ExitConditionBlock; 3643 3644 // Walk the 'element' expression to see if there are any side-effects. We 3645 // generate new blocks as necessary. We DON'T add the statement by default to 3646 // the CFG unless it contains control-flow. 3647 CFGBlock *EntryConditionBlock = Visit(S->getElement(), 3648 AddStmtChoice::NotAlwaysAdd); 3649 if (Block) { 3650 if (badCFG) 3651 return nullptr; 3652 Block = nullptr; 3653 } 3654 3655 // The condition block is the implicit successor for the loop body as well as 3656 // any code above the loop. 3657 Succ = EntryConditionBlock; 3658 3659 // Now create the true branch. 3660 { 3661 // Save the current values for Succ, continue and break targets. 3662 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 3663 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 3664 save_break(BreakJumpTarget); 3665 3666 // Add an intermediate block between the BodyBlock and the 3667 // EntryConditionBlock to represent the "loop back" transition, for looping 3668 // back to the head of the loop. 3669 CFGBlock *LoopBackBlock = nullptr; 3670 Succ = LoopBackBlock = createBlock(); 3671 LoopBackBlock->setLoopTarget(S); 3672 3673 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 3674 ContinueJumpTarget = JumpTarget(Succ, ScopePos); 3675 3676 CFGBlock *BodyBlock = addStmt(S->getBody()); 3677 3678 if (!BodyBlock) 3679 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;" 3680 else if (Block) { 3681 if (badCFG) 3682 return nullptr; 3683 } 3684 3685 // This new body block is a successor to our "exit" condition block. 3686 addSuccessor(ExitConditionBlock, BodyBlock); 3687 } 3688 3689 // Link up the condition block with the code that follows the loop. 3690 // (the false branch). 3691 addSuccessor(ExitConditionBlock, LoopSuccessor); 3692 3693 // Now create a prologue block to contain the collection expression. 3694 Block = createBlock(); 3695 return addStmt(S->getCollection()); 3696 } 3697 3698 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { 3699 // Inline the body. 3700 return addStmt(S->getSubStmt()); 3701 // TODO: consider adding cleanups for the end of @autoreleasepool scope. 3702 } 3703 3704 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) { 3705 // FIXME: Add locking 'primitives' to CFG for @synchronized. 3706 3707 // Inline the body. 3708 CFGBlock *SyncBlock = addStmt(S->getSynchBody()); 3709 3710 // The sync body starts its own basic block. This makes it a little easier 3711 // for diagnostic clients. 3712 if (SyncBlock) { 3713 if (badCFG) 3714 return nullptr; 3715 3716 Block = nullptr; 3717 Succ = SyncBlock; 3718 } 3719 3720 // Add the @synchronized to the CFG. 3721 autoCreateBlock(); 3722 appendStmt(Block, S); 3723 3724 // Inline the sync expression. 3725 return addStmt(S->getSynchExpr()); 3726 } 3727 3728 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) { 3729 autoCreateBlock(); 3730 3731 // Add the PseudoObject as the last thing. 3732 appendStmt(Block, E); 3733 3734 CFGBlock *lastBlock = Block; 3735 3736 // Before that, evaluate all of the semantics in order. In 3737 // CFG-land, that means appending them in reverse order. 3738 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) { 3739 Expr *Semantic = E->getSemanticExpr(--i); 3740 3741 // If the semantic is an opaque value, we're being asked to bind 3742 // it to its source expression. 3743 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) 3744 Semantic = OVE->getSourceExpr(); 3745 3746 if (CFGBlock *B = Visit(Semantic)) 3747 lastBlock = B; 3748 } 3749 3750 return lastBlock; 3751 } 3752 3753 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) { 3754 CFGBlock *LoopSuccessor = nullptr; 3755 3756 // Save local scope position because in case of condition variable ScopePos 3757 // won't be restored when traversing AST. 3758 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3759 3760 // Create local scope for possible condition variable. 3761 // Store scope position for continue statement. 3762 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 3763 if (VarDecl *VD = W->getConditionVariable()) { 3764 addLocalScopeForVarDecl(VD); 3765 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W); 3766 } 3767 addLoopExit(W); 3768 3769 // "while" is a control-flow statement. Thus we stop processing the current 3770 // block. 3771 if (Block) { 3772 if (badCFG) 3773 return nullptr; 3774 LoopSuccessor = Block; 3775 Block = nullptr; 3776 } else { 3777 LoopSuccessor = Succ; 3778 } 3779 3780 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr; 3781 3782 // Process the loop body. 3783 { 3784 assert(W->getBody()); 3785 3786 // Save the current values for Block, Succ, continue and break targets. 3787 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 3788 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 3789 save_break(BreakJumpTarget); 3790 3791 // Create an empty block to represent the transition block for looping back 3792 // to the head of the loop. 3793 Succ = TransitionBlock = createBlock(false); 3794 TransitionBlock->setLoopTarget(W); 3795 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); 3796 3797 // All breaks should go to the code following the loop. 3798 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 3799 3800 // Loop body should end with destructor of Condition variable (if any). 3801 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W); 3802 3803 // If body is not a compound statement create implicit scope 3804 // and add destructors. 3805 if (!isa<CompoundStmt>(W->getBody())) 3806 addLocalScopeAndDtors(W->getBody()); 3807 3808 // Create the body. The returned block is the entry to the loop body. 3809 BodyBlock = addStmt(W->getBody()); 3810 3811 if (!BodyBlock) 3812 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;" 3813 else if (Block && badCFG) 3814 return nullptr; 3815 } 3816 3817 // Because of short-circuit evaluation, the condition of the loop can span 3818 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 3819 // evaluate the condition. 3820 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr; 3821 3822 do { 3823 Expr *C = W->getCond(); 3824 3825 // Specially handle logical operators, which have a slightly 3826 // more optimal CFG representation. 3827 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens())) 3828 if (Cond->isLogicalOp()) { 3829 std::tie(EntryConditionBlock, ExitConditionBlock) = 3830 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor); 3831 break; 3832 } 3833 3834 // The default case when not handling logical operators. 3835 ExitConditionBlock = createBlock(false); 3836 ExitConditionBlock->setTerminator(W); 3837 3838 // Now add the actual condition to the condition block. 3839 // Because the condition itself may contain control-flow, new blocks may 3840 // be created. Thus we update "Succ" after adding the condition. 3841 Block = ExitConditionBlock; 3842 Block = EntryConditionBlock = addStmt(C); 3843 3844 // If this block contains a condition variable, add both the condition 3845 // variable and initializer to the CFG. 3846 if (VarDecl *VD = W->getConditionVariable()) { 3847 if (Expr *Init = VD->getInit()) { 3848 autoCreateBlock(); 3849 const DeclStmt *DS = W->getConditionVariableDeclStmt(); 3850 assert(DS->isSingleDecl()); 3851 findConstructionContexts( 3852 ConstructionContextLayer::create(cfg->getBumpVectorContext(), 3853 const_cast<DeclStmt *>(DS)), 3854 Init); 3855 appendStmt(Block, DS); 3856 EntryConditionBlock = addStmt(Init); 3857 assert(Block == EntryConditionBlock); 3858 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C); 3859 } 3860 } 3861 3862 if (Block && badCFG) 3863 return nullptr; 3864 3865 // See if this is a known constant. 3866 const TryResult& KnownVal = tryEvaluateBool(C); 3867 3868 // Add the loop body entry as a successor to the condition. 3869 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock); 3870 // Link up the condition block with the code that follows the loop. (the 3871 // false branch). 3872 addSuccessor(ExitConditionBlock, 3873 KnownVal.isTrue() ? nullptr : LoopSuccessor); 3874 } while(false); 3875 3876 // Link up the loop-back block to the entry condition block. 3877 addSuccessor(TransitionBlock, EntryConditionBlock); 3878 3879 // There can be no more statements in the condition block since we loop back 3880 // to this block. NULL out Block to force lazy creation of another block. 3881 Block = nullptr; 3882 3883 // Return the condition block, which is the dominating block for the loop. 3884 Succ = EntryConditionBlock; 3885 return EntryConditionBlock; 3886 } 3887 3888 CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, 3889 AddStmtChoice asc) { 3890 if (asc.alwaysAdd(*this, A)) { 3891 autoCreateBlock(); 3892 appendStmt(Block, A); 3893 } 3894 3895 CFGBlock *B = Block; 3896 3897 if (CFGBlock *R = Visit(A->getSubExpr())) 3898 B = R; 3899 3900 auto *OVE = dyn_cast<OpaqueValueExpr>(A->getCommonExpr()); 3901 assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an " 3902 "OpaqueValueExpr!"); 3903 if (CFGBlock *R = Visit(OVE->getSourceExpr())) 3904 B = R; 3905 3906 return B; 3907 } 3908 3909 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) { 3910 // ObjCAtCatchStmt are treated like labels, so they are the first statement 3911 // in a block. 3912 3913 // Save local scope position because in case of exception variable ScopePos 3914 // won't be restored when traversing AST. 3915 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3916 3917 if (CS->getCatchBody()) 3918 addStmt(CS->getCatchBody()); 3919 3920 CFGBlock *CatchBlock = Block; 3921 if (!CatchBlock) 3922 CatchBlock = createBlock(); 3923 3924 appendStmt(CatchBlock, CS); 3925 3926 // Also add the ObjCAtCatchStmt as a label, like with regular labels. 3927 CatchBlock->setLabel(CS); 3928 3929 // Bail out if the CFG is bad. 3930 if (badCFG) 3931 return nullptr; 3932 3933 // We set Block to NULL to allow lazy creation of a new block (if necessary). 3934 Block = nullptr; 3935 3936 return CatchBlock; 3937 } 3938 3939 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { 3940 // If we were in the middle of a block we stop processing that block. 3941 if (badCFG) 3942 return nullptr; 3943 3944 // Create the new block. 3945 Block = createBlock(false); 3946 3947 if (TryTerminatedBlock) 3948 // The current try statement is the only successor. 3949 addSuccessor(Block, TryTerminatedBlock); 3950 else 3951 // otherwise the Exit block is the only successor. 3952 addSuccessor(Block, &cfg->getExit()); 3953 3954 // Add the statement to the block. This may create new blocks if S contains 3955 // control-flow (short-circuit operations). 3956 return VisitStmt(S, AddStmtChoice::AlwaysAdd); 3957 } 3958 3959 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) { 3960 // "@try"/"@catch" is a control-flow statement. Thus we stop processing the 3961 // current block. 3962 CFGBlock *TrySuccessor = nullptr; 3963 3964 if (Block) { 3965 if (badCFG) 3966 return nullptr; 3967 TrySuccessor = Block; 3968 } else 3969 TrySuccessor = Succ; 3970 3971 // FIXME: Implement @finally support. 3972 if (Terminator->getFinallyStmt()) 3973 return NYS(); 3974 3975 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 3976 3977 // Create a new block that will contain the try statement. 3978 CFGBlock *NewTryTerminatedBlock = createBlock(false); 3979 // Add the terminator in the try block. 3980 NewTryTerminatedBlock->setTerminator(Terminator); 3981 3982 bool HasCatchAll = false; 3983 for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) { 3984 // The code after the try is the implicit successor. 3985 Succ = TrySuccessor; 3986 if (CS->hasEllipsis()) { 3987 HasCatchAll = true; 3988 } 3989 Block = nullptr; 3990 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS); 3991 if (!CatchBlock) 3992 return nullptr; 3993 // Add this block to the list of successors for the block with the try 3994 // statement. 3995 addSuccessor(NewTryTerminatedBlock, CatchBlock); 3996 } 3997 3998 // FIXME: This needs updating when @finally support is added. 3999 if (!HasCatchAll) { 4000 if (PrevTryTerminatedBlock) 4001 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 4002 else 4003 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 4004 } 4005 4006 // The code after the try is the implicit successor. 4007 Succ = TrySuccessor; 4008 4009 // Save the current "try" context. 4010 SaveAndRestore<CFGBlock *> SaveTry(TryTerminatedBlock, NewTryTerminatedBlock); 4011 cfg->addTryDispatchBlock(TryTerminatedBlock); 4012 4013 assert(Terminator->getTryBody() && "try must contain a non-NULL body"); 4014 Block = nullptr; 4015 return addStmt(Terminator->getTryBody()); 4016 } 4017 4018 CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME, 4019 AddStmtChoice asc) { 4020 findConstructionContextsForArguments(ME); 4021 4022 autoCreateBlock(); 4023 appendObjCMessage(Block, ME); 4024 4025 return VisitChildren(ME); 4026 } 4027 4028 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) { 4029 // If we were in the middle of a block we stop processing that block. 4030 if (badCFG) 4031 return nullptr; 4032 4033 // Create the new block. 4034 Block = createBlock(false); 4035 4036 if (TryTerminatedBlock) 4037 // The current try statement is the only successor. 4038 addSuccessor(Block, TryTerminatedBlock); 4039 else 4040 // otherwise the Exit block is the only successor. 4041 addSuccessor(Block, &cfg->getExit()); 4042 4043 // Add the statement to the block. This may create new blocks if S contains 4044 // control-flow (short-circuit operations). 4045 return VisitStmt(T, AddStmtChoice::AlwaysAdd); 4046 } 4047 4048 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) { 4049 CFGBlock *LoopSuccessor = nullptr; 4050 4051 addLoopExit(D); 4052 4053 // "do...while" is a control-flow statement. Thus we stop processing the 4054 // current block. 4055 if (Block) { 4056 if (badCFG) 4057 return nullptr; 4058 LoopSuccessor = Block; 4059 } else 4060 LoopSuccessor = Succ; 4061 4062 // Because of short-circuit evaluation, the condition of the loop can span 4063 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 4064 // evaluate the condition. 4065 CFGBlock *ExitConditionBlock = createBlock(false); 4066 CFGBlock *EntryConditionBlock = ExitConditionBlock; 4067 4068 // Set the terminator for the "exit" condition block. 4069 ExitConditionBlock->setTerminator(D); 4070 4071 // Now add the actual condition to the condition block. Because the condition 4072 // itself may contain control-flow, new blocks may be created. 4073 if (Stmt *C = D->getCond()) { 4074 Block = ExitConditionBlock; 4075 EntryConditionBlock = addStmt(C); 4076 if (Block) { 4077 if (badCFG) 4078 return nullptr; 4079 } 4080 } 4081 4082 // The condition block is the implicit successor for the loop body. 4083 Succ = EntryConditionBlock; 4084 4085 // See if this is a known constant. 4086 const TryResult &KnownVal = tryEvaluateBool(D->getCond()); 4087 4088 // Process the loop body. 4089 CFGBlock *BodyBlock = nullptr; 4090 { 4091 assert(D->getBody()); 4092 4093 // Save the current values for Block, Succ, and continue and break targets 4094 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 4095 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 4096 save_break(BreakJumpTarget); 4097 4098 // All continues within this loop should go to the condition block 4099 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 4100 4101 // All breaks should go to the code following the loop. 4102 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 4103 4104 // NULL out Block to force lazy instantiation of blocks for the body. 4105 Block = nullptr; 4106 4107 // If body is not a compound statement create implicit scope 4108 // and add destructors. 4109 if (!isa<CompoundStmt>(D->getBody())) 4110 addLocalScopeAndDtors(D->getBody()); 4111 4112 // Create the body. The returned block is the entry to the loop body. 4113 BodyBlock = addStmt(D->getBody()); 4114 4115 if (!BodyBlock) 4116 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" 4117 else if (Block) { 4118 if (badCFG) 4119 return nullptr; 4120 } 4121 4122 // Add an intermediate block between the BodyBlock and the 4123 // ExitConditionBlock to represent the "loop back" transition. Create an 4124 // empty block to represent the transition block for looping back to the 4125 // head of the loop. 4126 // FIXME: Can we do this more efficiently without adding another block? 4127 Block = nullptr; 4128 Succ = BodyBlock; 4129 CFGBlock *LoopBackBlock = createBlock(); 4130 LoopBackBlock->setLoopTarget(D); 4131 4132 if (!KnownVal.isFalse()) 4133 // Add the loop body entry as a successor to the condition. 4134 addSuccessor(ExitConditionBlock, LoopBackBlock); 4135 else 4136 addSuccessor(ExitConditionBlock, nullptr); 4137 } 4138 4139 // Link up the condition block with the code that follows the loop. 4140 // (the false branch). 4141 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor); 4142 4143 // There can be no more statements in the body block(s) since we loop back to 4144 // the body. NULL out Block to force lazy creation of another block. 4145 Block = nullptr; 4146 4147 // Return the loop body, which is the dominating block for the loop. 4148 Succ = BodyBlock; 4149 return BodyBlock; 4150 } 4151 4152 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) { 4153 // "continue" is a control-flow statement. Thus we stop processing the 4154 // current block. 4155 if (badCFG) 4156 return nullptr; 4157 4158 // Now create a new block that ends with the continue statement. 4159 Block = createBlock(false); 4160 Block->setTerminator(C); 4161 4162 // If there is no target for the continue, then we are looking at an 4163 // incomplete AST. This means the CFG cannot be constructed. 4164 if (ContinueJumpTarget.block) { 4165 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C); 4166 addSuccessor(Block, ContinueJumpTarget.block); 4167 } else 4168 badCFG = true; 4169 4170 return Block; 4171 } 4172 4173 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 4174 AddStmtChoice asc) { 4175 if (asc.alwaysAdd(*this, E)) { 4176 autoCreateBlock(); 4177 appendStmt(Block, E); 4178 } 4179 4180 // VLA types have expressions that must be evaluated. 4181 // Evaluation is done only for `sizeof`. 4182 4183 if (E->getKind() != UETT_SizeOf) 4184 return Block; 4185 4186 CFGBlock *lastBlock = Block; 4187 4188 if (E->isArgumentType()) { 4189 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); 4190 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) 4191 lastBlock = addStmt(VA->getSizeExpr()); 4192 } 4193 return lastBlock; 4194 } 4195 4196 /// VisitStmtExpr - Utility method to handle (nested) statement 4197 /// expressions (a GCC extension). 4198 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) { 4199 if (asc.alwaysAdd(*this, SE)) { 4200 autoCreateBlock(); 4201 appendStmt(Block, SE); 4202 } 4203 return VisitCompoundStmt(SE->getSubStmt(), /*ExternallyDestructed=*/true); 4204 } 4205 4206 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) { 4207 // "switch" is a control-flow statement. Thus we stop processing the current 4208 // block. 4209 CFGBlock *SwitchSuccessor = nullptr; 4210 4211 // Save local scope position because in case of condition variable ScopePos 4212 // won't be restored when traversing AST. 4213 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 4214 4215 // Create local scope for C++17 switch init-stmt if one exists. 4216 if (Stmt *Init = Terminator->getInit()) 4217 addLocalScopeForStmt(Init); 4218 4219 // Create local scope for possible condition variable. 4220 // Store scope position. Add implicit destructor. 4221 if (VarDecl *VD = Terminator->getConditionVariable()) 4222 addLocalScopeForVarDecl(VD); 4223 4224 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator); 4225 4226 if (Block) { 4227 if (badCFG) 4228 return nullptr; 4229 SwitchSuccessor = Block; 4230 } else SwitchSuccessor = Succ; 4231 4232 // Save the current "switch" context. 4233 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), 4234 save_default(DefaultCaseBlock); 4235 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 4236 4237 // Set the "default" case to be the block after the switch statement. If the 4238 // switch statement contains a "default:", this value will be overwritten with 4239 // the block for that code. 4240 DefaultCaseBlock = SwitchSuccessor; 4241 4242 // Create a new block that will contain the switch statement. 4243 SwitchTerminatedBlock = createBlock(false); 4244 4245 // Now process the switch body. The code after the switch is the implicit 4246 // successor. 4247 Succ = SwitchSuccessor; 4248 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos); 4249 4250 // When visiting the body, the case statements should automatically get linked 4251 // up to the switch. We also don't keep a pointer to the body, since all 4252 // control-flow from the switch goes to case/default statements. 4253 assert(Terminator->getBody() && "switch must contain a non-NULL body"); 4254 Block = nullptr; 4255 4256 // For pruning unreachable case statements, save the current state 4257 // for tracking the condition value. 4258 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered, 4259 false); 4260 4261 // Determine if the switch condition can be explicitly evaluated. 4262 assert(Terminator->getCond() && "switch condition must be non-NULL"); 4263 Expr::EvalResult result; 4264 bool b = tryEvaluate(Terminator->getCond(), result); 4265 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond, 4266 b ? &result : nullptr); 4267 4268 // If body is not a compound statement create implicit scope 4269 // and add destructors. 4270 if (!isa<CompoundStmt>(Terminator->getBody())) 4271 addLocalScopeAndDtors(Terminator->getBody()); 4272 4273 addStmt(Terminator->getBody()); 4274 if (Block) { 4275 if (badCFG) 4276 return nullptr; 4277 } 4278 4279 // If we have no "default:" case, the default transition is to the code 4280 // following the switch body. Moreover, take into account if all the 4281 // cases of a switch are covered (e.g., switching on an enum value). 4282 // 4283 // Note: We add a successor to a switch that is considered covered yet has no 4284 // case statements if the enumeration has no enumerators. 4285 bool SwitchAlwaysHasSuccessor = false; 4286 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered; 4287 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() && 4288 Terminator->getSwitchCaseList(); 4289 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock, 4290 !SwitchAlwaysHasSuccessor); 4291 4292 // Add the terminator and condition in the switch block. 4293 SwitchTerminatedBlock->setTerminator(Terminator); 4294 Block = SwitchTerminatedBlock; 4295 CFGBlock *LastBlock = addStmt(Terminator->getCond()); 4296 4297 // If the SwitchStmt contains a condition variable, add both the 4298 // SwitchStmt and the condition variable initialization to the CFG. 4299 if (VarDecl *VD = Terminator->getConditionVariable()) { 4300 if (Expr *Init = VD->getInit()) { 4301 autoCreateBlock(); 4302 appendStmt(Block, Terminator->getConditionVariableDeclStmt()); 4303 LastBlock = addStmt(Init); 4304 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init); 4305 } 4306 } 4307 4308 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG. 4309 if (Stmt *Init = Terminator->getInit()) { 4310 autoCreateBlock(); 4311 LastBlock = addStmt(Init); 4312 } 4313 4314 return LastBlock; 4315 } 4316 4317 static bool shouldAddCase(bool &switchExclusivelyCovered, 4318 const Expr::EvalResult *switchCond, 4319 const CaseStmt *CS, 4320 ASTContext &Ctx) { 4321 if (!switchCond) 4322 return true; 4323 4324 bool addCase = false; 4325 4326 if (!switchExclusivelyCovered) { 4327 if (switchCond->Val.isInt()) { 4328 // Evaluate the LHS of the case value. 4329 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx); 4330 const llvm::APSInt &condInt = switchCond->Val.getInt(); 4331 4332 if (condInt == lhsInt) { 4333 addCase = true; 4334 switchExclusivelyCovered = true; 4335 } 4336 else if (condInt > lhsInt) { 4337 if (const Expr *RHS = CS->getRHS()) { 4338 // Evaluate the RHS of the case value. 4339 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx); 4340 if (V2 >= condInt) { 4341 addCase = true; 4342 switchExclusivelyCovered = true; 4343 } 4344 } 4345 } 4346 } 4347 else 4348 addCase = true; 4349 } 4350 return addCase; 4351 } 4352 4353 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) { 4354 // CaseStmts are essentially labels, so they are the first statement in a 4355 // block. 4356 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr; 4357 4358 if (Stmt *Sub = CS->getSubStmt()) { 4359 // For deeply nested chains of CaseStmts, instead of doing a recursion 4360 // (which can blow out the stack), manually unroll and create blocks 4361 // along the way. 4362 while (isa<CaseStmt>(Sub)) { 4363 CFGBlock *currentBlock = createBlock(false); 4364 currentBlock->setLabel(CS); 4365 4366 if (TopBlock) 4367 addSuccessor(LastBlock, currentBlock); 4368 else 4369 TopBlock = currentBlock; 4370 4371 addSuccessor(SwitchTerminatedBlock, 4372 shouldAddCase(switchExclusivelyCovered, switchCond, 4373 CS, *Context) 4374 ? currentBlock : nullptr); 4375 4376 LastBlock = currentBlock; 4377 CS = cast<CaseStmt>(Sub); 4378 Sub = CS->getSubStmt(); 4379 } 4380 4381 addStmt(Sub); 4382 } 4383 4384 CFGBlock *CaseBlock = Block; 4385 if (!CaseBlock) 4386 CaseBlock = createBlock(); 4387 4388 // Cases statements partition blocks, so this is the top of the basic block we 4389 // were processing (the "case XXX:" is the label). 4390 CaseBlock->setLabel(CS); 4391 4392 if (badCFG) 4393 return nullptr; 4394 4395 // Add this block to the list of successors for the block with the switch 4396 // statement. 4397 assert(SwitchTerminatedBlock); 4398 addSuccessor(SwitchTerminatedBlock, CaseBlock, 4399 shouldAddCase(switchExclusivelyCovered, switchCond, 4400 CS, *Context)); 4401 4402 // We set Block to NULL to allow lazy creation of a new block (if necessary). 4403 Block = nullptr; 4404 4405 if (TopBlock) { 4406 addSuccessor(LastBlock, CaseBlock); 4407 Succ = TopBlock; 4408 } else { 4409 // This block is now the implicit successor of other blocks. 4410 Succ = CaseBlock; 4411 } 4412 4413 return Succ; 4414 } 4415 4416 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) { 4417 if (Terminator->getSubStmt()) 4418 addStmt(Terminator->getSubStmt()); 4419 4420 DefaultCaseBlock = Block; 4421 4422 if (!DefaultCaseBlock) 4423 DefaultCaseBlock = createBlock(); 4424 4425 // Default statements partition blocks, so this is the top of the basic block 4426 // we were processing (the "default:" is the label). 4427 DefaultCaseBlock->setLabel(Terminator); 4428 4429 if (badCFG) 4430 return nullptr; 4431 4432 // Unlike case statements, we don't add the default block to the successors 4433 // for the switch statement immediately. This is done when we finish 4434 // processing the switch statement. This allows for the default case 4435 // (including a fall-through to the code after the switch statement) to always 4436 // be the last successor of a switch-terminated block. 4437 4438 // We set Block to NULL to allow lazy creation of a new block (if necessary). 4439 Block = nullptr; 4440 4441 // This block is now the implicit successor of other blocks. 4442 Succ = DefaultCaseBlock; 4443 4444 return DefaultCaseBlock; 4445 } 4446 4447 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { 4448 // "try"/"catch" is a control-flow statement. Thus we stop processing the 4449 // current block. 4450 CFGBlock *TrySuccessor = nullptr; 4451 4452 if (Block) { 4453 if (badCFG) 4454 return nullptr; 4455 TrySuccessor = Block; 4456 } else 4457 TrySuccessor = Succ; 4458 4459 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 4460 4461 // Create a new block that will contain the try statement. 4462 CFGBlock *NewTryTerminatedBlock = createBlock(false); 4463 // Add the terminator in the try block. 4464 NewTryTerminatedBlock->setTerminator(Terminator); 4465 4466 bool HasCatchAll = false; 4467 for (unsigned I = 0, E = Terminator->getNumHandlers(); I != E; ++I) { 4468 // The code after the try is the implicit successor. 4469 Succ = TrySuccessor; 4470 CXXCatchStmt *CS = Terminator->getHandler(I); 4471 if (CS->getExceptionDecl() == nullptr) { 4472 HasCatchAll = true; 4473 } 4474 Block = nullptr; 4475 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); 4476 if (!CatchBlock) 4477 return nullptr; 4478 // Add this block to the list of successors for the block with the try 4479 // statement. 4480 addSuccessor(NewTryTerminatedBlock, CatchBlock); 4481 } 4482 if (!HasCatchAll) { 4483 if (PrevTryTerminatedBlock) 4484 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 4485 else 4486 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 4487 } 4488 4489 // The code after the try is the implicit successor. 4490 Succ = TrySuccessor; 4491 4492 // Save the current "try" context. 4493 SaveAndRestore<CFGBlock *> SaveTry(TryTerminatedBlock, NewTryTerminatedBlock); 4494 cfg->addTryDispatchBlock(TryTerminatedBlock); 4495 4496 assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); 4497 Block = nullptr; 4498 return addStmt(Terminator->getTryBlock()); 4499 } 4500 4501 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) { 4502 // CXXCatchStmt are treated like labels, so they are the first statement in a 4503 // block. 4504 4505 // Save local scope position because in case of exception variable ScopePos 4506 // won't be restored when traversing AST. 4507 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 4508 4509 // Create local scope for possible exception variable. 4510 // Store scope position. Add implicit destructor. 4511 if (VarDecl *VD = CS->getExceptionDecl()) { 4512 LocalScope::const_iterator BeginScopePos = ScopePos; 4513 addLocalScopeForVarDecl(VD); 4514 addAutomaticObjHandling(ScopePos, BeginScopePos, CS); 4515 } 4516 4517 if (CS->getHandlerBlock()) 4518 addStmt(CS->getHandlerBlock()); 4519 4520 CFGBlock *CatchBlock = Block; 4521 if (!CatchBlock) 4522 CatchBlock = createBlock(); 4523 4524 // CXXCatchStmt is more than just a label. They have semantic meaning 4525 // as well, as they implicitly "initialize" the catch variable. Add 4526 // it to the CFG as a CFGElement so that the control-flow of these 4527 // semantics gets captured. 4528 appendStmt(CatchBlock, CS); 4529 4530 // Also add the CXXCatchStmt as a label, to mirror handling of regular 4531 // labels. 4532 CatchBlock->setLabel(CS); 4533 4534 // Bail out if the CFG is bad. 4535 if (badCFG) 4536 return nullptr; 4537 4538 // We set Block to NULL to allow lazy creation of a new block (if necessary). 4539 Block = nullptr; 4540 4541 return CatchBlock; 4542 } 4543 4544 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) { 4545 // C++0x for-range statements are specified as [stmt.ranged]: 4546 // 4547 // { 4548 // auto && __range = range-init; 4549 // for ( auto __begin = begin-expr, 4550 // __end = end-expr; 4551 // __begin != __end; 4552 // ++__begin ) { 4553 // for-range-declaration = *__begin; 4554 // statement 4555 // } 4556 // } 4557 4558 // Save local scope position before the addition of the implicit variables. 4559 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 4560 4561 // Create local scopes and destructors for range, begin and end variables. 4562 if (Stmt *Range = S->getRangeStmt()) 4563 addLocalScopeForStmt(Range); 4564 if (Stmt *Begin = S->getBeginStmt()) 4565 addLocalScopeForStmt(Begin); 4566 if (Stmt *End = S->getEndStmt()) 4567 addLocalScopeForStmt(End); 4568 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S); 4569 4570 LocalScope::const_iterator ContinueScopePos = ScopePos; 4571 4572 // "for" is a control-flow statement. Thus we stop processing the current 4573 // block. 4574 CFGBlock *LoopSuccessor = nullptr; 4575 if (Block) { 4576 if (badCFG) 4577 return nullptr; 4578 LoopSuccessor = Block; 4579 } else 4580 LoopSuccessor = Succ; 4581 4582 // Save the current value for the break targets. 4583 // All breaks should go to the code following the loop. 4584 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 4585 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 4586 4587 // The block for the __begin != __end expression. 4588 CFGBlock *ConditionBlock = createBlock(false); 4589 ConditionBlock->setTerminator(S); 4590 4591 // Now add the actual condition to the condition block. 4592 if (Expr *C = S->getCond()) { 4593 Block = ConditionBlock; 4594 CFGBlock *BeginConditionBlock = addStmt(C); 4595 if (badCFG) 4596 return nullptr; 4597 assert(BeginConditionBlock == ConditionBlock && 4598 "condition block in for-range was unexpectedly complex"); 4599 (void)BeginConditionBlock; 4600 } 4601 4602 // The condition block is the implicit successor for the loop body as well as 4603 // any code above the loop. 4604 Succ = ConditionBlock; 4605 4606 // See if this is a known constant. 4607 TryResult KnownVal(true); 4608 4609 if (S->getCond()) 4610 KnownVal = tryEvaluateBool(S->getCond()); 4611 4612 // Now create the loop body. 4613 { 4614 assert(S->getBody()); 4615 4616 // Save the current values for Block, Succ, and continue targets. 4617 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 4618 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 4619 4620 // Generate increment code in its own basic block. This is the target of 4621 // continue statements. 4622 Block = nullptr; 4623 Succ = addStmt(S->getInc()); 4624 if (badCFG) 4625 return nullptr; 4626 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 4627 4628 // The starting block for the loop increment is the block that should 4629 // represent the 'loop target' for looping back to the start of the loop. 4630 ContinueJumpTarget.block->setLoopTarget(S); 4631 4632 // Finish up the increment block and prepare to start the loop body. 4633 assert(Block); 4634 if (badCFG) 4635 return nullptr; 4636 Block = nullptr; 4637 4638 // Add implicit scope and dtors for loop variable. 4639 addLocalScopeAndDtors(S->getLoopVarStmt()); 4640 4641 // If body is not a compound statement create implicit scope 4642 // and add destructors. 4643 if (!isa<CompoundStmt>(S->getBody())) 4644 addLocalScopeAndDtors(S->getBody()); 4645 4646 // Populate a new block to contain the loop body and loop variable. 4647 addStmt(S->getBody()); 4648 4649 if (badCFG) 4650 return nullptr; 4651 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt()); 4652 if (badCFG) 4653 return nullptr; 4654 4655 // This new body block is a successor to our condition block. 4656 addSuccessor(ConditionBlock, 4657 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock); 4658 } 4659 4660 // Link up the condition block with the code that follows the loop (the 4661 // false branch). 4662 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor); 4663 4664 // Add the initialization statements. 4665 Block = createBlock(); 4666 addStmt(S->getBeginStmt()); 4667 addStmt(S->getEndStmt()); 4668 CFGBlock *Head = addStmt(S->getRangeStmt()); 4669 if (S->getInit()) 4670 Head = addStmt(S->getInit()); 4671 return Head; 4672 } 4673 4674 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E, 4675 AddStmtChoice asc, bool ExternallyDestructed) { 4676 if (BuildOpts.AddTemporaryDtors) { 4677 // If adding implicit destructors visit the full expression for adding 4678 // destructors of temporaries. 4679 TempDtorContext Context; 4680 VisitForTemporaryDtors(E->getSubExpr(), ExternallyDestructed, Context); 4681 4682 // Full expression has to be added as CFGStmt so it will be sequenced 4683 // before destructors of it's temporaries. 4684 asc = asc.withAlwaysAdd(true); 4685 } 4686 return Visit(E->getSubExpr(), asc); 4687 } 4688 4689 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 4690 AddStmtChoice asc) { 4691 if (asc.alwaysAdd(*this, E)) { 4692 autoCreateBlock(); 4693 appendStmt(Block, E); 4694 4695 findConstructionContexts( 4696 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E), 4697 E->getSubExpr()); 4698 4699 // We do not want to propagate the AlwaysAdd property. 4700 asc = asc.withAlwaysAdd(false); 4701 } 4702 return Visit(E->getSubExpr(), asc); 4703 } 4704 4705 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, 4706 AddStmtChoice asc) { 4707 // If the constructor takes objects as arguments by value, we need to properly 4708 // construct these objects. Construction contexts we find here aren't for the 4709 // constructor C, they're for its arguments only. 4710 findConstructionContextsForArguments(C); 4711 4712 autoCreateBlock(); 4713 appendConstructor(Block, C); 4714 4715 return VisitChildren(C); 4716 } 4717 4718 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE, 4719 AddStmtChoice asc) { 4720 autoCreateBlock(); 4721 appendStmt(Block, NE); 4722 4723 findConstructionContexts( 4724 ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE), 4725 const_cast<CXXConstructExpr *>(NE->getConstructExpr())); 4726 4727 if (NE->getInitializer()) 4728 Block = Visit(NE->getInitializer()); 4729 4730 if (BuildOpts.AddCXXNewAllocator) 4731 appendNewAllocator(Block, NE); 4732 4733 if (NE->isArray() && *NE->getArraySize()) 4734 Block = Visit(*NE->getArraySize()); 4735 4736 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(), 4737 E = NE->placement_arg_end(); I != E; ++I) 4738 Block = Visit(*I); 4739 4740 return Block; 4741 } 4742 4743 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE, 4744 AddStmtChoice asc) { 4745 autoCreateBlock(); 4746 appendStmt(Block, DE); 4747 QualType DTy = DE->getDestroyedType(); 4748 if (!DTy.isNull()) { 4749 DTy = DTy.getNonReferenceType(); 4750 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl(); 4751 if (RD) { 4752 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor()) 4753 appendDeleteDtor(Block, RD, DE); 4754 } 4755 } 4756 4757 return VisitChildren(DE); 4758 } 4759 4760 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 4761 AddStmtChoice asc) { 4762 if (asc.alwaysAdd(*this, E)) { 4763 autoCreateBlock(); 4764 appendStmt(Block, E); 4765 // We do not want to propagate the AlwaysAdd property. 4766 asc = asc.withAlwaysAdd(false); 4767 } 4768 return Visit(E->getSubExpr(), asc); 4769 } 4770 4771 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 4772 AddStmtChoice asc) { 4773 // If the constructor takes objects as arguments by value, we need to properly 4774 // construct these objects. Construction contexts we find here aren't for the 4775 // constructor C, they're for its arguments only. 4776 findConstructionContextsForArguments(C); 4777 4778 autoCreateBlock(); 4779 appendConstructor(Block, C); 4780 return VisitChildren(C); 4781 } 4782 4783 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, 4784 AddStmtChoice asc) { 4785 if (asc.alwaysAdd(*this, E)) { 4786 autoCreateBlock(); 4787 appendStmt(Block, E); 4788 } 4789 4790 if (E->getCastKind() == CK_IntegralToBoolean) 4791 tryEvaluateBool(E->getSubExpr()->IgnoreParens()); 4792 4793 return Visit(E->getSubExpr(), AddStmtChoice()); 4794 } 4795 4796 CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) { 4797 return Visit(E->getSubExpr(), AddStmtChoice()); 4798 } 4799 4800 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) { 4801 // Lazily create the indirect-goto dispatch block if there isn't one already. 4802 CFGBlock *IBlock = cfg->getIndirectGotoBlock(); 4803 4804 if (!IBlock) { 4805 IBlock = createBlock(false); 4806 cfg->setIndirectGotoBlock(IBlock); 4807 } 4808 4809 // IndirectGoto is a control-flow statement. Thus we stop processing the 4810 // current block and create a new one. 4811 if (badCFG) 4812 return nullptr; 4813 4814 Block = createBlock(false); 4815 Block->setTerminator(I); 4816 addSuccessor(Block, IBlock); 4817 return addStmt(I->getTarget()); 4818 } 4819 4820 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed, 4821 TempDtorContext &Context) { 4822 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors); 4823 4824 tryAgain: 4825 if (!E) { 4826 badCFG = true; 4827 return nullptr; 4828 } 4829 switch (E->getStmtClass()) { 4830 default: 4831 return VisitChildrenForTemporaryDtors(E, false, Context); 4832 4833 case Stmt::InitListExprClass: 4834 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context); 4835 4836 case Stmt::BinaryOperatorClass: 4837 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E), 4838 ExternallyDestructed, 4839 Context); 4840 4841 case Stmt::CXXBindTemporaryExprClass: 4842 return VisitCXXBindTemporaryExprForTemporaryDtors( 4843 cast<CXXBindTemporaryExpr>(E), ExternallyDestructed, Context); 4844 4845 case Stmt::BinaryConditionalOperatorClass: 4846 case Stmt::ConditionalOperatorClass: 4847 return VisitConditionalOperatorForTemporaryDtors( 4848 cast<AbstractConditionalOperator>(E), ExternallyDestructed, Context); 4849 4850 case Stmt::ImplicitCastExprClass: 4851 // For implicit cast we want ExternallyDestructed to be passed further. 4852 E = cast<CastExpr>(E)->getSubExpr(); 4853 goto tryAgain; 4854 4855 case Stmt::CXXFunctionalCastExprClass: 4856 // For functional cast we want ExternallyDestructed to be passed further. 4857 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr(); 4858 goto tryAgain; 4859 4860 case Stmt::ConstantExprClass: 4861 E = cast<ConstantExpr>(E)->getSubExpr(); 4862 goto tryAgain; 4863 4864 case Stmt::ParenExprClass: 4865 E = cast<ParenExpr>(E)->getSubExpr(); 4866 goto tryAgain; 4867 4868 case Stmt::MaterializeTemporaryExprClass: { 4869 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E); 4870 ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression); 4871 SmallVector<const Expr *, 2> CommaLHSs; 4872 SmallVector<SubobjectAdjustment, 2> Adjustments; 4873 // Find the expression whose lifetime needs to be extended. 4874 E = const_cast<Expr *>( 4875 cast<MaterializeTemporaryExpr>(E) 4876 ->getSubExpr() 4877 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments)); 4878 // Visit the skipped comma operator left-hand sides for other temporaries. 4879 for (const Expr *CommaLHS : CommaLHSs) { 4880 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS), 4881 /*ExternallyDestructed=*/false, Context); 4882 } 4883 goto tryAgain; 4884 } 4885 4886 case Stmt::BlockExprClass: 4887 // Don't recurse into blocks; their subexpressions don't get evaluated 4888 // here. 4889 return Block; 4890 4891 case Stmt::LambdaExprClass: { 4892 // For lambda expressions, only recurse into the capture initializers, 4893 // and not the body. 4894 auto *LE = cast<LambdaExpr>(E); 4895 CFGBlock *B = Block; 4896 for (Expr *Init : LE->capture_inits()) { 4897 if (Init) { 4898 if (CFGBlock *R = VisitForTemporaryDtors( 4899 Init, /*ExternallyDestructed=*/true, Context)) 4900 B = R; 4901 } 4902 } 4903 return B; 4904 } 4905 4906 case Stmt::StmtExprClass: 4907 // Don't recurse into statement expressions; any cleanups inside them 4908 // will be wrapped in their own ExprWithCleanups. 4909 return Block; 4910 4911 case Stmt::CXXDefaultArgExprClass: 4912 E = cast<CXXDefaultArgExpr>(E)->getExpr(); 4913 goto tryAgain; 4914 4915 case Stmt::CXXDefaultInitExprClass: 4916 E = cast<CXXDefaultInitExpr>(E)->getExpr(); 4917 goto tryAgain; 4918 } 4919 } 4920 4921 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E, 4922 bool ExternallyDestructed, 4923 TempDtorContext &Context) { 4924 if (isa<LambdaExpr>(E)) { 4925 // Do not visit the children of lambdas; they have their own CFGs. 4926 return Block; 4927 } 4928 4929 // When visiting children for destructors we want to visit them in reverse 4930 // order that they will appear in the CFG. Because the CFG is built 4931 // bottom-up, this means we visit them in their natural order, which 4932 // reverses them in the CFG. 4933 CFGBlock *B = Block; 4934 for (Stmt *Child : E->children()) 4935 if (Child) 4936 if (CFGBlock *R = VisitForTemporaryDtors(Child, ExternallyDestructed, Context)) 4937 B = R; 4938 4939 return B; 4940 } 4941 4942 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors( 4943 BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) { 4944 if (E->isCommaOp()) { 4945 // For the comma operator, the LHS expression is evaluated before the RHS 4946 // expression, so prepend temporary destructors for the LHS first. 4947 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context); 4948 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), ExternallyDestructed, Context); 4949 return RHSBlock ? RHSBlock : LHSBlock; 4950 } 4951 4952 if (E->isLogicalOp()) { 4953 VisitForTemporaryDtors(E->getLHS(), false, Context); 4954 TryResult RHSExecuted = tryEvaluateBool(E->getLHS()); 4955 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr) 4956 RHSExecuted.negate(); 4957 4958 // We do not know at CFG-construction time whether the right-hand-side was 4959 // executed, thus we add a branch node that depends on the temporary 4960 // constructor call. 4961 TempDtorContext RHSContext( 4962 bothKnownTrue(Context.KnownExecuted, RHSExecuted)); 4963 VisitForTemporaryDtors(E->getRHS(), false, RHSContext); 4964 InsertTempDtorDecisionBlock(RHSContext); 4965 4966 return Block; 4967 } 4968 4969 if (E->isAssignmentOp()) { 4970 // For assignment operators, the RHS expression is evaluated before the LHS 4971 // expression, so prepend temporary destructors for the RHS first. 4972 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context); 4973 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context); 4974 return LHSBlock ? LHSBlock : RHSBlock; 4975 } 4976 4977 // Any other operator is visited normally. 4978 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context); 4979 } 4980 4981 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( 4982 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) { 4983 // First add destructors for temporaries in subexpression. 4984 // Because VisitCXXBindTemporaryExpr calls setDestructed: 4985 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), true, Context); 4986 if (!ExternallyDestructed) { 4987 // If lifetime of temporary is not prolonged (by assigning to constant 4988 // reference) add destructor for it. 4989 4990 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor(); 4991 4992 if (Dtor->getParent()->isAnyDestructorNoReturn()) { 4993 // If the destructor is marked as a no-return destructor, we need to 4994 // create a new block for the destructor which does not have as a 4995 // successor anything built thus far. Control won't flow out of this 4996 // block. 4997 if (B) Succ = B; 4998 Block = createNoReturnBlock(); 4999 } else if (Context.needsTempDtorBranch()) { 5000 // If we need to introduce a branch, we add a new block that we will hook 5001 // up to a decision block later. 5002 if (B) Succ = B; 5003 Block = createBlock(); 5004 } else { 5005 autoCreateBlock(); 5006 } 5007 if (Context.needsTempDtorBranch()) { 5008 Context.setDecisionPoint(Succ, E); 5009 } 5010 appendTemporaryDtor(Block, E); 5011 5012 B = Block; 5013 } 5014 return B; 5015 } 5016 5017 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context, 5018 CFGBlock *FalseSucc) { 5019 if (!Context.TerminatorExpr) { 5020 // If no temporary was found, we do not need to insert a decision point. 5021 return; 5022 } 5023 assert(Context.TerminatorExpr); 5024 CFGBlock *Decision = createBlock(false); 5025 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, 5026 CFGTerminator::TemporaryDtorsBranch)); 5027 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse()); 5028 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ, 5029 !Context.KnownExecuted.isTrue()); 5030 Block = Decision; 5031 } 5032 5033 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( 5034 AbstractConditionalOperator *E, bool ExternallyDestructed, 5035 TempDtorContext &Context) { 5036 VisitForTemporaryDtors(E->getCond(), false, Context); 5037 CFGBlock *ConditionBlock = Block; 5038 CFGBlock *ConditionSucc = Succ; 5039 TryResult ConditionVal = tryEvaluateBool(E->getCond()); 5040 TryResult NegatedVal = ConditionVal; 5041 if (NegatedVal.isKnown()) NegatedVal.negate(); 5042 5043 TempDtorContext TrueContext( 5044 bothKnownTrue(Context.KnownExecuted, ConditionVal)); 5045 VisitForTemporaryDtors(E->getTrueExpr(), ExternallyDestructed, TrueContext); 5046 CFGBlock *TrueBlock = Block; 5047 5048 Block = ConditionBlock; 5049 Succ = ConditionSucc; 5050 TempDtorContext FalseContext( 5051 bothKnownTrue(Context.KnownExecuted, NegatedVal)); 5052 VisitForTemporaryDtors(E->getFalseExpr(), ExternallyDestructed, FalseContext); 5053 5054 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) { 5055 InsertTempDtorDecisionBlock(FalseContext, TrueBlock); 5056 } else if (TrueContext.TerminatorExpr) { 5057 Block = TrueBlock; 5058 InsertTempDtorDecisionBlock(TrueContext); 5059 } else { 5060 InsertTempDtorDecisionBlock(FalseContext); 5061 } 5062 return Block; 5063 } 5064 5065 CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D, 5066 AddStmtChoice asc) { 5067 if (asc.alwaysAdd(*this, D)) { 5068 autoCreateBlock(); 5069 appendStmt(Block, D); 5070 } 5071 5072 // Iterate over all used expression in clauses. 5073 CFGBlock *B = Block; 5074 5075 // Reverse the elements to process them in natural order. Iterators are not 5076 // bidirectional, so we need to create temp vector. 5077 SmallVector<Stmt *, 8> Used( 5078 OMPExecutableDirective::used_clauses_children(D->clauses())); 5079 for (Stmt *S : llvm::reverse(Used)) { 5080 assert(S && "Expected non-null used-in-clause child."); 5081 if (CFGBlock *R = Visit(S)) 5082 B = R; 5083 } 5084 // Visit associated structured block if any. 5085 if (!D->isStandaloneDirective()) { 5086 Stmt *S = D->getRawStmt(); 5087 if (!isa<CompoundStmt>(S)) 5088 addLocalScopeAndDtors(S); 5089 if (CFGBlock *R = addStmt(S)) 5090 B = R; 5091 } 5092 5093 return B; 5094 } 5095 5096 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 5097 /// no successors or predecessors. If this is the first block created in the 5098 /// CFG, it is automatically set to be the Entry and Exit of the CFG. 5099 CFGBlock *CFG::createBlock() { 5100 bool first_block = begin() == end(); 5101 5102 // Create the block. 5103 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 5104 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this); 5105 Blocks.push_back(Mem, BlkBVC); 5106 5107 // If this is the first block, set it as the Entry and Exit. 5108 if (first_block) 5109 Entry = Exit = &back(); 5110 5111 // Return the block. 5112 return &back(); 5113 } 5114 5115 /// buildCFG - Constructs a CFG from an AST. 5116 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement, 5117 ASTContext *C, const BuildOptions &BO) { 5118 CFGBuilder Builder(C, BO); 5119 return Builder.buildCFG(D, Statement); 5120 } 5121 5122 bool CFG::isLinear() const { 5123 // Quick path: if we only have the ENTRY block, the EXIT block, and some code 5124 // in between, then we have no room for control flow. 5125 if (size() <= 3) 5126 return true; 5127 5128 // Traverse the CFG until we find a branch. 5129 // TODO: While this should still be very fast, 5130 // maybe we should cache the answer. 5131 llvm::SmallPtrSet<const CFGBlock *, 4> Visited; 5132 const CFGBlock *B = Entry; 5133 while (B != Exit) { 5134 auto IteratorAndFlag = Visited.insert(B); 5135 if (!IteratorAndFlag.second) { 5136 // We looped back to a block that we've already visited. Not linear. 5137 return false; 5138 } 5139 5140 // Iterate over reachable successors. 5141 const CFGBlock *FirstReachableB = nullptr; 5142 for (const CFGBlock::AdjacentBlock &AB : B->succs()) { 5143 if (!AB.isReachable()) 5144 continue; 5145 5146 if (FirstReachableB == nullptr) { 5147 FirstReachableB = &*AB; 5148 } else { 5149 // We've encountered a branch. It's not a linear CFG. 5150 return false; 5151 } 5152 } 5153 5154 if (!FirstReachableB) { 5155 // We reached a dead end. EXIT is unreachable. This is linear enough. 5156 return true; 5157 } 5158 5159 // There's only one way to move forward. Proceed. 5160 B = FirstReachableB; 5161 } 5162 5163 // We reached EXIT and found no branches. 5164 return true; 5165 } 5166 5167 const CXXDestructorDecl * 5168 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { 5169 switch (getKind()) { 5170 case CFGElement::Initializer: 5171 case CFGElement::NewAllocator: 5172 case CFGElement::LoopExit: 5173 case CFGElement::LifetimeEnds: 5174 case CFGElement::Statement: 5175 case CFGElement::Constructor: 5176 case CFGElement::CXXRecordTypedCall: 5177 case CFGElement::ScopeBegin: 5178 case CFGElement::ScopeEnd: 5179 llvm_unreachable("getDestructorDecl should only be used with " 5180 "ImplicitDtors"); 5181 case CFGElement::AutomaticObjectDtor: { 5182 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl(); 5183 QualType ty = var->getType(); 5184 5185 // FIXME: See CFGBuilder::addLocalScopeForVarDecl. 5186 // 5187 // Lifetime-extending constructs are handled here. This works for a single 5188 // temporary in an initializer expression. 5189 if (ty->isReferenceType()) { 5190 if (const Expr *Init = var->getInit()) { 5191 ty = getReferenceInitTemporaryType(Init); 5192 } 5193 } 5194 5195 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) { 5196 ty = arrayType->getElementType(); 5197 } 5198 5199 // The situation when the type of the lifetime-extending reference 5200 // does not correspond to the type of the object is supposed 5201 // to be handled by now. In particular, 'ty' is now the unwrapped 5202 // record type. 5203 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl(); 5204 assert(classDecl); 5205 return classDecl->getDestructor(); 5206 } 5207 case CFGElement::DeleteDtor: { 5208 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr(); 5209 QualType DTy = DE->getDestroyedType(); 5210 DTy = DTy.getNonReferenceType(); 5211 const CXXRecordDecl *classDecl = 5212 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl(); 5213 return classDecl->getDestructor(); 5214 } 5215 case CFGElement::TemporaryDtor: { 5216 const CXXBindTemporaryExpr *bindExpr = 5217 castAs<CFGTemporaryDtor>().getBindTemporaryExpr(); 5218 const CXXTemporary *temp = bindExpr->getTemporary(); 5219 return temp->getDestructor(); 5220 } 5221 case CFGElement::BaseDtor: 5222 case CFGElement::MemberDtor: 5223 // Not yet supported. 5224 return nullptr; 5225 } 5226 llvm_unreachable("getKind() returned bogus value"); 5227 } 5228 5229 //===----------------------------------------------------------------------===// 5230 // CFGBlock operations. 5231 //===----------------------------------------------------------------------===// 5232 5233 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable) 5234 : ReachableBlock(IsReachable ? B : nullptr), 5235 UnreachableBlock(!IsReachable ? B : nullptr, 5236 B && IsReachable ? AB_Normal : AB_Unreachable) {} 5237 5238 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock) 5239 : ReachableBlock(B), 5240 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock, 5241 B == AlternateBlock ? AB_Alternate : AB_Normal) {} 5242 5243 void CFGBlock::addSuccessor(AdjacentBlock Succ, 5244 BumpVectorContext &C) { 5245 if (CFGBlock *B = Succ.getReachableBlock()) 5246 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C); 5247 5248 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock()) 5249 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C); 5250 5251 Succs.push_back(Succ, C); 5252 } 5253 5254 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 5255 const CFGBlock *From, const CFGBlock *To) { 5256 if (F.IgnoreNullPredecessors && !From) 5257 return true; 5258 5259 if (To && From && F.IgnoreDefaultsWithCoveredEnums) { 5260 // If the 'To' has no label or is labeled but the label isn't a 5261 // CaseStmt then filter this edge. 5262 if (const SwitchStmt *S = 5263 dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) { 5264 if (S->isAllEnumCasesCovered()) { 5265 const Stmt *L = To->getLabel(); 5266 if (!L || !isa<CaseStmt>(L)) 5267 return true; 5268 } 5269 } 5270 } 5271 5272 return false; 5273 } 5274 5275 //===----------------------------------------------------------------------===// 5276 // CFG pretty printing 5277 //===----------------------------------------------------------------------===// 5278 5279 namespace { 5280 5281 class StmtPrinterHelper : public PrinterHelper { 5282 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>; 5283 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>; 5284 5285 StmtMapTy StmtMap; 5286 DeclMapTy DeclMap; 5287 signed currentBlock = 0; 5288 unsigned currStmt = 0; 5289 const LangOptions &LangOpts; 5290 5291 public: 5292 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 5293 : LangOpts(LO) { 5294 if (!cfg) 5295 return; 5296 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 5297 unsigned j = 1; 5298 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 5299 BI != BEnd; ++BI, ++j ) { 5300 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) { 5301 const Stmt *stmt= SE->getStmt(); 5302 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 5303 StmtMap[stmt] = P; 5304 5305 switch (stmt->getStmtClass()) { 5306 case Stmt::DeclStmtClass: 5307 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P; 5308 break; 5309 case Stmt::IfStmtClass: { 5310 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable(); 5311 if (var) 5312 DeclMap[var] = P; 5313 break; 5314 } 5315 case Stmt::ForStmtClass: { 5316 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable(); 5317 if (var) 5318 DeclMap[var] = P; 5319 break; 5320 } 5321 case Stmt::WhileStmtClass: { 5322 const VarDecl *var = 5323 cast<WhileStmt>(stmt)->getConditionVariable(); 5324 if (var) 5325 DeclMap[var] = P; 5326 break; 5327 } 5328 case Stmt::SwitchStmtClass: { 5329 const VarDecl *var = 5330 cast<SwitchStmt>(stmt)->getConditionVariable(); 5331 if (var) 5332 DeclMap[var] = P; 5333 break; 5334 } 5335 case Stmt::CXXCatchStmtClass: { 5336 const VarDecl *var = 5337 cast<CXXCatchStmt>(stmt)->getExceptionDecl(); 5338 if (var) 5339 DeclMap[var] = P; 5340 break; 5341 } 5342 default: 5343 break; 5344 } 5345 } 5346 } 5347 } 5348 } 5349 5350 ~StmtPrinterHelper() override = default; 5351 5352 const LangOptions &getLangOpts() const { return LangOpts; } 5353 void setBlockID(signed i) { currentBlock = i; } 5354 void setStmtID(unsigned i) { currStmt = i; } 5355 5356 bool handledStmt(Stmt *S, raw_ostream &OS) override { 5357 StmtMapTy::iterator I = StmtMap.find(S); 5358 5359 if (I == StmtMap.end()) 5360 return false; 5361 5362 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 5363 && I->second.second == currStmt) { 5364 return false; 5365 } 5366 5367 OS << "[B" << I->second.first << "." << I->second.second << "]"; 5368 return true; 5369 } 5370 5371 bool handleDecl(const Decl *D, raw_ostream &OS) { 5372 DeclMapTy::iterator I = DeclMap.find(D); 5373 5374 if (I == DeclMap.end()) 5375 return false; 5376 5377 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 5378 && I->second.second == currStmt) { 5379 return false; 5380 } 5381 5382 OS << "[B" << I->second.first << "." << I->second.second << "]"; 5383 return true; 5384 } 5385 }; 5386 5387 class CFGBlockTerminatorPrint 5388 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 5389 raw_ostream &OS; 5390 StmtPrinterHelper* Helper; 5391 PrintingPolicy Policy; 5392 5393 public: 5394 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper, 5395 const PrintingPolicy &Policy) 5396 : OS(os), Helper(helper), Policy(Policy) { 5397 this->Policy.IncludeNewlines = false; 5398 } 5399 5400 void VisitIfStmt(IfStmt *I) { 5401 OS << "if "; 5402 if (Stmt *C = I->getCond()) 5403 C->printPretty(OS, Helper, Policy); 5404 } 5405 5406 // Default case. 5407 void VisitStmt(Stmt *Terminator) { 5408 Terminator->printPretty(OS, Helper, Policy); 5409 } 5410 5411 void VisitDeclStmt(DeclStmt *DS) { 5412 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 5413 OS << "static init " << VD->getName(); 5414 } 5415 5416 void VisitForStmt(ForStmt *F) { 5417 OS << "for (" ; 5418 if (F->getInit()) 5419 OS << "..."; 5420 OS << "; "; 5421 if (Stmt *C = F->getCond()) 5422 C->printPretty(OS, Helper, Policy); 5423 OS << "; "; 5424 if (F->getInc()) 5425 OS << "..."; 5426 OS << ")"; 5427 } 5428 5429 void VisitWhileStmt(WhileStmt *W) { 5430 OS << "while " ; 5431 if (Stmt *C = W->getCond()) 5432 C->printPretty(OS, Helper, Policy); 5433 } 5434 5435 void VisitDoStmt(DoStmt *D) { 5436 OS << "do ... while "; 5437 if (Stmt *C = D->getCond()) 5438 C->printPretty(OS, Helper, Policy); 5439 } 5440 5441 void VisitSwitchStmt(SwitchStmt *Terminator) { 5442 OS << "switch "; 5443 Terminator->getCond()->printPretty(OS, Helper, Policy); 5444 } 5445 5446 void VisitCXXTryStmt(CXXTryStmt *) { OS << "try ..."; } 5447 5448 void VisitObjCAtTryStmt(ObjCAtTryStmt *) { OS << "@try ..."; } 5449 5450 void VisitSEHTryStmt(SEHTryStmt *CS) { OS << "__try ..."; } 5451 5452 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) { 5453 if (Stmt *Cond = C->getCond()) 5454 Cond->printPretty(OS, Helper, Policy); 5455 OS << " ? ... : ..."; 5456 } 5457 5458 void VisitChooseExpr(ChooseExpr *C) { 5459 OS << "__builtin_choose_expr( "; 5460 if (Stmt *Cond = C->getCond()) 5461 Cond->printPretty(OS, Helper, Policy); 5462 OS << " )"; 5463 } 5464 5465 void VisitIndirectGotoStmt(IndirectGotoStmt *I) { 5466 OS << "goto *"; 5467 if (Stmt *T = I->getTarget()) 5468 T->printPretty(OS, Helper, Policy); 5469 } 5470 5471 void VisitBinaryOperator(BinaryOperator* B) { 5472 if (!B->isLogicalOp()) { 5473 VisitExpr(B); 5474 return; 5475 } 5476 5477 if (B->getLHS()) 5478 B->getLHS()->printPretty(OS, Helper, Policy); 5479 5480 switch (B->getOpcode()) { 5481 case BO_LOr: 5482 OS << " || ..."; 5483 return; 5484 case BO_LAnd: 5485 OS << " && ..."; 5486 return; 5487 default: 5488 llvm_unreachable("Invalid logical operator."); 5489 } 5490 } 5491 5492 void VisitExpr(Expr *E) { 5493 E->printPretty(OS, Helper, Policy); 5494 } 5495 5496 public: 5497 void print(CFGTerminator T) { 5498 switch (T.getKind()) { 5499 case CFGTerminator::StmtBranch: 5500 Visit(T.getStmt()); 5501 break; 5502 case CFGTerminator::TemporaryDtorsBranch: 5503 OS << "(Temp Dtor) "; 5504 Visit(T.getStmt()); 5505 break; 5506 case CFGTerminator::VirtualBaseBranch: 5507 OS << "(See if most derived ctor has already initialized vbases)"; 5508 break; 5509 } 5510 } 5511 }; 5512 5513 } // namespace 5514 5515 static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper, 5516 const CXXCtorInitializer *I) { 5517 if (I->isBaseInitializer()) 5518 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 5519 else if (I->isDelegatingInitializer()) 5520 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName(); 5521 else 5522 OS << I->getAnyMember()->getName(); 5523 OS << "("; 5524 if (Expr *IE = I->getInit()) 5525 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); 5526 OS << ")"; 5527 5528 if (I->isBaseInitializer()) 5529 OS << " (Base initializer)"; 5530 else if (I->isDelegatingInitializer()) 5531 OS << " (Delegating initializer)"; 5532 else 5533 OS << " (Member initializer)"; 5534 } 5535 5536 static void print_construction_context(raw_ostream &OS, 5537 StmtPrinterHelper &Helper, 5538 const ConstructionContext *CC) { 5539 SmallVector<const Stmt *, 3> Stmts; 5540 switch (CC->getKind()) { 5541 case ConstructionContext::SimpleConstructorInitializerKind: { 5542 OS << ", "; 5543 const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC); 5544 print_initializer(OS, Helper, SICC->getCXXCtorInitializer()); 5545 return; 5546 } 5547 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: { 5548 OS << ", "; 5549 const auto *CICC = 5550 cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC); 5551 print_initializer(OS, Helper, CICC->getCXXCtorInitializer()); 5552 Stmts.push_back(CICC->getCXXBindTemporaryExpr()); 5553 break; 5554 } 5555 case ConstructionContext::SimpleVariableKind: { 5556 const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC); 5557 Stmts.push_back(SDSCC->getDeclStmt()); 5558 break; 5559 } 5560 case ConstructionContext::CXX17ElidedCopyVariableKind: { 5561 const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC); 5562 Stmts.push_back(CDSCC->getDeclStmt()); 5563 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr()); 5564 break; 5565 } 5566 case ConstructionContext::NewAllocatedObjectKind: { 5567 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC); 5568 Stmts.push_back(NECC->getCXXNewExpr()); 5569 break; 5570 } 5571 case ConstructionContext::SimpleReturnedValueKind: { 5572 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC); 5573 Stmts.push_back(RSCC->getReturnStmt()); 5574 break; 5575 } 5576 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { 5577 const auto *RSCC = 5578 cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC); 5579 Stmts.push_back(RSCC->getReturnStmt()); 5580 Stmts.push_back(RSCC->getCXXBindTemporaryExpr()); 5581 break; 5582 } 5583 case ConstructionContext::SimpleTemporaryObjectKind: { 5584 const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC); 5585 Stmts.push_back(TOCC->getCXXBindTemporaryExpr()); 5586 Stmts.push_back(TOCC->getMaterializedTemporaryExpr()); 5587 break; 5588 } 5589 case ConstructionContext::ElidedTemporaryObjectKind: { 5590 const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC); 5591 Stmts.push_back(TOCC->getCXXBindTemporaryExpr()); 5592 Stmts.push_back(TOCC->getMaterializedTemporaryExpr()); 5593 Stmts.push_back(TOCC->getConstructorAfterElision()); 5594 break; 5595 } 5596 case ConstructionContext::ArgumentKind: { 5597 const auto *ACC = cast<ArgumentConstructionContext>(CC); 5598 if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) { 5599 OS << ", "; 5600 Helper.handledStmt(const_cast<Stmt *>(BTE), OS); 5601 } 5602 OS << ", "; 5603 Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS); 5604 OS << "+" << ACC->getIndex(); 5605 return; 5606 } 5607 } 5608 for (auto I: Stmts) 5609 if (I) { 5610 OS << ", "; 5611 Helper.handledStmt(const_cast<Stmt *>(I), OS); 5612 } 5613 } 5614 5615 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper, 5616 const CFGElement &E); 5617 5618 void CFGElement::dumpToStream(llvm::raw_ostream &OS) const { 5619 StmtPrinterHelper Helper(nullptr, {}); 5620 print_elem(OS, Helper, *this); 5621 } 5622 5623 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper, 5624 const CFGElement &E) { 5625 switch (E.getKind()) { 5626 case CFGElement::Kind::Statement: 5627 case CFGElement::Kind::CXXRecordTypedCall: 5628 case CFGElement::Kind::Constructor: { 5629 CFGStmt CS = E.castAs<CFGStmt>(); 5630 const Stmt *S = CS.getStmt(); 5631 assert(S != nullptr && "Expecting non-null Stmt"); 5632 5633 // special printing for statement-expressions. 5634 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) { 5635 const CompoundStmt *Sub = SE->getSubStmt(); 5636 5637 auto Children = Sub->children(); 5638 if (Children.begin() != Children.end()) { 5639 OS << "({ ... ; "; 5640 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 5641 OS << " })\n"; 5642 return; 5643 } 5644 } 5645 // special printing for comma expressions. 5646 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 5647 if (B->getOpcode() == BO_Comma) { 5648 OS << "... , "; 5649 Helper.handledStmt(B->getRHS(),OS); 5650 OS << '\n'; 5651 return; 5652 } 5653 } 5654 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); 5655 5656 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) { 5657 if (isa<CXXOperatorCallExpr>(S)) 5658 OS << " (OperatorCall)"; 5659 OS << " (CXXRecordTypedCall"; 5660 print_construction_context(OS, Helper, VTC->getConstructionContext()); 5661 OS << ")"; 5662 } else if (isa<CXXOperatorCallExpr>(S)) { 5663 OS << " (OperatorCall)"; 5664 } else if (isa<CXXBindTemporaryExpr>(S)) { 5665 OS << " (BindTemporary)"; 5666 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) { 5667 OS << " (CXXConstructExpr"; 5668 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) { 5669 print_construction_context(OS, Helper, CE->getConstructionContext()); 5670 } 5671 OS << ", " << CCE->getType() << ")"; 5672 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) { 5673 OS << " (" << CE->getStmtClassName() << ", " << CE->getCastKindName() 5674 << ", " << CE->getType() << ")"; 5675 } 5676 5677 // Expressions need a newline. 5678 if (isa<Expr>(S)) 5679 OS << '\n'; 5680 5681 break; 5682 } 5683 5684 case CFGElement::Kind::Initializer: 5685 print_initializer(OS, Helper, E.castAs<CFGInitializer>().getInitializer()); 5686 OS << '\n'; 5687 break; 5688 5689 case CFGElement::Kind::AutomaticObjectDtor: { 5690 CFGAutomaticObjDtor DE = E.castAs<CFGAutomaticObjDtor>(); 5691 const VarDecl *VD = DE.getVarDecl(); 5692 Helper.handleDecl(VD, OS); 5693 5694 QualType T = VD->getType(); 5695 if (T->isReferenceType()) 5696 T = getReferenceInitTemporaryType(VD->getInit(), nullptr); 5697 5698 OS << ".~"; 5699 T.getUnqualifiedType().print(OS, PrintingPolicy(Helper.getLangOpts())); 5700 OS << "() (Implicit destructor)\n"; 5701 break; 5702 } 5703 5704 case CFGElement::Kind::LifetimeEnds: 5705 Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS); 5706 OS << " (Lifetime ends)\n"; 5707 break; 5708 5709 case CFGElement::Kind::LoopExit: 5710 OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName() << " (LoopExit)\n"; 5711 break; 5712 5713 case CFGElement::Kind::ScopeBegin: 5714 OS << "CFGScopeBegin("; 5715 if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl()) 5716 OS << VD->getQualifiedNameAsString(); 5717 OS << ")\n"; 5718 break; 5719 5720 case CFGElement::Kind::ScopeEnd: 5721 OS << "CFGScopeEnd("; 5722 if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl()) 5723 OS << VD->getQualifiedNameAsString(); 5724 OS << ")\n"; 5725 break; 5726 5727 case CFGElement::Kind::NewAllocator: 5728 OS << "CFGNewAllocator("; 5729 if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr()) 5730 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts())); 5731 OS << ")\n"; 5732 break; 5733 5734 case CFGElement::Kind::DeleteDtor: { 5735 CFGDeleteDtor DE = E.castAs<CFGDeleteDtor>(); 5736 const CXXRecordDecl *RD = DE.getCXXRecordDecl(); 5737 if (!RD) 5738 return; 5739 CXXDeleteExpr *DelExpr = 5740 const_cast<CXXDeleteExpr*>(DE.getDeleteExpr()); 5741 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS); 5742 OS << "->~" << RD->getName().str() << "()"; 5743 OS << " (Implicit destructor)\n"; 5744 break; 5745 } 5746 5747 case CFGElement::Kind::BaseDtor: { 5748 const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier(); 5749 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; 5750 OS << " (Base object destructor)\n"; 5751 break; 5752 } 5753 5754 case CFGElement::Kind::MemberDtor: { 5755 const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl(); 5756 const Type *T = FD->getType()->getBaseElementTypeUnsafe(); 5757 OS << "this->" << FD->getName(); 5758 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; 5759 OS << " (Member object destructor)\n"; 5760 break; 5761 } 5762 5763 case CFGElement::Kind::TemporaryDtor: { 5764 const CXXBindTemporaryExpr *BT = 5765 E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr(); 5766 OS << "~"; 5767 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts())); 5768 OS << "() (Temporary object destructor)\n"; 5769 break; 5770 } 5771 } 5772 } 5773 5774 static void print_block(raw_ostream &OS, const CFG* cfg, 5775 const CFGBlock &B, 5776 StmtPrinterHelper &Helper, bool print_edges, 5777 bool ShowColors) { 5778 Helper.setBlockID(B.getBlockID()); 5779 5780 // Print the header. 5781 if (ShowColors) 5782 OS.changeColor(raw_ostream::YELLOW, true); 5783 5784 OS << "\n [B" << B.getBlockID(); 5785 5786 if (&B == &cfg->getEntry()) 5787 OS << " (ENTRY)]\n"; 5788 else if (&B == &cfg->getExit()) 5789 OS << " (EXIT)]\n"; 5790 else if (&B == cfg->getIndirectGotoBlock()) 5791 OS << " (INDIRECT GOTO DISPATCH)]\n"; 5792 else if (B.hasNoReturnElement()) 5793 OS << " (NORETURN)]\n"; 5794 else 5795 OS << "]\n"; 5796 5797 if (ShowColors) 5798 OS.resetColor(); 5799 5800 // Print the label of this block. 5801 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) { 5802 if (print_edges) 5803 OS << " "; 5804 5805 if (LabelStmt *L = dyn_cast<LabelStmt>(Label)) 5806 OS << L->getName(); 5807 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 5808 OS << "case "; 5809 if (const Expr *LHS = C->getLHS()) 5810 LHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); 5811 if (const Expr *RHS = C->getRHS()) { 5812 OS << " ... "; 5813 RHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); 5814 } 5815 } else if (isa<DefaultStmt>(Label)) 5816 OS << "default"; 5817 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 5818 OS << "catch ("; 5819 if (const VarDecl *ED = CS->getExceptionDecl()) 5820 ED->print(OS, PrintingPolicy(Helper.getLangOpts()), 0); 5821 else 5822 OS << "..."; 5823 OS << ")"; 5824 } else if (ObjCAtCatchStmt *CS = dyn_cast<ObjCAtCatchStmt>(Label)) { 5825 OS << "@catch ("; 5826 if (const VarDecl *PD = CS->getCatchParamDecl()) 5827 PD->print(OS, PrintingPolicy(Helper.getLangOpts()), 0); 5828 else 5829 OS << "..."; 5830 OS << ")"; 5831 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) { 5832 OS << "__except ("; 5833 ES->getFilterExpr()->printPretty(OS, &Helper, 5834 PrintingPolicy(Helper.getLangOpts()), 0); 5835 OS << ")"; 5836 } else 5837 llvm_unreachable("Invalid label statement in CFGBlock."); 5838 5839 OS << ":\n"; 5840 } 5841 5842 // Iterate through the statements in the block and print them. 5843 unsigned j = 1; 5844 5845 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 5846 I != E ; ++I, ++j ) { 5847 // Print the statement # in the basic block and the statement itself. 5848 if (print_edges) 5849 OS << " "; 5850 5851 OS << llvm::format("%3d", j) << ": "; 5852 5853 Helper.setStmtID(j); 5854 5855 print_elem(OS, Helper, *I); 5856 } 5857 5858 // Print the terminator of this block. 5859 if (B.getTerminator().isValid()) { 5860 if (ShowColors) 5861 OS.changeColor(raw_ostream::GREEN); 5862 5863 OS << " T: "; 5864 5865 Helper.setBlockID(-1); 5866 5867 PrintingPolicy PP(Helper.getLangOpts()); 5868 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP); 5869 TPrinter.print(B.getTerminator()); 5870 OS << '\n'; 5871 5872 if (ShowColors) 5873 OS.resetColor(); 5874 } 5875 5876 if (print_edges) { 5877 // Print the predecessors of this block. 5878 if (!B.pred_empty()) { 5879 const raw_ostream::Colors Color = raw_ostream::BLUE; 5880 if (ShowColors) 5881 OS.changeColor(Color); 5882 OS << " Preds " ; 5883 if (ShowColors) 5884 OS.resetColor(); 5885 OS << '(' << B.pred_size() << "):"; 5886 unsigned i = 0; 5887 5888 if (ShowColors) 5889 OS.changeColor(Color); 5890 5891 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 5892 I != E; ++I, ++i) { 5893 if (i % 10 == 8) 5894 OS << "\n "; 5895 5896 CFGBlock *B = *I; 5897 bool Reachable = true; 5898 if (!B) { 5899 Reachable = false; 5900 B = I->getPossiblyUnreachableBlock(); 5901 } 5902 5903 OS << " B" << B->getBlockID(); 5904 if (!Reachable) 5905 OS << "(Unreachable)"; 5906 } 5907 5908 if (ShowColors) 5909 OS.resetColor(); 5910 5911 OS << '\n'; 5912 } 5913 5914 // Print the successors of this block. 5915 if (!B.succ_empty()) { 5916 const raw_ostream::Colors Color = raw_ostream::MAGENTA; 5917 if (ShowColors) 5918 OS.changeColor(Color); 5919 OS << " Succs "; 5920 if (ShowColors) 5921 OS.resetColor(); 5922 OS << '(' << B.succ_size() << "):"; 5923 unsigned i = 0; 5924 5925 if (ShowColors) 5926 OS.changeColor(Color); 5927 5928 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 5929 I != E; ++I, ++i) { 5930 if (i % 10 == 8) 5931 OS << "\n "; 5932 5933 CFGBlock *B = *I; 5934 5935 bool Reachable = true; 5936 if (!B) { 5937 Reachable = false; 5938 B = I->getPossiblyUnreachableBlock(); 5939 } 5940 5941 if (B) { 5942 OS << " B" << B->getBlockID(); 5943 if (!Reachable) 5944 OS << "(Unreachable)"; 5945 } 5946 else { 5947 OS << " NULL"; 5948 } 5949 } 5950 5951 if (ShowColors) 5952 OS.resetColor(); 5953 OS << '\n'; 5954 } 5955 } 5956 } 5957 5958 /// dump - A simple pretty printer of a CFG that outputs to stderr. 5959 void CFG::dump(const LangOptions &LO, bool ShowColors) const { 5960 print(llvm::errs(), LO, ShowColors); 5961 } 5962 5963 /// print - A simple pretty printer of a CFG that outputs to an ostream. 5964 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const { 5965 StmtPrinterHelper Helper(this, LO); 5966 5967 // Print the entry block. 5968 print_block(OS, this, getEntry(), Helper, true, ShowColors); 5969 5970 // Iterate through the CFGBlocks and print them one by one. 5971 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 5972 // Skip the entry block, because we already printed it. 5973 if (&(**I) == &getEntry() || &(**I) == &getExit()) 5974 continue; 5975 5976 print_block(OS, this, **I, Helper, true, ShowColors); 5977 } 5978 5979 // Print the exit block. 5980 print_block(OS, this, getExit(), Helper, true, ShowColors); 5981 OS << '\n'; 5982 OS.flush(); 5983 } 5984 5985 size_t CFGBlock::getIndexInCFG() const { 5986 return llvm::find(*getParent(), this) - getParent()->begin(); 5987 } 5988 5989 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 5990 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO, 5991 bool ShowColors) const { 5992 print(llvm::errs(), cfg, LO, ShowColors); 5993 } 5994 5995 LLVM_DUMP_METHOD void CFGBlock::dump() const { 5996 dump(getParent(), LangOptions(), false); 5997 } 5998 5999 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 6000 /// Generally this will only be called from CFG::print. 6001 void CFGBlock::print(raw_ostream &OS, const CFG* cfg, 6002 const LangOptions &LO, bool ShowColors) const { 6003 StmtPrinterHelper Helper(cfg, LO); 6004 print_block(OS, cfg, *this, Helper, true, ShowColors); 6005 OS << '\n'; 6006 } 6007 6008 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 6009 void CFGBlock::printTerminator(raw_ostream &OS, 6010 const LangOptions &LO) const { 6011 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO)); 6012 TPrinter.print(getTerminator()); 6013 } 6014 6015 /// printTerminatorJson - Pretty-prints the terminator in JSON format. 6016 void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO, 6017 bool AddQuotes) const { 6018 std::string Buf; 6019 llvm::raw_string_ostream TempOut(Buf); 6020 6021 printTerminator(TempOut, LO); 6022 6023 Out << JsonFormat(TempOut.str(), AddQuotes); 6024 } 6025 6026 // Returns true if by simply looking at the block, we can be sure that it 6027 // results in a sink during analysis. This is useful to know when the analysis 6028 // was interrupted, and we try to figure out if it would sink eventually. 6029 // There may be many more reasons why a sink would appear during analysis 6030 // (eg. checkers may generate sinks arbitrarily), but here we only consider 6031 // sinks that would be obvious by looking at the CFG. 6032 static bool isImmediateSinkBlock(const CFGBlock *Blk) { 6033 if (Blk->hasNoReturnElement()) 6034 return true; 6035 6036 // FIXME: Throw-expressions are currently generating sinks during analysis: 6037 // they're not supported yet, and also often used for actually terminating 6038 // the program. So we should treat them as sinks in this analysis as well, 6039 // at least for now, but once we have better support for exceptions, 6040 // we'd need to carefully handle the case when the throw is being 6041 // immediately caught. 6042 if (llvm::any_of(*Blk, [](const CFGElement &Elm) { 6043 if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>()) 6044 if (isa<CXXThrowExpr>(StmtElm->getStmt())) 6045 return true; 6046 return false; 6047 })) 6048 return true; 6049 6050 return false; 6051 } 6052 6053 bool CFGBlock::isInevitablySinking() const { 6054 const CFG &Cfg = *getParent(); 6055 6056 const CFGBlock *StartBlk = this; 6057 if (isImmediateSinkBlock(StartBlk)) 6058 return true; 6059 6060 llvm::SmallVector<const CFGBlock *, 32> DFSWorkList; 6061 llvm::SmallPtrSet<const CFGBlock *, 32> Visited; 6062 6063 DFSWorkList.push_back(StartBlk); 6064 while (!DFSWorkList.empty()) { 6065 const CFGBlock *Blk = DFSWorkList.back(); 6066 DFSWorkList.pop_back(); 6067 Visited.insert(Blk); 6068 6069 // If at least one path reaches the CFG exit, it means that control is 6070 // returned to the caller. For now, say that we are not sure what 6071 // happens next. If necessary, this can be improved to analyze 6072 // the parent StackFrameContext's call site in a similar manner. 6073 if (Blk == &Cfg.getExit()) 6074 return false; 6075 6076 for (const auto &Succ : Blk->succs()) { 6077 if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) { 6078 if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) { 6079 // If the block has reachable child blocks that aren't no-return, 6080 // add them to the worklist. 6081 DFSWorkList.push_back(SuccBlk); 6082 } 6083 } 6084 } 6085 } 6086 6087 // Nothing reached the exit. It can only mean one thing: there's no return. 6088 return true; 6089 } 6090 6091 const Expr *CFGBlock::getLastCondition() const { 6092 // If the terminator is a temporary dtor or a virtual base, etc, we can't 6093 // retrieve a meaningful condition, bail out. 6094 if (Terminator.getKind() != CFGTerminator::StmtBranch) 6095 return nullptr; 6096 6097 // Also, if this method was called on a block that doesn't have 2 successors, 6098 // this block doesn't have retrievable condition. 6099 if (succ_size() < 2) 6100 return nullptr; 6101 6102 // FIXME: Is there a better condition expression we can return in this case? 6103 if (size() == 0) 6104 return nullptr; 6105 6106 auto StmtElem = rbegin()->getAs<CFGStmt>(); 6107 if (!StmtElem) 6108 return nullptr; 6109 6110 const Stmt *Cond = StmtElem->getStmt(); 6111 if (isa<ObjCForCollectionStmt>(Cond) || isa<DeclStmt>(Cond)) 6112 return nullptr; 6113 6114 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence 6115 // the cast<>. 6116 return cast<Expr>(Cond)->IgnoreParens(); 6117 } 6118 6119 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) { 6120 Stmt *Terminator = getTerminatorStmt(); 6121 if (!Terminator) 6122 return nullptr; 6123 6124 Expr *E = nullptr; 6125 6126 switch (Terminator->getStmtClass()) { 6127 default: 6128 break; 6129 6130 case Stmt::CXXForRangeStmtClass: 6131 E = cast<CXXForRangeStmt>(Terminator)->getCond(); 6132 break; 6133 6134 case Stmt::ForStmtClass: 6135 E = cast<ForStmt>(Terminator)->getCond(); 6136 break; 6137 6138 case Stmt::WhileStmtClass: 6139 E = cast<WhileStmt>(Terminator)->getCond(); 6140 break; 6141 6142 case Stmt::DoStmtClass: 6143 E = cast<DoStmt>(Terminator)->getCond(); 6144 break; 6145 6146 case Stmt::IfStmtClass: 6147 E = cast<IfStmt>(Terminator)->getCond(); 6148 break; 6149 6150 case Stmt::ChooseExprClass: 6151 E = cast<ChooseExpr>(Terminator)->getCond(); 6152 break; 6153 6154 case Stmt::IndirectGotoStmtClass: 6155 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 6156 break; 6157 6158 case Stmt::SwitchStmtClass: 6159 E = cast<SwitchStmt>(Terminator)->getCond(); 6160 break; 6161 6162 case Stmt::BinaryConditionalOperatorClass: 6163 E = cast<BinaryConditionalOperator>(Terminator)->getCond(); 6164 break; 6165 6166 case Stmt::ConditionalOperatorClass: 6167 E = cast<ConditionalOperator>(Terminator)->getCond(); 6168 break; 6169 6170 case Stmt::BinaryOperatorClass: // '&&' and '||' 6171 E = cast<BinaryOperator>(Terminator)->getLHS(); 6172 break; 6173 6174 case Stmt::ObjCForCollectionStmtClass: 6175 return Terminator; 6176 } 6177 6178 if (!StripParens) 6179 return E; 6180 6181 return E ? E->IgnoreParens() : nullptr; 6182 } 6183 6184 //===----------------------------------------------------------------------===// 6185 // CFG Graphviz Visualization 6186 //===----------------------------------------------------------------------===// 6187 6188 static StmtPrinterHelper *GraphHelper; 6189 6190 void CFG::viewCFG(const LangOptions &LO) const { 6191 StmtPrinterHelper H(this, LO); 6192 GraphHelper = &H; 6193 llvm::ViewGraph(this,"CFG"); 6194 GraphHelper = nullptr; 6195 } 6196 6197 namespace llvm { 6198 6199 template<> 6200 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 6201 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 6202 6203 static std::string getNodeLabel(const CFGBlock *Node, const CFG *Graph) { 6204 std::string OutSStr; 6205 llvm::raw_string_ostream Out(OutSStr); 6206 print_block(Out,Graph, *Node, *GraphHelper, false, false); 6207 std::string& OutStr = Out.str(); 6208 6209 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 6210 6211 // Process string output to make it nicer... 6212 for (unsigned i = 0; i != OutStr.length(); ++i) 6213 if (OutStr[i] == '\n') { // Left justify 6214 OutStr[i] = '\\'; 6215 OutStr.insert(OutStr.begin()+i+1, 'l'); 6216 } 6217 6218 return OutStr; 6219 } 6220 }; 6221 6222 } // namespace llvm 6223