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