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