1 //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the CFG and CFGBuilder classes for representing and
11 // building Control-Flow Graphs (CFGs) from ASTs.
13 //===----------------------------------------------------------------------===//
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"
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"
31 using namespace clang;
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();
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:
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.
59 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
61 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
63 bool alwaysAdd(CFGBuilder &builder,
64 const Stmt *stmt) const;
66 /// Return a copy of this object, except with the 'always-add' bit
68 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
69 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
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
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
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),
99 typedef BumpVector<VarDecl*> AutomaticVarsTy;
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;
106 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
107 /// Invalid iterator (with null Scope) has VarIter equal to 0.
111 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
112 /// Incrementing invalid iterator is allowed and will result in invalid
115 : Scope(nullptr), VarIter(0) {}
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)
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];
132 VarDecl *operator*() const {
133 return *this->operator->();
136 const_iterator &operator++() {
140 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
146 const_iterator operator++(int) {
147 const_iterator P = *this;
152 bool operator==(const const_iterator &rhs) const {
153 return Scope == rhs.Scope && VarIter == rhs.VarIter;
155 bool operator!=(const const_iterator &rhs) const {
156 return !(*this == rhs);
159 explicit operator bool() const {
160 return *this != const_iterator();
163 int distance(const_iterator L);
166 friend class const_iterator;
169 BumpVectorContext ctx;
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.
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) {}
182 /// Begin of scope in direction of CFG building (backwards).
183 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
185 void addVar(VarDecl *VD) {
186 Vars.push_back(VD, ctx);
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) {
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.");
202 D += F.VarIter - L.VarIter;
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) {}
215 LocalScope::const_iterator scopePosition;
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.
225 TryResult(bool b) : X(b ? 1 : 0) {}
226 TryResult() : X(-1) {}
228 bool isTrue() const { return X == 1; }
229 bool isFalse() const { return X == 0; }
230 bool isKnown() const { return X >= 0; }
237 TryResult bothKnownTrue(TryResult R1, TryResult R2) {
238 if (!R1.isKnown() || !R2.isKnown())
240 return TryResult(R1.isTrue() && R2.isTrue());
243 class reverse_children {
244 llvm::SmallVector<Stmt *, 12> childrenBuf;
245 ArrayRef<Stmt*> children;
247 reverse_children(Stmt *S);
249 typedef ArrayRef<Stmt*>::reverse_iterator iterator;
250 iterator begin() const { return children.rbegin(); }
251 iterator end() const { return children.rend(); }
255 reverse_children::reverse_children(Stmt *S) {
256 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
257 children = CE->getRawSubExprs();
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()),
272 // Default case for all other statements.
273 for (Stmt *SubStmt : S->children())
274 childrenBuf.push_back(SubStmt);
276 // This needs to be done *after* childrenBuf has been populated.
277 children = childrenBuf;
280 /// CFGBuilder - This class implements CFG construction from an AST.
281 /// The builder is stateful: an instance of the builder should be used to only
282 /// construct a single CFG.
286 /// CFGBuilder builder;
287 /// CFG* cfg = builder.BuildAST(stmt1);
289 /// CFG construction is done via a recursive walk of an AST. We actually parse
290 /// the AST in reverse order so that the successor of a basic block is
291 /// constructed prior to its predecessor. This allows us to nicely capture
292 /// implicit fall-throughs without extra basic blocks.
295 typedef BlockScopePosPair JumpTarget;
296 typedef BlockScopePosPair JumpSource;
299 std::unique_ptr<CFG> cfg;
303 JumpTarget ContinueJumpTarget;
304 JumpTarget BreakJumpTarget;
305 CFGBlock *SwitchTerminatedBlock;
306 CFGBlock *DefaultCaseBlock;
307 CFGBlock *TryTerminatedBlock;
309 // Current position in local scope.
310 LocalScope::const_iterator ScopePos;
312 // LabelMap records the mapping from Label expressions to their jump targets.
313 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
316 // A list of blocks that end with a "goto" that must be backpatched to their
317 // resolved targets upon completion of CFG construction.
318 typedef std::vector<JumpSource> BackpatchBlocksTy;
319 BackpatchBlocksTy BackpatchBlocks;
321 // A list of labels whose address has been taken (for indirect gotos).
322 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
323 LabelSetTy AddressTakenLabels;
326 const CFG::BuildOptions &BuildOpts;
328 // State to track for building switch statements.
329 bool switchExclusivelyCovered;
330 Expr::EvalResult *switchCond;
332 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
333 const Stmt *lastLookup;
335 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
336 // during construction of branches for chained logical operators.
337 typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
338 CachedBoolEvalsTy CachedBoolEvals;
341 explicit CFGBuilder(ASTContext *astContext,
342 const CFG::BuildOptions &buildOpts)
343 : Context(astContext), cfg(new CFG()), // crew a new CFG
344 Block(nullptr), Succ(nullptr),
345 SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr),
346 TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts),
347 switchExclusivelyCovered(false), switchCond(nullptr),
348 cachedEntry(nullptr), lastLookup(nullptr) {}
350 // buildCFG - Used by external clients to construct the CFG.
351 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
353 bool alwaysAdd(const Stmt *stmt);
356 // Visitors to walk an AST and construct the CFG.
357 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
358 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
359 CFGBlock *VisitBreakStmt(BreakStmt *B);
360 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
361 CFGBlock *VisitCaseStmt(CaseStmt *C);
362 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
363 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
364 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
366 CFGBlock *VisitContinueStmt(ContinueStmt *C);
367 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
369 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
370 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
371 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
372 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
373 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
374 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
376 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
378 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
379 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
380 CFGBlock *VisitDeclStmt(DeclStmt *DS);
381 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
382 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
383 CFGBlock *VisitDoStmt(DoStmt *D);
384 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
385 CFGBlock *VisitForStmt(ForStmt *F);
386 CFGBlock *VisitGotoStmt(GotoStmt *G);
387 CFGBlock *VisitIfStmt(IfStmt *I);
388 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
389 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
390 CFGBlock *VisitLabelStmt(LabelStmt *L);
391 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
392 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
393 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
396 CFGBlock *FalseBlock);
397 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
398 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
399 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
400 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
401 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
402 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
403 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
404 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
405 CFGBlock *VisitReturnStmt(ReturnStmt *R);
406 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
407 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
408 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
410 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
411 CFGBlock *VisitWhileStmt(WhileStmt *W);
413 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
414 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
415 CFGBlock *VisitChildren(Stmt *S);
416 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
418 /// When creating the CFG for temporary destructors, we want to mirror the
419 /// branch structure of the corresponding constructor calls.
420 /// Thus, while visiting a statement for temporary destructors, we keep a
421 /// context to keep track of the following information:
422 /// - whether a subexpression is executed unconditionally
423 /// - if a subexpression is executed conditionally, the first
424 /// CXXBindTemporaryExpr we encounter in that subexpression (which
425 /// corresponds to the last temporary destructor we have to call for this
426 /// subexpression) and the CFG block at that point (which will become the
427 /// successor block when inserting the decision point).
429 /// That way, we can build the branch structure for temporary destructors as
431 /// 1. If a subexpression is executed unconditionally, we add the temporary
432 /// destructor calls to the current block.
433 /// 2. If a subexpression is executed conditionally, when we encounter a
434 /// CXXBindTemporaryExpr:
435 /// a) If it is the first temporary destructor call in the subexpression,
436 /// we remember the CXXBindTemporaryExpr and the current block in the
437 /// TempDtorContext; we start a new block, and insert the temporary
439 /// b) Otherwise, add the temporary destructor call to the current block.
440 /// 3. When we finished visiting a conditionally executed subexpression,
441 /// and we found at least one temporary constructor during the visitation
442 /// (2.a has executed), we insert a decision block that uses the
443 /// CXXBindTemporaryExpr as terminator, and branches to the current block
444 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
445 /// branches to the stored successor.
446 struct TempDtorContext {
448 : IsConditional(false), KnownExecuted(true), Succ(nullptr),
449 TerminatorExpr(nullptr) {}
451 TempDtorContext(TryResult KnownExecuted)
452 : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr),
453 TerminatorExpr(nullptr) {}
455 /// Returns whether we need to start a new branch for a temporary destructor
456 /// call. This is the case when the temporary destructor is
457 /// conditionally executed, and it is the first one we encounter while
458 /// visiting a subexpression - other temporary destructors at the same level
459 /// will be added to the same block and are executed under the same
461 bool needsTempDtorBranch() const {
462 return IsConditional && !TerminatorExpr;
465 /// Remember the successor S of a temporary destructor decision branch for
466 /// the corresponding CXXBindTemporaryExpr E.
467 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
472 const bool IsConditional;
473 const TryResult KnownExecuted;
475 CXXBindTemporaryExpr *TerminatorExpr;
478 // Visitors to walk an AST and generate destructors of temporaries in
480 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
481 TempDtorContext &Context);
482 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
483 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
484 TempDtorContext &Context);
485 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
486 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
487 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
488 AbstractConditionalOperator *E, bool BindToTemporary,
489 TempDtorContext &Context);
490 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
491 CFGBlock *FalseSucc = nullptr);
493 // NYS == Not Yet Supported
499 void autoCreateBlock() { if (!Block) Block = createBlock(); }
500 CFGBlock *createBlock(bool add_successor = true);
501 CFGBlock *createNoReturnBlock();
503 CFGBlock *addStmt(Stmt *S) {
504 return Visit(S, AddStmtChoice::AlwaysAdd);
506 CFGBlock *addInitializer(CXXCtorInitializer *I);
507 void addAutomaticObjDtors(LocalScope::const_iterator B,
508 LocalScope::const_iterator E, Stmt *S);
509 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
511 // Local scopes creation.
512 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
514 void addLocalScopeForStmt(Stmt *S);
515 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
516 LocalScope* Scope = nullptr);
517 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
519 void addLocalScopeAndDtors(Stmt *S);
521 // Interface to CFGBlock - adding CFGElements.
522 void appendStmt(CFGBlock *B, const Stmt *S) {
523 if (alwaysAdd(S) && cachedEntry)
524 cachedEntry->second = B;
526 // All block-level expressions should have already been IgnoreParens()ed.
527 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
528 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
530 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
531 B->appendInitializer(I, cfg->getBumpVectorContext());
533 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
534 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
536 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
537 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
539 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
540 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
542 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
543 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
545 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
546 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
549 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
550 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
553 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
554 LocalScope::const_iterator B, LocalScope::const_iterator E);
556 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
557 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
558 cfg->getBumpVectorContext());
561 /// Add a reachable successor to a block, with the alternate variant that is
563 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
564 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
565 cfg->getBumpVectorContext());
568 /// \brief Find a relational comparison with an expression evaluating to a
569 /// boolean and a constant other than 0 and 1.
570 /// e.g. if ((x < y) == 10)
571 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
572 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
573 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
575 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
576 const Expr *BoolExpr = RHSExpr;
577 bool IntFirst = true;
579 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
584 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
587 llvm::APInt IntValue = IntLiteral->getValue();
588 if ((IntValue == 1) || (IntValue == 0))
591 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
592 !IntValue.isNegative();
594 BinaryOperatorKind Bok = B->getOpcode();
595 if (Bok == BO_GT || Bok == BO_GE) {
596 // Always true for 10 > bool and bool > -1
597 // Always false for -1 > bool and bool > 10
598 return TryResult(IntFirst == IntLarger);
600 // Always true for -1 < bool and bool < 10
601 // Always false for 10 < bool and bool < -1
602 return TryResult(IntFirst != IntLarger);
606 /// Find an incorrect equality comparison. Either with an expression
607 /// evaluating to a boolean and a constant other than 0 and 1.
608 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
609 /// true/false e.q. (x & 8) == 4.
610 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
611 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
612 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
614 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
615 const Expr *BoolExpr = RHSExpr;
618 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
625 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
626 if (BitOp && (BitOp->getOpcode() == BO_And ||
627 BitOp->getOpcode() == BO_Or)) {
628 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
629 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
631 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
634 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
639 llvm::APInt L1 = IntLiteral->getValue();
640 llvm::APInt L2 = IntLiteral2->getValue();
641 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
642 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
643 if (BuildOpts.Observer)
644 BuildOpts.Observer->compareBitwiseEquality(B,
645 B->getOpcode() != BO_EQ);
646 TryResult(B->getOpcode() != BO_EQ);
648 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
649 llvm::APInt IntValue = IntLiteral->getValue();
650 if ((IntValue == 1) || (IntValue == 0)) {
653 return TryResult(B->getOpcode() != BO_EQ);
659 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
660 const llvm::APSInt &Value1,
661 const llvm::APSInt &Value2) {
662 assert(Value1.isSigned() == Value2.isSigned());
667 return TryResult(Value1 == Value2);
669 return TryResult(Value1 != Value2);
671 return TryResult(Value1 < Value2);
673 return TryResult(Value1 <= Value2);
675 return TryResult(Value1 > Value2);
677 return TryResult(Value1 >= Value2);
681 /// \brief Find a pair of comparison expressions with or without parentheses
682 /// with a shared variable and constants and a logical operator between them
683 /// that always evaluates to either true or false.
684 /// e.g. if (x != 3 || x != 4)
685 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
686 assert(B->isLogicalOp());
687 const BinaryOperator *LHS =
688 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
689 const BinaryOperator *RHS =
690 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
694 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
697 BinaryOperatorKind BO1 = LHS->getOpcode();
698 const DeclRefExpr *Decl1 =
699 dyn_cast<DeclRefExpr>(LHS->getLHS()->IgnoreParenImpCasts());
700 const IntegerLiteral *Literal1 =
701 dyn_cast<IntegerLiteral>(LHS->getRHS()->IgnoreParens());
702 if (!Decl1 && !Literal1) {
705 else if (BO1 == BO_GE)
707 else if (BO1 == BO_LT)
709 else if (BO1 == BO_LE)
711 Decl1 = dyn_cast<DeclRefExpr>(LHS->getRHS()->IgnoreParenImpCasts());
712 Literal1 = dyn_cast<IntegerLiteral>(LHS->getLHS()->IgnoreParens());
715 if (!Decl1 || !Literal1)
718 BinaryOperatorKind BO2 = RHS->getOpcode();
719 const DeclRefExpr *Decl2 =
720 dyn_cast<DeclRefExpr>(RHS->getLHS()->IgnoreParenImpCasts());
721 const IntegerLiteral *Literal2 =
722 dyn_cast<IntegerLiteral>(RHS->getRHS()->IgnoreParens());
723 if (!Decl2 && !Literal2) {
726 else if (BO2 == BO_GE)
728 else if (BO2 == BO_LT)
730 else if (BO2 == BO_LE)
732 Decl2 = dyn_cast<DeclRefExpr>(RHS->getRHS()->IgnoreParenImpCasts());
733 Literal2 = dyn_cast<IntegerLiteral>(RHS->getLHS()->IgnoreParens());
736 if (!Decl2 || !Literal2)
739 // Check that it is the same variable on both sides.
740 if (Decl1->getDecl() != Decl2->getDecl())
745 if (!Literal1->EvaluateAsInt(L1, *Context) ||
746 !Literal2->EvaluateAsInt(L2, *Context))
749 // Can't compare signed with unsigned or with different bit width.
750 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
753 // Values that will be used to determine if result of logical
754 // operator is always true/false
755 const llvm::APSInt Values[] = {
756 // Value less than both Value1 and Value2
757 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
760 // Value between Value1 and Value2
761 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
765 // Value greater than both Value1 and Value2
766 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
769 // Check whether expression is always true/false by evaluating the following
770 // * variable x is less than the smallest literal.
771 // * variable x is equal to the smallest literal.
772 // * Variable x is between smallest and largest literal.
773 // * Variable x is equal to the largest literal.
774 // * Variable x is greater than largest literal.
775 bool AlwaysTrue = true, AlwaysFalse = true;
776 for (unsigned int ValueIndex = 0;
777 ValueIndex < sizeof(Values) / sizeof(Values[0]);
779 llvm::APSInt Value = Values[ValueIndex];
780 TryResult Res1, Res2;
781 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
782 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
784 if (!Res1.isKnown() || !Res2.isKnown())
787 if (B->getOpcode() == BO_LAnd) {
788 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
789 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
791 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
792 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
796 if (AlwaysTrue || AlwaysFalse) {
797 if (BuildOpts.Observer)
798 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
799 return TryResult(AlwaysTrue);
804 /// Try and evaluate an expression to an integer constant.
805 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
806 if (!BuildOpts.PruneTriviallyFalseEdges)
808 return !S->isTypeDependent() &&
809 !S->isValueDependent() &&
810 S->EvaluateAsRValue(outResult, *Context);
813 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
814 /// if we can evaluate to a known value, otherwise return -1.
815 TryResult tryEvaluateBool(Expr *S) {
816 if (!BuildOpts.PruneTriviallyFalseEdges ||
817 S->isTypeDependent() || S->isValueDependent())
820 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
821 if (Bop->isLogicalOp()) {
822 // Check the cache first.
823 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
824 if (I != CachedBoolEvals.end())
825 return I->second; // already in map;
827 // Retrieve result at first, or the map might be updated.
828 TryResult Result = evaluateAsBooleanConditionNoCache(S);
829 CachedBoolEvals[S] = Result; // update or insert
833 switch (Bop->getOpcode()) {
835 // For 'x & 0' and 'x * 0', we can determine that
836 // the value is always false.
839 // If either operand is zero, we know the value
842 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
843 if (!IntVal.getBoolValue()) {
844 return TryResult(false);
847 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
848 if (!IntVal.getBoolValue()) {
849 return TryResult(false);
858 return evaluateAsBooleanConditionNoCache(S);
861 /// \brief Evaluate as boolean \param E without using the cache.
862 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
863 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
864 if (Bop->isLogicalOp()) {
865 TryResult LHS = tryEvaluateBool(Bop->getLHS());
867 // We were able to evaluate the LHS, see if we can get away with not
868 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
869 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
872 TryResult RHS = tryEvaluateBool(Bop->getRHS());
874 if (Bop->getOpcode() == BO_LOr)
875 return LHS.isTrue() || RHS.isTrue();
877 return LHS.isTrue() && RHS.isTrue();
880 TryResult RHS = tryEvaluateBool(Bop->getRHS());
882 // We can't evaluate the LHS; however, sometimes the result
883 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
884 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
887 TryResult BopRes = checkIncorrectLogicOperator(Bop);
888 if (BopRes.isKnown())
889 return BopRes.isTrue();
894 } else if (Bop->isEqualityOp()) {
895 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
896 if (BopRes.isKnown())
897 return BopRes.isTrue();
898 } else if (Bop->isRelationalOp()) {
899 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
900 if (BopRes.isKnown())
901 return BopRes.isTrue();
906 if (E->EvaluateAsBooleanCondition(Result, *Context))
914 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
915 const Stmt *stmt) const {
916 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
919 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
920 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
922 if (!BuildOpts.forcedBlkExprs)
925 if (lastLookup == stmt) {
927 assert(cachedEntry->first == stmt);
935 // Perform the lookup!
936 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
939 // No need to update 'cachedEntry', since it will always be null.
940 assert(!cachedEntry);
944 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
945 if (itr == fb->end()) {
946 cachedEntry = nullptr;
954 // FIXME: Add support for dependent-sized array types in C++?
955 // Does it even make sense to build a CFG for an uninstantiated template?
956 static const VariableArrayType *FindVA(const Type *t) {
957 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
958 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
959 if (vat->getSizeExpr())
962 t = vt->getElementType().getTypePtr();
968 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
969 /// arbitrary statement. Examples include a single expression or a function
970 /// body (compound statement). The ownership of the returned CFG is
971 /// transferred to the caller. If CFG construction fails, this method returns
973 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
978 // Create an empty block that will serve as the exit block for the CFG. Since
979 // this is the first block added to the CFG, it will be implicitly registered
980 // as the exit block.
981 Succ = createBlock();
982 assert(Succ == &cfg->getExit());
983 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
985 if (BuildOpts.AddImplicitDtors)
986 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
987 addImplicitDtorsForDestructor(DD);
989 // Visit the statements and create the CFG.
990 CFGBlock *B = addStmt(Statement);
995 // For C++ constructor add initializers to CFG.
996 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
997 for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
998 E = CD->init_rend(); I != E; ++I) {
999 B = addInitializer(*I);
1008 // Backpatch the gotos whose label -> block mappings we didn't know when we
1009 // encountered them.
1010 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1011 E = BackpatchBlocks.end(); I != E; ++I ) {
1013 CFGBlock *B = I->block;
1014 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
1015 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
1017 // If there is no target for the goto, then we are looking at an
1018 // incomplete AST. Handle this by not registering a successor.
1019 if (LI == LabelMap.end()) continue;
1021 JumpTarget JT = LI->second;
1022 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1024 addSuccessor(B, JT.block);
1027 // Add successors to the Indirect Goto Dispatch block (if we have one).
1028 if (CFGBlock *B = cfg->getIndirectGotoBlock())
1029 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1030 E = AddressTakenLabels.end(); I != E; ++I ) {
1032 // Lookup the target block.
1033 LabelMapTy::iterator LI = LabelMap.find(*I);
1035 // If there is no target block that contains label, then we are looking
1036 // at an incomplete AST. Handle this by not registering a successor.
1037 if (LI == LabelMap.end()) continue;
1039 addSuccessor(B, LI->second.block);
1042 // Create an empty entry block that has no predecessors.
1043 cfg->setEntry(createBlock());
1045 return std::move(cfg);
1048 /// createBlock - Used to lazily create blocks that are connected
1049 /// to the current (global) succcessor.
1050 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1051 CFGBlock *B = cfg->createBlock();
1052 if (add_successor && Succ)
1053 addSuccessor(B, Succ);
1057 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1058 /// CFG. It is *not* connected to the current (global) successor, and instead
1059 /// directly tied to the exit block in order to be reachable.
1060 CFGBlock *CFGBuilder::createNoReturnBlock() {
1061 CFGBlock *B = createBlock(false);
1062 B->setHasNoReturnElement();
1063 addSuccessor(B, &cfg->getExit(), Succ);
1067 /// addInitializer - Add C++ base or member initializer element to CFG.
1068 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
1069 if (!BuildOpts.AddInitializers)
1072 bool HasTemporaries = false;
1074 // Destructors of temporaries in initialization expression should be called
1075 // after initialization finishes.
1076 Expr *Init = I->getInit();
1078 HasTemporaries = isa<ExprWithCleanups>(Init);
1080 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1081 // Generate destructors for temporaries in initialization expression.
1082 TempDtorContext Context;
1083 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1084 /*BindToTemporary=*/false, Context);
1089 appendInitializer(Block, I);
1092 if (HasTemporaries) {
1093 // For expression with temporaries go directly to subexpression to omit
1094 // generating destructors for the second time.
1095 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1097 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1098 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1099 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1100 // may cause the same Expr to appear more than once in the CFG. Doing it
1101 // here is safe because there's only one initializer per field.
1103 appendStmt(Block, Default);
1104 if (Stmt *Child = Default->getExpr())
1105 if (CFGBlock *R = Visit(Child))
1116 /// \brief Retrieve the type of the temporary object whose lifetime was
1117 /// extended by a local reference with the given initializer.
1118 static QualType getReferenceInitTemporaryType(ASTContext &Context,
1121 // Skip parentheses.
1122 Init = Init->IgnoreParens();
1124 // Skip through cleanups.
1125 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1126 Init = EWC->getSubExpr();
1130 // Skip through the temporary-materialization expression.
1131 if (const MaterializeTemporaryExpr *MTE
1132 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1133 Init = MTE->GetTemporaryExpr();
1137 // Skip derived-to-base and no-op casts.
1138 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1139 if ((CE->getCastKind() == CK_DerivedToBase ||
1140 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1141 CE->getCastKind() == CK_NoOp) &&
1142 Init->getType()->isRecordType()) {
1143 Init = CE->getSubExpr();
1148 // Skip member accesses into rvalues.
1149 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1150 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1151 Init = ME->getBase();
1159 return Init->getType();
1162 /// addAutomaticObjDtors - Add to current block automatic objects destructors
1163 /// for objects in range of local scope positions. Use S as trigger statement
1164 /// for destructors.
1165 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
1166 LocalScope::const_iterator E, Stmt *S) {
1167 if (!BuildOpts.AddImplicitDtors)
1173 // We need to append the destructors in reverse order, but any one of them
1174 // may be a no-return destructor which changes the CFG. As a result, buffer
1175 // this sequence up and replay them in reverse order when appending onto the
1177 SmallVector<VarDecl*, 10> Decls;
1178 Decls.reserve(B.distance(E));
1179 for (LocalScope::const_iterator I = B; I != E; ++I)
1180 Decls.push_back(*I);
1182 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1185 // If this destructor is marked as a no-return destructor, we need to
1186 // create a new block for the destructor which does not have as a successor
1187 // anything built thus far: control won't flow out of this block.
1188 QualType Ty = (*I)->getType();
1189 if (Ty->isReferenceType()) {
1190 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
1192 Ty = Context->getBaseElementType(Ty);
1194 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
1195 Block = createNoReturnBlock();
1199 appendAutomaticObjDtor(Block, *I, S);
1203 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
1204 /// base and member objects in destructor.
1205 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1206 assert (BuildOpts.AddImplicitDtors
1207 && "Can be called only when dtors should be added");
1208 const CXXRecordDecl *RD = DD->getParent();
1210 // At the end destroy virtual base objects.
1211 for (const auto &VI : RD->vbases()) {
1212 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
1213 if (!CD->hasTrivialDestructor()) {
1215 appendBaseDtor(Block, &VI);
1219 // Before virtual bases destroy direct base objects.
1220 for (const auto &BI : RD->bases()) {
1221 if (!BI.isVirtual()) {
1222 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
1223 if (!CD->hasTrivialDestructor()) {
1225 appendBaseDtor(Block, &BI);
1230 // First destroy member objects.
1231 for (auto *FI : RD->fields()) {
1232 // Check for constant size array. Set type to array element type.
1233 QualType QT = FI->getType();
1234 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1235 if (AT->getSize() == 0)
1237 QT = AT->getElementType();
1240 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1241 if (!CD->hasTrivialDestructor()) {
1243 appendMemberDtor(Block, FI);
1248 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1249 /// way return valid LocalScope object.
1250 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
1252 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1253 Scope = alloc.Allocate<LocalScope>();
1254 BumpVectorContext ctx(alloc);
1255 new (Scope) LocalScope(ctx, ScopePos);
1260 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
1261 /// that should create implicit scope (e.g. if/else substatements).
1262 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
1263 if (!BuildOpts.AddImplicitDtors)
1266 LocalScope *Scope = nullptr;
1268 // For compound statement we will be creating explicit scope.
1269 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1270 for (auto *BI : CS->body()) {
1271 Stmt *SI = BI->stripLabelLikeStatements();
1272 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
1273 Scope = addLocalScopeForDeclStmt(DS, Scope);
1278 // For any other statement scope will be implicit and as such will be
1279 // interesting only for DeclStmt.
1280 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
1281 addLocalScopeForDeclStmt(DS);
1284 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1285 /// reuse Scope if not NULL.
1286 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
1287 LocalScope* Scope) {
1288 if (!BuildOpts.AddImplicitDtors)
1291 for (auto *DI : DS->decls())
1292 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
1293 Scope = addLocalScopeForVarDecl(VD, Scope);
1297 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1298 /// create add scope for automatic objects and temporary objects bound to
1299 /// const reference. Will reuse Scope if not NULL.
1300 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
1301 LocalScope* Scope) {
1302 if (!BuildOpts.AddImplicitDtors)
1305 // Check if variable is local.
1306 switch (VD->getStorageClass()) {
1311 default: return Scope;
1314 // Check for const references bound to temporary. Set type to pointee.
1315 QualType QT = VD->getType();
1316 if (QT.getTypePtr()->isReferenceType()) {
1317 // Attempt to determine whether this declaration lifetime-extends a
1320 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1321 // temporaries, and a single declaration can extend multiple temporaries.
1322 // We should look at the storage duration on each nested
1323 // MaterializeTemporaryExpr instead.
1324 const Expr *Init = VD->getInit();
1327 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
1328 Init = EWC->getSubExpr();
1329 if (!isa<MaterializeTemporaryExpr>(Init))
1332 // Lifetime-extending a temporary.
1333 QT = getReferenceInitTemporaryType(*Context, Init);
1336 // Check for constant size array. Set type to array element type.
1337 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1338 if (AT->getSize() == 0)
1340 QT = AT->getElementType();
1343 // Check if type is a C++ class with non-trivial destructor.
1344 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1345 if (!CD->hasTrivialDestructor()) {
1346 // Add the variable to scope
1347 Scope = createOrReuseLocalScope(Scope);
1349 ScopePos = Scope->begin();
1354 /// addLocalScopeAndDtors - For given statement add local scope for it and
1355 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
1356 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
1357 if (!BuildOpts.AddImplicitDtors)
1360 LocalScope::const_iterator scopeBeginPos = ScopePos;
1361 addLocalScopeForStmt(S);
1362 addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
1365 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1366 /// variables with automatic storage duration to CFGBlock's elements vector.
1367 /// Elements will be prepended to physical beginning of the vector which
1368 /// happens to be logical end. Use blocks terminator as statement that specifies
1369 /// destructors call site.
1370 /// FIXME: This mechanism for adding automatic destructors doesn't handle
1371 /// no-return destructors properly.
1372 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
1373 LocalScope::const_iterator B, LocalScope::const_iterator E) {
1374 BumpVectorContext &C = cfg->getBumpVectorContext();
1375 CFGBlock::iterator InsertPos
1376 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1377 for (LocalScope::const_iterator I = B; I != E; ++I)
1378 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1379 Blk->getTerminator());
1382 /// Visit - Walk the subtree of a statement and add extra
1383 /// blocks for ternary operators, &&, and ||. We also process "," and
1384 /// DeclStmts (which may contain nested control-flow).
1385 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
1391 if (Expr *E = dyn_cast<Expr>(S))
1392 S = E->IgnoreParens();
1394 switch (S->getStmtClass()) {
1396 return VisitStmt(S, asc);
1398 case Stmt::AddrLabelExprClass:
1399 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
1401 case Stmt::BinaryConditionalOperatorClass:
1402 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1404 case Stmt::BinaryOperatorClass:
1405 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
1407 case Stmt::BlockExprClass:
1408 return VisitNoRecurse(cast<Expr>(S), asc);
1410 case Stmt::BreakStmtClass:
1411 return VisitBreakStmt(cast<BreakStmt>(S));
1413 case Stmt::CallExprClass:
1414 case Stmt::CXXOperatorCallExprClass:
1415 case Stmt::CXXMemberCallExprClass:
1416 case Stmt::UserDefinedLiteralClass:
1417 return VisitCallExpr(cast<CallExpr>(S), asc);
1419 case Stmt::CaseStmtClass:
1420 return VisitCaseStmt(cast<CaseStmt>(S));
1422 case Stmt::ChooseExprClass:
1423 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
1425 case Stmt::CompoundStmtClass:
1426 return VisitCompoundStmt(cast<CompoundStmt>(S));
1428 case Stmt::ConditionalOperatorClass:
1429 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
1431 case Stmt::ContinueStmtClass:
1432 return VisitContinueStmt(cast<ContinueStmt>(S));
1434 case Stmt::CXXCatchStmtClass:
1435 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1437 case Stmt::ExprWithCleanupsClass:
1438 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
1440 case Stmt::CXXDefaultArgExprClass:
1441 case Stmt::CXXDefaultInitExprClass:
1442 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1443 // called function's declaration, not by the caller. If we simply add
1444 // this expression to the CFG, we could end up with the same Expr
1445 // appearing multiple times.
1446 // PR13385 / <rdar://problem/12156507>
1448 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1449 // expression to be used in the same function (through aggregate
1451 return VisitStmt(S, asc);
1453 case Stmt::CXXBindTemporaryExprClass:
1454 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1456 case Stmt::CXXConstructExprClass:
1457 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1459 case Stmt::CXXNewExprClass:
1460 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1462 case Stmt::CXXDeleteExprClass:
1463 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1465 case Stmt::CXXFunctionalCastExprClass:
1466 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1468 case Stmt::CXXTemporaryObjectExprClass:
1469 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1471 case Stmt::CXXThrowExprClass:
1472 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
1474 case Stmt::CXXTryStmtClass:
1475 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
1477 case Stmt::CXXForRangeStmtClass:
1478 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1480 case Stmt::DeclStmtClass:
1481 return VisitDeclStmt(cast<DeclStmt>(S));
1483 case Stmt::DefaultStmtClass:
1484 return VisitDefaultStmt(cast<DefaultStmt>(S));
1486 case Stmt::DoStmtClass:
1487 return VisitDoStmt(cast<DoStmt>(S));
1489 case Stmt::ForStmtClass:
1490 return VisitForStmt(cast<ForStmt>(S));
1492 case Stmt::GotoStmtClass:
1493 return VisitGotoStmt(cast<GotoStmt>(S));
1495 case Stmt::IfStmtClass:
1496 return VisitIfStmt(cast<IfStmt>(S));
1498 case Stmt::ImplicitCastExprClass:
1499 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
1501 case Stmt::IndirectGotoStmtClass:
1502 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
1504 case Stmt::LabelStmtClass:
1505 return VisitLabelStmt(cast<LabelStmt>(S));
1507 case Stmt::LambdaExprClass:
1508 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1510 case Stmt::MemberExprClass:
1511 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1513 case Stmt::NullStmtClass:
1516 case Stmt::ObjCAtCatchStmtClass:
1517 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1519 case Stmt::ObjCAutoreleasePoolStmtClass:
1520 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1522 case Stmt::ObjCAtSynchronizedStmtClass:
1523 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
1525 case Stmt::ObjCAtThrowStmtClass:
1526 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
1528 case Stmt::ObjCAtTryStmtClass:
1529 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
1531 case Stmt::ObjCForCollectionStmtClass:
1532 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
1534 case Stmt::OpaqueValueExprClass:
1537 case Stmt::PseudoObjectExprClass:
1538 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1540 case Stmt::ReturnStmtClass:
1541 return VisitReturnStmt(cast<ReturnStmt>(S));
1543 case Stmt::UnaryExprOrTypeTraitExprClass:
1544 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1547 case Stmt::StmtExprClass:
1548 return VisitStmtExpr(cast<StmtExpr>(S), asc);
1550 case Stmt::SwitchStmtClass:
1551 return VisitSwitchStmt(cast<SwitchStmt>(S));
1553 case Stmt::UnaryOperatorClass:
1554 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1556 case Stmt::WhileStmtClass:
1557 return VisitWhileStmt(cast<WhileStmt>(S));
1561 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
1562 if (asc.alwaysAdd(*this, S)) {
1564 appendStmt(Block, S);
1567 return VisitChildren(S);
1570 /// VisitChildren - Visit the children of a Stmt.
1571 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1572 CFGBlock *B = Block;
1574 // Visit the children in their reverse order so that they appear in
1575 // left-to-right (natural) order in the CFG.
1576 reverse_children RChildren(S);
1577 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1579 if (Stmt *Child = *I)
1580 if (CFGBlock *R = Visit(Child))
1586 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1587 AddStmtChoice asc) {
1588 AddressTakenLabels.insert(A->getLabel());
1590 if (asc.alwaysAdd(*this, A)) {
1592 appendStmt(Block, A);
1598 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
1599 AddStmtChoice asc) {
1600 if (asc.alwaysAdd(*this, U)) {
1602 appendStmt(Block, U);
1605 return Visit(U->getSubExpr(), AddStmtChoice());
1608 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1609 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1610 appendStmt(ConfluenceBlock, B);
1615 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1616 ConfluenceBlock).first;
1619 std::pair<CFGBlock*, CFGBlock*>
1620 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1622 CFGBlock *TrueBlock,
1623 CFGBlock *FalseBlock) {
1625 // Introspect the RHS. If it is a nested logical operation, we recursively
1626 // build the CFG using this function. Otherwise, resort to default
1627 // CFG construction behavior.
1628 Expr *RHS = B->getRHS()->IgnoreParens();
1629 CFGBlock *RHSBlock, *ExitBlock;
1632 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1633 if (B_RHS->isLogicalOp()) {
1634 std::tie(RHSBlock, ExitBlock) =
1635 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1639 // The RHS is not a nested logical operation. Don't push the terminator
1640 // down further, but instead visit RHS and construct the respective
1641 // pieces of the CFG, and link up the RHSBlock with the terminator
1642 // we have been provided.
1643 ExitBlock = RHSBlock = createBlock(false);
1646 assert(TrueBlock == FalseBlock);
1647 addSuccessor(RHSBlock, TrueBlock);
1650 RHSBlock->setTerminator(Term);
1651 TryResult KnownVal = tryEvaluateBool(RHS);
1652 if (!KnownVal.isKnown())
1653 KnownVal = tryEvaluateBool(B);
1654 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1655 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
1659 RHSBlock = addStmt(RHS);
1664 return std::make_pair(nullptr, nullptr);
1666 // Generate the blocks for evaluating the LHS.
1667 Expr *LHS = B->getLHS()->IgnoreParens();
1669 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1670 if (B_LHS->isLogicalOp()) {
1671 if (B->getOpcode() == BO_LOr)
1672 FalseBlock = RHSBlock;
1674 TrueBlock = RHSBlock;
1676 // For the LHS, treat 'B' as the terminator that we want to sink
1677 // into the nested branch. The RHS always gets the top-most
1679 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1682 // Create the block evaluating the LHS.
1683 // This contains the '&&' or '||' as the terminator.
1684 CFGBlock *LHSBlock = createBlock(false);
1685 LHSBlock->setTerminator(B);
1688 CFGBlock *EntryLHSBlock = addStmt(LHS);
1691 return std::make_pair(nullptr, nullptr);
1693 // See if this is a known constant.
1694 TryResult KnownVal = tryEvaluateBool(LHS);
1696 // Now link the LHSBlock with RHSBlock.
1697 if (B->getOpcode() == BO_LOr) {
1698 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
1699 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
1701 assert(B->getOpcode() == BO_LAnd);
1702 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
1703 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
1706 return std::make_pair(EntryLHSBlock, ExitBlock);
1710 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1711 AddStmtChoice asc) {
1713 if (B->isLogicalOp())
1714 return VisitLogicalOperator(B);
1716 if (B->getOpcode() == BO_Comma) { // ,
1718 appendStmt(Block, B);
1719 addStmt(B->getRHS());
1720 return addStmt(B->getLHS());
1723 if (B->isAssignmentOp()) {
1724 if (asc.alwaysAdd(*this, B)) {
1726 appendStmt(Block, B);
1729 return Visit(B->getRHS());
1732 if (asc.alwaysAdd(*this, B)) {
1734 appendStmt(Block, B);
1737 CFGBlock *RBlock = Visit(B->getRHS());
1738 CFGBlock *LBlock = Visit(B->getLHS());
1739 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1740 // containing a DoStmt, and the LHS doesn't create a new block, then we should
1741 // return RBlock. Otherwise we'll incorrectly return NULL.
1742 return (LBlock ? LBlock : RBlock);
1745 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
1746 if (asc.alwaysAdd(*this, E)) {
1748 appendStmt(Block, E);
1753 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1754 // "break" is a control-flow statement. Thus we stop processing the current
1759 // Now create a new block that ends with the break statement.
1760 Block = createBlock(false);
1761 Block->setTerminator(B);
1763 // If there is no target for the break, then we are looking at an incomplete
1764 // AST. This means that the CFG cannot be constructed.
1765 if (BreakJumpTarget.block) {
1766 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1767 addSuccessor(Block, BreakJumpTarget.block);
1775 static bool CanThrow(Expr *E, ASTContext &Ctx) {
1776 QualType Ty = E->getType();
1777 if (Ty->isFunctionPointerType())
1778 Ty = Ty->getAs<PointerType>()->getPointeeType();
1779 else if (Ty->isBlockPointerType())
1780 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
1782 const FunctionType *FT = Ty->getAs<FunctionType>();
1784 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
1785 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
1786 Proto->isNothrow(Ctx))
1792 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
1793 // Compute the callee type.
1794 QualType calleeType = C->getCallee()->getType();
1795 if (calleeType == Context->BoundMemberTy) {
1796 QualType boundType = Expr::findBoundMemberType(C->getCallee());
1798 // We should only get a null bound type if processing a dependent
1799 // CFG. Recover by assuming nothing.
1800 if (!boundType.isNull()) calleeType = boundType;
1803 // If this is a call to a no-return function, this stops the block here.
1804 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1806 bool AddEHEdge = false;
1808 // Languages without exceptions are assumed to not throw.
1809 if (Context->getLangOpts().Exceptions) {
1810 if (BuildOpts.AddEHEdges)
1814 // If this is a call to a builtin function, it might not actually evaluate
1815 // its arguments. Don't add them to the CFG if this is the case.
1816 bool OmitArguments = false;
1818 if (FunctionDecl *FD = C->getDirectCallee()) {
1819 if (FD->isNoReturn())
1821 if (FD->hasAttr<NoThrowAttr>())
1823 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
1824 OmitArguments = true;
1827 if (!CanThrow(C->getCallee(), *Context))
1830 if (OmitArguments) {
1831 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
1832 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
1834 appendStmt(Block, C);
1835 return Visit(C->getCallee());
1838 if (!NoReturn && !AddEHEdge) {
1839 return VisitStmt(C, asc.withAlwaysAdd(true));
1849 Block = createNoReturnBlock();
1851 Block = createBlock();
1853 appendStmt(Block, C);
1856 // Add exceptional edges.
1857 if (TryTerminatedBlock)
1858 addSuccessor(Block, TryTerminatedBlock);
1860 addSuccessor(Block, &cfg->getExit());
1863 return VisitChildren(C);
1866 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1867 AddStmtChoice asc) {
1868 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1869 appendStmt(ConfluenceBlock, C);
1873 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1874 Succ = ConfluenceBlock;
1876 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
1880 Succ = ConfluenceBlock;
1882 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
1886 Block = createBlock(false);
1887 // See if this is a known constant.
1888 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1889 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
1890 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
1891 Block->setTerminator(C);
1892 return addStmt(C->getCond());
1896 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
1897 addLocalScopeAndDtors(C);
1898 CFGBlock *LastBlock = Block;
1900 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1902 // If we hit a segment of code just containing ';' (NullStmts), we can
1903 // get a null block back. In such cases, just use the LastBlock
1904 if (CFGBlock *newBlock = addStmt(*I))
1905 LastBlock = newBlock;
1914 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
1915 AddStmtChoice asc) {
1916 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
1917 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
1919 // Create the confluence block that will "merge" the results of the ternary
1921 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1922 appendStmt(ConfluenceBlock, C);
1926 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1928 // Create a block for the LHS expression if there is an LHS expression. A
1929 // GCC extension allows LHS to be NULL, causing the condition to be the
1930 // value that is returned instead.
1931 // e.g: x ?: y is shorthand for: x ? x : y;
1932 Succ = ConfluenceBlock;
1934 CFGBlock *LHSBlock = nullptr;
1935 const Expr *trueExpr = C->getTrueExpr();
1936 if (trueExpr != opaqueValue) {
1937 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
1943 LHSBlock = ConfluenceBlock;
1945 // Create the block for the RHS expression.
1946 Succ = ConfluenceBlock;
1947 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
1951 // If the condition is a logical '&&' or '||', build a more accurate CFG.
1952 if (BinaryOperator *Cond =
1953 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
1954 if (Cond->isLogicalOp())
1955 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
1957 // Create the block that will contain the condition.
1958 Block = createBlock(false);
1960 // See if this is a known constant.
1961 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1962 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
1963 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
1964 Block->setTerminator(C);
1965 Expr *condExpr = C->getCond();
1968 // Run the condition expression if it's not trivially expressed in
1969 // terms of the opaque value (or if there is no opaque value).
1970 if (condExpr != opaqueValue)
1973 // Before that, run the common subexpression if there was one.
1974 // At least one of this or the above will be run.
1975 return addStmt(BCO->getCommon());
1978 return addStmt(condExpr);
1981 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
1982 // Check if the Decl is for an __label__. If so, elide it from the
1984 if (isa<LabelDecl>(*DS->decl_begin()))
1987 // This case also handles static_asserts.
1988 if (DS->isSingleDecl())
1989 return VisitDeclSubExpr(DS);
1991 CFGBlock *B = nullptr;
1993 // Build an individual DeclStmt for each decl.
1994 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
1995 E = DS->decl_rend();
1997 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
1998 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
1999 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
2001 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2002 // automatically freed with the CFG.
2003 DeclGroupRef DG(*I);
2005 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
2006 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
2007 cfg->addSyntheticDeclStmt(DSNew, DS);
2009 // Append the fake DeclStmt to block.
2010 B = VisitDeclSubExpr(DSNew);
2016 /// VisitDeclSubExpr - Utility method to add block-level expressions for
2017 /// DeclStmts and initializers in them.
2018 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
2019 assert(DS->isSingleDecl() && "Can handle single declarations only.");
2020 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
2023 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2024 // runtime semantics.
2028 bool HasTemporaries = false;
2030 // Guard static initializers under a branch.
2031 CFGBlock *blockAfterStaticInit = nullptr;
2033 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2034 // For static variables, we need to create a branch to track
2035 // whether or not they are initialized.
2042 blockAfterStaticInit = Succ;
2045 // Destructors of temporaries in initialization expression should be called
2046 // after initialization finishes.
2047 Expr *Init = VD->getInit();
2049 HasTemporaries = isa<ExprWithCleanups>(Init);
2051 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
2052 // Generate destructors for temporaries in initialization expression.
2053 TempDtorContext Context;
2054 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2055 /*BindToTemporary=*/false, Context);
2060 appendStmt(Block, DS);
2062 // Keep track of the last non-null block, as 'Block' can be nulled out
2063 // if the initializer expression is something like a 'while' in a
2064 // statement-expression.
2065 CFGBlock *LastBlock = Block;
2068 if (HasTemporaries) {
2069 // For expression with temporaries go directly to subexpression to omit
2070 // generating destructors for the second time.
2071 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2072 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2073 LastBlock = newBlock;
2076 if (CFGBlock *newBlock = Visit(Init))
2077 LastBlock = newBlock;
2081 // If the type of VD is a VLA, then we must process its size expressions.
2082 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
2083 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
2084 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2085 LastBlock = newBlock;
2088 // Remove variable from local scope.
2089 if (ScopePos && VD == *ScopePos)
2092 CFGBlock *B = LastBlock;
2093 if (blockAfterStaticInit) {
2095 Block = createBlock(false);
2096 Block->setTerminator(DS);
2097 addSuccessor(Block, blockAfterStaticInit);
2098 addSuccessor(Block, B);
2105 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
2106 // We may see an if statement in the middle of a basic block, or it may be the
2107 // first statement we are processing. In either case, we create a new basic
2108 // block. First, we create the blocks for the then...else statements, and
2109 // then we create the block containing the if statement. If we were in the
2110 // middle of a block, we stop processing that block. That block is then the
2111 // implicit successor for the "then" and "else" clauses.
2113 // Save local scope position because in case of condition variable ScopePos
2114 // won't be restored when traversing AST.
2115 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2117 // Create local scope for possible condition variable.
2118 // Store scope position. Add implicit destructor.
2119 if (VarDecl *VD = I->getConditionVariable()) {
2120 LocalScope::const_iterator BeginScopePos = ScopePos;
2121 addLocalScopeForVarDecl(VD);
2122 addAutomaticObjDtors(ScopePos, BeginScopePos, I);
2125 // The block we were processing is now finished. Make it the successor
2133 // Process the false branch.
2134 CFGBlock *ElseBlock = Succ;
2136 if (Stmt *Else = I->getElse()) {
2137 SaveAndRestore<CFGBlock*> sv(Succ);
2139 // NULL out Block so that the recursive call to Visit will
2140 // create a new basic block.
2143 // If branch is not a compound statement create implicit scope
2144 // and add destructors.
2145 if (!isa<CompoundStmt>(Else))
2146 addLocalScopeAndDtors(Else);
2148 ElseBlock = addStmt(Else);
2150 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2151 ElseBlock = sv.get();
2158 // Process the true branch.
2159 CFGBlock *ThenBlock;
2161 Stmt *Then = I->getThen();
2163 SaveAndRestore<CFGBlock*> sv(Succ);
2166 // If branch is not a compound statement create implicit scope
2167 // and add destructors.
2168 if (!isa<CompoundStmt>(Then))
2169 addLocalScopeAndDtors(Then);
2171 ThenBlock = addStmt(Then);
2174 // We can reach here if the "then" body has all NullStmts.
2175 // Create an empty block so we can distinguish between true and false
2176 // branches in path-sensitive analyses.
2177 ThenBlock = createBlock(false);
2178 addSuccessor(ThenBlock, sv.get());
2185 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2186 // having these handle the actual control-flow jump. Note that
2187 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2188 // we resort to the old control-flow behavior. This special handling
2189 // removes infeasible paths from the control-flow graph by having the
2190 // control-flow transfer of '&&' or '||' go directly into the then/else
2192 if (!I->getConditionVariable())
2193 if (BinaryOperator *Cond =
2194 dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
2195 if (Cond->isLogicalOp())
2196 return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2198 // Now create a new block containing the if statement.
2199 Block = createBlock(false);
2201 // Set the terminator of the new block to the If statement.
2202 Block->setTerminator(I);
2204 // See if this is a known constant.
2205 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
2207 // Add the successors. If we know that specific branches are
2208 // unreachable, inform addSuccessor() of that knowledge.
2209 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2210 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
2212 // Add the condition as the last statement in the new block. This may create
2213 // new blocks as the condition may contain control-flow. Any newly created
2214 // blocks will be pointed to be "Block".
2215 CFGBlock *LastBlock = addStmt(I->getCond());
2217 // Finally, if the IfStmt contains a condition variable, add it and its
2218 // initializer to the CFG.
2219 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2221 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2228 CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
2229 // If we were in the middle of a block we stop processing that block.
2231 // NOTE: If a "return" appears in the middle of a block, this means that the
2232 // code afterwards is DEAD (unreachable). We still keep a basic block
2233 // for that code; a simple "mark-and-sweep" from the entry block will be
2234 // able to report such dead blocks.
2236 // Create the new block.
2237 Block = createBlock(false);
2239 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
2241 // If the one of the destructors does not return, we already have the Exit
2242 // block as a successor.
2243 if (!Block->hasNoReturnElement())
2244 addSuccessor(Block, &cfg->getExit());
2246 // Add the return statement to the block. This may create new blocks if R
2247 // contains control-flow (short-circuit operations).
2248 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
2251 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
2252 // Get the block of the labeled statement. Add it to our map.
2253 addStmt(L->getSubStmt());
2254 CFGBlock *LabelBlock = Block;
2256 if (!LabelBlock) // This can happen when the body is empty, i.e.
2257 LabelBlock = createBlock(); // scopes that only contains NullStmts.
2259 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2260 "label already in map");
2261 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
2263 // Labels partition blocks, so this is the end of the basic block we were
2264 // processing (L is the block's label). Because this is label (and we have
2265 // already processed the substatement) there is no extra control-flow to worry
2267 LabelBlock->setLabel(L);
2271 // We set Block to NULL to allow lazy creation of a new block (if necessary);
2274 // This block is now the implicit successor of other blocks.
2280 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2281 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2282 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2283 et = E->capture_init_end(); it != et; ++it) {
2284 if (Expr *Init = *it) {
2285 CFGBlock *Tmp = Visit(Init);
2293 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
2294 // Goto is a control-flow statement. Thus we stop processing the current
2295 // block and create a new one.
2297 Block = createBlock(false);
2298 Block->setTerminator(G);
2300 // If we already know the mapping to the label block add the successor now.
2301 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
2303 if (I == LabelMap.end())
2304 // We will need to backpatch this block later.
2305 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2307 JumpTarget JT = I->second;
2308 addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
2309 addSuccessor(Block, JT.block);
2315 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
2316 CFGBlock *LoopSuccessor = nullptr;
2318 // Save local scope position because in case of condition variable ScopePos
2319 // won't be restored when traversing AST.
2320 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2322 // Create local scope for init statement and possible condition variable.
2323 // Add destructor for init statement and condition variable.
2324 // Store scope position for continue statement.
2325 if (Stmt *Init = F->getInit())
2326 addLocalScopeForStmt(Init);
2327 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2329 if (VarDecl *VD = F->getConditionVariable())
2330 addLocalScopeForVarDecl(VD);
2331 LocalScope::const_iterator ContinueScopePos = ScopePos;
2333 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
2335 // "for" is a control-flow statement. Thus we stop processing the current
2340 LoopSuccessor = Block;
2342 LoopSuccessor = Succ;
2344 // Save the current value for the break targets.
2345 // All breaks should go to the code following the loop.
2346 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2347 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2349 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
2351 // Now create the loop body.
2353 assert(F->getBody());
2355 // Save the current values for Block, Succ, continue and break targets.
2356 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2357 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
2359 // Create an empty block to represent the transition block for looping back
2360 // to the head of the loop. If we have increment code, it will
2361 // go in this block as well.
2362 Block = Succ = TransitionBlock = createBlock(false);
2363 TransitionBlock->setLoopTarget(F);
2365 if (Stmt *I = F->getInc()) {
2366 // Generate increment code in its own basic block. This is the target of
2367 // continue statements.
2371 // Finish up the increment (or empty) block if it hasn't been already.
2373 assert(Block == Succ);
2379 // The starting block for the loop increment is the block that should
2380 // represent the 'loop target' for looping back to the start of the loop.
2381 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2382 ContinueJumpTarget.block->setLoopTarget(F);
2384 // Loop body should end with destructor of Condition variable (if any).
2385 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
2387 // If body is not a compound statement create implicit scope
2388 // and add destructors.
2389 if (!isa<CompoundStmt>(F->getBody()))
2390 addLocalScopeAndDtors(F->getBody());
2392 // Now populate the body block, and in the process create new blocks as we
2393 // walk the body of the loop.
2394 BodyBlock = addStmt(F->getBody());
2397 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2398 // Use the continue jump target as the proxy for the body.
2399 BodyBlock = ContinueJumpTarget.block;
2405 // Because of short-circuit evaluation, the condition of the loop can span
2406 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2407 // evaluate the condition.
2408 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
2411 Expr *C = F->getCond();
2413 // Specially handle logical operators, which have a slightly
2414 // more optimal CFG representation.
2415 if (BinaryOperator *Cond =
2416 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
2417 if (Cond->isLogicalOp()) {
2418 std::tie(EntryConditionBlock, ExitConditionBlock) =
2419 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2423 // The default case when not handling logical operators.
2424 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2425 ExitConditionBlock->setTerminator(F);
2427 // See if this is a known constant.
2428 TryResult KnownVal(true);
2431 // Now add the actual condition to the condition block.
2432 // Because the condition itself may contain control-flow, new blocks may
2433 // be created. Thus we update "Succ" after adding the condition.
2434 Block = ExitConditionBlock;
2435 EntryConditionBlock = addStmt(C);
2437 // If this block contains a condition variable, add both the condition
2438 // variable and initializer to the CFG.
2439 if (VarDecl *VD = F->getConditionVariable()) {
2440 if (Expr *Init = VD->getInit()) {
2442 appendStmt(Block, F->getConditionVariableDeclStmt());
2443 EntryConditionBlock = addStmt(Init);
2444 assert(Block == EntryConditionBlock);
2448 if (Block && badCFG)
2451 KnownVal = tryEvaluateBool(C);
2454 // Add the loop body entry as a successor to the condition.
2455 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
2456 // Link up the condition block with the code that follows the loop. (the
2458 addSuccessor(ExitConditionBlock,
2459 KnownVal.isTrue() ? nullptr : LoopSuccessor);
2463 // Link up the loop-back block to the entry condition block.
2464 addSuccessor(TransitionBlock, EntryConditionBlock);
2466 // The condition block is the implicit successor for any code above the loop.
2467 Succ = EntryConditionBlock;
2469 // If the loop contains initialization, create a new block for those
2470 // statements. This block can also contain statements that precede the loop.
2471 if (Stmt *I = F->getInit()) {
2472 Block = createBlock();
2476 // There is no loop initialization. We are thus basically a while loop.
2477 // NULL out Block to force lazy block construction.
2479 Succ = EntryConditionBlock;
2480 return EntryConditionBlock;
2483 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
2484 if (asc.alwaysAdd(*this, M)) {
2486 appendStmt(Block, M);
2488 return Visit(M->getBase());
2491 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
2492 // Objective-C fast enumeration 'for' statements:
2493 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2495 // for ( Type newVariable in collection_expression ) { statements }
2500 // 1. collection_expression
2501 // T. jump to loop_entry
2503 // 1. side-effects of element expression
2504 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2505 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2508 // T. jump to loop_entry
2514 // Type existingItem;
2515 // for ( existingItem in expression ) { statements }
2519 // the same with newVariable replaced with existingItem; the binding works
2520 // the same except that for one ObjCForCollectionStmt::getElement() returns
2521 // a DeclStmt and the other returns a DeclRefExpr.
2524 CFGBlock *LoopSuccessor = nullptr;
2529 LoopSuccessor = Block;
2532 LoopSuccessor = Succ;
2534 // Build the condition blocks.
2535 CFGBlock *ExitConditionBlock = createBlock(false);
2537 // Set the terminator for the "exit" condition block.
2538 ExitConditionBlock->setTerminator(S);
2540 // The last statement in the block should be the ObjCForCollectionStmt, which
2541 // performs the actual binding to 'element' and determines if there are any
2542 // more items in the collection.
2543 appendStmt(ExitConditionBlock, S);
2544 Block = ExitConditionBlock;
2546 // Walk the 'element' expression to see if there are any side-effects. We
2547 // generate new blocks as necessary. We DON'T add the statement by default to
2548 // the CFG unless it contains control-flow.
2549 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2550 AddStmtChoice::NotAlwaysAdd);
2557 // The condition block is the implicit successor for the loop body as well as
2558 // any code above the loop.
2559 Succ = EntryConditionBlock;
2561 // Now create the true branch.
2563 // Save the current values for Succ, continue and break targets.
2564 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2565 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2566 save_break(BreakJumpTarget);
2568 // Add an intermediate block between the BodyBlock and the
2569 // EntryConditionBlock to represent the "loop back" transition, for looping
2570 // back to the head of the loop.
2571 CFGBlock *LoopBackBlock = nullptr;
2572 Succ = LoopBackBlock = createBlock();
2573 LoopBackBlock->setLoopTarget(S);
2575 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2576 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
2578 CFGBlock *BodyBlock = addStmt(S->getBody());
2581 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
2587 // This new body block is a successor to our "exit" condition block.
2588 addSuccessor(ExitConditionBlock, BodyBlock);
2591 // Link up the condition block with the code that follows the loop.
2592 // (the false branch).
2593 addSuccessor(ExitConditionBlock, LoopSuccessor);
2595 // Now create a prologue block to contain the collection expression.
2596 Block = createBlock();
2597 return addStmt(S->getCollection());
2600 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2602 return addStmt(S->getSubStmt());
2603 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2606 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
2607 // FIXME: Add locking 'primitives' to CFG for @synchronized.
2610 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
2612 // The sync body starts its own basic block. This makes it a little easier
2613 // for diagnostic clients.
2622 // Add the @synchronized to the CFG.
2624 appendStmt(Block, S);
2626 // Inline the sync expression.
2627 return addStmt(S->getSynchExpr());
2630 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
2635 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2638 // Add the PseudoObject as the last thing.
2639 appendStmt(Block, E);
2641 CFGBlock *lastBlock = Block;
2643 // Before that, evaluate all of the semantics in order. In
2644 // CFG-land, that means appending them in reverse order.
2645 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2646 Expr *Semantic = E->getSemanticExpr(--i);
2648 // If the semantic is an opaque value, we're being asked to bind
2649 // it to its source expression.
2650 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2651 Semantic = OVE->getSourceExpr();
2653 if (CFGBlock *B = Visit(Semantic))
2660 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
2661 CFGBlock *LoopSuccessor = nullptr;
2663 // Save local scope position because in case of condition variable ScopePos
2664 // won't be restored when traversing AST.
2665 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2667 // Create local scope for possible condition variable.
2668 // Store scope position for continue statement.
2669 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2670 if (VarDecl *VD = W->getConditionVariable()) {
2671 addLocalScopeForVarDecl(VD);
2672 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2675 // "while" is a control-flow statement. Thus we stop processing the current
2680 LoopSuccessor = Block;
2683 LoopSuccessor = Succ;
2686 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
2688 // Process the loop body.
2690 assert(W->getBody());
2692 // Save the current values for Block, Succ, continue and break targets.
2693 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2694 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2695 save_break(BreakJumpTarget);
2697 // Create an empty block to represent the transition block for looping back
2698 // to the head of the loop.
2699 Succ = TransitionBlock = createBlock(false);
2700 TransitionBlock->setLoopTarget(W);
2701 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
2703 // All breaks should go to the code following the loop.
2704 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2706 // Loop body should end with destructor of Condition variable (if any).
2707 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2709 // If body is not a compound statement create implicit scope
2710 // and add destructors.
2711 if (!isa<CompoundStmt>(W->getBody()))
2712 addLocalScopeAndDtors(W->getBody());
2714 // Create the body. The returned block is the entry to the loop body.
2715 BodyBlock = addStmt(W->getBody());
2718 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
2719 else if (Block && badCFG)
2723 // Because of short-circuit evaluation, the condition of the loop can span
2724 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2725 // evaluate the condition.
2726 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
2729 Expr *C = W->getCond();
2731 // Specially handle logical operators, which have a slightly
2732 // more optimal CFG representation.
2733 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
2734 if (Cond->isLogicalOp()) {
2735 std::tie(EntryConditionBlock, ExitConditionBlock) =
2736 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
2740 // The default case when not handling logical operators.
2741 ExitConditionBlock = createBlock(false);
2742 ExitConditionBlock->setTerminator(W);
2744 // Now add the actual condition to the condition block.
2745 // Because the condition itself may contain control-flow, new blocks may
2746 // be created. Thus we update "Succ" after adding the condition.
2747 Block = ExitConditionBlock;
2748 Block = EntryConditionBlock = addStmt(C);
2750 // If this block contains a condition variable, add both the condition
2751 // variable and initializer to the CFG.
2752 if (VarDecl *VD = W->getConditionVariable()) {
2753 if (Expr *Init = VD->getInit()) {
2755 appendStmt(Block, W->getConditionVariableDeclStmt());
2756 EntryConditionBlock = addStmt(Init);
2757 assert(Block == EntryConditionBlock);
2761 if (Block && badCFG)
2764 // See if this is a known constant.
2765 const TryResult& KnownVal = tryEvaluateBool(C);
2767 // Add the loop body entry as a successor to the condition.
2768 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
2769 // Link up the condition block with the code that follows the loop. (the
2771 addSuccessor(ExitConditionBlock,
2772 KnownVal.isTrue() ? nullptr : LoopSuccessor);
2776 // Link up the loop-back block to the entry condition block.
2777 addSuccessor(TransitionBlock, EntryConditionBlock);
2779 // There can be no more statements in the condition block since we loop back
2780 // to this block. NULL out Block to force lazy creation of another block.
2783 // Return the condition block, which is the dominating block for the loop.
2784 Succ = EntryConditionBlock;
2785 return EntryConditionBlock;
2789 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
2790 // FIXME: For now we pretend that @catch and the code it contains does not
2795 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
2796 // FIXME: This isn't complete. We basically treat @throw like a return
2799 // If we were in the middle of a block we stop processing that block.
2803 // Create the new block.
2804 Block = createBlock(false);
2806 // The Exit block is the only successor.
2807 addSuccessor(Block, &cfg->getExit());
2809 // Add the statement to the block. This may create new blocks if S contains
2810 // control-flow (short-circuit operations).
2811 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
2814 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
2815 // If we were in the middle of a block we stop processing that block.
2819 // Create the new block.
2820 Block = createBlock(false);
2822 if (TryTerminatedBlock)
2823 // The current try statement is the only successor.
2824 addSuccessor(Block, TryTerminatedBlock);
2826 // otherwise the Exit block is the only successor.
2827 addSuccessor(Block, &cfg->getExit());
2829 // Add the statement to the block. This may create new blocks if S contains
2830 // control-flow (short-circuit operations).
2831 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
2834 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
2835 CFGBlock *LoopSuccessor = nullptr;
2837 // "do...while" is a control-flow statement. Thus we stop processing the
2842 LoopSuccessor = Block;
2844 LoopSuccessor = Succ;
2846 // Because of short-circuit evaluation, the condition of the loop can span
2847 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2848 // evaluate the condition.
2849 CFGBlock *ExitConditionBlock = createBlock(false);
2850 CFGBlock *EntryConditionBlock = ExitConditionBlock;
2852 // Set the terminator for the "exit" condition block.
2853 ExitConditionBlock->setTerminator(D);
2855 // Now add the actual condition to the condition block. Because the condition
2856 // itself may contain control-flow, new blocks may be created.
2857 if (Stmt *C = D->getCond()) {
2858 Block = ExitConditionBlock;
2859 EntryConditionBlock = addStmt(C);
2866 // The condition block is the implicit successor for the loop body.
2867 Succ = EntryConditionBlock;
2869 // See if this is a known constant.
2870 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
2872 // Process the loop body.
2873 CFGBlock *BodyBlock = nullptr;
2875 assert(D->getBody());
2877 // Save the current values for Block, Succ, and continue and break targets
2878 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2879 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2880 save_break(BreakJumpTarget);
2882 // All continues within this loop should go to the condition block
2883 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
2885 // All breaks should go to the code following the loop.
2886 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2888 // NULL out Block to force lazy instantiation of blocks for the body.
2891 // If body is not a compound statement create implicit scope
2892 // and add destructors.
2893 if (!isa<CompoundStmt>(D->getBody()))
2894 addLocalScopeAndDtors(D->getBody());
2896 // Create the body. The returned block is the entry to the loop body.
2897 BodyBlock = addStmt(D->getBody());
2900 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
2906 if (!KnownVal.isFalse()) {
2907 // Add an intermediate block between the BodyBlock and the
2908 // ExitConditionBlock to represent the "loop back" transition. Create an
2909 // empty block to represent the transition block for looping back to the
2910 // head of the loop.
2911 // FIXME: Can we do this more efficiently without adding another block?
2914 CFGBlock *LoopBackBlock = createBlock();
2915 LoopBackBlock->setLoopTarget(D);
2917 // Add the loop body entry as a successor to the condition.
2918 addSuccessor(ExitConditionBlock, LoopBackBlock);
2921 addSuccessor(ExitConditionBlock, nullptr);
2924 // Link up the condition block with the code that follows the loop.
2925 // (the false branch).
2926 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
2928 // There can be no more statements in the body block(s) since we loop back to
2929 // the body. NULL out Block to force lazy creation of another block.
2932 // Return the loop body, which is the dominating block for the loop.
2937 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
2938 // "continue" is a control-flow statement. Thus we stop processing the
2943 // Now create a new block that ends with the continue statement.
2944 Block = createBlock(false);
2945 Block->setTerminator(C);
2947 // If there is no target for the continue, then we are looking at an
2948 // incomplete AST. This means the CFG cannot be constructed.
2949 if (ContinueJumpTarget.block) {
2950 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
2951 addSuccessor(Block, ContinueJumpTarget.block);
2958 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
2959 AddStmtChoice asc) {
2961 if (asc.alwaysAdd(*this, E)) {
2963 appendStmt(Block, E);
2966 // VLA types have expressions that must be evaluated.
2967 CFGBlock *lastBlock = Block;
2969 if (E->isArgumentType()) {
2970 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
2971 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
2972 lastBlock = addStmt(VA->getSizeExpr());
2977 /// VisitStmtExpr - Utility method to handle (nested) statement
2978 /// expressions (a GCC extension).
2979 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
2980 if (asc.alwaysAdd(*this, SE)) {
2982 appendStmt(Block, SE);
2984 return VisitCompoundStmt(SE->getSubStmt());
2987 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
2988 // "switch" is a control-flow statement. Thus we stop processing the current
2990 CFGBlock *SwitchSuccessor = nullptr;
2992 // Save local scope position because in case of condition variable ScopePos
2993 // won't be restored when traversing AST.
2994 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2996 // Create local scope for possible condition variable.
2997 // Store scope position. Add implicit destructor.
2998 if (VarDecl *VD = Terminator->getConditionVariable()) {
2999 LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
3000 addLocalScopeForVarDecl(VD);
3001 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
3007 SwitchSuccessor = Block;
3008 } else SwitchSuccessor = Succ;
3010 // Save the current "switch" context.
3011 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
3012 save_default(DefaultCaseBlock);
3013 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3015 // Set the "default" case to be the block after the switch statement. If the
3016 // switch statement contains a "default:", this value will be overwritten with
3017 // the block for that code.
3018 DefaultCaseBlock = SwitchSuccessor;
3020 // Create a new block that will contain the switch statement.
3021 SwitchTerminatedBlock = createBlock(false);
3023 // Now process the switch body. The code after the switch is the implicit
3025 Succ = SwitchSuccessor;
3026 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
3028 // When visiting the body, the case statements should automatically get linked
3029 // up to the switch. We also don't keep a pointer to the body, since all
3030 // control-flow from the switch goes to case/default statements.
3031 assert(Terminator->getBody() && "switch must contain a non-NULL body");
3034 // For pruning unreachable case statements, save the current state
3035 // for tracking the condition value.
3036 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3039 // Determine if the switch condition can be explicitly evaluated.
3040 assert(Terminator->getCond() && "switch condition must be non-NULL");
3041 Expr::EvalResult result;
3042 bool b = tryEvaluate(Terminator->getCond(), result);
3043 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
3044 b ? &result : nullptr);
3046 // If body is not a compound statement create implicit scope
3047 // and add destructors.
3048 if (!isa<CompoundStmt>(Terminator->getBody()))
3049 addLocalScopeAndDtors(Terminator->getBody());
3051 addStmt(Terminator->getBody());
3057 // If we have no "default:" case, the default transition is to the code
3058 // following the switch body. Moreover, take into account if all the
3059 // cases of a switch are covered (e.g., switching on an enum value).
3061 // Note: We add a successor to a switch that is considered covered yet has no
3062 // case statements if the enumeration has no enumerators.
3063 bool SwitchAlwaysHasSuccessor = false;
3064 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3065 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3066 Terminator->getSwitchCaseList();
3067 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3068 !SwitchAlwaysHasSuccessor);
3070 // Add the terminator and condition in the switch block.
3071 SwitchTerminatedBlock->setTerminator(Terminator);
3072 Block = SwitchTerminatedBlock;
3073 CFGBlock *LastBlock = addStmt(Terminator->getCond());
3075 // Finally, if the SwitchStmt contains a condition variable, add both the
3076 // SwitchStmt and the condition variable initialization to the CFG.
3077 if (VarDecl *VD = Terminator->getConditionVariable()) {
3078 if (Expr *Init = VD->getInit()) {
3080 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
3081 LastBlock = addStmt(Init);
3088 static bool shouldAddCase(bool &switchExclusivelyCovered,
3089 const Expr::EvalResult *switchCond,
3095 bool addCase = false;
3097 if (!switchExclusivelyCovered) {
3098 if (switchCond->Val.isInt()) {
3099 // Evaluate the LHS of the case value.
3100 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
3101 const llvm::APSInt &condInt = switchCond->Val.getInt();
3103 if (condInt == lhsInt) {
3105 switchExclusivelyCovered = true;
3107 else if (condInt < lhsInt) {
3108 if (const Expr *RHS = CS->getRHS()) {
3109 // Evaluate the RHS of the case value.
3110 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
3111 if (V2 <= condInt) {
3113 switchExclusivelyCovered = true;
3124 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
3125 // CaseStmts are essentially labels, so they are the first statement in a
3127 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
3129 if (Stmt *Sub = CS->getSubStmt()) {
3130 // For deeply nested chains of CaseStmts, instead of doing a recursion
3131 // (which can blow out the stack), manually unroll and create blocks
3133 while (isa<CaseStmt>(Sub)) {
3134 CFGBlock *currentBlock = createBlock(false);
3135 currentBlock->setLabel(CS);
3138 addSuccessor(LastBlock, currentBlock);
3140 TopBlock = currentBlock;
3142 addSuccessor(SwitchTerminatedBlock,
3143 shouldAddCase(switchExclusivelyCovered, switchCond,
3145 ? currentBlock : nullptr);
3147 LastBlock = currentBlock;
3148 CS = cast<CaseStmt>(Sub);
3149 Sub = CS->getSubStmt();
3155 CFGBlock *CaseBlock = Block;
3157 CaseBlock = createBlock();
3159 // Cases statements partition blocks, so this is the top of the basic block we
3160 // were processing (the "case XXX:" is the label).
3161 CaseBlock->setLabel(CS);
3166 // Add this block to the list of successors for the block with the switch
3168 assert(SwitchTerminatedBlock);
3169 addSuccessor(SwitchTerminatedBlock, CaseBlock,
3170 shouldAddCase(switchExclusivelyCovered, switchCond,
3173 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3177 addSuccessor(LastBlock, CaseBlock);
3180 // This block is now the implicit successor of other blocks.
3187 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
3188 if (Terminator->getSubStmt())
3189 addStmt(Terminator->getSubStmt());
3191 DefaultCaseBlock = Block;
3193 if (!DefaultCaseBlock)
3194 DefaultCaseBlock = createBlock();
3196 // Default statements partition blocks, so this is the top of the basic block
3197 // we were processing (the "default:" is the label).
3198 DefaultCaseBlock->setLabel(Terminator);
3203 // Unlike case statements, we don't add the default block to the successors
3204 // for the switch statement immediately. This is done when we finish
3205 // processing the switch statement. This allows for the default case
3206 // (including a fall-through to the code after the switch statement) to always
3207 // be the last successor of a switch-terminated block.
3209 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3212 // This block is now the implicit successor of other blocks.
3213 Succ = DefaultCaseBlock;
3215 return DefaultCaseBlock;
3218 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3219 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3221 CFGBlock *TrySuccessor = nullptr;
3226 TrySuccessor = Block;
3227 } else TrySuccessor = Succ;
3229 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
3231 // Create a new block that will contain the try statement.
3232 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3233 // Add the terminator in the try block.
3234 NewTryTerminatedBlock->setTerminator(Terminator);
3236 bool HasCatchAll = false;
3237 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3238 // The code after the try is the implicit successor.
3239 Succ = TrySuccessor;
3240 CXXCatchStmt *CS = Terminator->getHandler(h);
3241 if (CS->getExceptionDecl() == nullptr) {
3245 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
3248 // Add this block to the list of successors for the block with the try
3250 addSuccessor(NewTryTerminatedBlock, CatchBlock);
3253 if (PrevTryTerminatedBlock)
3254 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
3256 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3259 // The code after the try is the implicit successor.
3260 Succ = TrySuccessor;
3262 // Save the current "try" context.
3263 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3264 cfg->addTryDispatchBlock(TryTerminatedBlock);
3266 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
3268 return addStmt(Terminator->getTryBlock());
3271 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
3272 // CXXCatchStmt are treated like labels, so they are the first statement in a
3275 // Save local scope position because in case of exception variable ScopePos
3276 // won't be restored when traversing AST.
3277 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3279 // Create local scope for possible exception variable.
3280 // Store scope position. Add implicit destructor.
3281 if (VarDecl *VD = CS->getExceptionDecl()) {
3282 LocalScope::const_iterator BeginScopePos = ScopePos;
3283 addLocalScopeForVarDecl(VD);
3284 addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
3287 if (CS->getHandlerBlock())
3288 addStmt(CS->getHandlerBlock());
3290 CFGBlock *CatchBlock = Block;
3292 CatchBlock = createBlock();
3294 // CXXCatchStmt is more than just a label. They have semantic meaning
3295 // as well, as they implicitly "initialize" the catch variable. Add
3296 // it to the CFG as a CFGElement so that the control-flow of these
3297 // semantics gets captured.
3298 appendStmt(CatchBlock, CS);
3300 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3302 CatchBlock->setLabel(CS);
3304 // Bail out if the CFG is bad.
3308 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3314 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
3315 // C++0x for-range statements are specified as [stmt.ranged]:
3318 // auto && __range = range-init;
3319 // for ( auto __begin = begin-expr,
3320 // __end = end-expr;
3321 // __begin != __end;
3323 // for-range-declaration = *__begin;
3328 // Save local scope position before the addition of the implicit variables.
3329 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3331 // Create local scopes and destructors for range, begin and end variables.
3332 if (Stmt *Range = S->getRangeStmt())
3333 addLocalScopeForStmt(Range);
3334 if (Stmt *BeginEnd = S->getBeginEndStmt())
3335 addLocalScopeForStmt(BeginEnd);
3336 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
3338 LocalScope::const_iterator ContinueScopePos = ScopePos;
3340 // "for" is a control-flow statement. Thus we stop processing the current
3342 CFGBlock *LoopSuccessor = nullptr;
3346 LoopSuccessor = Block;
3348 LoopSuccessor = Succ;
3350 // Save the current value for the break targets.
3351 // All breaks should go to the code following the loop.
3352 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3353 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3355 // The block for the __begin != __end expression.
3356 CFGBlock *ConditionBlock = createBlock(false);
3357 ConditionBlock->setTerminator(S);
3359 // Now add the actual condition to the condition block.
3360 if (Expr *C = S->getCond()) {
3361 Block = ConditionBlock;
3362 CFGBlock *BeginConditionBlock = addStmt(C);
3365 assert(BeginConditionBlock == ConditionBlock &&
3366 "condition block in for-range was unexpectedly complex");
3367 (void)BeginConditionBlock;
3370 // The condition block is the implicit successor for the loop body as well as
3371 // any code above the loop.
3372 Succ = ConditionBlock;
3374 // See if this is a known constant.
3375 TryResult KnownVal(true);
3378 KnownVal = tryEvaluateBool(S->getCond());
3380 // Now create the loop body.
3382 assert(S->getBody());
3384 // Save the current values for Block, Succ, and continue targets.
3385 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3386 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3388 // Generate increment code in its own basic block. This is the target of
3389 // continue statements.
3391 Succ = addStmt(S->getInc());
3392 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3394 // The starting block for the loop increment is the block that should
3395 // represent the 'loop target' for looping back to the start of the loop.
3396 ContinueJumpTarget.block->setLoopTarget(S);
3398 // Finish up the increment block and prepare to start the loop body.
3404 // Add implicit scope and dtors for loop variable.
3405 addLocalScopeAndDtors(S->getLoopVarStmt());
3407 // Populate a new block to contain the loop body and loop variable.
3408 addStmt(S->getBody());
3411 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
3415 // This new body block is a successor to our condition block.
3416 addSuccessor(ConditionBlock,
3417 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
3420 // Link up the condition block with the code that follows the loop (the
3422 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
3424 // Add the initialization statements.
3425 Block = createBlock();
3426 addStmt(S->getBeginEndStmt());
3427 return addStmt(S->getRangeStmt());
3430 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
3431 AddStmtChoice asc) {
3432 if (BuildOpts.AddTemporaryDtors) {
3433 // If adding implicit destructors visit the full expression for adding
3434 // destructors of temporaries.
3435 TempDtorContext Context;
3436 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
3438 // Full expression has to be added as CFGStmt so it will be sequenced
3439 // before destructors of it's temporaries.
3440 asc = asc.withAlwaysAdd(true);
3442 return Visit(E->getSubExpr(), asc);
3445 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3446 AddStmtChoice asc) {
3447 if (asc.alwaysAdd(*this, E)) {
3449 appendStmt(Block, E);
3451 // We do not want to propagate the AlwaysAdd property.
3452 asc = asc.withAlwaysAdd(false);
3454 return Visit(E->getSubExpr(), asc);
3457 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3458 AddStmtChoice asc) {
3460 appendStmt(Block, C);
3462 return VisitChildren(C);
3465 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3466 AddStmtChoice asc) {
3469 appendStmt(Block, NE);
3471 if (NE->getInitializer())
3472 Block = Visit(NE->getInitializer());
3473 if (BuildOpts.AddCXXNewAllocator)
3474 appendNewAllocator(Block, NE);
3476 Block = Visit(NE->getArraySize());
3477 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3478 E = NE->placement_arg_end(); I != E; ++I)
3483 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3484 AddStmtChoice asc) {
3486 appendStmt(Block, DE);
3487 QualType DTy = DE->getDestroyedType();
3488 DTy = DTy.getNonReferenceType();
3489 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3491 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
3492 appendDeleteDtor(Block, RD, DE);
3495 return VisitChildren(DE);
3498 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3499 AddStmtChoice asc) {
3500 if (asc.alwaysAdd(*this, E)) {
3502 appendStmt(Block, E);
3503 // We do not want to propagate the AlwaysAdd property.
3504 asc = asc.withAlwaysAdd(false);
3506 return Visit(E->getSubExpr(), asc);
3509 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3510 AddStmtChoice asc) {
3512 appendStmt(Block, C);
3513 return VisitChildren(C);
3516 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3517 AddStmtChoice asc) {
3518 if (asc.alwaysAdd(*this, E)) {
3520 appendStmt(Block, E);
3522 return Visit(E->getSubExpr(), AddStmtChoice());
3525 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
3526 // Lazily create the indirect-goto dispatch block if there isn't one already.
3527 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
3530 IBlock = createBlock(false);
3531 cfg->setIndirectGotoBlock(IBlock);
3534 // IndirectGoto is a control-flow statement. Thus we stop processing the
3535 // current block and create a new one.
3539 Block = createBlock(false);
3540 Block->setTerminator(I);
3541 addSuccessor(Block, IBlock);
3542 return addStmt(I->getTarget());
3545 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
3546 TempDtorContext &Context) {
3547 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3554 switch (E->getStmtClass()) {
3556 return VisitChildrenForTemporaryDtors(E, Context);
3558 case Stmt::BinaryOperatorClass:
3559 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
3562 case Stmt::CXXBindTemporaryExprClass:
3563 return VisitCXXBindTemporaryExprForTemporaryDtors(
3564 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
3566 case Stmt::BinaryConditionalOperatorClass:
3567 case Stmt::ConditionalOperatorClass:
3568 return VisitConditionalOperatorForTemporaryDtors(
3569 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
3571 case Stmt::ImplicitCastExprClass:
3572 // For implicit cast we want BindToTemporary to be passed further.
3573 E = cast<CastExpr>(E)->getSubExpr();
3576 case Stmt::CXXFunctionalCastExprClass:
3577 // For functional cast we want BindToTemporary to be passed further.
3578 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
3581 case Stmt::ParenExprClass:
3582 E = cast<ParenExpr>(E)->getSubExpr();
3585 case Stmt::MaterializeTemporaryExprClass: {
3586 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
3587 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
3588 SmallVector<const Expr *, 2> CommaLHSs;
3589 SmallVector<SubobjectAdjustment, 2> Adjustments;
3590 // Find the expression whose lifetime needs to be extended.
3591 E = const_cast<Expr *>(
3592 cast<MaterializeTemporaryExpr>(E)
3593 ->GetTemporaryExpr()
3594 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
3595 // Visit the skipped comma operator left-hand sides for other temporaries.
3596 for (const Expr *CommaLHS : CommaLHSs) {
3597 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
3598 /*BindToTemporary=*/false, Context);
3603 case Stmt::BlockExprClass:
3604 // Don't recurse into blocks; their subexpressions don't get evaluated
3608 case Stmt::LambdaExprClass: {
3609 // For lambda expressions, only recurse into the capture initializers,
3610 // and not the body.
3611 auto *LE = cast<LambdaExpr>(E);
3612 CFGBlock *B = Block;
3613 for (Expr *Init : LE->capture_inits()) {
3614 if (CFGBlock *R = VisitForTemporaryDtors(
3615 Init, /*BindToTemporary=*/false, Context))
3621 case Stmt::CXXDefaultArgExprClass:
3622 E = cast<CXXDefaultArgExpr>(E)->getExpr();
3625 case Stmt::CXXDefaultInitExprClass:
3626 E = cast<CXXDefaultInitExpr>(E)->getExpr();
3631 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
3632 TempDtorContext &Context) {
3633 if (isa<LambdaExpr>(E)) {
3634 // Do not visit the children of lambdas; they have their own CFGs.
3638 // When visiting children for destructors we want to visit them in reverse
3639 // order that they will appear in the CFG. Because the CFG is built
3640 // bottom-up, this means we visit them in their natural order, which
3641 // reverses them in the CFG.
3642 CFGBlock *B = Block;
3643 for (Stmt *Child : E->children())
3645 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
3651 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
3652 BinaryOperator *E, TempDtorContext &Context) {
3653 if (E->isLogicalOp()) {
3654 VisitForTemporaryDtors(E->getLHS(), false, Context);
3655 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
3656 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
3657 RHSExecuted.negate();
3659 // We do not know at CFG-construction time whether the right-hand-side was
3660 // executed, thus we add a branch node that depends on the temporary
3661 // constructor call.
3662 TempDtorContext RHSContext(
3663 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
3664 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
3665 InsertTempDtorDecisionBlock(RHSContext);
3670 if (E->isAssignmentOp()) {
3671 // For assignment operator (=) LHS expression is visited
3672 // before RHS expression. For destructors visit them in reverse order.
3673 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3674 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3675 return LHSBlock ? LHSBlock : RHSBlock;
3678 // For any other binary operator RHS expression is visited before
3679 // LHS expression (order of children). For destructors visit them in reverse
3681 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3682 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3683 return RHSBlock ? RHSBlock : LHSBlock;
3686 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
3687 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
3688 // First add destructors for temporaries in subexpression.
3689 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
3690 if (!BindToTemporary) {
3691 // If lifetime of temporary is not prolonged (by assigning to constant
3692 // reference) add destructor for it.
3694 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
3696 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
3697 // If the destructor is marked as a no-return destructor, we need to
3698 // create a new block for the destructor which does not have as a
3699 // successor anything built thus far. Control won't flow out of this
3702 Block = createNoReturnBlock();
3703 } else if (Context.needsTempDtorBranch()) {
3704 // If we need to introduce a branch, we add a new block that we will hook
3705 // up to a decision block later.
3707 Block = createBlock();
3711 if (Context.needsTempDtorBranch()) {
3712 Context.setDecisionPoint(Succ, E);
3714 appendTemporaryDtor(Block, E);
3721 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
3722 CFGBlock *FalseSucc) {
3723 if (!Context.TerminatorExpr) {
3724 // If no temporary was found, we do not need to insert a decision point.
3727 assert(Context.TerminatorExpr);
3728 CFGBlock *Decision = createBlock(false);
3729 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
3730 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
3731 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
3732 !Context.KnownExecuted.isTrue());
3736 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
3737 AbstractConditionalOperator *E, bool BindToTemporary,
3738 TempDtorContext &Context) {
3739 VisitForTemporaryDtors(E->getCond(), false, Context);
3740 CFGBlock *ConditionBlock = Block;
3741 CFGBlock *ConditionSucc = Succ;
3742 TryResult ConditionVal = tryEvaluateBool(E->getCond());
3743 TryResult NegatedVal = ConditionVal;
3744 if (NegatedVal.isKnown()) NegatedVal.negate();
3746 TempDtorContext TrueContext(
3747 bothKnownTrue(Context.KnownExecuted, ConditionVal));
3748 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
3749 CFGBlock *TrueBlock = Block;
3751 Block = ConditionBlock;
3752 Succ = ConditionSucc;
3753 TempDtorContext FalseContext(
3754 bothKnownTrue(Context.KnownExecuted, NegatedVal));
3755 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
3757 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
3758 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
3759 } else if (TrueContext.TerminatorExpr) {
3761 InsertTempDtorDecisionBlock(TrueContext);
3763 InsertTempDtorDecisionBlock(FalseContext);
3768 } // end anonymous namespace
3770 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
3771 /// no successors or predecessors. If this is the first block created in the
3772 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
3773 CFGBlock *CFG::createBlock() {
3774 bool first_block = begin() == end();
3776 // Create the block.
3777 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
3778 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
3779 Blocks.push_back(Mem, BlkBVC);
3781 // If this is the first block, set it as the Entry and Exit.
3783 Entry = Exit = &back();
3785 // Return the block.
3789 /// buildCFG - Constructs a CFG from an AST.
3790 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
3791 ASTContext *C, const BuildOptions &BO) {
3792 CFGBuilder Builder(C, BO);
3793 return Builder.buildCFG(D, Statement);
3796 const CXXDestructorDecl *
3797 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
3798 switch (getKind()) {
3799 case CFGElement::Statement:
3800 case CFGElement::Initializer:
3801 case CFGElement::NewAllocator:
3802 llvm_unreachable("getDestructorDecl should only be used with "
3804 case CFGElement::AutomaticObjectDtor: {
3805 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
3806 QualType ty = var->getType();
3807 ty = ty.getNonReferenceType();
3808 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
3809 ty = arrayType->getElementType();
3811 const RecordType *recordType = ty->getAs<RecordType>();
3812 const CXXRecordDecl *classDecl =
3813 cast<CXXRecordDecl>(recordType->getDecl());
3814 return classDecl->getDestructor();
3816 case CFGElement::DeleteDtor: {
3817 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
3818 QualType DTy = DE->getDestroyedType();
3819 DTy = DTy.getNonReferenceType();
3820 const CXXRecordDecl *classDecl =
3821 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
3822 return classDecl->getDestructor();
3824 case CFGElement::TemporaryDtor: {
3825 const CXXBindTemporaryExpr *bindExpr =
3826 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
3827 const CXXTemporary *temp = bindExpr->getTemporary();
3828 return temp->getDestructor();
3830 case CFGElement::BaseDtor:
3831 case CFGElement::MemberDtor:
3833 // Not yet supported.
3836 llvm_unreachable("getKind() returned bogus value");
3839 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
3840 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
3841 return DD->isNoReturn();
3845 //===----------------------------------------------------------------------===//
3846 // CFGBlock operations.
3847 //===----------------------------------------------------------------------===//
3849 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
3850 : ReachableBlock(IsReachable ? B : nullptr),
3851 UnreachableBlock(!IsReachable ? B : nullptr,
3852 B && IsReachable ? AB_Normal : AB_Unreachable) {}
3854 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
3855 : ReachableBlock(B),
3856 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
3857 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
3859 void CFGBlock::addSuccessor(AdjacentBlock Succ,
3860 BumpVectorContext &C) {
3861 if (CFGBlock *B = Succ.getReachableBlock())
3862 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
3864 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
3865 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
3867 Succs.push_back(Succ, C);
3870 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
3871 const CFGBlock *From, const CFGBlock *To) {
3873 if (F.IgnoreNullPredecessors && !From)
3876 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
3877 // If the 'To' has no label or is labeled but the label isn't a
3878 // CaseStmt then filter this edge.
3879 if (const SwitchStmt *S =
3880 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
3881 if (S->isAllEnumCasesCovered()) {
3882 const Stmt *L = To->getLabel();
3883 if (!L || !isa<CaseStmt>(L))
3892 //===----------------------------------------------------------------------===//
3893 // CFG pretty printing
3894 //===----------------------------------------------------------------------===//
3898 class StmtPrinterHelper : public PrinterHelper {
3899 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
3900 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
3903 signed currentBlock;
3905 const LangOptions &LangOpts;
3908 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
3909 : currentBlock(0), currStmt(0), LangOpts(LO)
3911 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
3913 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
3914 BI != BEnd; ++BI, ++j ) {
3915 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
3916 const Stmt *stmt= SE->getStmt();
3917 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
3920 switch (stmt->getStmtClass()) {
3921 case Stmt::DeclStmtClass:
3922 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
3924 case Stmt::IfStmtClass: {
3925 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
3930 case Stmt::ForStmtClass: {
3931 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
3936 case Stmt::WhileStmtClass: {
3937 const VarDecl *var =
3938 cast<WhileStmt>(stmt)->getConditionVariable();
3943 case Stmt::SwitchStmtClass: {
3944 const VarDecl *var =
3945 cast<SwitchStmt>(stmt)->getConditionVariable();
3950 case Stmt::CXXCatchStmtClass: {
3951 const VarDecl *var =
3952 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
3965 ~StmtPrinterHelper() override {}
3967 const LangOptions &getLangOpts() const { return LangOpts; }
3968 void setBlockID(signed i) { currentBlock = i; }
3969 void setStmtID(unsigned i) { currStmt = i; }
3971 bool handledStmt(Stmt *S, raw_ostream &OS) override {
3972 StmtMapTy::iterator I = StmtMap.find(S);
3974 if (I == StmtMap.end())
3977 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
3978 && I->second.second == currStmt) {
3982 OS << "[B" << I->second.first << "." << I->second.second << "]";
3986 bool handleDecl(const Decl *D, raw_ostream &OS) {
3987 DeclMapTy::iterator I = DeclMap.find(D);
3989 if (I == DeclMap.end())
3992 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
3993 && I->second.second == currStmt) {
3997 OS << "[B" << I->second.first << "." << I->second.second << "]";
4001 } // end anonymous namespace
4005 class CFGBlockTerminatorPrint
4006 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
4009 StmtPrinterHelper* Helper;
4010 PrintingPolicy Policy;
4012 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
4013 const PrintingPolicy &Policy)
4014 : OS(os), Helper(helper), Policy(Policy) {
4015 this->Policy.IncludeNewlines = false;
4018 void VisitIfStmt(IfStmt *I) {
4020 if (Stmt *C = I->getCond())
4021 C->printPretty(OS, Helper, Policy);
4025 void VisitStmt(Stmt *Terminator) {
4026 Terminator->printPretty(OS, Helper, Policy);
4029 void VisitDeclStmt(DeclStmt *DS) {
4030 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4031 OS << "static init " << VD->getName();
4034 void VisitForStmt(ForStmt *F) {
4039 if (Stmt *C = F->getCond())
4040 C->printPretty(OS, Helper, Policy);
4047 void VisitWhileStmt(WhileStmt *W) {
4049 if (Stmt *C = W->getCond())
4050 C->printPretty(OS, Helper, Policy);
4053 void VisitDoStmt(DoStmt *D) {
4054 OS << "do ... while ";
4055 if (Stmt *C = D->getCond())
4056 C->printPretty(OS, Helper, Policy);
4059 void VisitSwitchStmt(SwitchStmt *Terminator) {
4061 Terminator->getCond()->printPretty(OS, Helper, Policy);
4064 void VisitCXXTryStmt(CXXTryStmt *CS) {
4068 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
4069 if (Stmt *Cond = C->getCond())
4070 Cond->printPretty(OS, Helper, Policy);
4071 OS << " ? ... : ...";
4074 void VisitChooseExpr(ChooseExpr *C) {
4075 OS << "__builtin_choose_expr( ";
4076 if (Stmt *Cond = C->getCond())
4077 Cond->printPretty(OS, Helper, Policy);
4081 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
4083 if (Stmt *T = I->getTarget())
4084 T->printPretty(OS, Helper, Policy);
4087 void VisitBinaryOperator(BinaryOperator* B) {
4088 if (!B->isLogicalOp()) {
4094 B->getLHS()->printPretty(OS, Helper, Policy);
4096 switch (B->getOpcode()) {
4104 llvm_unreachable("Invalid logical operator.");
4108 void VisitExpr(Expr *E) {
4109 E->printPretty(OS, Helper, Policy);
4113 void print(CFGTerminator T) {
4114 if (T.isTemporaryDtorsBranch())
4115 OS << "(Temp Dtor) ";
4119 } // end anonymous namespace
4121 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
4122 const CFGElement &E) {
4123 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4124 const Stmt *S = CS->getStmt();
4125 assert(S != nullptr && "Expecting non-null Stmt");
4127 // special printing for statement-expressions.
4128 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4129 const CompoundStmt *Sub = SE->getSubStmt();
4131 if (Sub->children()) {
4133 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4138 // special printing for comma expressions.
4139 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4140 if (B->getOpcode() == BO_Comma) {
4142 Helper.handledStmt(B->getRHS(),OS);
4147 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4149 if (isa<CXXOperatorCallExpr>(S)) {
4150 OS << " (OperatorCall)";
4152 else if (isa<CXXBindTemporaryExpr>(S)) {
4153 OS << " (BindTemporary)";
4155 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4156 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
4158 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
4159 OS << " (" << CE->getStmtClassName() << ", "
4160 << CE->getCastKindName()
4161 << ", " << CE->getType().getAsString()
4165 // Expressions need a newline.
4169 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
4170 const CXXCtorInitializer *I = IE->getInitializer();
4171 if (I->isBaseInitializer())
4172 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
4173 else if (I->isDelegatingInitializer())
4174 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
4175 else OS << I->getAnyMember()->getName();
4178 if (Expr *IE = I->getInit())
4179 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4182 if (I->isBaseInitializer())
4183 OS << " (Base initializer)\n";
4184 else if (I->isDelegatingInitializer())
4185 OS << " (Delegating initializer)\n";
4186 else OS << " (Member initializer)\n";
4188 } else if (Optional<CFGAutomaticObjDtor> DE =
4189 E.getAs<CFGAutomaticObjDtor>()) {
4190 const VarDecl *VD = DE->getVarDecl();
4191 Helper.handleDecl(VD, OS);
4193 const Type* T = VD->getType().getTypePtr();
4194 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4195 T = RT->getPointeeType().getTypePtr();
4196 T = T->getBaseElementTypeUnsafe();
4198 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4199 OS << " (Implicit destructor)\n";
4201 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4202 OS << "CFGNewAllocator(";
4203 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4204 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4206 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4207 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4210 CXXDeleteExpr *DelExpr =
4211 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
4212 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
4213 OS << "->~" << RD->getName().str() << "()";
4214 OS << " (Implicit destructor)\n";
4215 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4216 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
4217 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
4218 OS << " (Base object destructor)\n";
4220 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4221 const FieldDecl *FD = ME->getFieldDecl();
4222 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
4223 OS << "this->" << FD->getName();
4224 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
4225 OS << " (Member object destructor)\n";
4227 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4228 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
4230 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4231 OS << "() (Temporary object destructor)\n";
4235 static void print_block(raw_ostream &OS, const CFG* cfg,
4237 StmtPrinterHelper &Helper, bool print_edges,
4240 Helper.setBlockID(B.getBlockID());
4242 // Print the header.
4244 OS.changeColor(raw_ostream::YELLOW, true);
4246 OS << "\n [B" << B.getBlockID();
4248 if (&B == &cfg->getEntry())
4249 OS << " (ENTRY)]\n";
4250 else if (&B == &cfg->getExit())
4252 else if (&B == cfg->getIndirectGotoBlock())
4253 OS << " (INDIRECT GOTO DISPATCH)]\n";
4254 else if (B.hasNoReturnElement())
4255 OS << " (NORETURN)]\n";
4262 // Print the label of this block.
4263 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
4268 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
4270 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
4273 C->getLHS()->printPretty(OS, &Helper,
4274 PrintingPolicy(Helper.getLangOpts()));
4277 C->getRHS()->printPretty(OS, &Helper,
4278 PrintingPolicy(Helper.getLangOpts()));
4280 } else if (isa<DefaultStmt>(Label))
4282 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
4284 if (CS->getExceptionDecl())
4285 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
4292 llvm_unreachable("Invalid label statement in CFGBlock.");
4297 // Iterate through the statements in the block and print them.
4300 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4301 I != E ; ++I, ++j ) {
4303 // Print the statement # in the basic block and the statement itself.
4307 OS << llvm::format("%3d", j) << ": ";
4309 Helper.setStmtID(j);
4311 print_elem(OS, Helper, *I);
4314 // Print the terminator of this block.
4315 if (B.getTerminator()) {
4317 OS.changeColor(raw_ostream::GREEN);
4321 Helper.setBlockID(-1);
4323 PrintingPolicy PP(Helper.getLangOpts());
4324 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
4325 TPrinter.print(B.getTerminator());
4333 // Print the predecessors of this block.
4334 if (!B.pred_empty()) {
4335 const raw_ostream::Colors Color = raw_ostream::BLUE;
4337 OS.changeColor(Color);
4341 OS << '(' << B.pred_size() << "):";
4345 OS.changeColor(Color);
4347 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4354 bool Reachable = true;
4357 B = I->getPossiblyUnreachableBlock();
4360 OS << " B" << B->getBlockID();
4362 OS << "(Unreachable)";
4371 // Print the successors of this block.
4372 if (!B.succ_empty()) {
4373 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4375 OS.changeColor(Color);
4379 OS << '(' << B.succ_size() << "):";
4383 OS.changeColor(Color);
4385 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4393 bool Reachable = true;
4396 B = I->getPossiblyUnreachableBlock();
4400 OS << " B" << B->getBlockID();
4402 OS << "(Unreachable)";
4417 /// dump - A simple pretty printer of a CFG that outputs to stderr.
4418 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4419 print(llvm::errs(), LO, ShowColors);
4422 /// print - A simple pretty printer of a CFG that outputs to an ostream.
4423 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
4424 StmtPrinterHelper Helper(this, LO);
4426 // Print the entry block.
4427 print_block(OS, this, getEntry(), Helper, true, ShowColors);
4429 // Iterate through the CFGBlocks and print them one by one.
4430 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4431 // Skip the entry block, because we already printed it.
4432 if (&(**I) == &getEntry() || &(**I) == &getExit())
4435 print_block(OS, this, **I, Helper, true, ShowColors);
4438 // Print the exit block.
4439 print_block(OS, this, getExit(), Helper, true, ShowColors);
4444 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
4445 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4446 bool ShowColors) const {
4447 print(llvm::errs(), cfg, LO, ShowColors);
4450 void CFGBlock::dump() const {
4451 dump(getParent(), LangOptions(), false);
4454 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4455 /// Generally this will only be called from CFG::print.
4456 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
4457 const LangOptions &LO, bool ShowColors) const {
4458 StmtPrinterHelper Helper(cfg, LO);
4459 print_block(OS, cfg, *this, Helper, true, ShowColors);
4463 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
4464 void CFGBlock::printTerminator(raw_ostream &OS,
4465 const LangOptions &LO) const {
4466 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
4467 TPrinter.print(getTerminator());
4470 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
4471 Stmt *Terminator = this->Terminator;
4477 switch (Terminator->getStmtClass()) {
4481 case Stmt::CXXForRangeStmtClass:
4482 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4485 case Stmt::ForStmtClass:
4486 E = cast<ForStmt>(Terminator)->getCond();
4489 case Stmt::WhileStmtClass:
4490 E = cast<WhileStmt>(Terminator)->getCond();
4493 case Stmt::DoStmtClass:
4494 E = cast<DoStmt>(Terminator)->getCond();
4497 case Stmt::IfStmtClass:
4498 E = cast<IfStmt>(Terminator)->getCond();
4501 case Stmt::ChooseExprClass:
4502 E = cast<ChooseExpr>(Terminator)->getCond();
4505 case Stmt::IndirectGotoStmtClass:
4506 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4509 case Stmt::SwitchStmtClass:
4510 E = cast<SwitchStmt>(Terminator)->getCond();
4513 case Stmt::BinaryConditionalOperatorClass:
4514 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4517 case Stmt::ConditionalOperatorClass:
4518 E = cast<ConditionalOperator>(Terminator)->getCond();
4521 case Stmt::BinaryOperatorClass: // '&&' and '||'
4522 E = cast<BinaryOperator>(Terminator)->getLHS();
4525 case Stmt::ObjCForCollectionStmtClass:
4532 return E ? E->IgnoreParens() : nullptr;
4535 //===----------------------------------------------------------------------===//
4536 // CFG Graphviz Visualization
4537 //===----------------------------------------------------------------------===//
4541 static StmtPrinterHelper* GraphHelper;
4544 void CFG::viewCFG(const LangOptions &LO) const {
4546 StmtPrinterHelper H(this, LO);
4548 llvm::ViewGraph(this,"CFG");
4549 GraphHelper = nullptr;
4555 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
4557 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4559 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
4562 std::string OutSStr;
4563 llvm::raw_string_ostream Out(OutSStr);
4564 print_block(Out,Graph, *Node, *GraphHelper, false, false);
4565 std::string& OutStr = Out.str();
4567 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4569 // Process string output to make it nicer...
4570 for (unsigned i = 0; i != OutStr.length(); ++i)
4571 if (OutStr[i] == '\n') { // Left justify
4573 OutStr.insert(OutStr.begin()+i+1, 'l');
4582 } // end namespace llvm