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