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