1 //===- CFG.cpp - Classes for representing and building CFGs ---------------===//
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/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclGroup.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/OperationKinds.h"
25 #include "clang/AST/PrettyPrinter.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/StmtObjC.h"
29 #include "clang/AST/StmtVisitor.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Analysis/Support/BumpVector.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/ExceptionSpecificationType.h"
34 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/LangOptions.h"
36 #include "clang/Basic/SourceLocation.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "llvm/ADT/APInt.h"
39 #include "llvm/ADT/APSInt.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/Optional.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/SetVector.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/Support/Allocator.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/DOTGraphTraits.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/Format.h"
53 #include "llvm/Support/GraphWriter.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 #include "llvm/Support/raw_ostream.h"
63 using namespace clang;
65 static SourceLocation GetEndLoc(Decl *D) {
66 if (VarDecl *VD = dyn_cast<VarDecl>(D))
67 if (Expr *Ex = VD->getInit())
68 return Ex->getSourceRange().getEnd();
69 return D->getLocation();
72 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
73 /// or EnumConstantDecl from the given Expr. If it fails, returns nullptr.
74 static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
75 E = E->IgnoreParens();
76 if (isa<IntegerLiteral>(E))
78 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
79 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
83 /// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is
84 /// an integer literal or an enum constant.
86 /// If this fails, at least one of the returned DeclRefExpr or Expr will be
88 static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *>
89 tryNormalizeBinaryOperator(const BinaryOperator *B) {
90 BinaryOperatorKind Op = B->getOpcode();
92 const Expr *MaybeDecl = B->getLHS();
93 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
94 // Expr looked like `0 == Foo` instead of `Foo == 0`
95 if (Constant == nullptr) {
101 else if (Op == BO_LT)
103 else if (Op == BO_LE)
106 MaybeDecl = B->getRHS();
107 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
110 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts());
111 return std::make_tuple(D, Op, Constant);
114 /// For an expression `x == Foo && x == Bar`, this determines whether the
115 /// `Foo` and `Bar` are either of the same enumeration type, or both integer
118 /// It's an error to pass this arguments that are not either IntegerLiterals
119 /// or DeclRefExprs (that have decls of type EnumConstantDecl)
120 static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
121 // User intent isn't clear if they're mixing int literals with enum
123 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2))
126 // Integer literal comparisons, regardless of literal type, are acceptable.
127 if (isa<IntegerLiteral>(E1))
130 // IntegerLiterals are handled above and only EnumConstantDecls are expected
132 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
133 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
134 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
136 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
137 const DeclContext *DC1 = Decl1->getDeclContext();
138 const DeclContext *DC2 = Decl2->getDeclContext();
140 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
148 /// The CFG builder uses a recursive algorithm to build the CFG. When
149 /// we process an expression, sometimes we know that we must add the
150 /// subexpressions as block-level expressions. For example:
154 /// When processing the '||' expression, we know that exp1 and exp2
155 /// need to be added as block-level expressions, even though they
156 /// might not normally need to be. AddStmtChoice records this
157 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
158 /// the builder has an option not to add a subexpression as a
159 /// block-level expression.
160 class AddStmtChoice {
162 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
164 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
166 bool alwaysAdd(CFGBuilder &builder,
167 const Stmt *stmt) const;
169 /// Return a copy of this object, except with the 'always-add' bit
170 /// set as specified.
171 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
172 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
179 /// LocalScope - Node in tree of local scopes created for C++ implicit
180 /// destructor calls generation. It contains list of automatic variables
181 /// declared in the scope and link to position in previous scope this scope
184 /// The process of creating local scopes is as follows:
185 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
186 /// - Before processing statements in scope (e.g. CompoundStmt) create
187 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
188 /// and set CFGBuilder::ScopePos to the end of new scope,
189 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
191 /// - For every normal (without jump) end of scope add to CFGBlock destructors
192 /// for objects in the current scope,
193 /// - For every jump add to CFGBlock destructors for objects
194 /// between CFGBuilder::ScopePos and local scope position saved for jump
195 /// target. Thanks to C++ restrictions on goto jumps we can be sure that
196 /// jump target position will be on the path to root from CFGBuilder::ScopePos
197 /// (adding any variable that doesn't need constructor to be called to
198 /// LocalScope can break this assumption),
202 friend class const_iterator;
204 using AutomaticVarsTy = BumpVector<VarDecl *>;
206 /// const_iterator - Iterates local scope backwards and jumps to previous
207 /// scope on reaching the beginning of currently iterated scope.
208 class const_iterator {
209 const LocalScope* Scope = nullptr;
211 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
212 /// Invalid iterator (with null Scope) has VarIter equal to 0.
213 unsigned VarIter = 0;
216 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
217 /// Incrementing invalid iterator is allowed and will result in invalid
219 const_iterator() = default;
221 /// Create valid iterator. In case when S.Prev is an invalid iterator and
222 /// I is equal to 0, this will create invalid iterator.
223 const_iterator(const LocalScope& S, unsigned I)
224 : Scope(&S), VarIter(I) {
225 // Iterator to "end" of scope is not allowed. Handle it by going up
226 // in scopes tree possibly up to invalid iterator in the root.
227 if (VarIter == 0 && Scope)
231 VarDecl *const* operator->() const {
232 assert(Scope && "Dereferencing invalid iterator is not allowed");
233 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
234 return &Scope->Vars[VarIter - 1];
236 VarDecl *operator*() const {
237 return *this->operator->();
240 const_iterator &operator++() {
244 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
250 const_iterator operator++(int) {
251 const_iterator P = *this;
256 bool operator==(const const_iterator &rhs) const {
257 return Scope == rhs.Scope && VarIter == rhs.VarIter;
259 bool operator!=(const const_iterator &rhs) const {
260 return !(*this == rhs);
263 explicit operator bool() const {
264 return *this != const_iterator();
267 int distance(const_iterator L);
268 const_iterator shared_parent(const_iterator L);
272 BumpVectorContext ctx;
274 /// Automatic variables in order of declaration.
275 AutomaticVarsTy Vars;
277 /// Iterator to variable in previous scope that was declared just before
278 /// begin of this scope.
282 /// Constructs empty scope linked to previous scope in specified place.
283 LocalScope(BumpVectorContext ctx, const_iterator P)
284 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
286 /// Begin of scope in direction of CFG building (backwards).
287 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
289 void addVar(VarDecl *VD) {
290 Vars.push_back(VD, ctx);
296 /// distance - Calculates distance from this to L. L must be reachable from this
297 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
298 /// number of scopes between this and L.
299 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
301 const_iterator F = *this;
302 while (F.Scope != L.Scope) {
303 assert(F != const_iterator() &&
304 "L iterator is not reachable from F iterator.");
308 D += F.VarIter - L.VarIter;
312 /// Calculates the closest parent of this iterator
313 /// that is in a scope reachable through the parents of L.
314 /// I.e. when using 'goto' from this to L, the lifetime of all variables
315 /// between this and shared_parent(L) end.
316 LocalScope::const_iterator
317 LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
318 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
320 ScopesOfL.insert(L.Scope);
321 if (L == const_iterator())
326 const_iterator F = *this;
328 if (ScopesOfL.count(F.Scope))
330 assert(F != const_iterator() &&
331 "L iterator is not reachable from F iterator.");
338 /// Structure for specifying position in CFG during its build process. It
339 /// consists of CFGBlock that specifies position in CFG and
340 /// LocalScope::const_iterator that specifies position in LocalScope graph.
341 struct BlockScopePosPair {
342 CFGBlock *block = nullptr;
343 LocalScope::const_iterator scopePosition;
345 BlockScopePosPair() = default;
346 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
347 : block(b), scopePosition(scopePos) {}
350 /// TryResult - a class representing a variant over the values
351 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
352 /// and is used by the CFGBuilder to decide if a branch condition
353 /// can be decided up front during CFG construction.
358 TryResult() = default;
359 TryResult(bool b) : X(b ? 1 : 0) {}
361 bool isTrue() const { return X == 1; }
362 bool isFalse() const { return X == 0; }
363 bool isKnown() const { return X >= 0; }
373 static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
374 if (!R1.isKnown() || !R2.isKnown())
376 return TryResult(R1.isTrue() && R2.isTrue());
381 class reverse_children {
382 llvm::SmallVector<Stmt *, 12> childrenBuf;
383 ArrayRef<Stmt *> children;
386 reverse_children(Stmt *S);
388 using iterator = ArrayRef<Stmt *>::reverse_iterator;
390 iterator begin() const { return children.rbegin(); }
391 iterator end() const { return children.rend(); }
396 reverse_children::reverse_children(Stmt *S) {
397 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
398 children = CE->getRawSubExprs();
401 switch (S->getStmtClass()) {
402 // Note: Fill in this switch with more cases we want to optimize.
403 case Stmt::InitListExprClass: {
404 InitListExpr *IE = cast<InitListExpr>(S);
405 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
413 // Default case for all other statements.
414 for (Stmt *SubStmt : S->children())
415 childrenBuf.push_back(SubStmt);
417 // This needs to be done *after* childrenBuf has been populated.
418 children = childrenBuf;
423 /// CFGBuilder - This class implements CFG construction from an AST.
424 /// The builder is stateful: an instance of the builder should be used to only
425 /// construct a single CFG.
429 /// CFGBuilder builder;
430 /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
432 /// CFG construction is done via a recursive walk of an AST. We actually parse
433 /// the AST in reverse order so that the successor of a basic block is
434 /// constructed prior to its predecessor. This allows us to nicely capture
435 /// implicit fall-throughs without extra basic blocks.
437 using JumpTarget = BlockScopePosPair;
438 using JumpSource = BlockScopePosPair;
441 std::unique_ptr<CFG> cfg;
444 CFGBlock *Block = nullptr;
446 // Block after the current block.
447 CFGBlock *Succ = nullptr;
449 JumpTarget ContinueJumpTarget;
450 JumpTarget BreakJumpTarget;
451 JumpTarget SEHLeaveJumpTarget;
452 CFGBlock *SwitchTerminatedBlock = nullptr;
453 CFGBlock *DefaultCaseBlock = nullptr;
455 // This can point either to a try or a __try block. The frontend forbids
456 // mixing both kinds in one function, so having one for both is enough.
457 CFGBlock *TryTerminatedBlock = nullptr;
459 // Current position in local scope.
460 LocalScope::const_iterator ScopePos;
462 // LabelMap records the mapping from Label expressions to their jump targets.
463 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
466 // A list of blocks that end with a "goto" that must be backpatched to their
467 // resolved targets upon completion of CFG construction.
468 using BackpatchBlocksTy = std::vector<JumpSource>;
469 BackpatchBlocksTy BackpatchBlocks;
471 // A list of labels whose address has been taken (for indirect gotos).
472 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
473 LabelSetTy AddressTakenLabels;
476 const CFG::BuildOptions &BuildOpts;
478 // State to track for building switch statements.
479 bool switchExclusivelyCovered = false;
480 Expr::EvalResult *switchCond = nullptr;
482 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
483 const Stmt *lastLookup = nullptr;
485 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
486 // during construction of branches for chained logical operators.
487 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
488 CachedBoolEvalsTy CachedBoolEvals;
491 explicit CFGBuilder(ASTContext *astContext,
492 const CFG::BuildOptions &buildOpts)
493 : Context(astContext), cfg(new CFG()), // crew a new CFG
494 BuildOpts(buildOpts) {}
496 // buildCFG - Used by external clients to construct the CFG.
497 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
499 bool alwaysAdd(const Stmt *stmt);
502 // Visitors to walk an AST and construct the CFG.
503 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
504 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
505 CFGBlock *VisitBreakStmt(BreakStmt *B);
506 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
507 CFGBlock *VisitCaseStmt(CaseStmt *C);
508 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
509 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
510 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
512 CFGBlock *VisitContinueStmt(ContinueStmt *C);
513 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
515 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
516 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
517 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
518 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
519 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
520 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
522 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
524 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
525 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
526 CFGBlock *VisitDeclStmt(DeclStmt *DS);
527 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
528 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
529 CFGBlock *VisitDoStmt(DoStmt *D);
530 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
531 CFGBlock *VisitForStmt(ForStmt *F);
532 CFGBlock *VisitGotoStmt(GotoStmt *G);
533 CFGBlock *VisitIfStmt(IfStmt *I);
534 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
535 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
536 CFGBlock *VisitLabelStmt(LabelStmt *L);
537 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
538 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
539 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
540 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
543 CFGBlock *FalseBlock);
544 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
545 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
546 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
547 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
548 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
549 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
550 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
551 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
552 CFGBlock *VisitReturnStmt(ReturnStmt *R);
553 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
554 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
555 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
556 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
557 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
558 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
559 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
561 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
562 CFGBlock *VisitWhileStmt(WhileStmt *W);
564 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
565 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
566 CFGBlock *VisitChildren(Stmt *S);
567 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
569 /// When creating the CFG for temporary destructors, we want to mirror the
570 /// branch structure of the corresponding constructor calls.
571 /// Thus, while visiting a statement for temporary destructors, we keep a
572 /// context to keep track of the following information:
573 /// - whether a subexpression is executed unconditionally
574 /// - if a subexpression is executed conditionally, the first
575 /// CXXBindTemporaryExpr we encounter in that subexpression (which
576 /// corresponds to the last temporary destructor we have to call for this
577 /// subexpression) and the CFG block at that point (which will become the
578 /// successor block when inserting the decision point).
580 /// That way, we can build the branch structure for temporary destructors as
582 /// 1. If a subexpression is executed unconditionally, we add the temporary
583 /// destructor calls to the current block.
584 /// 2. If a subexpression is executed conditionally, when we encounter a
585 /// CXXBindTemporaryExpr:
586 /// a) If it is the first temporary destructor call in the subexpression,
587 /// we remember the CXXBindTemporaryExpr and the current block in the
588 /// TempDtorContext; we start a new block, and insert the temporary
590 /// b) Otherwise, add the temporary destructor call to the current block.
591 /// 3. When we finished visiting a conditionally executed subexpression,
592 /// and we found at least one temporary constructor during the visitation
593 /// (2.a has executed), we insert a decision block that uses the
594 /// CXXBindTemporaryExpr as terminator, and branches to the current block
595 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
596 /// branches to the stored successor.
597 struct TempDtorContext {
598 TempDtorContext() = default;
599 TempDtorContext(TryResult KnownExecuted)
600 : IsConditional(true), KnownExecuted(KnownExecuted) {}
602 /// Returns whether we need to start a new branch for a temporary destructor
603 /// call. This is the case when the temporary destructor is
604 /// conditionally executed, and it is the first one we encounter while
605 /// visiting a subexpression - other temporary destructors at the same level
606 /// will be added to the same block and are executed under the same
608 bool needsTempDtorBranch() const {
609 return IsConditional && !TerminatorExpr;
612 /// Remember the successor S of a temporary destructor decision branch for
613 /// the corresponding CXXBindTemporaryExpr E.
614 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
619 const bool IsConditional = false;
620 const TryResult KnownExecuted = true;
621 CFGBlock *Succ = nullptr;
622 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
625 // Visitors to walk an AST and generate destructors of temporaries in
627 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
628 TempDtorContext &Context);
629 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
630 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
631 TempDtorContext &Context);
632 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
633 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
634 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
635 AbstractConditionalOperator *E, bool BindToTemporary,
636 TempDtorContext &Context);
637 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
638 CFGBlock *FalseSucc = nullptr);
640 // NYS == Not Yet Supported
646 void autoCreateBlock() { if (!Block) Block = createBlock(); }
647 CFGBlock *createBlock(bool add_successor = true);
648 CFGBlock *createNoReturnBlock();
650 CFGBlock *addStmt(Stmt *S) {
651 return Visit(S, AddStmtChoice::AlwaysAdd);
654 CFGBlock *addInitializer(CXXCtorInitializer *I);
655 void addLoopExit(const Stmt *LoopStmt);
656 void addAutomaticObjDtors(LocalScope::const_iterator B,
657 LocalScope::const_iterator E, Stmt *S);
658 void addLifetimeEnds(LocalScope::const_iterator B,
659 LocalScope::const_iterator E, Stmt *S);
660 void addAutomaticObjHandling(LocalScope::const_iterator B,
661 LocalScope::const_iterator E, Stmt *S);
662 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
664 // Local scopes creation.
665 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
667 void addLocalScopeForStmt(Stmt *S);
668 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
669 LocalScope* Scope = nullptr);
670 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
672 void addLocalScopeAndDtors(Stmt *S);
674 // Interface to CFGBlock - adding CFGElements.
676 void appendStmt(CFGBlock *B, const Stmt *S) {
677 if (alwaysAdd(S) && cachedEntry)
678 cachedEntry->second = B;
680 // All block-level expressions should have already been IgnoreParens()ed.
681 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
682 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
685 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
686 B->appendInitializer(I, cfg->getBumpVectorContext());
689 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
690 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
693 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
694 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
697 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
698 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
701 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
702 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
705 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
706 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
709 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
710 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
713 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
714 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
717 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
718 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
721 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
722 LocalScope::const_iterator B, LocalScope::const_iterator E);
724 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
725 LocalScope::const_iterator B,
726 LocalScope::const_iterator E);
728 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
729 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
730 cfg->getBumpVectorContext());
733 /// Add a reachable successor to a block, with the alternate variant that is
735 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
736 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
737 cfg->getBumpVectorContext());
740 /// \brief Find a relational comparison with an expression evaluating to a
741 /// boolean and a constant other than 0 and 1.
742 /// e.g. if ((x < y) == 10)
743 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
744 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
745 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
747 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
748 const Expr *BoolExpr = RHSExpr;
749 bool IntFirst = true;
751 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
756 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
759 llvm::APInt IntValue = IntLiteral->getValue();
760 if ((IntValue == 1) || (IntValue == 0))
763 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
764 !IntValue.isNegative();
766 BinaryOperatorKind Bok = B->getOpcode();
767 if (Bok == BO_GT || Bok == BO_GE) {
768 // Always true for 10 > bool and bool > -1
769 // Always false for -1 > bool and bool > 10
770 return TryResult(IntFirst == IntLarger);
772 // Always true for -1 < bool and bool < 10
773 // Always false for 10 < bool and bool < -1
774 return TryResult(IntFirst != IntLarger);
778 /// Find an incorrect equality comparison. Either with an expression
779 /// evaluating to a boolean and a constant other than 0 and 1.
780 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
781 /// true/false e.q. (x & 8) == 4.
782 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
783 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
784 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
786 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
787 const Expr *BoolExpr = RHSExpr;
790 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
797 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
798 if (BitOp && (BitOp->getOpcode() == BO_And ||
799 BitOp->getOpcode() == BO_Or)) {
800 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
801 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
803 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
806 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
811 llvm::APInt L1 = IntLiteral->getValue();
812 llvm::APInt L2 = IntLiteral2->getValue();
813 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
814 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
815 if (BuildOpts.Observer)
816 BuildOpts.Observer->compareBitwiseEquality(B,
817 B->getOpcode() != BO_EQ);
818 TryResult(B->getOpcode() != BO_EQ);
820 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
821 llvm::APInt IntValue = IntLiteral->getValue();
822 if ((IntValue == 1) || (IntValue == 0)) {
825 return TryResult(B->getOpcode() != BO_EQ);
831 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
832 const llvm::APSInt &Value1,
833 const llvm::APSInt &Value2) {
834 assert(Value1.isSigned() == Value2.isSigned());
839 return TryResult(Value1 == Value2);
841 return TryResult(Value1 != Value2);
843 return TryResult(Value1 < Value2);
845 return TryResult(Value1 <= Value2);
847 return TryResult(Value1 > Value2);
849 return TryResult(Value1 >= Value2);
853 /// \brief Find a pair of comparison expressions with or without parentheses
854 /// with a shared variable and constants and a logical operator between them
855 /// that always evaluates to either true or false.
856 /// e.g. if (x != 3 || x != 4)
857 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
858 assert(B->isLogicalOp());
859 const BinaryOperator *LHS =
860 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
861 const BinaryOperator *RHS =
862 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
866 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
869 const DeclRefExpr *Decl1;
871 BinaryOperatorKind BO1;
872 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
874 if (!Decl1 || !Expr1)
877 const DeclRefExpr *Decl2;
879 BinaryOperatorKind BO2;
880 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
882 if (!Decl2 || !Expr2)
885 // Check that it is the same variable on both sides.
886 if (Decl1->getDecl() != Decl2->getDecl())
889 // Make sure the user's intent is clear (e.g. they're comparing against two
890 // int literals, or two things from the same enum)
891 if (!areExprTypesCompatible(Expr1, Expr2))
896 if (!Expr1->EvaluateAsInt(L1, *Context) ||
897 !Expr2->EvaluateAsInt(L2, *Context))
900 // Can't compare signed with unsigned or with different bit width.
901 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
904 // Values that will be used to determine if result of logical
905 // operator is always true/false
906 const llvm::APSInt Values[] = {
907 // Value less than both Value1 and Value2
908 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
911 // Value between Value1 and Value2
912 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
916 // Value greater than both Value1 and Value2
917 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
920 // Check whether expression is always true/false by evaluating the following
921 // * variable x is less than the smallest literal.
922 // * variable x is equal to the smallest literal.
923 // * Variable x is between smallest and largest literal.
924 // * Variable x is equal to the largest literal.
925 // * Variable x is greater than largest literal.
926 bool AlwaysTrue = true, AlwaysFalse = true;
927 for (const llvm::APSInt &Value : Values) {
928 TryResult Res1, Res2;
929 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
930 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
932 if (!Res1.isKnown() || !Res2.isKnown())
935 if (B->getOpcode() == BO_LAnd) {
936 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
937 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
939 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
940 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
944 if (AlwaysTrue || AlwaysFalse) {
945 if (BuildOpts.Observer)
946 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
947 return TryResult(AlwaysTrue);
952 /// Try and evaluate an expression to an integer constant.
953 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
954 if (!BuildOpts.PruneTriviallyFalseEdges)
956 return !S->isTypeDependent() &&
957 !S->isValueDependent() &&
958 S->EvaluateAsRValue(outResult, *Context);
961 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
962 /// if we can evaluate to a known value, otherwise return -1.
963 TryResult tryEvaluateBool(Expr *S) {
964 if (!BuildOpts.PruneTriviallyFalseEdges ||
965 S->isTypeDependent() || S->isValueDependent())
968 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
969 if (Bop->isLogicalOp()) {
970 // Check the cache first.
971 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
972 if (I != CachedBoolEvals.end())
973 return I->second; // already in map;
975 // Retrieve result at first, or the map might be updated.
976 TryResult Result = evaluateAsBooleanConditionNoCache(S);
977 CachedBoolEvals[S] = Result; // update or insert
981 switch (Bop->getOpcode()) {
983 // For 'x & 0' and 'x * 0', we can determine that
984 // the value is always false.
987 // If either operand is zero, we know the value
990 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
991 if (!IntVal.getBoolValue()) {
992 return TryResult(false);
995 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
996 if (!IntVal.getBoolValue()) {
997 return TryResult(false);
1006 return evaluateAsBooleanConditionNoCache(S);
1009 /// \brief Evaluate as boolean \param E without using the cache.
1010 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1011 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1012 if (Bop->isLogicalOp()) {
1013 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1014 if (LHS.isKnown()) {
1015 // We were able to evaluate the LHS, see if we can get away with not
1016 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1017 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1018 return LHS.isTrue();
1020 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1021 if (RHS.isKnown()) {
1022 if (Bop->getOpcode() == BO_LOr)
1023 return LHS.isTrue() || RHS.isTrue();
1025 return LHS.isTrue() && RHS.isTrue();
1028 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1029 if (RHS.isKnown()) {
1030 // We can't evaluate the LHS; however, sometimes the result
1031 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1032 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1033 return RHS.isTrue();
1035 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1036 if (BopRes.isKnown())
1037 return BopRes.isTrue();
1042 } else if (Bop->isEqualityOp()) {
1043 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1044 if (BopRes.isKnown())
1045 return BopRes.isTrue();
1046 } else if (Bop->isRelationalOp()) {
1047 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1048 if (BopRes.isKnown())
1049 return BopRes.isTrue();
1054 if (E->EvaluateAsBooleanCondition(Result, *Context))
1060 bool hasTrivialDestructor(VarDecl *VD);
1065 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1066 const Stmt *stmt) const {
1067 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1070 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
1071 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1073 if (!BuildOpts.forcedBlkExprs)
1076 if (lastLookup == stmt) {
1078 assert(cachedEntry->first == stmt);
1086 // Perform the lookup!
1087 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1090 // No need to update 'cachedEntry', since it will always be null.
1091 assert(!cachedEntry);
1095 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
1096 if (itr == fb->end()) {
1097 cachedEntry = nullptr;
1101 cachedEntry = &*itr;
1105 // FIXME: Add support for dependent-sized array types in C++?
1106 // Does it even make sense to build a CFG for an uninstantiated template?
1107 static const VariableArrayType *FindVA(const Type *t) {
1108 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1109 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
1110 if (vat->getSizeExpr())
1113 t = vt->getElementType().getTypePtr();
1119 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1120 /// arbitrary statement. Examples include a single expression or a function
1121 /// body (compound statement). The ownership of the returned CFG is
1122 /// transferred to the caller. If CFG construction fails, this method returns
1124 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
1129 // Create an empty block that will serve as the exit block for the CFG. Since
1130 // this is the first block added to the CFG, it will be implicitly registered
1131 // as the exit block.
1132 Succ = createBlock();
1133 assert(Succ == &cfg->getExit());
1134 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
1136 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1137 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1139 if (BuildOpts.AddImplicitDtors)
1140 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1141 addImplicitDtorsForDestructor(DD);
1143 // Visit the statements and create the CFG.
1144 CFGBlock *B = addStmt(Statement);
1149 // For C++ constructor add initializers to CFG.
1150 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
1151 for (auto *I : llvm::reverse(CD->inits())) {
1152 B = addInitializer(I);
1161 // Backpatch the gotos whose label -> block mappings we didn't know when we
1162 // encountered them.
1163 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1164 E = BackpatchBlocks.end(); I != E; ++I ) {
1166 CFGBlock *B = I->block;
1167 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
1168 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
1170 // If there is no target for the goto, then we are looking at an
1171 // incomplete AST. Handle this by not registering a successor.
1172 if (LI == LabelMap.end()) continue;
1174 JumpTarget JT = LI->second;
1175 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1177 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1179 addSuccessor(B, JT.block);
1182 // Add successors to the Indirect Goto Dispatch block (if we have one).
1183 if (CFGBlock *B = cfg->getIndirectGotoBlock())
1184 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1185 E = AddressTakenLabels.end(); I != E; ++I ) {
1186 // Lookup the target block.
1187 LabelMapTy::iterator LI = LabelMap.find(*I);
1189 // If there is no target block that contains label, then we are looking
1190 // at an incomplete AST. Handle this by not registering a successor.
1191 if (LI == LabelMap.end()) continue;
1193 addSuccessor(B, LI->second.block);
1196 // Create an empty entry block that has no predecessors.
1197 cfg->setEntry(createBlock());
1199 return std::move(cfg);
1202 /// createBlock - Used to lazily create blocks that are connected
1203 /// to the current (global) succcessor.
1204 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1205 CFGBlock *B = cfg->createBlock();
1206 if (add_successor && Succ)
1207 addSuccessor(B, Succ);
1211 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1212 /// CFG. It is *not* connected to the current (global) successor, and instead
1213 /// directly tied to the exit block in order to be reachable.
1214 CFGBlock *CFGBuilder::createNoReturnBlock() {
1215 CFGBlock *B = createBlock(false);
1216 B->setHasNoReturnElement();
1217 addSuccessor(B, &cfg->getExit(), Succ);
1221 /// addInitializer - Add C++ base or member initializer element to CFG.
1222 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
1223 if (!BuildOpts.AddInitializers)
1226 bool HasTemporaries = false;
1228 // Destructors of temporaries in initialization expression should be called
1229 // after initialization finishes.
1230 Expr *Init = I->getInit();
1232 HasTemporaries = isa<ExprWithCleanups>(Init);
1234 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1235 // Generate destructors for temporaries in initialization expression.
1236 TempDtorContext Context;
1237 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1238 /*BindToTemporary=*/false, Context);
1243 appendInitializer(Block, I);
1246 if (HasTemporaries) {
1247 // For expression with temporaries go directly to subexpression to omit
1248 // generating destructors for the second time.
1249 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1251 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1252 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1253 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1254 // may cause the same Expr to appear more than once in the CFG. Doing it
1255 // here is safe because there's only one initializer per field.
1257 appendStmt(Block, Default);
1258 if (Stmt *Child = Default->getExpr())
1259 if (CFGBlock *R = Visit(Child))
1270 /// \brief Retrieve the type of the temporary object whose lifetime was
1271 /// extended by a local reference with the given initializer.
1272 static QualType getReferenceInitTemporaryType(ASTContext &Context,
1274 bool *FoundMTE = nullptr) {
1276 // Skip parentheses.
1277 Init = Init->IgnoreParens();
1279 // Skip through cleanups.
1280 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1281 Init = EWC->getSubExpr();
1285 // Skip through the temporary-materialization expression.
1286 if (const MaterializeTemporaryExpr *MTE
1287 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1288 Init = MTE->GetTemporaryExpr();
1294 // Skip derived-to-base and no-op casts.
1295 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1296 if ((CE->getCastKind() == CK_DerivedToBase ||
1297 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1298 CE->getCastKind() == CK_NoOp) &&
1299 Init->getType()->isRecordType()) {
1300 Init = CE->getSubExpr();
1305 // Skip member accesses into rvalues.
1306 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1307 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1308 Init = ME->getBase();
1316 return Init->getType();
1319 // TODO: Support adding LoopExit element to the CFG in case where the loop is
1320 // ended by ReturnStmt, GotoStmt or ThrowExpr.
1321 void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1322 if(!BuildOpts.AddLoopExit)
1325 appendLoopExit(Block, LoopStmt);
1328 void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1329 LocalScope::const_iterator E,
1331 if (BuildOpts.AddImplicitDtors)
1332 addAutomaticObjDtors(B, E, S);
1333 if (BuildOpts.AddLifetime)
1334 addLifetimeEnds(B, E, S);
1337 /// Add to current block automatic objects that leave the scope.
1338 void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1339 LocalScope::const_iterator E, Stmt *S) {
1340 if (!BuildOpts.AddLifetime)
1346 // To go from B to E, one first goes up the scopes from B to P
1347 // then sideways in one scope from P to P' and then down
1348 // the scopes from P' to E.
1349 // The lifetime of all objects between B and P end.
1350 LocalScope::const_iterator P = B.shared_parent(E);
1351 int dist = B.distance(P);
1355 // We need to perform the scope leaving in reverse order
1356 SmallVector<VarDecl *, 10> DeclsTrivial;
1357 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1358 DeclsTrivial.reserve(dist);
1359 DeclsNonTrivial.reserve(dist);
1361 for (LocalScope::const_iterator I = B; I != P; ++I)
1362 if (hasTrivialDestructor(*I))
1363 DeclsTrivial.push_back(*I);
1365 DeclsNonTrivial.push_back(*I);
1368 // object with trivial destructor end their lifetime last (when storage
1370 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1371 E = DeclsTrivial.rend();
1373 appendLifetimeEnds(Block, *I, S);
1375 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1376 I = DeclsNonTrivial.rbegin(),
1377 E = DeclsNonTrivial.rend();
1379 appendLifetimeEnds(Block, *I, S);
1382 /// addAutomaticObjDtors - Add to current block automatic objects destructors
1383 /// for objects in range of local scope positions. Use S as trigger statement
1384 /// for destructors.
1385 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
1386 LocalScope::const_iterator E, Stmt *S) {
1387 if (!BuildOpts.AddImplicitDtors)
1393 // We need to append the destructors in reverse order, but any one of them
1394 // may be a no-return destructor which changes the CFG. As a result, buffer
1395 // this sequence up and replay them in reverse order when appending onto the
1397 SmallVector<VarDecl*, 10> Decls;
1398 Decls.reserve(B.distance(E));
1399 for (LocalScope::const_iterator I = B; I != E; ++I)
1400 Decls.push_back(*I);
1402 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1405 // If this destructor is marked as a no-return destructor, we need to
1406 // create a new block for the destructor which does not have as a successor
1407 // anything built thus far: control won't flow out of this block.
1408 QualType Ty = (*I)->getType();
1409 if (Ty->isReferenceType()) {
1410 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
1412 Ty = Context->getBaseElementType(Ty);
1414 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
1415 Block = createNoReturnBlock();
1419 appendAutomaticObjDtor(Block, *I, S);
1423 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
1424 /// base and member objects in destructor.
1425 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1426 assert(BuildOpts.AddImplicitDtors &&
1427 "Can be called only when dtors should be added");
1428 const CXXRecordDecl *RD = DD->getParent();
1430 // At the end destroy virtual base objects.
1431 for (const auto &VI : RD->vbases()) {
1432 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
1433 if (!CD->hasTrivialDestructor()) {
1435 appendBaseDtor(Block, &VI);
1439 // Before virtual bases destroy direct base objects.
1440 for (const auto &BI : RD->bases()) {
1441 if (!BI.isVirtual()) {
1442 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
1443 if (!CD->hasTrivialDestructor()) {
1445 appendBaseDtor(Block, &BI);
1450 // First destroy member objects.
1451 for (auto *FI : RD->fields()) {
1452 // Check for constant size array. Set type to array element type.
1453 QualType QT = FI->getType();
1454 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1455 if (AT->getSize() == 0)
1457 QT = AT->getElementType();
1460 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1461 if (!CD->hasTrivialDestructor()) {
1463 appendMemberDtor(Block, FI);
1468 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1469 /// way return valid LocalScope object.
1470 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
1473 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1474 return new (alloc.Allocate<LocalScope>())
1475 LocalScope(BumpVectorContext(alloc), ScopePos);
1478 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
1479 /// that should create implicit scope (e.g. if/else substatements).
1480 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
1481 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
1484 LocalScope *Scope = nullptr;
1486 // For compound statement we will be creating explicit scope.
1487 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1488 for (auto *BI : CS->body()) {
1489 Stmt *SI = BI->stripLabelLikeStatements();
1490 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
1491 Scope = addLocalScopeForDeclStmt(DS, Scope);
1496 // For any other statement scope will be implicit and as such will be
1497 // interesting only for DeclStmt.
1498 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
1499 addLocalScopeForDeclStmt(DS);
1502 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1503 /// reuse Scope if not NULL.
1504 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
1505 LocalScope* Scope) {
1506 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
1509 for (auto *DI : DS->decls())
1510 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
1511 Scope = addLocalScopeForVarDecl(VD, Scope);
1515 bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1516 // Check for const references bound to temporary. Set type to pointee.
1517 QualType QT = VD->getType();
1518 if (QT.getTypePtr()->isReferenceType()) {
1519 // Attempt to determine whether this declaration lifetime-extends a
1522 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1523 // temporaries, and a single declaration can extend multiple temporaries.
1524 // We should look at the storage duration on each nested
1525 // MaterializeTemporaryExpr instead.
1527 const Expr *Init = VD->getInit();
1531 // Lifetime-extending a temporary.
1532 bool FoundMTE = false;
1533 QT = getReferenceInitTemporaryType(*Context, Init, &FoundMTE);
1538 // Check for constant size array. Set type to array element type.
1539 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1540 if (AT->getSize() == 0)
1542 QT = AT->getElementType();
1545 // Check if type is a C++ class with non-trivial destructor.
1546 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1547 return !CD->hasDefinition() || CD->hasTrivialDestructor();
1551 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1552 /// create add scope for automatic objects and temporary objects bound to
1553 /// const reference. Will reuse Scope if not NULL.
1554 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
1555 LocalScope* Scope) {
1556 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1557 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1558 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
1561 // Check if variable is local.
1562 switch (VD->getStorageClass()) {
1567 default: return Scope;
1570 if (BuildOpts.AddImplicitDtors) {
1571 if (!hasTrivialDestructor(VD)) {
1572 // Add the variable to scope
1573 Scope = createOrReuseLocalScope(Scope);
1575 ScopePos = Scope->begin();
1580 assert(BuildOpts.AddLifetime);
1581 // Add the variable to scope
1582 Scope = createOrReuseLocalScope(Scope);
1584 ScopePos = Scope->begin();
1588 /// addLocalScopeAndDtors - For given statement add local scope for it and
1589 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
1590 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
1591 LocalScope::const_iterator scopeBeginPos = ScopePos;
1592 addLocalScopeForStmt(S);
1593 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
1596 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1597 /// variables with automatic storage duration to CFGBlock's elements vector.
1598 /// Elements will be prepended to physical beginning of the vector which
1599 /// happens to be logical end. Use blocks terminator as statement that specifies
1600 /// destructors call site.
1601 /// FIXME: This mechanism for adding automatic destructors doesn't handle
1602 /// no-return destructors properly.
1603 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
1604 LocalScope::const_iterator B, LocalScope::const_iterator E) {
1605 if (!BuildOpts.AddImplicitDtors)
1607 BumpVectorContext &C = cfg->getBumpVectorContext();
1608 CFGBlock::iterator InsertPos
1609 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1610 for (LocalScope::const_iterator I = B; I != E; ++I)
1611 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1612 Blk->getTerminator());
1615 /// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
1616 /// variables with automatic storage duration to CFGBlock's elements vector.
1617 /// Elements will be prepended to physical beginning of the vector which
1618 /// happens to be logical end. Use blocks terminator as statement that specifies
1619 /// where lifetime ends.
1620 void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
1621 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
1622 if (!BuildOpts.AddLifetime)
1624 BumpVectorContext &C = cfg->getBumpVectorContext();
1625 CFGBlock::iterator InsertPos =
1626 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
1627 for (LocalScope::const_iterator I = B; I != E; ++I)
1628 InsertPos = Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminator());
1631 /// Visit - Walk the subtree of a statement and add extra
1632 /// blocks for ternary operators, &&, and ||. We also process "," and
1633 /// DeclStmts (which may contain nested control-flow).
1634 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
1640 if (Expr *E = dyn_cast<Expr>(S))
1641 S = E->IgnoreParens();
1643 switch (S->getStmtClass()) {
1645 return VisitStmt(S, asc);
1647 case Stmt::AddrLabelExprClass:
1648 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
1650 case Stmt::BinaryConditionalOperatorClass:
1651 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1653 case Stmt::BinaryOperatorClass:
1654 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
1656 case Stmt::BlockExprClass:
1657 return VisitBlockExpr(cast<BlockExpr>(S), asc);
1659 case Stmt::BreakStmtClass:
1660 return VisitBreakStmt(cast<BreakStmt>(S));
1662 case Stmt::CallExprClass:
1663 case Stmt::CXXOperatorCallExprClass:
1664 case Stmt::CXXMemberCallExprClass:
1665 case Stmt::UserDefinedLiteralClass:
1666 return VisitCallExpr(cast<CallExpr>(S), asc);
1668 case Stmt::CaseStmtClass:
1669 return VisitCaseStmt(cast<CaseStmt>(S));
1671 case Stmt::ChooseExprClass:
1672 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
1674 case Stmt::CompoundStmtClass:
1675 return VisitCompoundStmt(cast<CompoundStmt>(S));
1677 case Stmt::ConditionalOperatorClass:
1678 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
1680 case Stmt::ContinueStmtClass:
1681 return VisitContinueStmt(cast<ContinueStmt>(S));
1683 case Stmt::CXXCatchStmtClass:
1684 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1686 case Stmt::ExprWithCleanupsClass:
1687 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
1689 case Stmt::CXXDefaultArgExprClass:
1690 case Stmt::CXXDefaultInitExprClass:
1691 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1692 // called function's declaration, not by the caller. If we simply add
1693 // this expression to the CFG, we could end up with the same Expr
1694 // appearing multiple times.
1695 // PR13385 / <rdar://problem/12156507>
1697 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1698 // expression to be used in the same function (through aggregate
1700 return VisitStmt(S, asc);
1702 case Stmt::CXXBindTemporaryExprClass:
1703 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1705 case Stmt::CXXConstructExprClass:
1706 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1708 case Stmt::CXXNewExprClass:
1709 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1711 case Stmt::CXXDeleteExprClass:
1712 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1714 case Stmt::CXXFunctionalCastExprClass:
1715 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1717 case Stmt::CXXTemporaryObjectExprClass:
1718 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1720 case Stmt::CXXThrowExprClass:
1721 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
1723 case Stmt::CXXTryStmtClass:
1724 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
1726 case Stmt::CXXForRangeStmtClass:
1727 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1729 case Stmt::DeclStmtClass:
1730 return VisitDeclStmt(cast<DeclStmt>(S));
1732 case Stmt::DefaultStmtClass:
1733 return VisitDefaultStmt(cast<DefaultStmt>(S));
1735 case Stmt::DoStmtClass:
1736 return VisitDoStmt(cast<DoStmt>(S));
1738 case Stmt::ForStmtClass:
1739 return VisitForStmt(cast<ForStmt>(S));
1741 case Stmt::GotoStmtClass:
1742 return VisitGotoStmt(cast<GotoStmt>(S));
1744 case Stmt::IfStmtClass:
1745 return VisitIfStmt(cast<IfStmt>(S));
1747 case Stmt::ImplicitCastExprClass:
1748 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
1750 case Stmt::IndirectGotoStmtClass:
1751 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
1753 case Stmt::LabelStmtClass:
1754 return VisitLabelStmt(cast<LabelStmt>(S));
1756 case Stmt::LambdaExprClass:
1757 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1759 case Stmt::MemberExprClass:
1760 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1762 case Stmt::NullStmtClass:
1765 case Stmt::ObjCAtCatchStmtClass:
1766 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1768 case Stmt::ObjCAutoreleasePoolStmtClass:
1769 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1771 case Stmt::ObjCAtSynchronizedStmtClass:
1772 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
1774 case Stmt::ObjCAtThrowStmtClass:
1775 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
1777 case Stmt::ObjCAtTryStmtClass:
1778 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
1780 case Stmt::ObjCForCollectionStmtClass:
1781 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
1783 case Stmt::OpaqueValueExprClass:
1786 case Stmt::PseudoObjectExprClass:
1787 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1789 case Stmt::ReturnStmtClass:
1790 return VisitReturnStmt(cast<ReturnStmt>(S));
1792 case Stmt::SEHExceptStmtClass:
1793 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
1795 case Stmt::SEHFinallyStmtClass:
1796 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
1798 case Stmt::SEHLeaveStmtClass:
1799 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
1801 case Stmt::SEHTryStmtClass:
1802 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
1804 case Stmt::UnaryExprOrTypeTraitExprClass:
1805 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1808 case Stmt::StmtExprClass:
1809 return VisitStmtExpr(cast<StmtExpr>(S), asc);
1811 case Stmt::SwitchStmtClass:
1812 return VisitSwitchStmt(cast<SwitchStmt>(S));
1814 case Stmt::UnaryOperatorClass:
1815 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1817 case Stmt::WhileStmtClass:
1818 return VisitWhileStmt(cast<WhileStmt>(S));
1822 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
1823 if (asc.alwaysAdd(*this, S)) {
1825 appendStmt(Block, S);
1828 return VisitChildren(S);
1831 /// VisitChildren - Visit the children of a Stmt.
1832 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1833 CFGBlock *B = Block;
1835 // Visit the children in their reverse order so that they appear in
1836 // left-to-right (natural) order in the CFG.
1837 reverse_children RChildren(S);
1838 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1840 if (Stmt *Child = *I)
1841 if (CFGBlock *R = Visit(Child))
1847 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1848 AddStmtChoice asc) {
1849 AddressTakenLabels.insert(A->getLabel());
1851 if (asc.alwaysAdd(*this, A)) {
1853 appendStmt(Block, A);
1859 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
1860 AddStmtChoice asc) {
1861 if (asc.alwaysAdd(*this, U)) {
1863 appendStmt(Block, U);
1866 return Visit(U->getSubExpr(), AddStmtChoice());
1869 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1870 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1871 appendStmt(ConfluenceBlock, B);
1876 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1877 ConfluenceBlock).first;
1880 std::pair<CFGBlock*, CFGBlock*>
1881 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1883 CFGBlock *TrueBlock,
1884 CFGBlock *FalseBlock) {
1885 // Introspect the RHS. If it is a nested logical operation, we recursively
1886 // build the CFG using this function. Otherwise, resort to default
1887 // CFG construction behavior.
1888 Expr *RHS = B->getRHS()->IgnoreParens();
1889 CFGBlock *RHSBlock, *ExitBlock;
1892 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1893 if (B_RHS->isLogicalOp()) {
1894 std::tie(RHSBlock, ExitBlock) =
1895 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1899 // The RHS is not a nested logical operation. Don't push the terminator
1900 // down further, but instead visit RHS and construct the respective
1901 // pieces of the CFG, and link up the RHSBlock with the terminator
1902 // we have been provided.
1903 ExitBlock = RHSBlock = createBlock(false);
1905 // Even though KnownVal is only used in the else branch of the next
1906 // conditional, tryEvaluateBool performs additional checking on the
1907 // Expr, so it should be called unconditionally.
1908 TryResult KnownVal = tryEvaluateBool(RHS);
1909 if (!KnownVal.isKnown())
1910 KnownVal = tryEvaluateBool(B);
1913 assert(TrueBlock == FalseBlock);
1914 addSuccessor(RHSBlock, TrueBlock);
1917 RHSBlock->setTerminator(Term);
1918 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1919 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
1923 RHSBlock = addStmt(RHS);
1928 return std::make_pair(nullptr, nullptr);
1930 // Generate the blocks for evaluating the LHS.
1931 Expr *LHS = B->getLHS()->IgnoreParens();
1933 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1934 if (B_LHS->isLogicalOp()) {
1935 if (B->getOpcode() == BO_LOr)
1936 FalseBlock = RHSBlock;
1938 TrueBlock = RHSBlock;
1940 // For the LHS, treat 'B' as the terminator that we want to sink
1941 // into the nested branch. The RHS always gets the top-most
1943 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1946 // Create the block evaluating the LHS.
1947 // This contains the '&&' or '||' as the terminator.
1948 CFGBlock *LHSBlock = createBlock(false);
1949 LHSBlock->setTerminator(B);
1952 CFGBlock *EntryLHSBlock = addStmt(LHS);
1955 return std::make_pair(nullptr, nullptr);
1957 // See if this is a known constant.
1958 TryResult KnownVal = tryEvaluateBool(LHS);
1960 // Now link the LHSBlock with RHSBlock.
1961 if (B->getOpcode() == BO_LOr) {
1962 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
1963 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
1965 assert(B->getOpcode() == BO_LAnd);
1966 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
1967 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
1970 return std::make_pair(EntryLHSBlock, ExitBlock);
1973 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1974 AddStmtChoice asc) {
1976 if (B->isLogicalOp())
1977 return VisitLogicalOperator(B);
1979 if (B->getOpcode() == BO_Comma) { // ,
1981 appendStmt(Block, B);
1982 addStmt(B->getRHS());
1983 return addStmt(B->getLHS());
1986 if (B->isAssignmentOp()) {
1987 if (asc.alwaysAdd(*this, B)) {
1989 appendStmt(Block, B);
1992 return Visit(B->getRHS());
1995 if (asc.alwaysAdd(*this, B)) {
1997 appendStmt(Block, B);
2000 CFGBlock *RBlock = Visit(B->getRHS());
2001 CFGBlock *LBlock = Visit(B->getLHS());
2002 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2003 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2004 // return RBlock. Otherwise we'll incorrectly return NULL.
2005 return (LBlock ? LBlock : RBlock);
2008 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
2009 if (asc.alwaysAdd(*this, E)) {
2011 appendStmt(Block, E);
2016 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2017 // "break" is a control-flow statement. Thus we stop processing the current
2022 // Now create a new block that ends with the break statement.
2023 Block = createBlock(false);
2024 Block->setTerminator(B);
2026 // If there is no target for the break, then we are looking at an incomplete
2027 // AST. This means that the CFG cannot be constructed.
2028 if (BreakJumpTarget.block) {
2029 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
2030 addSuccessor(Block, BreakJumpTarget.block);
2037 static bool CanThrow(Expr *E, ASTContext &Ctx) {
2038 QualType Ty = E->getType();
2039 if (Ty->isFunctionPointerType())
2040 Ty = Ty->getAs<PointerType>()->getPointeeType();
2041 else if (Ty->isBlockPointerType())
2042 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
2044 const FunctionType *FT = Ty->getAs<FunctionType>();
2046 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
2047 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
2048 Proto->isNothrow(Ctx))
2054 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
2055 // Compute the callee type.
2056 QualType calleeType = C->getCallee()->getType();
2057 if (calleeType == Context->BoundMemberTy) {
2058 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2060 // We should only get a null bound type if processing a dependent
2061 // CFG. Recover by assuming nothing.
2062 if (!boundType.isNull()) calleeType = boundType;
2065 // If this is a call to a no-return function, this stops the block here.
2066 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2068 bool AddEHEdge = false;
2070 // Languages without exceptions are assumed to not throw.
2071 if (Context->getLangOpts().Exceptions) {
2072 if (BuildOpts.AddEHEdges)
2076 // If this is a call to a builtin function, it might not actually evaluate
2077 // its arguments. Don't add them to the CFG if this is the case.
2078 bool OmitArguments = false;
2080 if (FunctionDecl *FD = C->getDirectCallee()) {
2081 if (FD->isNoReturn())
2083 if (FD->hasAttr<NoThrowAttr>())
2085 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
2086 OmitArguments = true;
2089 if (!CanThrow(C->getCallee(), *Context))
2092 if (OmitArguments) {
2093 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2094 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2096 appendStmt(Block, C);
2097 return Visit(C->getCallee());
2100 if (!NoReturn && !AddEHEdge) {
2101 return VisitStmt(C, asc.withAlwaysAdd(true));
2111 Block = createNoReturnBlock();
2113 Block = createBlock();
2115 appendStmt(Block, C);
2118 // Add exceptional edges.
2119 if (TryTerminatedBlock)
2120 addSuccessor(Block, TryTerminatedBlock);
2122 addSuccessor(Block, &cfg->getExit());
2125 return VisitChildren(C);
2128 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2129 AddStmtChoice asc) {
2130 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2131 appendStmt(ConfluenceBlock, C);
2135 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2136 Succ = ConfluenceBlock;
2138 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
2142 Succ = ConfluenceBlock;
2144 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
2148 Block = createBlock(false);
2149 // See if this is a known constant.
2150 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2151 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2152 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
2153 Block->setTerminator(C);
2154 return addStmt(C->getCond());
2157 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
2158 LocalScope::const_iterator scopeBeginPos = ScopePos;
2159 addLocalScopeForStmt(C);
2161 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
2162 // If the body ends with a ReturnStmt, the dtors will be added in
2164 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
2167 CFGBlock *LastBlock = Block;
2169 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2171 // If we hit a segment of code just containing ';' (NullStmts), we can
2172 // get a null block back. In such cases, just use the LastBlock
2173 if (CFGBlock *newBlock = addStmt(*I))
2174 LastBlock = newBlock;
2183 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
2184 AddStmtChoice asc) {
2185 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
2186 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
2188 // Create the confluence block that will "merge" the results of the ternary
2190 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2191 appendStmt(ConfluenceBlock, C);
2195 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2197 // Create a block for the LHS expression if there is an LHS expression. A
2198 // GCC extension allows LHS to be NULL, causing the condition to be the
2199 // value that is returned instead.
2200 // e.g: x ?: y is shorthand for: x ? x : y;
2201 Succ = ConfluenceBlock;
2203 CFGBlock *LHSBlock = nullptr;
2204 const Expr *trueExpr = C->getTrueExpr();
2205 if (trueExpr != opaqueValue) {
2206 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
2212 LHSBlock = ConfluenceBlock;
2214 // Create the block for the RHS expression.
2215 Succ = ConfluenceBlock;
2216 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
2220 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2221 if (BinaryOperator *Cond =
2222 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2223 if (Cond->isLogicalOp())
2224 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2226 // Create the block that will contain the condition.
2227 Block = createBlock(false);
2229 // See if this is a known constant.
2230 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2231 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2232 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
2233 Block->setTerminator(C);
2234 Expr *condExpr = C->getCond();
2237 // Run the condition expression if it's not trivially expressed in
2238 // terms of the opaque value (or if there is no opaque value).
2239 if (condExpr != opaqueValue)
2242 // Before that, run the common subexpression if there was one.
2243 // At least one of this or the above will be run.
2244 return addStmt(BCO->getCommon());
2247 return addStmt(condExpr);
2250 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
2251 // Check if the Decl is for an __label__. If so, elide it from the
2253 if (isa<LabelDecl>(*DS->decl_begin()))
2256 // This case also handles static_asserts.
2257 if (DS->isSingleDecl())
2258 return VisitDeclSubExpr(DS);
2260 CFGBlock *B = nullptr;
2262 // Build an individual DeclStmt for each decl.
2263 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2264 E = DS->decl_rend();
2266 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
2267 unsigned A = alignof(DeclStmt) < 8 ? 8 : alignof(DeclStmt);
2269 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2270 // automatically freed with the CFG.
2271 DeclGroupRef DG(*I);
2273 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
2274 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
2275 cfg->addSyntheticDeclStmt(DSNew, DS);
2277 // Append the fake DeclStmt to block.
2278 B = VisitDeclSubExpr(DSNew);
2284 /// VisitDeclSubExpr - Utility method to add block-level expressions for
2285 /// DeclStmts and initializers in them.
2286 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
2287 assert(DS->isSingleDecl() && "Can handle single declarations only.");
2288 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
2291 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2292 // runtime semantics.
2296 bool HasTemporaries = false;
2298 // Guard static initializers under a branch.
2299 CFGBlock *blockAfterStaticInit = nullptr;
2301 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2302 // For static variables, we need to create a branch to track
2303 // whether or not they are initialized.
2310 blockAfterStaticInit = Succ;
2313 // Destructors of temporaries in initialization expression should be called
2314 // after initialization finishes.
2315 Expr *Init = VD->getInit();
2317 HasTemporaries = isa<ExprWithCleanups>(Init);
2319 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
2320 // Generate destructors for temporaries in initialization expression.
2321 TempDtorContext Context;
2322 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2323 /*BindToTemporary=*/false, Context);
2328 appendStmt(Block, DS);
2330 // Keep track of the last non-null block, as 'Block' can be nulled out
2331 // if the initializer expression is something like a 'while' in a
2332 // statement-expression.
2333 CFGBlock *LastBlock = Block;
2336 if (HasTemporaries) {
2337 // For expression with temporaries go directly to subexpression to omit
2338 // generating destructors for the second time.
2339 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2340 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2341 LastBlock = newBlock;
2344 if (CFGBlock *newBlock = Visit(Init))
2345 LastBlock = newBlock;
2349 // If the type of VD is a VLA, then we must process its size expressions.
2350 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
2351 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
2352 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2353 LastBlock = newBlock;
2356 // Remove variable from local scope.
2357 if (ScopePos && VD == *ScopePos)
2360 CFGBlock *B = LastBlock;
2361 if (blockAfterStaticInit) {
2363 Block = createBlock(false);
2364 Block->setTerminator(DS);
2365 addSuccessor(Block, blockAfterStaticInit);
2366 addSuccessor(Block, B);
2373 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
2374 // We may see an if statement in the middle of a basic block, or it may be the
2375 // first statement we are processing. In either case, we create a new basic
2376 // block. First, we create the blocks for the then...else statements, and
2377 // then we create the block containing the if statement. If we were in the
2378 // middle of a block, we stop processing that block. That block is then the
2379 // implicit successor for the "then" and "else" clauses.
2381 // Save local scope position because in case of condition variable ScopePos
2382 // won't be restored when traversing AST.
2383 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2385 // Create local scope for C++17 if init-stmt if one exists.
2386 if (Stmt *Init = I->getInit())
2387 addLocalScopeForStmt(Init);
2389 // Create local scope for possible condition variable.
2390 // Store scope position. Add implicit destructor.
2391 if (VarDecl *VD = I->getConditionVariable())
2392 addLocalScopeForVarDecl(VD);
2394 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
2396 // The block we were processing is now finished. Make it the successor
2404 // Process the false branch.
2405 CFGBlock *ElseBlock = Succ;
2407 if (Stmt *Else = I->getElse()) {
2408 SaveAndRestore<CFGBlock*> sv(Succ);
2410 // NULL out Block so that the recursive call to Visit will
2411 // create a new basic block.
2414 // If branch is not a compound statement create implicit scope
2415 // and add destructors.
2416 if (!isa<CompoundStmt>(Else))
2417 addLocalScopeAndDtors(Else);
2419 ElseBlock = addStmt(Else);
2421 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2422 ElseBlock = sv.get();
2429 // Process the true branch.
2430 CFGBlock *ThenBlock;
2432 Stmt *Then = I->getThen();
2434 SaveAndRestore<CFGBlock*> sv(Succ);
2437 // If branch is not a compound statement create implicit scope
2438 // and add destructors.
2439 if (!isa<CompoundStmt>(Then))
2440 addLocalScopeAndDtors(Then);
2442 ThenBlock = addStmt(Then);
2445 // We can reach here if the "then" body has all NullStmts.
2446 // Create an empty block so we can distinguish between true and false
2447 // branches in path-sensitive analyses.
2448 ThenBlock = createBlock(false);
2449 addSuccessor(ThenBlock, sv.get());
2456 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2457 // having these handle the actual control-flow jump. Note that
2458 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2459 // we resort to the old control-flow behavior. This special handling
2460 // removes infeasible paths from the control-flow graph by having the
2461 // control-flow transfer of '&&' or '||' go directly into the then/else
2463 BinaryOperator *Cond =
2464 I->getConditionVariable()
2466 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
2467 CFGBlock *LastBlock;
2468 if (Cond && Cond->isLogicalOp())
2469 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2471 // Now create a new block containing the if statement.
2472 Block = createBlock(false);
2474 // Set the terminator of the new block to the If statement.
2475 Block->setTerminator(I);
2477 // See if this is a known constant.
2478 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
2480 // Add the successors. If we know that specific branches are
2481 // unreachable, inform addSuccessor() of that knowledge.
2482 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2483 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
2485 // Add the condition as the last statement in the new block. This may
2486 // create new blocks as the condition may contain control-flow. Any newly
2487 // created blocks will be pointed to be "Block".
2488 LastBlock = addStmt(I->getCond());
2490 // If the IfStmt contains a condition variable, add it and its
2491 // initializer to the CFG.
2492 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2494 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2498 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2499 if (Stmt *Init = I->getInit()) {
2501 LastBlock = addStmt(Init);
2507 CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
2508 // If we were in the middle of a block we stop processing that block.
2510 // NOTE: If a "return" appears in the middle of a block, this means that the
2511 // code afterwards is DEAD (unreachable). We still keep a basic block
2512 // for that code; a simple "mark-and-sweep" from the entry block will be
2513 // able to report such dead blocks.
2515 // Create the new block.
2516 Block = createBlock(false);
2518 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), R);
2520 // If the one of the destructors does not return, we already have the Exit
2521 // block as a successor.
2522 if (!Block->hasNoReturnElement())
2523 addSuccessor(Block, &cfg->getExit());
2525 // Add the return statement to the block. This may create new blocks if R
2526 // contains control-flow (short-circuit operations).
2527 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
2530 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
2531 // SEHExceptStmt are treated like labels, so they are the first statement in a
2534 // Save local scope position because in case of exception variable ScopePos
2535 // won't be restored when traversing AST.
2536 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2538 addStmt(ES->getBlock());
2539 CFGBlock *SEHExceptBlock = Block;
2540 if (!SEHExceptBlock)
2541 SEHExceptBlock = createBlock();
2543 appendStmt(SEHExceptBlock, ES);
2545 // Also add the SEHExceptBlock as a label, like with regular labels.
2546 SEHExceptBlock->setLabel(ES);
2548 // Bail out if the CFG is bad.
2552 // We set Block to NULL to allow lazy creation of a new block (if necessary).
2555 return SEHExceptBlock;
2558 CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
2559 return VisitCompoundStmt(FS->getBlock());
2562 CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
2563 // "__leave" is a control-flow statement. Thus we stop processing the current
2568 // Now create a new block that ends with the __leave statement.
2569 Block = createBlock(false);
2570 Block->setTerminator(LS);
2572 // If there is no target for the __leave, then we are looking at an incomplete
2573 // AST. This means that the CFG cannot be constructed.
2574 if (SEHLeaveJumpTarget.block) {
2575 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
2576 addSuccessor(Block, SEHLeaveJumpTarget.block);
2583 CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
2584 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
2585 // processing the current block.
2586 CFGBlock *SEHTrySuccessor = nullptr;
2591 SEHTrySuccessor = Block;
2592 } else SEHTrySuccessor = Succ;
2594 // FIXME: Implement __finally support.
2595 if (Terminator->getFinallyHandler())
2598 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
2600 // Create a new block that will contain the __try statement.
2601 CFGBlock *NewTryTerminatedBlock = createBlock(false);
2603 // Add the terminator in the __try block.
2604 NewTryTerminatedBlock->setTerminator(Terminator);
2606 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
2607 // The code after the try is the implicit successor if there's an __except.
2608 Succ = SEHTrySuccessor;
2610 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
2613 // Add this block to the list of successors for the block with the try
2615 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
2617 if (PrevSEHTryTerminatedBlock)
2618 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
2620 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2622 // The code after the try is the implicit successor.
2623 Succ = SEHTrySuccessor;
2625 // Save the current "__try" context.
2626 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
2627 NewTryTerminatedBlock);
2628 cfg->addTryDispatchBlock(TryTerminatedBlock);
2630 // Save the current value for the __leave target.
2631 // All __leaves should go to the code following the __try
2632 // (FIXME: or if the __try has a __finally, to the __finally.)
2633 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
2634 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
2636 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
2638 return addStmt(Terminator->getTryBlock());
2641 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
2642 // Get the block of the labeled statement. Add it to our map.
2643 addStmt(L->getSubStmt());
2644 CFGBlock *LabelBlock = Block;
2646 if (!LabelBlock) // This can happen when the body is empty, i.e.
2647 LabelBlock = createBlock(); // scopes that only contains NullStmts.
2649 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2650 "label already in map");
2651 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
2653 // Labels partition blocks, so this is the end of the basic block we were
2654 // processing (L is the block's label). Because this is label (and we have
2655 // already processed the substatement) there is no extra control-flow to worry
2657 LabelBlock->setLabel(L);
2661 // We set Block to NULL to allow lazy creation of a new block (if necessary);
2664 // This block is now the implicit successor of other blocks.
2670 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
2671 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2672 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
2673 if (Expr *CopyExpr = CI.getCopyExpr()) {
2674 CFGBlock *Tmp = Visit(CopyExpr);
2682 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2683 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2684 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2685 et = E->capture_init_end(); it != et; ++it) {
2686 if (Expr *Init = *it) {
2687 CFGBlock *Tmp = Visit(Init);
2695 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
2696 // Goto is a control-flow statement. Thus we stop processing the current
2697 // block and create a new one.
2699 Block = createBlock(false);
2700 Block->setTerminator(G);
2702 // If we already know the mapping to the label block add the successor now.
2703 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
2705 if (I == LabelMap.end())
2706 // We will need to backpatch this block later.
2707 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2709 JumpTarget JT = I->second;
2710 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
2711 addSuccessor(Block, JT.block);
2717 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
2718 CFGBlock *LoopSuccessor = nullptr;
2720 // Save local scope position because in case of condition variable ScopePos
2721 // won't be restored when traversing AST.
2722 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2724 // Create local scope for init statement and possible condition variable.
2725 // Add destructor for init statement and condition variable.
2726 // Store scope position for continue statement.
2727 if (Stmt *Init = F->getInit())
2728 addLocalScopeForStmt(Init);
2729 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2731 if (VarDecl *VD = F->getConditionVariable())
2732 addLocalScopeForVarDecl(VD);
2733 LocalScope::const_iterator ContinueScopePos = ScopePos;
2735 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
2739 // "for" is a control-flow statement. Thus we stop processing the current
2744 LoopSuccessor = Block;
2746 LoopSuccessor = Succ;
2748 // Save the current value for the break targets.
2749 // All breaks should go to the code following the loop.
2750 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2751 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2753 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
2755 // Now create the loop body.
2757 assert(F->getBody());
2759 // Save the current values for Block, Succ, continue and break targets.
2760 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2761 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
2763 // Create an empty block to represent the transition block for looping back
2764 // to the head of the loop. If we have increment code, it will
2765 // go in this block as well.
2766 Block = Succ = TransitionBlock = createBlock(false);
2767 TransitionBlock->setLoopTarget(F);
2769 if (Stmt *I = F->getInc()) {
2770 // Generate increment code in its own basic block. This is the target of
2771 // continue statements.
2775 // Finish up the increment (or empty) block if it hasn't been already.
2777 assert(Block == Succ);
2783 // The starting block for the loop increment is the block that should
2784 // represent the 'loop target' for looping back to the start of the loop.
2785 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2786 ContinueJumpTarget.block->setLoopTarget(F);
2788 // Loop body should end with destructor of Condition variable (if any).
2789 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
2791 // If body is not a compound statement create implicit scope
2792 // and add destructors.
2793 if (!isa<CompoundStmt>(F->getBody()))
2794 addLocalScopeAndDtors(F->getBody());
2796 // Now populate the body block, and in the process create new blocks as we
2797 // walk the body of the loop.
2798 BodyBlock = addStmt(F->getBody());
2801 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2802 // Use the continue jump target as the proxy for the body.
2803 BodyBlock = ContinueJumpTarget.block;
2809 // Because of short-circuit evaluation, the condition of the loop can span
2810 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2811 // evaluate the condition.
2812 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
2815 Expr *C = F->getCond();
2817 // Specially handle logical operators, which have a slightly
2818 // more optimal CFG representation.
2819 if (BinaryOperator *Cond =
2820 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
2821 if (Cond->isLogicalOp()) {
2822 std::tie(EntryConditionBlock, ExitConditionBlock) =
2823 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2827 // The default case when not handling logical operators.
2828 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2829 ExitConditionBlock->setTerminator(F);
2831 // See if this is a known constant.
2832 TryResult KnownVal(true);
2835 // Now add the actual condition to the condition block.
2836 // Because the condition itself may contain control-flow, new blocks may
2837 // be created. Thus we update "Succ" after adding the condition.
2838 Block = ExitConditionBlock;
2839 EntryConditionBlock = addStmt(C);
2841 // If this block contains a condition variable, add both the condition
2842 // variable and initializer to the CFG.
2843 if (VarDecl *VD = F->getConditionVariable()) {
2844 if (Expr *Init = VD->getInit()) {
2846 appendStmt(Block, F->getConditionVariableDeclStmt());
2847 EntryConditionBlock = addStmt(Init);
2848 assert(Block == EntryConditionBlock);
2852 if (Block && badCFG)
2855 KnownVal = tryEvaluateBool(C);
2858 // Add the loop body entry as a successor to the condition.
2859 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
2860 // Link up the condition block with the code that follows the loop. (the
2862 addSuccessor(ExitConditionBlock,
2863 KnownVal.isTrue() ? nullptr : LoopSuccessor);
2866 // Link up the loop-back block to the entry condition block.
2867 addSuccessor(TransitionBlock, EntryConditionBlock);
2869 // The condition block is the implicit successor for any code above the loop.
2870 Succ = EntryConditionBlock;
2872 // If the loop contains initialization, create a new block for those
2873 // statements. This block can also contain statements that precede the loop.
2874 if (Stmt *I = F->getInit()) {
2875 Block = createBlock();
2879 // There is no loop initialization. We are thus basically a while loop.
2880 // NULL out Block to force lazy block construction.
2882 Succ = EntryConditionBlock;
2883 return EntryConditionBlock;
2886 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
2887 if (asc.alwaysAdd(*this, M)) {
2889 appendStmt(Block, M);
2891 return Visit(M->getBase());
2894 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
2895 // Objective-C fast enumeration 'for' statements:
2896 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2898 // for ( Type newVariable in collection_expression ) { statements }
2903 // 1. collection_expression
2904 // T. jump to loop_entry
2906 // 1. side-effects of element expression
2907 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2908 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2911 // T. jump to loop_entry
2917 // Type existingItem;
2918 // for ( existingItem in expression ) { statements }
2922 // the same with newVariable replaced with existingItem; the binding works
2923 // the same except that for one ObjCForCollectionStmt::getElement() returns
2924 // a DeclStmt and the other returns a DeclRefExpr.
2926 CFGBlock *LoopSuccessor = nullptr;
2931 LoopSuccessor = Block;
2934 LoopSuccessor = Succ;
2936 // Build the condition blocks.
2937 CFGBlock *ExitConditionBlock = createBlock(false);
2939 // Set the terminator for the "exit" condition block.
2940 ExitConditionBlock->setTerminator(S);
2942 // The last statement in the block should be the ObjCForCollectionStmt, which
2943 // performs the actual binding to 'element' and determines if there are any
2944 // more items in the collection.
2945 appendStmt(ExitConditionBlock, S);
2946 Block = ExitConditionBlock;
2948 // Walk the 'element' expression to see if there are any side-effects. We
2949 // generate new blocks as necessary. We DON'T add the statement by default to
2950 // the CFG unless it contains control-flow.
2951 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2952 AddStmtChoice::NotAlwaysAdd);
2959 // The condition block is the implicit successor for the loop body as well as
2960 // any code above the loop.
2961 Succ = EntryConditionBlock;
2963 // Now create the true branch.
2965 // Save the current values for Succ, continue and break targets.
2966 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2967 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2968 save_break(BreakJumpTarget);
2970 // Add an intermediate block between the BodyBlock and the
2971 // EntryConditionBlock to represent the "loop back" transition, for looping
2972 // back to the head of the loop.
2973 CFGBlock *LoopBackBlock = nullptr;
2974 Succ = LoopBackBlock = createBlock();
2975 LoopBackBlock->setLoopTarget(S);
2977 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2978 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
2980 CFGBlock *BodyBlock = addStmt(S->getBody());
2983 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
2989 // This new body block is a successor to our "exit" condition block.
2990 addSuccessor(ExitConditionBlock, BodyBlock);
2993 // Link up the condition block with the code that follows the loop.
2994 // (the false branch).
2995 addSuccessor(ExitConditionBlock, LoopSuccessor);
2997 // Now create a prologue block to contain the collection expression.
2998 Block = createBlock();
2999 return addStmt(S->getCollection());
3002 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3004 return addStmt(S->getSubStmt());
3005 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3008 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
3009 // FIXME: Add locking 'primitives' to CFG for @synchronized.
3012 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
3014 // The sync body starts its own basic block. This makes it a little easier
3015 // for diagnostic clients.
3024 // Add the @synchronized to the CFG.
3026 appendStmt(Block, S);
3028 // Inline the sync expression.
3029 return addStmt(S->getSynchExpr());
3032 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
3037 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3040 // Add the PseudoObject as the last thing.
3041 appendStmt(Block, E);
3043 CFGBlock *lastBlock = Block;
3045 // Before that, evaluate all of the semantics in order. In
3046 // CFG-land, that means appending them in reverse order.
3047 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3048 Expr *Semantic = E->getSemanticExpr(--i);
3050 // If the semantic is an opaque value, we're being asked to bind
3051 // it to its source expression.
3052 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3053 Semantic = OVE->getSourceExpr();
3055 if (CFGBlock *B = Visit(Semantic))
3062 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
3063 CFGBlock *LoopSuccessor = nullptr;
3065 // Save local scope position because in case of condition variable ScopePos
3066 // won't be restored when traversing AST.
3067 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3069 // Create local scope for possible condition variable.
3070 // Store scope position for continue statement.
3071 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3072 if (VarDecl *VD = W->getConditionVariable()) {
3073 addLocalScopeForVarDecl(VD);
3074 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3078 // "while" is a control-flow statement. Thus we stop processing the current
3083 LoopSuccessor = Block;
3086 LoopSuccessor = Succ;
3089 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3091 // Process the loop body.
3093 assert(W->getBody());
3095 // Save the current values for Block, Succ, continue and break targets.
3096 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3097 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3098 save_break(BreakJumpTarget);
3100 // Create an empty block to represent the transition block for looping back
3101 // to the head of the loop.
3102 Succ = TransitionBlock = createBlock(false);
3103 TransitionBlock->setLoopTarget(W);
3104 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
3106 // All breaks should go to the code following the loop.
3107 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3109 // Loop body should end with destructor of Condition variable (if any).
3110 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3112 // If body is not a compound statement create implicit scope
3113 // and add destructors.
3114 if (!isa<CompoundStmt>(W->getBody()))
3115 addLocalScopeAndDtors(W->getBody());
3117 // Create the body. The returned block is the entry to the loop body.
3118 BodyBlock = addStmt(W->getBody());
3121 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
3122 else if (Block && badCFG)
3126 // Because of short-circuit evaluation, the condition of the loop can span
3127 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3128 // evaluate the condition.
3129 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3132 Expr *C = W->getCond();
3134 // Specially handle logical operators, which have a slightly
3135 // more optimal CFG representation.
3136 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
3137 if (Cond->isLogicalOp()) {
3138 std::tie(EntryConditionBlock, ExitConditionBlock) =
3139 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
3143 // The default case when not handling logical operators.
3144 ExitConditionBlock = createBlock(false);
3145 ExitConditionBlock->setTerminator(W);
3147 // Now add the actual condition to the condition block.
3148 // Because the condition itself may contain control-flow, new blocks may
3149 // be created. Thus we update "Succ" after adding the condition.
3150 Block = ExitConditionBlock;
3151 Block = EntryConditionBlock = addStmt(C);
3153 // If this block contains a condition variable, add both the condition
3154 // variable and initializer to the CFG.
3155 if (VarDecl *VD = W->getConditionVariable()) {
3156 if (Expr *Init = VD->getInit()) {
3158 appendStmt(Block, W->getConditionVariableDeclStmt());
3159 EntryConditionBlock = addStmt(Init);
3160 assert(Block == EntryConditionBlock);
3164 if (Block && badCFG)
3167 // See if this is a known constant.
3168 const TryResult& KnownVal = tryEvaluateBool(C);
3170 // Add the loop body entry as a successor to the condition.
3171 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
3172 // Link up the condition block with the code that follows the loop. (the
3174 addSuccessor(ExitConditionBlock,
3175 KnownVal.isTrue() ? nullptr : LoopSuccessor);
3178 // Link up the loop-back block to the entry condition block.
3179 addSuccessor(TransitionBlock, EntryConditionBlock);
3181 // There can be no more statements in the condition block since we loop back
3182 // to this block. NULL out Block to force lazy creation of another block.
3185 // Return the condition block, which is the dominating block for the loop.
3186 Succ = EntryConditionBlock;
3187 return EntryConditionBlock;
3190 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
3191 // FIXME: For now we pretend that @catch and the code it contains does not
3196 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
3197 // FIXME: This isn't complete. We basically treat @throw like a return
3200 // If we were in the middle of a block we stop processing that block.
3204 // Create the new block.
3205 Block = createBlock(false);
3207 // The Exit block is the only successor.
3208 addSuccessor(Block, &cfg->getExit());
3210 // Add the statement to the block. This may create new blocks if S contains
3211 // control-flow (short-circuit operations).
3212 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
3215 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
3216 // If we were in the middle of a block we stop processing that block.
3220 // Create the new block.
3221 Block = createBlock(false);
3223 if (TryTerminatedBlock)
3224 // The current try statement is the only successor.
3225 addSuccessor(Block, TryTerminatedBlock);
3227 // otherwise the Exit block is the only successor.
3228 addSuccessor(Block, &cfg->getExit());
3230 // Add the statement to the block. This may create new blocks if S contains
3231 // control-flow (short-circuit operations).
3232 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
3235 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
3236 CFGBlock *LoopSuccessor = nullptr;
3240 // "do...while" is a control-flow statement. Thus we stop processing the
3245 LoopSuccessor = Block;
3247 LoopSuccessor = Succ;
3249 // Because of short-circuit evaluation, the condition of the loop can span
3250 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3251 // evaluate the condition.
3252 CFGBlock *ExitConditionBlock = createBlock(false);
3253 CFGBlock *EntryConditionBlock = ExitConditionBlock;
3255 // Set the terminator for the "exit" condition block.
3256 ExitConditionBlock->setTerminator(D);
3258 // Now add the actual condition to the condition block. Because the condition
3259 // itself may contain control-flow, new blocks may be created.
3260 if (Stmt *C = D->getCond()) {
3261 Block = ExitConditionBlock;
3262 EntryConditionBlock = addStmt(C);
3269 // The condition block is the implicit successor for the loop body.
3270 Succ = EntryConditionBlock;
3272 // See if this is a known constant.
3273 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
3275 // Process the loop body.
3276 CFGBlock *BodyBlock = nullptr;
3278 assert(D->getBody());
3280 // Save the current values for Block, Succ, and continue and break targets
3281 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3282 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3283 save_break(BreakJumpTarget);
3285 // All continues within this loop should go to the condition block
3286 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
3288 // All breaks should go to the code following the loop.
3289 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3291 // NULL out Block to force lazy instantiation of blocks for the body.
3294 // If body is not a compound statement create implicit scope
3295 // and add destructors.
3296 if (!isa<CompoundStmt>(D->getBody()))
3297 addLocalScopeAndDtors(D->getBody());
3299 // Create the body. The returned block is the entry to the loop body.
3300 BodyBlock = addStmt(D->getBody());
3303 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
3309 // Add an intermediate block between the BodyBlock and the
3310 // ExitConditionBlock to represent the "loop back" transition. Create an
3311 // empty block to represent the transition block for looping back to the
3312 // head of the loop.
3313 // FIXME: Can we do this more efficiently without adding another block?
3316 CFGBlock *LoopBackBlock = createBlock();
3317 LoopBackBlock->setLoopTarget(D);
3319 if (!KnownVal.isFalse())
3320 // Add the loop body entry as a successor to the condition.
3321 addSuccessor(ExitConditionBlock, LoopBackBlock);
3323 addSuccessor(ExitConditionBlock, nullptr);
3326 // Link up the condition block with the code that follows the loop.
3327 // (the false branch).
3328 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
3330 // There can be no more statements in the body block(s) since we loop back to
3331 // the body. NULL out Block to force lazy creation of another block.
3334 // Return the loop body, which is the dominating block for the loop.
3339 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
3340 // "continue" is a control-flow statement. Thus we stop processing the
3345 // Now create a new block that ends with the continue statement.
3346 Block = createBlock(false);
3347 Block->setTerminator(C);
3349 // If there is no target for the continue, then we are looking at an
3350 // incomplete AST. This means the CFG cannot be constructed.
3351 if (ContinueJumpTarget.block) {
3352 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
3353 addSuccessor(Block, ContinueJumpTarget.block);
3360 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3361 AddStmtChoice asc) {
3362 if (asc.alwaysAdd(*this, E)) {
3364 appendStmt(Block, E);
3367 // VLA types have expressions that must be evaluated.
3368 CFGBlock *lastBlock = Block;
3370 if (E->isArgumentType()) {
3371 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
3372 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
3373 lastBlock = addStmt(VA->getSizeExpr());
3378 /// VisitStmtExpr - Utility method to handle (nested) statement
3379 /// expressions (a GCC extension).
3380 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
3381 if (asc.alwaysAdd(*this, SE)) {
3383 appendStmt(Block, SE);
3385 return VisitCompoundStmt(SE->getSubStmt());
3388 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
3389 // "switch" is a control-flow statement. Thus we stop processing the current
3391 CFGBlock *SwitchSuccessor = nullptr;
3393 // Save local scope position because in case of condition variable ScopePos
3394 // won't be restored when traversing AST.
3395 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3397 // Create local scope for C++17 switch init-stmt if one exists.
3398 if (Stmt *Init = Terminator->getInit())
3399 addLocalScopeForStmt(Init);
3401 // Create local scope for possible condition variable.
3402 // Store scope position. Add implicit destructor.
3403 if (VarDecl *VD = Terminator->getConditionVariable())
3404 addLocalScopeForVarDecl(VD);
3406 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
3411 SwitchSuccessor = Block;
3412 } else SwitchSuccessor = Succ;
3414 // Save the current "switch" context.
3415 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
3416 save_default(DefaultCaseBlock);
3417 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3419 // Set the "default" case to be the block after the switch statement. If the
3420 // switch statement contains a "default:", this value will be overwritten with
3421 // the block for that code.
3422 DefaultCaseBlock = SwitchSuccessor;
3424 // Create a new block that will contain the switch statement.
3425 SwitchTerminatedBlock = createBlock(false);
3427 // Now process the switch body. The code after the switch is the implicit
3429 Succ = SwitchSuccessor;
3430 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
3432 // When visiting the body, the case statements should automatically get linked
3433 // up to the switch. We also don't keep a pointer to the body, since all
3434 // control-flow from the switch goes to case/default statements.
3435 assert(Terminator->getBody() && "switch must contain a non-NULL body");
3438 // For pruning unreachable case statements, save the current state
3439 // for tracking the condition value.
3440 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3443 // Determine if the switch condition can be explicitly evaluated.
3444 assert(Terminator->getCond() && "switch condition must be non-NULL");
3445 Expr::EvalResult result;
3446 bool b = tryEvaluate(Terminator->getCond(), result);
3447 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
3448 b ? &result : nullptr);
3450 // If body is not a compound statement create implicit scope
3451 // and add destructors.
3452 if (!isa<CompoundStmt>(Terminator->getBody()))
3453 addLocalScopeAndDtors(Terminator->getBody());
3455 addStmt(Terminator->getBody());
3461 // If we have no "default:" case, the default transition is to the code
3462 // following the switch body. Moreover, take into account if all the
3463 // cases of a switch are covered (e.g., switching on an enum value).
3465 // Note: We add a successor to a switch that is considered covered yet has no
3466 // case statements if the enumeration has no enumerators.
3467 bool SwitchAlwaysHasSuccessor = false;
3468 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3469 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3470 Terminator->getSwitchCaseList();
3471 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3472 !SwitchAlwaysHasSuccessor);
3474 // Add the terminator and condition in the switch block.
3475 SwitchTerminatedBlock->setTerminator(Terminator);
3476 Block = SwitchTerminatedBlock;
3477 CFGBlock *LastBlock = addStmt(Terminator->getCond());
3479 // If the SwitchStmt contains a condition variable, add both the
3480 // SwitchStmt and the condition variable initialization to the CFG.
3481 if (VarDecl *VD = Terminator->getConditionVariable()) {
3482 if (Expr *Init = VD->getInit()) {
3484 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
3485 LastBlock = addStmt(Init);
3489 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
3490 if (Stmt *Init = Terminator->getInit()) {
3492 LastBlock = addStmt(Init);
3498 static bool shouldAddCase(bool &switchExclusivelyCovered,
3499 const Expr::EvalResult *switchCond,
3505 bool addCase = false;
3507 if (!switchExclusivelyCovered) {
3508 if (switchCond->Val.isInt()) {
3509 // Evaluate the LHS of the case value.
3510 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
3511 const llvm::APSInt &condInt = switchCond->Val.getInt();
3513 if (condInt == lhsInt) {
3515 switchExclusivelyCovered = true;
3517 else if (condInt > lhsInt) {
3518 if (const Expr *RHS = CS->getRHS()) {
3519 // Evaluate the RHS of the case value.
3520 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
3521 if (V2 >= condInt) {
3523 switchExclusivelyCovered = true;
3534 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
3535 // CaseStmts are essentially labels, so they are the first statement in a
3537 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
3539 if (Stmt *Sub = CS->getSubStmt()) {
3540 // For deeply nested chains of CaseStmts, instead of doing a recursion
3541 // (which can blow out the stack), manually unroll and create blocks
3543 while (isa<CaseStmt>(Sub)) {
3544 CFGBlock *currentBlock = createBlock(false);
3545 currentBlock->setLabel(CS);
3548 addSuccessor(LastBlock, currentBlock);
3550 TopBlock = currentBlock;
3552 addSuccessor(SwitchTerminatedBlock,
3553 shouldAddCase(switchExclusivelyCovered, switchCond,
3555 ? currentBlock : nullptr);
3557 LastBlock = currentBlock;
3558 CS = cast<CaseStmt>(Sub);
3559 Sub = CS->getSubStmt();
3565 CFGBlock *CaseBlock = Block;
3567 CaseBlock = createBlock();
3569 // Cases statements partition blocks, so this is the top of the basic block we
3570 // were processing (the "case XXX:" is the label).
3571 CaseBlock->setLabel(CS);
3576 // Add this block to the list of successors for the block with the switch
3578 assert(SwitchTerminatedBlock);
3579 addSuccessor(SwitchTerminatedBlock, CaseBlock,
3580 shouldAddCase(switchExclusivelyCovered, switchCond,
3583 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3587 addSuccessor(LastBlock, CaseBlock);
3590 // This block is now the implicit successor of other blocks.
3597 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
3598 if (Terminator->getSubStmt())
3599 addStmt(Terminator->getSubStmt());
3601 DefaultCaseBlock = Block;
3603 if (!DefaultCaseBlock)
3604 DefaultCaseBlock = createBlock();
3606 // Default statements partition blocks, so this is the top of the basic block
3607 // we were processing (the "default:" is the label).
3608 DefaultCaseBlock->setLabel(Terminator);
3613 // Unlike case statements, we don't add the default block to the successors
3614 // for the switch statement immediately. This is done when we finish
3615 // processing the switch statement. This allows for the default case
3616 // (including a fall-through to the code after the switch statement) to always
3617 // be the last successor of a switch-terminated block.
3619 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3622 // This block is now the implicit successor of other blocks.
3623 Succ = DefaultCaseBlock;
3625 return DefaultCaseBlock;
3628 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3629 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3631 CFGBlock *TrySuccessor = nullptr;
3636 TrySuccessor = Block;
3637 } else TrySuccessor = Succ;
3639 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
3641 // Create a new block that will contain the try statement.
3642 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3643 // Add the terminator in the try block.
3644 NewTryTerminatedBlock->setTerminator(Terminator);
3646 bool HasCatchAll = false;
3647 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3648 // The code after the try is the implicit successor.
3649 Succ = TrySuccessor;
3650 CXXCatchStmt *CS = Terminator->getHandler(h);
3651 if (CS->getExceptionDecl() == nullptr) {
3655 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
3658 // Add this block to the list of successors for the block with the try
3660 addSuccessor(NewTryTerminatedBlock, CatchBlock);
3663 if (PrevTryTerminatedBlock)
3664 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
3666 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3669 // The code after the try is the implicit successor.
3670 Succ = TrySuccessor;
3672 // Save the current "try" context.
3673 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3674 cfg->addTryDispatchBlock(TryTerminatedBlock);
3676 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
3678 return addStmt(Terminator->getTryBlock());
3681 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
3682 // CXXCatchStmt are treated like labels, so they are the first statement in a
3685 // Save local scope position because in case of exception variable ScopePos
3686 // won't be restored when traversing AST.
3687 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3689 // Create local scope for possible exception variable.
3690 // Store scope position. Add implicit destructor.
3691 if (VarDecl *VD = CS->getExceptionDecl()) {
3692 LocalScope::const_iterator BeginScopePos = ScopePos;
3693 addLocalScopeForVarDecl(VD);
3694 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
3697 if (CS->getHandlerBlock())
3698 addStmt(CS->getHandlerBlock());
3700 CFGBlock *CatchBlock = Block;
3702 CatchBlock = createBlock();
3704 // CXXCatchStmt is more than just a label. They have semantic meaning
3705 // as well, as they implicitly "initialize" the catch variable. Add
3706 // it to the CFG as a CFGElement so that the control-flow of these
3707 // semantics gets captured.
3708 appendStmt(CatchBlock, CS);
3710 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3712 CatchBlock->setLabel(CS);
3714 // Bail out if the CFG is bad.
3718 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3724 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
3725 // C++0x for-range statements are specified as [stmt.ranged]:
3728 // auto && __range = range-init;
3729 // for ( auto __begin = begin-expr,
3730 // __end = end-expr;
3731 // __begin != __end;
3733 // for-range-declaration = *__begin;
3738 // Save local scope position before the addition of the implicit variables.
3739 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3741 // Create local scopes and destructors for range, begin and end variables.
3742 if (Stmt *Range = S->getRangeStmt())
3743 addLocalScopeForStmt(Range);
3744 if (Stmt *Begin = S->getBeginStmt())
3745 addLocalScopeForStmt(Begin);
3746 if (Stmt *End = S->getEndStmt())
3747 addLocalScopeForStmt(End);
3748 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
3750 LocalScope::const_iterator ContinueScopePos = ScopePos;
3752 // "for" is a control-flow statement. Thus we stop processing the current
3754 CFGBlock *LoopSuccessor = nullptr;
3758 LoopSuccessor = Block;
3760 LoopSuccessor = Succ;
3762 // Save the current value for the break targets.
3763 // All breaks should go to the code following the loop.
3764 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3765 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3767 // The block for the __begin != __end expression.
3768 CFGBlock *ConditionBlock = createBlock(false);
3769 ConditionBlock->setTerminator(S);
3771 // Now add the actual condition to the condition block.
3772 if (Expr *C = S->getCond()) {
3773 Block = ConditionBlock;
3774 CFGBlock *BeginConditionBlock = addStmt(C);
3777 assert(BeginConditionBlock == ConditionBlock &&
3778 "condition block in for-range was unexpectedly complex");
3779 (void)BeginConditionBlock;
3782 // The condition block is the implicit successor for the loop body as well as
3783 // any code above the loop.
3784 Succ = ConditionBlock;
3786 // See if this is a known constant.
3787 TryResult KnownVal(true);
3790 KnownVal = tryEvaluateBool(S->getCond());
3792 // Now create the loop body.
3794 assert(S->getBody());
3796 // Save the current values for Block, Succ, and continue targets.
3797 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3798 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3800 // Generate increment code in its own basic block. This is the target of
3801 // continue statements.
3803 Succ = addStmt(S->getInc());
3806 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3808 // The starting block for the loop increment is the block that should
3809 // represent the 'loop target' for looping back to the start of the loop.
3810 ContinueJumpTarget.block->setLoopTarget(S);
3812 // Finish up the increment block and prepare to start the loop body.
3818 // Add implicit scope and dtors for loop variable.
3819 addLocalScopeAndDtors(S->getLoopVarStmt());
3821 // Populate a new block to contain the loop body and loop variable.
3822 addStmt(S->getBody());
3825 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
3829 // This new body block is a successor to our condition block.
3830 addSuccessor(ConditionBlock,
3831 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
3834 // Link up the condition block with the code that follows the loop (the
3836 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
3838 // Add the initialization statements.
3839 Block = createBlock();
3840 addStmt(S->getBeginStmt());
3841 addStmt(S->getEndStmt());
3842 return addStmt(S->getRangeStmt());
3845 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
3846 AddStmtChoice asc) {
3847 if (BuildOpts.AddTemporaryDtors) {
3848 // If adding implicit destructors visit the full expression for adding
3849 // destructors of temporaries.
3850 TempDtorContext Context;
3851 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
3853 // Full expression has to be added as CFGStmt so it will be sequenced
3854 // before destructors of it's temporaries.
3855 asc = asc.withAlwaysAdd(true);
3857 return Visit(E->getSubExpr(), asc);
3860 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3861 AddStmtChoice asc) {
3862 if (asc.alwaysAdd(*this, E)) {
3864 appendStmt(Block, E);
3866 // We do not want to propagate the AlwaysAdd property.
3867 asc = asc.withAlwaysAdd(false);
3869 return Visit(E->getSubExpr(), asc);
3872 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3873 AddStmtChoice asc) {
3875 appendStmt(Block, C);
3877 return VisitChildren(C);
3880 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3881 AddStmtChoice asc) {
3883 appendStmt(Block, NE);
3885 if (NE->getInitializer())
3886 Block = Visit(NE->getInitializer());
3887 if (BuildOpts.AddCXXNewAllocator)
3888 appendNewAllocator(Block, NE);
3890 Block = Visit(NE->getArraySize());
3891 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3892 E = NE->placement_arg_end(); I != E; ++I)
3897 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3898 AddStmtChoice asc) {
3900 appendStmt(Block, DE);
3901 QualType DTy = DE->getDestroyedType();
3902 if (!DTy.isNull()) {
3903 DTy = DTy.getNonReferenceType();
3904 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3906 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
3907 appendDeleteDtor(Block, RD, DE);
3911 return VisitChildren(DE);
3914 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3915 AddStmtChoice asc) {
3916 if (asc.alwaysAdd(*this, E)) {
3918 appendStmt(Block, E);
3919 // We do not want to propagate the AlwaysAdd property.
3920 asc = asc.withAlwaysAdd(false);
3922 return Visit(E->getSubExpr(), asc);
3925 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3926 AddStmtChoice asc) {
3928 appendStmt(Block, C);
3929 return VisitChildren(C);
3932 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3933 AddStmtChoice asc) {
3934 if (asc.alwaysAdd(*this, E)) {
3936 appendStmt(Block, E);
3938 return Visit(E->getSubExpr(), AddStmtChoice());
3941 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
3942 // Lazily create the indirect-goto dispatch block if there isn't one already.
3943 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
3946 IBlock = createBlock(false);
3947 cfg->setIndirectGotoBlock(IBlock);
3950 // IndirectGoto is a control-flow statement. Thus we stop processing the
3951 // current block and create a new one.
3955 Block = createBlock(false);
3956 Block->setTerminator(I);
3957 addSuccessor(Block, IBlock);
3958 return addStmt(I->getTarget());
3961 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
3962 TempDtorContext &Context) {
3963 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3970 switch (E->getStmtClass()) {
3972 return VisitChildrenForTemporaryDtors(E, Context);
3974 case Stmt::BinaryOperatorClass:
3975 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
3978 case Stmt::CXXBindTemporaryExprClass:
3979 return VisitCXXBindTemporaryExprForTemporaryDtors(
3980 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
3982 case Stmt::BinaryConditionalOperatorClass:
3983 case Stmt::ConditionalOperatorClass:
3984 return VisitConditionalOperatorForTemporaryDtors(
3985 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
3987 case Stmt::ImplicitCastExprClass:
3988 // For implicit cast we want BindToTemporary to be passed further.
3989 E = cast<CastExpr>(E)->getSubExpr();
3992 case Stmt::CXXFunctionalCastExprClass:
3993 // For functional cast we want BindToTemporary to be passed further.
3994 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
3997 case Stmt::ParenExprClass:
3998 E = cast<ParenExpr>(E)->getSubExpr();
4001 case Stmt::MaterializeTemporaryExprClass: {
4002 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4003 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
4004 SmallVector<const Expr *, 2> CommaLHSs;
4005 SmallVector<SubobjectAdjustment, 2> Adjustments;
4006 // Find the expression whose lifetime needs to be extended.
4007 E = const_cast<Expr *>(
4008 cast<MaterializeTemporaryExpr>(E)
4009 ->GetTemporaryExpr()
4010 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4011 // Visit the skipped comma operator left-hand sides for other temporaries.
4012 for (const Expr *CommaLHS : CommaLHSs) {
4013 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
4014 /*BindToTemporary=*/false, Context);
4019 case Stmt::BlockExprClass:
4020 // Don't recurse into blocks; their subexpressions don't get evaluated
4024 case Stmt::LambdaExprClass: {
4025 // For lambda expressions, only recurse into the capture initializers,
4026 // and not the body.
4027 auto *LE = cast<LambdaExpr>(E);
4028 CFGBlock *B = Block;
4029 for (Expr *Init : LE->capture_inits()) {
4030 if (CFGBlock *R = VisitForTemporaryDtors(
4031 Init, /*BindToTemporary=*/false, Context))
4037 case Stmt::CXXDefaultArgExprClass:
4038 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4041 case Stmt::CXXDefaultInitExprClass:
4042 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4047 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
4048 TempDtorContext &Context) {
4049 if (isa<LambdaExpr>(E)) {
4050 // Do not visit the children of lambdas; they have their own CFGs.
4054 // When visiting children for destructors we want to visit them in reverse
4055 // order that they will appear in the CFG. Because the CFG is built
4056 // bottom-up, this means we visit them in their natural order, which
4057 // reverses them in the CFG.
4058 CFGBlock *B = Block;
4059 for (Stmt *Child : E->children())
4061 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
4067 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
4068 BinaryOperator *E, TempDtorContext &Context) {
4069 if (E->isLogicalOp()) {
4070 VisitForTemporaryDtors(E->getLHS(), false, Context);
4071 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
4072 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
4073 RHSExecuted.negate();
4075 // We do not know at CFG-construction time whether the right-hand-side was
4076 // executed, thus we add a branch node that depends on the temporary
4077 // constructor call.
4078 TempDtorContext RHSContext(
4079 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
4080 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
4081 InsertTempDtorDecisionBlock(RHSContext);
4086 if (E->isAssignmentOp()) {
4087 // For assignment operator (=) LHS expression is visited
4088 // before RHS expression. For destructors visit them in reverse order.
4089 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4090 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4091 return LHSBlock ? LHSBlock : RHSBlock;
4094 // For any other binary operator RHS expression is visited before
4095 // LHS expression (order of children). For destructors visit them in reverse
4097 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4098 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4099 return RHSBlock ? RHSBlock : LHSBlock;
4102 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
4103 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
4104 // First add destructors for temporaries in subexpression.
4105 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
4106 if (!BindToTemporary) {
4107 // If lifetime of temporary is not prolonged (by assigning to constant
4108 // reference) add destructor for it.
4110 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
4112 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
4113 // If the destructor is marked as a no-return destructor, we need to
4114 // create a new block for the destructor which does not have as a
4115 // successor anything built thus far. Control won't flow out of this
4118 Block = createNoReturnBlock();
4119 } else if (Context.needsTempDtorBranch()) {
4120 // If we need to introduce a branch, we add a new block that we will hook
4121 // up to a decision block later.
4123 Block = createBlock();
4127 if (Context.needsTempDtorBranch()) {
4128 Context.setDecisionPoint(Succ, E);
4130 appendTemporaryDtor(Block, E);
4137 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
4138 CFGBlock *FalseSucc) {
4139 if (!Context.TerminatorExpr) {
4140 // If no temporary was found, we do not need to insert a decision point.
4143 assert(Context.TerminatorExpr);
4144 CFGBlock *Decision = createBlock(false);
4145 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
4146 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
4147 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
4148 !Context.KnownExecuted.isTrue());
4152 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
4153 AbstractConditionalOperator *E, bool BindToTemporary,
4154 TempDtorContext &Context) {
4155 VisitForTemporaryDtors(E->getCond(), false, Context);
4156 CFGBlock *ConditionBlock = Block;
4157 CFGBlock *ConditionSucc = Succ;
4158 TryResult ConditionVal = tryEvaluateBool(E->getCond());
4159 TryResult NegatedVal = ConditionVal;
4160 if (NegatedVal.isKnown()) NegatedVal.negate();
4162 TempDtorContext TrueContext(
4163 bothKnownTrue(Context.KnownExecuted, ConditionVal));
4164 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
4165 CFGBlock *TrueBlock = Block;
4167 Block = ConditionBlock;
4168 Succ = ConditionSucc;
4169 TempDtorContext FalseContext(
4170 bothKnownTrue(Context.KnownExecuted, NegatedVal));
4171 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
4173 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
4174 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
4175 } else if (TrueContext.TerminatorExpr) {
4177 InsertTempDtorDecisionBlock(TrueContext);
4179 InsertTempDtorDecisionBlock(FalseContext);
4184 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
4185 /// no successors or predecessors. If this is the first block created in the
4186 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
4187 CFGBlock *CFG::createBlock() {
4188 bool first_block = begin() == end();
4190 // Create the block.
4191 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
4192 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
4193 Blocks.push_back(Mem, BlkBVC);
4195 // If this is the first block, set it as the Entry and Exit.
4197 Entry = Exit = &back();
4199 // Return the block.
4203 /// buildCFG - Constructs a CFG from an AST.
4204 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4205 ASTContext *C, const BuildOptions &BO) {
4206 CFGBuilder Builder(C, BO);
4207 return Builder.buildCFG(D, Statement);
4210 const CXXDestructorDecl *
4211 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
4212 switch (getKind()) {
4213 case CFGElement::Statement:
4214 case CFGElement::Initializer:
4215 case CFGElement::NewAllocator:
4216 case CFGElement::LoopExit:
4217 case CFGElement::LifetimeEnds:
4218 llvm_unreachable("getDestructorDecl should only be used with "
4220 case CFGElement::AutomaticObjectDtor: {
4221 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
4222 QualType ty = var->getType();
4224 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4226 // Lifetime-extending constructs are handled here. This works for a single
4227 // temporary in an initializer expression.
4228 if (ty->isReferenceType()) {
4229 if (const Expr *Init = var->getInit()) {
4230 ty = getReferenceInitTemporaryType(astContext, Init);
4234 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
4235 ty = arrayType->getElementType();
4237 const RecordType *recordType = ty->getAs<RecordType>();
4238 const CXXRecordDecl *classDecl =
4239 cast<CXXRecordDecl>(recordType->getDecl());
4240 return classDecl->getDestructor();
4242 case CFGElement::DeleteDtor: {
4243 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
4244 QualType DTy = DE->getDestroyedType();
4245 DTy = DTy.getNonReferenceType();
4246 const CXXRecordDecl *classDecl =
4247 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
4248 return classDecl->getDestructor();
4250 case CFGElement::TemporaryDtor: {
4251 const CXXBindTemporaryExpr *bindExpr =
4252 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
4253 const CXXTemporary *temp = bindExpr->getTemporary();
4254 return temp->getDestructor();
4256 case CFGElement::BaseDtor:
4257 case CFGElement::MemberDtor:
4258 // Not yet supported.
4261 llvm_unreachable("getKind() returned bogus value");
4264 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
4265 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
4266 return DD->isNoReturn();
4270 //===----------------------------------------------------------------------===//
4271 // CFGBlock operations.
4272 //===----------------------------------------------------------------------===//
4274 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
4275 : ReachableBlock(IsReachable ? B : nullptr),
4276 UnreachableBlock(!IsReachable ? B : nullptr,
4277 B && IsReachable ? AB_Normal : AB_Unreachable) {}
4279 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
4280 : ReachableBlock(B),
4281 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
4282 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
4284 void CFGBlock::addSuccessor(AdjacentBlock Succ,
4285 BumpVectorContext &C) {
4286 if (CFGBlock *B = Succ.getReachableBlock())
4287 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
4289 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
4290 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
4292 Succs.push_back(Succ, C);
4295 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
4296 const CFGBlock *From, const CFGBlock *To) {
4297 if (F.IgnoreNullPredecessors && !From)
4300 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
4301 // If the 'To' has no label or is labeled but the label isn't a
4302 // CaseStmt then filter this edge.
4303 if (const SwitchStmt *S =
4304 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
4305 if (S->isAllEnumCasesCovered()) {
4306 const Stmt *L = To->getLabel();
4307 if (!L || !isa<CaseStmt>(L))
4316 //===----------------------------------------------------------------------===//
4317 // CFG pretty printing
4318 //===----------------------------------------------------------------------===//
4322 class StmtPrinterHelper : public PrinterHelper {
4323 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
4324 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
4328 signed currentBlock = 0;
4329 unsigned currStmt = 0;
4330 const LangOptions &LangOpts;
4333 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
4335 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4337 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
4338 BI != BEnd; ++BI, ++j ) {
4339 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4340 const Stmt *stmt= SE->getStmt();
4341 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
4344 switch (stmt->getStmtClass()) {
4345 case Stmt::DeclStmtClass:
4346 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4348 case Stmt::IfStmtClass: {
4349 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4354 case Stmt::ForStmtClass: {
4355 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4360 case Stmt::WhileStmtClass: {
4361 const VarDecl *var =
4362 cast<WhileStmt>(stmt)->getConditionVariable();
4367 case Stmt::SwitchStmtClass: {
4368 const VarDecl *var =
4369 cast<SwitchStmt>(stmt)->getConditionVariable();
4374 case Stmt::CXXCatchStmtClass: {
4375 const VarDecl *var =
4376 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4389 ~StmtPrinterHelper() override = default;
4391 const LangOptions &getLangOpts() const { return LangOpts; }
4392 void setBlockID(signed i) { currentBlock = i; }
4393 void setStmtID(unsigned i) { currStmt = i; }
4395 bool handledStmt(Stmt *S, raw_ostream &OS) override {
4396 StmtMapTy::iterator I = StmtMap.find(S);
4398 if (I == StmtMap.end())
4401 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
4402 && I->second.second == currStmt) {
4406 OS << "[B" << I->second.first << "." << I->second.second << "]";
4410 bool handleDecl(const Decl *D, raw_ostream &OS) {
4411 DeclMapTy::iterator I = DeclMap.find(D);
4413 if (I == DeclMap.end())
4416 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
4417 && I->second.second == currStmt) {
4421 OS << "[B" << I->second.first << "." << I->second.second << "]";
4426 class CFGBlockTerminatorPrint
4427 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
4429 StmtPrinterHelper* Helper;
4430 PrintingPolicy Policy;
4433 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
4434 const PrintingPolicy &Policy)
4435 : OS(os), Helper(helper), Policy(Policy) {
4436 this->Policy.IncludeNewlines = false;
4439 void VisitIfStmt(IfStmt *I) {
4441 if (Stmt *C = I->getCond())
4442 C->printPretty(OS, Helper, Policy);
4446 void VisitStmt(Stmt *Terminator) {
4447 Terminator->printPretty(OS, Helper, Policy);
4450 void VisitDeclStmt(DeclStmt *DS) {
4451 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4452 OS << "static init " << VD->getName();
4455 void VisitForStmt(ForStmt *F) {
4460 if (Stmt *C = F->getCond())
4461 C->printPretty(OS, Helper, Policy);
4468 void VisitWhileStmt(WhileStmt *W) {
4470 if (Stmt *C = W->getCond())
4471 C->printPretty(OS, Helper, Policy);
4474 void VisitDoStmt(DoStmt *D) {
4475 OS << "do ... while ";
4476 if (Stmt *C = D->getCond())
4477 C->printPretty(OS, Helper, Policy);
4480 void VisitSwitchStmt(SwitchStmt *Terminator) {
4482 Terminator->getCond()->printPretty(OS, Helper, Policy);
4485 void VisitCXXTryStmt(CXXTryStmt *CS) {
4489 void VisitSEHTryStmt(SEHTryStmt *CS) {
4493 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
4494 if (Stmt *Cond = C->getCond())
4495 Cond->printPretty(OS, Helper, Policy);
4496 OS << " ? ... : ...";
4499 void VisitChooseExpr(ChooseExpr *C) {
4500 OS << "__builtin_choose_expr( ";
4501 if (Stmt *Cond = C->getCond())
4502 Cond->printPretty(OS, Helper, Policy);
4506 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
4508 if (Stmt *T = I->getTarget())
4509 T->printPretty(OS, Helper, Policy);
4512 void VisitBinaryOperator(BinaryOperator* B) {
4513 if (!B->isLogicalOp()) {
4519 B->getLHS()->printPretty(OS, Helper, Policy);
4521 switch (B->getOpcode()) {
4529 llvm_unreachable("Invalid logical operator.");
4533 void VisitExpr(Expr *E) {
4534 E->printPretty(OS, Helper, Policy);
4538 void print(CFGTerminator T) {
4539 if (T.isTemporaryDtorsBranch())
4540 OS << "(Temp Dtor) ";
4547 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
4548 const CFGElement &E) {
4549 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4550 const Stmt *S = CS->getStmt();
4551 assert(S != nullptr && "Expecting non-null Stmt");
4553 // special printing for statement-expressions.
4554 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4555 const CompoundStmt *Sub = SE->getSubStmt();
4557 auto Children = Sub->children();
4558 if (Children.begin() != Children.end()) {
4560 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4565 // special printing for comma expressions.
4566 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4567 if (B->getOpcode() == BO_Comma) {
4569 Helper.handledStmt(B->getRHS(),OS);
4574 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4576 if (isa<CXXOperatorCallExpr>(S)) {
4577 OS << " (OperatorCall)";
4579 else if (isa<CXXBindTemporaryExpr>(S)) {
4580 OS << " (BindTemporary)";
4582 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4583 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
4585 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
4586 OS << " (" << CE->getStmtClassName() << ", "
4587 << CE->getCastKindName()
4588 << ", " << CE->getType().getAsString()
4592 // Expressions need a newline.
4595 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
4596 const CXXCtorInitializer *I = IE->getInitializer();
4597 if (I->isBaseInitializer())
4598 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
4599 else if (I->isDelegatingInitializer())
4600 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
4601 else OS << I->getAnyMember()->getName();
4604 if (Expr *IE = I->getInit())
4605 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4608 if (I->isBaseInitializer())
4609 OS << " (Base initializer)\n";
4610 else if (I->isDelegatingInitializer())
4611 OS << " (Delegating initializer)\n";
4612 else OS << " (Member initializer)\n";
4613 } else if (Optional<CFGAutomaticObjDtor> DE =
4614 E.getAs<CFGAutomaticObjDtor>()) {
4615 const VarDecl *VD = DE->getVarDecl();
4616 Helper.handleDecl(VD, OS);
4618 const Type* T = VD->getType().getTypePtr();
4619 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4620 T = RT->getPointeeType().getTypePtr();
4621 T = T->getBaseElementTypeUnsafe();
4623 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4624 OS << " (Implicit destructor)\n";
4625 } else if (Optional<CFGLifetimeEnds> DE = E.getAs<CFGLifetimeEnds>()) {
4626 const VarDecl *VD = DE->getVarDecl();
4627 Helper.handleDecl(VD, OS);
4629 OS << " (Lifetime ends)\n";
4630 } else if (Optional<CFGLoopExit> LE = E.getAs<CFGLoopExit>()) {
4631 const Stmt *LoopStmt = LE->getLoopStmt();
4632 OS << LoopStmt->getStmtClassName() << " (LoopExit)\n";
4633 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4634 OS << "CFGNewAllocator(";
4635 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4636 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4638 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4639 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4642 CXXDeleteExpr *DelExpr =
4643 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
4644 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
4645 OS << "->~" << RD->getName().str() << "()";
4646 OS << " (Implicit destructor)\n";
4647 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4648 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
4649 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
4650 OS << " (Base object destructor)\n";
4651 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4652 const FieldDecl *FD = ME->getFieldDecl();
4653 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
4654 OS << "this->" << FD->getName();
4655 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
4656 OS << " (Member object destructor)\n";
4657 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4658 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
4660 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4661 OS << "() (Temporary object destructor)\n";
4665 static void print_block(raw_ostream &OS, const CFG* cfg,
4667 StmtPrinterHelper &Helper, bool print_edges,
4669 Helper.setBlockID(B.getBlockID());
4671 // Print the header.
4673 OS.changeColor(raw_ostream::YELLOW, true);
4675 OS << "\n [B" << B.getBlockID();
4677 if (&B == &cfg->getEntry())
4678 OS << " (ENTRY)]\n";
4679 else if (&B == &cfg->getExit())
4681 else if (&B == cfg->getIndirectGotoBlock())
4682 OS << " (INDIRECT GOTO DISPATCH)]\n";
4683 else if (B.hasNoReturnElement())
4684 OS << " (NORETURN)]\n";
4691 // Print the label of this block.
4692 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
4696 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
4698 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
4701 C->getLHS()->printPretty(OS, &Helper,
4702 PrintingPolicy(Helper.getLangOpts()));
4705 C->getRHS()->printPretty(OS, &Helper,
4706 PrintingPolicy(Helper.getLangOpts()));
4708 } else if (isa<DefaultStmt>(Label))
4710 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
4712 if (CS->getExceptionDecl())
4713 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
4718 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
4720 ES->getFilterExpr()->printPretty(OS, &Helper,
4721 PrintingPolicy(Helper.getLangOpts()), 0);
4724 llvm_unreachable("Invalid label statement in CFGBlock.");
4729 // Iterate through the statements in the block and print them.
4732 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4733 I != E ; ++I, ++j ) {
4734 // Print the statement # in the basic block and the statement itself.
4738 OS << llvm::format("%3d", j) << ": ";
4740 Helper.setStmtID(j);
4742 print_elem(OS, Helper, *I);
4745 // Print the terminator of this block.
4746 if (B.getTerminator()) {
4748 OS.changeColor(raw_ostream::GREEN);
4752 Helper.setBlockID(-1);
4754 PrintingPolicy PP(Helper.getLangOpts());
4755 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
4756 TPrinter.print(B.getTerminator());
4764 // Print the predecessors of this block.
4765 if (!B.pred_empty()) {
4766 const raw_ostream::Colors Color = raw_ostream::BLUE;
4768 OS.changeColor(Color);
4772 OS << '(' << B.pred_size() << "):";
4776 OS.changeColor(Color);
4778 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4784 bool Reachable = true;
4787 B = I->getPossiblyUnreachableBlock();
4790 OS << " B" << B->getBlockID();
4792 OS << "(Unreachable)";
4801 // Print the successors of this block.
4802 if (!B.succ_empty()) {
4803 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4805 OS.changeColor(Color);
4809 OS << '(' << B.succ_size() << "):";
4813 OS.changeColor(Color);
4815 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4822 bool Reachable = true;
4825 B = I->getPossiblyUnreachableBlock();
4829 OS << " B" << B->getBlockID();
4831 OS << "(Unreachable)";
4845 /// dump - A simple pretty printer of a CFG that outputs to stderr.
4846 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4847 print(llvm::errs(), LO, ShowColors);
4850 /// print - A simple pretty printer of a CFG that outputs to an ostream.
4851 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
4852 StmtPrinterHelper Helper(this, LO);
4854 // Print the entry block.
4855 print_block(OS, this, getEntry(), Helper, true, ShowColors);
4857 // Iterate through the CFGBlocks and print them one by one.
4858 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4859 // Skip the entry block, because we already printed it.
4860 if (&(**I) == &getEntry() || &(**I) == &getExit())
4863 print_block(OS, this, **I, Helper, true, ShowColors);
4866 // Print the exit block.
4867 print_block(OS, this, getExit(), Helper, true, ShowColors);
4872 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
4873 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4874 bool ShowColors) const {
4875 print(llvm::errs(), cfg, LO, ShowColors);
4878 LLVM_DUMP_METHOD void CFGBlock::dump() const {
4879 dump(getParent(), LangOptions(), false);
4882 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4883 /// Generally this will only be called from CFG::print.
4884 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
4885 const LangOptions &LO, bool ShowColors) const {
4886 StmtPrinterHelper Helper(cfg, LO);
4887 print_block(OS, cfg, *this, Helper, true, ShowColors);
4891 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
4892 void CFGBlock::printTerminator(raw_ostream &OS,
4893 const LangOptions &LO) const {
4894 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
4895 TPrinter.print(getTerminator());
4898 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
4899 Stmt *Terminator = this->Terminator;
4905 switch (Terminator->getStmtClass()) {
4909 case Stmt::CXXForRangeStmtClass:
4910 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4913 case Stmt::ForStmtClass:
4914 E = cast<ForStmt>(Terminator)->getCond();
4917 case Stmt::WhileStmtClass:
4918 E = cast<WhileStmt>(Terminator)->getCond();
4921 case Stmt::DoStmtClass:
4922 E = cast<DoStmt>(Terminator)->getCond();
4925 case Stmt::IfStmtClass:
4926 E = cast<IfStmt>(Terminator)->getCond();
4929 case Stmt::ChooseExprClass:
4930 E = cast<ChooseExpr>(Terminator)->getCond();
4933 case Stmt::IndirectGotoStmtClass:
4934 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4937 case Stmt::SwitchStmtClass:
4938 E = cast<SwitchStmt>(Terminator)->getCond();
4941 case Stmt::BinaryConditionalOperatorClass:
4942 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4945 case Stmt::ConditionalOperatorClass:
4946 E = cast<ConditionalOperator>(Terminator)->getCond();
4949 case Stmt::BinaryOperatorClass: // '&&' and '||'
4950 E = cast<BinaryOperator>(Terminator)->getLHS();
4953 case Stmt::ObjCForCollectionStmtClass:
4960 return E ? E->IgnoreParens() : nullptr;
4963 //===----------------------------------------------------------------------===//
4964 // CFG Graphviz Visualization
4965 //===----------------------------------------------------------------------===//
4968 static StmtPrinterHelper* GraphHelper;
4971 void CFG::viewCFG(const LangOptions &LO) const {
4973 StmtPrinterHelper H(this, LO);
4975 llvm::ViewGraph(this,"CFG");
4976 GraphHelper = nullptr;
4983 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
4984 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
4986 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
4988 std::string OutSStr;
4989 llvm::raw_string_ostream Out(OutSStr);
4990 print_block(Out,Graph, *Node, *GraphHelper, false, false);
4991 std::string& OutStr = Out.str();
4993 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4995 // Process string output to make it nicer...
4996 for (unsigned i = 0; i != OutStr.length(); ++i)
4997 if (OutStr[i] == '\n') { // Left justify
4999 OutStr.insert(OutStr.begin()+i+1, 'l');