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