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