1 //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the CFG and CFGBuilder classes for representing and
11 // building Control-Flow Graphs (CFGs) from ASTs.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Analysis/CFG.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/PrettyPrinter.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/Builtins.h"
23 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/GraphWriter.h"
29 #include "llvm/Support/SaveAndRestore.h"
31 using namespace clang;
35 static SourceLocation GetEndLoc(Decl *D) {
36 if (VarDecl *VD = dyn_cast<VarDecl>(D))
37 if (Expr *Ex = VD->getInit())
38 return Ex->getSourceRange().getEnd();
39 return D->getLocation();
42 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
43 /// or EnumConstantDecl from the given Expr. If it fails, returns nullptr.
44 const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
45 E = E->IgnoreParens();
46 if (isa<IntegerLiteral>(E))
48 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
49 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
53 /// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is
54 /// an integer literal or an enum constant.
56 /// If this fails, at least one of the returned DeclRefExpr or Expr will be
58 static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *>
59 tryNormalizeBinaryOperator(const BinaryOperator *B) {
60 BinaryOperatorKind Op = B->getOpcode();
62 const Expr *MaybeDecl = B->getLHS();
63 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
64 // Expr looked like `0 == Foo` instead of `Foo == 0`
65 if (Constant == nullptr) {
76 MaybeDecl = B->getRHS();
77 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
80 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts());
81 return std::make_tuple(D, Op, Constant);
84 /// For an expression `x == Foo && x == Bar`, this determines whether the
85 /// `Foo` and `Bar` are either of the same enumeration type, or both integer
88 /// It's an error to pass this arguments that are not either IntegerLiterals
89 /// or DeclRefExprs (that have decls of type EnumConstantDecl)
90 static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
91 // User intent isn't clear if they're mixing int literals with enum
93 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2))
96 // Integer literal comparisons, regardless of literal type, are acceptable.
97 if (isa<IntegerLiteral>(E1))
100 // IntegerLiterals are handled above and only EnumConstantDecls are expected
102 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
103 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
104 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
106 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
107 const DeclContext *DC1 = Decl1->getDeclContext();
108 const DeclContext *DC2 = Decl2->getDeclContext();
110 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
116 /// The CFG builder uses a recursive algorithm to build the CFG. When
117 /// we process an expression, sometimes we know that we must add the
118 /// subexpressions as block-level expressions. For example:
122 /// When processing the '||' expression, we know that exp1 and exp2
123 /// need to be added as block-level expressions, even though they
124 /// might not normally need to be. AddStmtChoice records this
125 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
126 /// the builder has an option not to add a subexpression as a
127 /// block-level expression.
129 class AddStmtChoice {
131 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
133 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
135 bool alwaysAdd(CFGBuilder &builder,
136 const Stmt *stmt) const;
138 /// Return a copy of this object, except with the 'always-add' bit
139 /// set as specified.
140 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
141 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
148 /// LocalScope - Node in tree of local scopes created for C++ implicit
149 /// destructor calls generation. It contains list of automatic variables
150 /// declared in the scope and link to position in previous scope this scope
153 /// The process of creating local scopes is as follows:
154 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
155 /// - Before processing statements in scope (e.g. CompoundStmt) create
156 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
157 /// and set CFGBuilder::ScopePos to the end of new scope,
158 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
160 /// - For every normal (without jump) end of scope add to CFGBlock destructors
161 /// for objects in the current scope,
162 /// - For every jump add to CFGBlock destructors for objects
163 /// between CFGBuilder::ScopePos and local scope position saved for jump
164 /// target. Thanks to C++ restrictions on goto jumps we can be sure that
165 /// jump target position will be on the path to root from CFGBuilder::ScopePos
166 /// (adding any variable that doesn't need constructor to be called to
167 /// LocalScope can break this assumption),
171 typedef BumpVector<VarDecl*> AutomaticVarsTy;
173 /// const_iterator - Iterates local scope backwards and jumps to previous
174 /// scope on reaching the beginning of currently iterated scope.
175 class const_iterator {
176 const LocalScope* Scope;
178 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
179 /// Invalid iterator (with null Scope) has VarIter equal to 0.
183 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
184 /// Incrementing invalid iterator is allowed and will result in invalid
187 : Scope(nullptr), VarIter(0) {}
189 /// Create valid iterator. In case when S.Prev is an invalid iterator and
190 /// I is equal to 0, this will create invalid iterator.
191 const_iterator(const LocalScope& S, unsigned I)
192 : Scope(&S), VarIter(I) {
193 // Iterator to "end" of scope is not allowed. Handle it by going up
194 // in scopes tree possibly up to invalid iterator in the root.
195 if (VarIter == 0 && Scope)
199 VarDecl *const* operator->() const {
200 assert (Scope && "Dereferencing invalid iterator is not allowed");
201 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
202 return &Scope->Vars[VarIter - 1];
204 VarDecl *operator*() const {
205 return *this->operator->();
208 const_iterator &operator++() {
212 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
218 const_iterator operator++(int) {
219 const_iterator P = *this;
224 bool operator==(const const_iterator &rhs) const {
225 return Scope == rhs.Scope && VarIter == rhs.VarIter;
227 bool operator!=(const const_iterator &rhs) const {
228 return !(*this == rhs);
231 explicit operator bool() const {
232 return *this != const_iterator();
235 int distance(const_iterator L);
236 const_iterator shared_parent(const_iterator L);
239 friend class const_iterator;
242 BumpVectorContext ctx;
244 /// Automatic variables in order of declaration.
245 AutomaticVarsTy Vars;
246 /// Iterator to variable in previous scope that was declared just before
247 /// begin of this scope.
251 /// Constructs empty scope linked to previous scope in specified place.
252 LocalScope(BumpVectorContext ctx, const_iterator P)
253 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
255 /// Begin of scope in direction of CFG building (backwards).
256 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
258 void addVar(VarDecl *VD) {
259 Vars.push_back(VD, ctx);
263 /// distance - Calculates distance from this to L. L must be reachable from this
264 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
265 /// number of scopes between this and L.
266 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
268 const_iterator F = *this;
269 while (F.Scope != L.Scope) {
270 assert (F != const_iterator()
271 && "L iterator is not reachable from F iterator.");
275 D += F.VarIter - L.VarIter;
279 /// Calculates the closest parent of this iterator
280 /// that is in a scope reachable through the parents of L.
281 /// I.e. when using 'goto' from this to L, the lifetime of all variables
282 /// between this and shared_parent(L) end.
283 LocalScope::const_iterator
284 LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
285 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
287 ScopesOfL.insert(L.Scope);
288 if (L == const_iterator())
293 const_iterator F = *this;
295 if (ScopesOfL.count(F.Scope))
297 assert(F != const_iterator() &&
298 "L iterator is not reachable from F iterator.");
303 /// Structure for specifying position in CFG during its build process. It
304 /// consists of CFGBlock that specifies position in CFG and
305 /// LocalScope::const_iterator that specifies position in LocalScope graph.
306 struct BlockScopePosPair {
307 BlockScopePosPair() : block(nullptr) {}
308 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
309 : block(b), scopePosition(scopePos) {}
312 LocalScope::const_iterator scopePosition;
315 /// TryResult - a class representing a variant over the values
316 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
317 /// and is used by the CFGBuilder to decide if a branch condition
318 /// can be decided up front during CFG construction.
322 TryResult(bool b) : X(b ? 1 : 0) {}
323 TryResult() : X(-1) {}
325 bool isTrue() const { return X == 1; }
326 bool isFalse() const { return X == 0; }
327 bool isKnown() const { return X >= 0; }
334 TryResult bothKnownTrue(TryResult R1, TryResult R2) {
335 if (!R1.isKnown() || !R2.isKnown())
337 return TryResult(R1.isTrue() && R2.isTrue());
340 class reverse_children {
341 llvm::SmallVector<Stmt *, 12> childrenBuf;
342 ArrayRef<Stmt*> children;
344 reverse_children(Stmt *S);
346 typedef ArrayRef<Stmt*>::reverse_iterator iterator;
347 iterator begin() const { return children.rbegin(); }
348 iterator end() const { return children.rend(); }
352 reverse_children::reverse_children(Stmt *S) {
353 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
354 children = CE->getRawSubExprs();
357 switch (S->getStmtClass()) {
358 // Note: Fill in this switch with more cases we want to optimize.
359 case Stmt::InitListExprClass: {
360 InitListExpr *IE = cast<InitListExpr>(S);
361 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
369 // Default case for all other statements.
370 for (Stmt *SubStmt : S->children())
371 childrenBuf.push_back(SubStmt);
373 // This needs to be done *after* childrenBuf has been populated.
374 children = childrenBuf;
377 /// CFGBuilder - This class implements CFG construction from an AST.
378 /// The builder is stateful: an instance of the builder should be used to only
379 /// construct a single CFG.
383 /// CFGBuilder builder;
384 /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
386 /// CFG construction is done via a recursive walk of an AST. We actually parse
387 /// the AST in reverse order so that the successor of a basic block is
388 /// constructed prior to its predecessor. This allows us to nicely capture
389 /// implicit fall-throughs without extra basic blocks.
392 typedef BlockScopePosPair JumpTarget;
393 typedef BlockScopePosPair JumpSource;
396 std::unique_ptr<CFG> cfg;
400 JumpTarget ContinueJumpTarget;
401 JumpTarget BreakJumpTarget;
402 CFGBlock *SwitchTerminatedBlock;
403 CFGBlock *DefaultCaseBlock;
404 CFGBlock *TryTerminatedBlock;
406 // Current position in local scope.
407 LocalScope::const_iterator ScopePos;
409 // LabelMap records the mapping from Label expressions to their jump targets.
410 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
413 // A list of blocks that end with a "goto" that must be backpatched to their
414 // resolved targets upon completion of CFG construction.
415 typedef std::vector<JumpSource> BackpatchBlocksTy;
416 BackpatchBlocksTy BackpatchBlocks;
418 // A list of labels whose address has been taken (for indirect gotos).
419 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
420 LabelSetTy AddressTakenLabels;
423 const CFG::BuildOptions &BuildOpts;
425 // State to track for building switch statements.
426 bool switchExclusivelyCovered;
427 Expr::EvalResult *switchCond;
429 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
430 const Stmt *lastLookup;
432 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
433 // during construction of branches for chained logical operators.
434 typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
435 CachedBoolEvalsTy CachedBoolEvals;
438 explicit CFGBuilder(ASTContext *astContext,
439 const CFG::BuildOptions &buildOpts)
440 : Context(astContext), cfg(new CFG()), // crew a new CFG
441 Block(nullptr), Succ(nullptr),
442 SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr),
443 TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts),
444 switchExclusivelyCovered(false), switchCond(nullptr),
445 cachedEntry(nullptr), lastLookup(nullptr) {}
447 // buildCFG - Used by external clients to construct the CFG.
448 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
450 bool alwaysAdd(const Stmt *stmt);
453 // Visitors to walk an AST and construct the CFG.
454 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
455 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
456 CFGBlock *VisitBreakStmt(BreakStmt *B);
457 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
458 CFGBlock *VisitCaseStmt(CaseStmt *C);
459 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
460 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
461 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
463 CFGBlock *VisitContinueStmt(ContinueStmt *C);
464 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
466 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
467 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
468 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
469 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
470 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
471 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
473 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
475 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
476 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
477 CFGBlock *VisitDeclStmt(DeclStmt *DS);
478 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
479 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
480 CFGBlock *VisitDoStmt(DoStmt *D);
481 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
482 CFGBlock *VisitForStmt(ForStmt *F);
483 CFGBlock *VisitGotoStmt(GotoStmt *G);
484 CFGBlock *VisitIfStmt(IfStmt *I);
485 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
486 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
487 CFGBlock *VisitLabelStmt(LabelStmt *L);
488 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
489 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
490 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
491 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
494 CFGBlock *FalseBlock);
495 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
496 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
497 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
498 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
499 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
500 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
501 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
502 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
503 CFGBlock *VisitReturnStmt(ReturnStmt *R);
504 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
505 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
506 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
508 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
509 CFGBlock *VisitWhileStmt(WhileStmt *W);
511 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
512 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
513 CFGBlock *VisitChildren(Stmt *S);
514 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
516 /// When creating the CFG for temporary destructors, we want to mirror the
517 /// branch structure of the corresponding constructor calls.
518 /// Thus, while visiting a statement for temporary destructors, we keep a
519 /// context to keep track of the following information:
520 /// - whether a subexpression is executed unconditionally
521 /// - if a subexpression is executed conditionally, the first
522 /// CXXBindTemporaryExpr we encounter in that subexpression (which
523 /// corresponds to the last temporary destructor we have to call for this
524 /// subexpression) and the CFG block at that point (which will become the
525 /// successor block when inserting the decision point).
527 /// That way, we can build the branch structure for temporary destructors as
529 /// 1. If a subexpression is executed unconditionally, we add the temporary
530 /// destructor calls to the current block.
531 /// 2. If a subexpression is executed conditionally, when we encounter a
532 /// CXXBindTemporaryExpr:
533 /// a) If it is the first temporary destructor call in the subexpression,
534 /// we remember the CXXBindTemporaryExpr and the current block in the
535 /// TempDtorContext; we start a new block, and insert the temporary
537 /// b) Otherwise, add the temporary destructor call to the current block.
538 /// 3. When we finished visiting a conditionally executed subexpression,
539 /// and we found at least one temporary constructor during the visitation
540 /// (2.a has executed), we insert a decision block that uses the
541 /// CXXBindTemporaryExpr as terminator, and branches to the current block
542 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
543 /// branches to the stored successor.
544 struct TempDtorContext {
546 : IsConditional(false), KnownExecuted(true), Succ(nullptr),
547 TerminatorExpr(nullptr) {}
549 TempDtorContext(TryResult KnownExecuted)
550 : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr),
551 TerminatorExpr(nullptr) {}
553 /// Returns whether we need to start a new branch for a temporary destructor
554 /// call. This is the case when the temporary destructor is
555 /// conditionally executed, and it is the first one we encounter while
556 /// visiting a subexpression - other temporary destructors at the same level
557 /// will be added to the same block and are executed under the same
559 bool needsTempDtorBranch() const {
560 return IsConditional && !TerminatorExpr;
563 /// Remember the successor S of a temporary destructor decision branch for
564 /// the corresponding CXXBindTemporaryExpr E.
565 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
570 const bool IsConditional;
571 const TryResult KnownExecuted;
573 CXXBindTemporaryExpr *TerminatorExpr;
576 // Visitors to walk an AST and generate destructors of temporaries in
578 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
579 TempDtorContext &Context);
580 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
581 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
582 TempDtorContext &Context);
583 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
584 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
585 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
586 AbstractConditionalOperator *E, bool BindToTemporary,
587 TempDtorContext &Context);
588 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
589 CFGBlock *FalseSucc = nullptr);
591 // NYS == Not Yet Supported
597 void autoCreateBlock() { if (!Block) Block = createBlock(); }
598 CFGBlock *createBlock(bool add_successor = true);
599 CFGBlock *createNoReturnBlock();
601 CFGBlock *addStmt(Stmt *S) {
602 return Visit(S, AddStmtChoice::AlwaysAdd);
604 CFGBlock *addInitializer(CXXCtorInitializer *I);
605 void addAutomaticObjDtors(LocalScope::const_iterator B,
606 LocalScope::const_iterator E, Stmt *S);
607 void addLifetimeEnds(LocalScope::const_iterator B,
608 LocalScope::const_iterator E, Stmt *S);
609 void addAutomaticObjHandling(LocalScope::const_iterator B,
610 LocalScope::const_iterator E, Stmt *S);
611 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
613 // Local scopes creation.
614 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
616 void addLocalScopeForStmt(Stmt *S);
617 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
618 LocalScope* Scope = nullptr);
619 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
621 void addLocalScopeAndDtors(Stmt *S);
623 // Interface to CFGBlock - adding CFGElements.
624 void appendStmt(CFGBlock *B, const Stmt *S) {
625 if (alwaysAdd(S) && cachedEntry)
626 cachedEntry->second = B;
628 // All block-level expressions should have already been IgnoreParens()ed.
629 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
630 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
632 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
633 B->appendInitializer(I, cfg->getBumpVectorContext());
635 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
636 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
638 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
639 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
641 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
642 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
644 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
645 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
647 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
648 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
651 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
652 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
655 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
656 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
659 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
660 LocalScope::const_iterator B, LocalScope::const_iterator E);
662 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
663 LocalScope::const_iterator B,
664 LocalScope::const_iterator E);
666 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
667 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
668 cfg->getBumpVectorContext());
671 /// Add a reachable successor to a block, with the alternate variant that is
673 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
674 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
675 cfg->getBumpVectorContext());
678 /// \brief Find a relational comparison with an expression evaluating to a
679 /// boolean and a constant other than 0 and 1.
680 /// e.g. if ((x < y) == 10)
681 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
682 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
683 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
685 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
686 const Expr *BoolExpr = RHSExpr;
687 bool IntFirst = true;
689 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
694 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
697 llvm::APInt IntValue = IntLiteral->getValue();
698 if ((IntValue == 1) || (IntValue == 0))
701 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
702 !IntValue.isNegative();
704 BinaryOperatorKind Bok = B->getOpcode();
705 if (Bok == BO_GT || Bok == BO_GE) {
706 // Always true for 10 > bool and bool > -1
707 // Always false for -1 > bool and bool > 10
708 return TryResult(IntFirst == IntLarger);
710 // Always true for -1 < bool and bool < 10
711 // Always false for 10 < bool and bool < -1
712 return TryResult(IntFirst != IntLarger);
716 /// Find an incorrect equality comparison. Either with an expression
717 /// evaluating to a boolean and a constant other than 0 and 1.
718 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
719 /// true/false e.q. (x & 8) == 4.
720 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
721 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
722 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
724 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
725 const Expr *BoolExpr = RHSExpr;
728 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
735 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
736 if (BitOp && (BitOp->getOpcode() == BO_And ||
737 BitOp->getOpcode() == BO_Or)) {
738 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
739 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
741 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
744 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
749 llvm::APInt L1 = IntLiteral->getValue();
750 llvm::APInt L2 = IntLiteral2->getValue();
751 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
752 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
753 if (BuildOpts.Observer)
754 BuildOpts.Observer->compareBitwiseEquality(B,
755 B->getOpcode() != BO_EQ);
756 TryResult(B->getOpcode() != BO_EQ);
758 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
759 llvm::APInt IntValue = IntLiteral->getValue();
760 if ((IntValue == 1) || (IntValue == 0)) {
763 return TryResult(B->getOpcode() != BO_EQ);
769 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
770 const llvm::APSInt &Value1,
771 const llvm::APSInt &Value2) {
772 assert(Value1.isSigned() == Value2.isSigned());
777 return TryResult(Value1 == Value2);
779 return TryResult(Value1 != Value2);
781 return TryResult(Value1 < Value2);
783 return TryResult(Value1 <= Value2);
785 return TryResult(Value1 > Value2);
787 return TryResult(Value1 >= Value2);
791 /// \brief Find a pair of comparison expressions with or without parentheses
792 /// with a shared variable and constants and a logical operator between them
793 /// that always evaluates to either true or false.
794 /// e.g. if (x != 3 || x != 4)
795 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
796 assert(B->isLogicalOp());
797 const BinaryOperator *LHS =
798 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
799 const BinaryOperator *RHS =
800 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
804 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
807 const DeclRefExpr *Decl1;
809 BinaryOperatorKind BO1;
810 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
812 if (!Decl1 || !Expr1)
815 const DeclRefExpr *Decl2;
817 BinaryOperatorKind BO2;
818 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
820 if (!Decl2 || !Expr2)
823 // Check that it is the same variable on both sides.
824 if (Decl1->getDecl() != Decl2->getDecl())
827 // Make sure the user's intent is clear (e.g. they're comparing against two
828 // int literals, or two things from the same enum)
829 if (!areExprTypesCompatible(Expr1, Expr2))
834 if (!Expr1->EvaluateAsInt(L1, *Context) ||
835 !Expr2->EvaluateAsInt(L2, *Context))
838 // Can't compare signed with unsigned or with different bit width.
839 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
842 // Values that will be used to determine if result of logical
843 // operator is always true/false
844 const llvm::APSInt Values[] = {
845 // Value less than both Value1 and Value2
846 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
849 // Value between Value1 and Value2
850 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
854 // Value greater than both Value1 and Value2
855 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
858 // Check whether expression is always true/false by evaluating the following
859 // * variable x is less than the smallest literal.
860 // * variable x is equal to the smallest literal.
861 // * Variable x is between smallest and largest literal.
862 // * Variable x is equal to the largest literal.
863 // * Variable x is greater than largest literal.
864 bool AlwaysTrue = true, AlwaysFalse = true;
865 for (const llvm::APSInt &Value : Values) {
866 TryResult Res1, Res2;
867 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
868 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
870 if (!Res1.isKnown() || !Res2.isKnown())
873 if (B->getOpcode() == BO_LAnd) {
874 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
875 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
877 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
878 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
882 if (AlwaysTrue || AlwaysFalse) {
883 if (BuildOpts.Observer)
884 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
885 return TryResult(AlwaysTrue);
890 /// Try and evaluate an expression to an integer constant.
891 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
892 if (!BuildOpts.PruneTriviallyFalseEdges)
894 return !S->isTypeDependent() &&
895 !S->isValueDependent() &&
896 S->EvaluateAsRValue(outResult, *Context);
899 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
900 /// if we can evaluate to a known value, otherwise return -1.
901 TryResult tryEvaluateBool(Expr *S) {
902 if (!BuildOpts.PruneTriviallyFalseEdges ||
903 S->isTypeDependent() || S->isValueDependent())
906 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
907 if (Bop->isLogicalOp()) {
908 // Check the cache first.
909 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
910 if (I != CachedBoolEvals.end())
911 return I->second; // already in map;
913 // Retrieve result at first, or the map might be updated.
914 TryResult Result = evaluateAsBooleanConditionNoCache(S);
915 CachedBoolEvals[S] = Result; // update or insert
919 switch (Bop->getOpcode()) {
921 // For 'x & 0' and 'x * 0', we can determine that
922 // the value is always false.
925 // If either operand is zero, we know the value
928 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
929 if (!IntVal.getBoolValue()) {
930 return TryResult(false);
933 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
934 if (!IntVal.getBoolValue()) {
935 return TryResult(false);
944 return evaluateAsBooleanConditionNoCache(S);
947 /// \brief Evaluate as boolean \param E without using the cache.
948 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
949 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
950 if (Bop->isLogicalOp()) {
951 TryResult LHS = tryEvaluateBool(Bop->getLHS());
953 // We were able to evaluate the LHS, see if we can get away with not
954 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
955 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
958 TryResult RHS = tryEvaluateBool(Bop->getRHS());
960 if (Bop->getOpcode() == BO_LOr)
961 return LHS.isTrue() || RHS.isTrue();
963 return LHS.isTrue() && RHS.isTrue();
966 TryResult RHS = tryEvaluateBool(Bop->getRHS());
968 // We can't evaluate the LHS; however, sometimes the result
969 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
970 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
973 TryResult BopRes = checkIncorrectLogicOperator(Bop);
974 if (BopRes.isKnown())
975 return BopRes.isTrue();
980 } else if (Bop->isEqualityOp()) {
981 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
982 if (BopRes.isKnown())
983 return BopRes.isTrue();
984 } else if (Bop->isRelationalOp()) {
985 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
986 if (BopRes.isKnown())
987 return BopRes.isTrue();
992 if (E->EvaluateAsBooleanCondition(Result, *Context))
998 bool hasTrivialDestructor(VarDecl *VD);
1001 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1002 const Stmt *stmt) const {
1003 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1006 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
1007 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1009 if (!BuildOpts.forcedBlkExprs)
1012 if (lastLookup == stmt) {
1014 assert(cachedEntry->first == stmt);
1022 // Perform the lookup!
1023 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1026 // No need to update 'cachedEntry', since it will always be null.
1027 assert(!cachedEntry);
1031 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
1032 if (itr == fb->end()) {
1033 cachedEntry = nullptr;
1037 cachedEntry = &*itr;
1041 // FIXME: Add support for dependent-sized array types in C++?
1042 // Does it even make sense to build a CFG for an uninstantiated template?
1043 static const VariableArrayType *FindVA(const Type *t) {
1044 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1045 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
1046 if (vat->getSizeExpr())
1049 t = vt->getElementType().getTypePtr();
1055 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1056 /// arbitrary statement. Examples include a single expression or a function
1057 /// body (compound statement). The ownership of the returned CFG is
1058 /// transferred to the caller. If CFG construction fails, this method returns
1060 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
1065 // Create an empty block that will serve as the exit block for the CFG. Since
1066 // this is the first block added to the CFG, it will be implicitly registered
1067 // as the exit block.
1068 Succ = createBlock();
1069 assert(Succ == &cfg->getExit());
1070 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
1072 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1073 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1075 if (BuildOpts.AddImplicitDtors)
1076 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1077 addImplicitDtorsForDestructor(DD);
1079 // Visit the statements and create the CFG.
1080 CFGBlock *B = addStmt(Statement);
1085 // For C++ constructor add initializers to CFG.
1086 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
1087 for (auto *I : llvm::reverse(CD->inits())) {
1088 B = addInitializer(I);
1097 // Backpatch the gotos whose label -> block mappings we didn't know when we
1098 // encountered them.
1099 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1100 E = BackpatchBlocks.end(); I != E; ++I ) {
1102 CFGBlock *B = I->block;
1103 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
1104 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
1106 // If there is no target for the goto, then we are looking at an
1107 // incomplete AST. Handle this by not registering a successor.
1108 if (LI == LabelMap.end()) continue;
1110 JumpTarget JT = LI->second;
1111 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1113 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1115 addSuccessor(B, JT.block);
1118 // Add successors to the Indirect Goto Dispatch block (if we have one).
1119 if (CFGBlock *B = cfg->getIndirectGotoBlock())
1120 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1121 E = AddressTakenLabels.end(); I != E; ++I ) {
1123 // Lookup the target block.
1124 LabelMapTy::iterator LI = LabelMap.find(*I);
1126 // If there is no target block that contains label, then we are looking
1127 // at an incomplete AST. Handle this by not registering a successor.
1128 if (LI == LabelMap.end()) continue;
1130 addSuccessor(B, LI->second.block);
1133 // Create an empty entry block that has no predecessors.
1134 cfg->setEntry(createBlock());
1136 return std::move(cfg);
1139 /// createBlock - Used to lazily create blocks that are connected
1140 /// to the current (global) succcessor.
1141 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1142 CFGBlock *B = cfg->createBlock();
1143 if (add_successor && Succ)
1144 addSuccessor(B, Succ);
1148 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1149 /// CFG. It is *not* connected to the current (global) successor, and instead
1150 /// directly tied to the exit block in order to be reachable.
1151 CFGBlock *CFGBuilder::createNoReturnBlock() {
1152 CFGBlock *B = createBlock(false);
1153 B->setHasNoReturnElement();
1154 addSuccessor(B, &cfg->getExit(), Succ);
1158 /// addInitializer - Add C++ base or member initializer element to CFG.
1159 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
1160 if (!BuildOpts.AddInitializers)
1163 bool HasTemporaries = false;
1165 // Destructors of temporaries in initialization expression should be called
1166 // after initialization finishes.
1167 Expr *Init = I->getInit();
1169 HasTemporaries = isa<ExprWithCleanups>(Init);
1171 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1172 // Generate destructors for temporaries in initialization expression.
1173 TempDtorContext Context;
1174 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1175 /*BindToTemporary=*/false, Context);
1180 appendInitializer(Block, I);
1183 if (HasTemporaries) {
1184 // For expression with temporaries go directly to subexpression to omit
1185 // generating destructors for the second time.
1186 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1188 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1189 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1190 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1191 // may cause the same Expr to appear more than once in the CFG. Doing it
1192 // here is safe because there's only one initializer per field.
1194 appendStmt(Block, Default);
1195 if (Stmt *Child = Default->getExpr())
1196 if (CFGBlock *R = Visit(Child))
1207 /// \brief Retrieve the type of the temporary object whose lifetime was
1208 /// extended by a local reference with the given initializer.
1209 static QualType getReferenceInitTemporaryType(ASTContext &Context,
1211 bool *FoundMTE = nullptr) {
1213 // Skip parentheses.
1214 Init = Init->IgnoreParens();
1216 // Skip through cleanups.
1217 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1218 Init = EWC->getSubExpr();
1222 // Skip through the temporary-materialization expression.
1223 if (const MaterializeTemporaryExpr *MTE
1224 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1225 Init = MTE->GetTemporaryExpr();
1231 // Skip derived-to-base and no-op casts.
1232 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1233 if ((CE->getCastKind() == CK_DerivedToBase ||
1234 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1235 CE->getCastKind() == CK_NoOp) &&
1236 Init->getType()->isRecordType()) {
1237 Init = CE->getSubExpr();
1242 // Skip member accesses into rvalues.
1243 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1244 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1245 Init = ME->getBase();
1253 return Init->getType();
1256 void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1257 LocalScope::const_iterator E,
1259 if (BuildOpts.AddImplicitDtors)
1260 addAutomaticObjDtors(B, E, S);
1261 if (BuildOpts.AddLifetime)
1262 addLifetimeEnds(B, E, S);
1265 /// Add to current block automatic objects that leave the scope.
1266 void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1267 LocalScope::const_iterator E, Stmt *S) {
1268 if (!BuildOpts.AddLifetime)
1274 // To go from B to E, one first goes up the scopes from B to P
1275 // then sideways in one scope from P to P' and then down
1276 // the scopes from P' to E.
1277 // The lifetime of all objects between B and P end.
1278 LocalScope::const_iterator P = B.shared_parent(E);
1279 int dist = B.distance(P);
1283 // We need to perform the scope leaving in reverse order
1284 SmallVector<VarDecl *, 10> DeclsTrivial;
1285 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1286 DeclsTrivial.reserve(dist);
1287 DeclsNonTrivial.reserve(dist);
1289 for (LocalScope::const_iterator I = B; I != P; ++I)
1290 if (hasTrivialDestructor(*I))
1291 DeclsTrivial.push_back(*I);
1293 DeclsNonTrivial.push_back(*I);
1296 // object with trivial destructor end their lifetime last (when storage
1298 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1299 E = DeclsTrivial.rend();
1301 appendLifetimeEnds(Block, *I, S);
1303 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1304 I = DeclsNonTrivial.rbegin(),
1305 E = DeclsNonTrivial.rend();
1307 appendLifetimeEnds(Block, *I, S);
1310 /// addAutomaticObjDtors - Add to current block automatic objects destructors
1311 /// for objects in range of local scope positions. Use S as trigger statement
1312 /// for destructors.
1313 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
1314 LocalScope::const_iterator E, Stmt *S) {
1315 if (!BuildOpts.AddImplicitDtors)
1321 // We need to append the destructors in reverse order, but any one of them
1322 // may be a no-return destructor which changes the CFG. As a result, buffer
1323 // this sequence up and replay them in reverse order when appending onto the
1325 SmallVector<VarDecl*, 10> Decls;
1326 Decls.reserve(B.distance(E));
1327 for (LocalScope::const_iterator I = B; I != E; ++I)
1328 Decls.push_back(*I);
1330 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1333 // If this destructor is marked as a no-return destructor, we need to
1334 // create a new block for the destructor which does not have as a successor
1335 // anything built thus far: control won't flow out of this block.
1336 QualType Ty = (*I)->getType();
1337 if (Ty->isReferenceType()) {
1338 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
1340 Ty = Context->getBaseElementType(Ty);
1342 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
1343 Block = createNoReturnBlock();
1347 appendAutomaticObjDtor(Block, *I, S);
1351 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
1352 /// base and member objects in destructor.
1353 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1354 assert (BuildOpts.AddImplicitDtors
1355 && "Can be called only when dtors should be added");
1356 const CXXRecordDecl *RD = DD->getParent();
1358 // At the end destroy virtual base objects.
1359 for (const auto &VI : RD->vbases()) {
1360 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
1361 if (!CD->hasTrivialDestructor()) {
1363 appendBaseDtor(Block, &VI);
1367 // Before virtual bases destroy direct base objects.
1368 for (const auto &BI : RD->bases()) {
1369 if (!BI.isVirtual()) {
1370 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
1371 if (!CD->hasTrivialDestructor()) {
1373 appendBaseDtor(Block, &BI);
1378 // First destroy member objects.
1379 for (auto *FI : RD->fields()) {
1380 // Check for constant size array. Set type to array element type.
1381 QualType QT = FI->getType();
1382 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1383 if (AT->getSize() == 0)
1385 QT = AT->getElementType();
1388 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1389 if (!CD->hasTrivialDestructor()) {
1391 appendMemberDtor(Block, FI);
1396 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1397 /// way return valid LocalScope object.
1398 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
1401 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1402 return new (alloc.Allocate<LocalScope>())
1403 LocalScope(BumpVectorContext(alloc), ScopePos);
1406 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
1407 /// that should create implicit scope (e.g. if/else substatements).
1408 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
1409 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
1412 LocalScope *Scope = nullptr;
1414 // For compound statement we will be creating explicit scope.
1415 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1416 for (auto *BI : CS->body()) {
1417 Stmt *SI = BI->stripLabelLikeStatements();
1418 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
1419 Scope = addLocalScopeForDeclStmt(DS, Scope);
1424 // For any other statement scope will be implicit and as such will be
1425 // interesting only for DeclStmt.
1426 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
1427 addLocalScopeForDeclStmt(DS);
1430 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1431 /// reuse Scope if not NULL.
1432 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
1433 LocalScope* Scope) {
1434 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
1437 for (auto *DI : DS->decls())
1438 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
1439 Scope = addLocalScopeForVarDecl(VD, Scope);
1443 bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1444 // Check for const references bound to temporary. Set type to pointee.
1445 QualType QT = VD->getType();
1446 if (QT.getTypePtr()->isReferenceType()) {
1447 // Attempt to determine whether this declaration lifetime-extends a
1450 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1451 // temporaries, and a single declaration can extend multiple temporaries.
1452 // We should look at the storage duration on each nested
1453 // MaterializeTemporaryExpr instead.
1455 const Expr *Init = VD->getInit();
1459 // Lifetime-extending a temporary.
1460 bool FoundMTE = false;
1461 QT = getReferenceInitTemporaryType(*Context, Init, &FoundMTE);
1466 // Check for constant size array. Set type to array element type.
1467 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1468 if (AT->getSize() == 0)
1470 QT = AT->getElementType();
1473 // Check if type is a C++ class with non-trivial destructor.
1474 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1475 return !CD->hasDefinition() || CD->hasTrivialDestructor();
1479 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1480 /// create add scope for automatic objects and temporary objects bound to
1481 /// const reference. Will reuse Scope if not NULL.
1482 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
1483 LocalScope* Scope) {
1484 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1485 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1486 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
1489 // Check if variable is local.
1490 switch (VD->getStorageClass()) {
1495 default: return Scope;
1498 if (BuildOpts.AddImplicitDtors) {
1499 if (!hasTrivialDestructor(VD)) {
1500 // Add the variable to scope
1501 Scope = createOrReuseLocalScope(Scope);
1503 ScopePos = Scope->begin();
1508 assert(BuildOpts.AddLifetime);
1509 // Add the variable to scope
1510 Scope = createOrReuseLocalScope(Scope);
1512 ScopePos = Scope->begin();
1516 /// addLocalScopeAndDtors - For given statement add local scope for it and
1517 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
1518 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
1519 LocalScope::const_iterator scopeBeginPos = ScopePos;
1520 addLocalScopeForStmt(S);
1521 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
1524 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1525 /// variables with automatic storage duration to CFGBlock's elements vector.
1526 /// Elements will be prepended to physical beginning of the vector which
1527 /// happens to be logical end. Use blocks terminator as statement that specifies
1528 /// destructors call site.
1529 /// FIXME: This mechanism for adding automatic destructors doesn't handle
1530 /// no-return destructors properly.
1531 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
1532 LocalScope::const_iterator B, LocalScope::const_iterator E) {
1533 if (!BuildOpts.AddImplicitDtors)
1535 BumpVectorContext &C = cfg->getBumpVectorContext();
1536 CFGBlock::iterator InsertPos
1537 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1538 for (LocalScope::const_iterator I = B; I != E; ++I)
1539 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1540 Blk->getTerminator());
1543 /// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
1544 /// variables with automatic storage duration to CFGBlock's elements vector.
1545 /// Elements will be prepended to physical beginning of the vector which
1546 /// happens to be logical end. Use blocks terminator as statement that specifies
1547 /// where lifetime ends.
1548 void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
1549 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
1550 if (!BuildOpts.AddLifetime)
1552 BumpVectorContext &C = cfg->getBumpVectorContext();
1553 CFGBlock::iterator InsertPos =
1554 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
1555 for (LocalScope::const_iterator I = B; I != E; ++I)
1556 InsertPos = Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminator());
1558 /// Visit - Walk the subtree of a statement and add extra
1559 /// blocks for ternary operators, &&, and ||. We also process "," and
1560 /// DeclStmts (which may contain nested control-flow).
1561 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
1567 if (Expr *E = dyn_cast<Expr>(S))
1568 S = E->IgnoreParens();
1570 switch (S->getStmtClass()) {
1572 return VisitStmt(S, asc);
1574 case Stmt::AddrLabelExprClass:
1575 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
1577 case Stmt::BinaryConditionalOperatorClass:
1578 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1580 case Stmt::BinaryOperatorClass:
1581 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
1583 case Stmt::BlockExprClass:
1584 return VisitBlockExpr(cast<BlockExpr>(S), asc);
1586 case Stmt::BreakStmtClass:
1587 return VisitBreakStmt(cast<BreakStmt>(S));
1589 case Stmt::CallExprClass:
1590 case Stmt::CXXOperatorCallExprClass:
1591 case Stmt::CXXMemberCallExprClass:
1592 case Stmt::UserDefinedLiteralClass:
1593 return VisitCallExpr(cast<CallExpr>(S), asc);
1595 case Stmt::CaseStmtClass:
1596 return VisitCaseStmt(cast<CaseStmt>(S));
1598 case Stmt::ChooseExprClass:
1599 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
1601 case Stmt::CompoundStmtClass:
1602 return VisitCompoundStmt(cast<CompoundStmt>(S));
1604 case Stmt::ConditionalOperatorClass:
1605 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
1607 case Stmt::ContinueStmtClass:
1608 return VisitContinueStmt(cast<ContinueStmt>(S));
1610 case Stmt::CXXCatchStmtClass:
1611 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1613 case Stmt::ExprWithCleanupsClass:
1614 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
1616 case Stmt::CXXDefaultArgExprClass:
1617 case Stmt::CXXDefaultInitExprClass:
1618 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1619 // called function's declaration, not by the caller. If we simply add
1620 // this expression to the CFG, we could end up with the same Expr
1621 // appearing multiple times.
1622 // PR13385 / <rdar://problem/12156507>
1624 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1625 // expression to be used in the same function (through aggregate
1627 return VisitStmt(S, asc);
1629 case Stmt::CXXBindTemporaryExprClass:
1630 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1632 case Stmt::CXXConstructExprClass:
1633 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1635 case Stmt::CXXNewExprClass:
1636 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1638 case Stmt::CXXDeleteExprClass:
1639 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1641 case Stmt::CXXFunctionalCastExprClass:
1642 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1644 case Stmt::CXXTemporaryObjectExprClass:
1645 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1647 case Stmt::CXXThrowExprClass:
1648 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
1650 case Stmt::CXXTryStmtClass:
1651 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
1653 case Stmt::CXXForRangeStmtClass:
1654 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1656 case Stmt::DeclStmtClass:
1657 return VisitDeclStmt(cast<DeclStmt>(S));
1659 case Stmt::DefaultStmtClass:
1660 return VisitDefaultStmt(cast<DefaultStmt>(S));
1662 case Stmt::DoStmtClass:
1663 return VisitDoStmt(cast<DoStmt>(S));
1665 case Stmt::ForStmtClass:
1666 return VisitForStmt(cast<ForStmt>(S));
1668 case Stmt::GotoStmtClass:
1669 return VisitGotoStmt(cast<GotoStmt>(S));
1671 case Stmt::IfStmtClass:
1672 return VisitIfStmt(cast<IfStmt>(S));
1674 case Stmt::ImplicitCastExprClass:
1675 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
1677 case Stmt::IndirectGotoStmtClass:
1678 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
1680 case Stmt::LabelStmtClass:
1681 return VisitLabelStmt(cast<LabelStmt>(S));
1683 case Stmt::LambdaExprClass:
1684 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1686 case Stmt::MemberExprClass:
1687 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1689 case Stmt::NullStmtClass:
1692 case Stmt::ObjCAtCatchStmtClass:
1693 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1695 case Stmt::ObjCAutoreleasePoolStmtClass:
1696 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1698 case Stmt::ObjCAtSynchronizedStmtClass:
1699 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
1701 case Stmt::ObjCAtThrowStmtClass:
1702 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
1704 case Stmt::ObjCAtTryStmtClass:
1705 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
1707 case Stmt::ObjCForCollectionStmtClass:
1708 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
1710 case Stmt::OpaqueValueExprClass:
1713 case Stmt::PseudoObjectExprClass:
1714 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1716 case Stmt::ReturnStmtClass:
1717 return VisitReturnStmt(cast<ReturnStmt>(S));
1719 case Stmt::UnaryExprOrTypeTraitExprClass:
1720 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1723 case Stmt::StmtExprClass:
1724 return VisitStmtExpr(cast<StmtExpr>(S), asc);
1726 case Stmt::SwitchStmtClass:
1727 return VisitSwitchStmt(cast<SwitchStmt>(S));
1729 case Stmt::UnaryOperatorClass:
1730 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1732 case Stmt::WhileStmtClass:
1733 return VisitWhileStmt(cast<WhileStmt>(S));
1737 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
1738 if (asc.alwaysAdd(*this, S)) {
1740 appendStmt(Block, S);
1743 return VisitChildren(S);
1746 /// VisitChildren - Visit the children of a Stmt.
1747 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1748 CFGBlock *B = Block;
1750 // Visit the children in their reverse order so that they appear in
1751 // left-to-right (natural) order in the CFG.
1752 reverse_children RChildren(S);
1753 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1755 if (Stmt *Child = *I)
1756 if (CFGBlock *R = Visit(Child))
1762 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1763 AddStmtChoice asc) {
1764 AddressTakenLabels.insert(A->getLabel());
1766 if (asc.alwaysAdd(*this, A)) {
1768 appendStmt(Block, A);
1774 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
1775 AddStmtChoice asc) {
1776 if (asc.alwaysAdd(*this, U)) {
1778 appendStmt(Block, U);
1781 return Visit(U->getSubExpr(), AddStmtChoice());
1784 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1785 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1786 appendStmt(ConfluenceBlock, B);
1791 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1792 ConfluenceBlock).first;
1795 std::pair<CFGBlock*, CFGBlock*>
1796 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1798 CFGBlock *TrueBlock,
1799 CFGBlock *FalseBlock) {
1801 // Introspect the RHS. If it is a nested logical operation, we recursively
1802 // build the CFG using this function. Otherwise, resort to default
1803 // CFG construction behavior.
1804 Expr *RHS = B->getRHS()->IgnoreParens();
1805 CFGBlock *RHSBlock, *ExitBlock;
1808 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1809 if (B_RHS->isLogicalOp()) {
1810 std::tie(RHSBlock, ExitBlock) =
1811 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1815 // The RHS is not a nested logical operation. Don't push the terminator
1816 // down further, but instead visit RHS and construct the respective
1817 // pieces of the CFG, and link up the RHSBlock with the terminator
1818 // we have been provided.
1819 ExitBlock = RHSBlock = createBlock(false);
1821 // Even though KnownVal is only used in the else branch of the next
1822 // conditional, tryEvaluateBool performs additional checking on the
1823 // Expr, so it should be called unconditionally.
1824 TryResult KnownVal = tryEvaluateBool(RHS);
1825 if (!KnownVal.isKnown())
1826 KnownVal = tryEvaluateBool(B);
1829 assert(TrueBlock == FalseBlock);
1830 addSuccessor(RHSBlock, TrueBlock);
1833 RHSBlock->setTerminator(Term);
1834 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1835 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
1839 RHSBlock = addStmt(RHS);
1844 return std::make_pair(nullptr, nullptr);
1846 // Generate the blocks for evaluating the LHS.
1847 Expr *LHS = B->getLHS()->IgnoreParens();
1849 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1850 if (B_LHS->isLogicalOp()) {
1851 if (B->getOpcode() == BO_LOr)
1852 FalseBlock = RHSBlock;
1854 TrueBlock = RHSBlock;
1856 // For the LHS, treat 'B' as the terminator that we want to sink
1857 // into the nested branch. The RHS always gets the top-most
1859 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1862 // Create the block evaluating the LHS.
1863 // This contains the '&&' or '||' as the terminator.
1864 CFGBlock *LHSBlock = createBlock(false);
1865 LHSBlock->setTerminator(B);
1868 CFGBlock *EntryLHSBlock = addStmt(LHS);
1871 return std::make_pair(nullptr, nullptr);
1873 // See if this is a known constant.
1874 TryResult KnownVal = tryEvaluateBool(LHS);
1876 // Now link the LHSBlock with RHSBlock.
1877 if (B->getOpcode() == BO_LOr) {
1878 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
1879 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
1881 assert(B->getOpcode() == BO_LAnd);
1882 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
1883 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
1886 return std::make_pair(EntryLHSBlock, ExitBlock);
1890 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1891 AddStmtChoice asc) {
1893 if (B->isLogicalOp())
1894 return VisitLogicalOperator(B);
1896 if (B->getOpcode() == BO_Comma) { // ,
1898 appendStmt(Block, B);
1899 addStmt(B->getRHS());
1900 return addStmt(B->getLHS());
1903 if (B->isAssignmentOp()) {
1904 if (asc.alwaysAdd(*this, B)) {
1906 appendStmt(Block, B);
1909 return Visit(B->getRHS());
1912 if (asc.alwaysAdd(*this, B)) {
1914 appendStmt(Block, B);
1917 CFGBlock *RBlock = Visit(B->getRHS());
1918 CFGBlock *LBlock = Visit(B->getLHS());
1919 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1920 // containing a DoStmt, and the LHS doesn't create a new block, then we should
1921 // return RBlock. Otherwise we'll incorrectly return NULL.
1922 return (LBlock ? LBlock : RBlock);
1925 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
1926 if (asc.alwaysAdd(*this, E)) {
1928 appendStmt(Block, E);
1933 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1934 // "break" is a control-flow statement. Thus we stop processing the current
1939 // Now create a new block that ends with the break statement.
1940 Block = createBlock(false);
1941 Block->setTerminator(B);
1943 // If there is no target for the break, then we are looking at an incomplete
1944 // AST. This means that the CFG cannot be constructed.
1945 if (BreakJumpTarget.block) {
1946 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
1947 addSuccessor(Block, BreakJumpTarget.block);
1955 static bool CanThrow(Expr *E, ASTContext &Ctx) {
1956 QualType Ty = E->getType();
1957 if (Ty->isFunctionPointerType())
1958 Ty = Ty->getAs<PointerType>()->getPointeeType();
1959 else if (Ty->isBlockPointerType())
1960 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
1962 const FunctionType *FT = Ty->getAs<FunctionType>();
1964 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
1965 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
1966 Proto->isNothrow(Ctx))
1972 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
1973 // Compute the callee type.
1974 QualType calleeType = C->getCallee()->getType();
1975 if (calleeType == Context->BoundMemberTy) {
1976 QualType boundType = Expr::findBoundMemberType(C->getCallee());
1978 // We should only get a null bound type if processing a dependent
1979 // CFG. Recover by assuming nothing.
1980 if (!boundType.isNull()) calleeType = boundType;
1983 // If this is a call to a no-return function, this stops the block here.
1984 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1986 bool AddEHEdge = false;
1988 // Languages without exceptions are assumed to not throw.
1989 if (Context->getLangOpts().Exceptions) {
1990 if (BuildOpts.AddEHEdges)
1994 // If this is a call to a builtin function, it might not actually evaluate
1995 // its arguments. Don't add them to the CFG if this is the case.
1996 bool OmitArguments = false;
1998 if (FunctionDecl *FD = C->getDirectCallee()) {
1999 if (FD->isNoReturn())
2001 if (FD->hasAttr<NoThrowAttr>())
2003 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
2004 OmitArguments = true;
2007 if (!CanThrow(C->getCallee(), *Context))
2010 if (OmitArguments) {
2011 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2012 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2014 appendStmt(Block, C);
2015 return Visit(C->getCallee());
2018 if (!NoReturn && !AddEHEdge) {
2019 return VisitStmt(C, asc.withAlwaysAdd(true));
2029 Block = createNoReturnBlock();
2031 Block = createBlock();
2033 appendStmt(Block, C);
2036 // Add exceptional edges.
2037 if (TryTerminatedBlock)
2038 addSuccessor(Block, TryTerminatedBlock);
2040 addSuccessor(Block, &cfg->getExit());
2043 return VisitChildren(C);
2046 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2047 AddStmtChoice asc) {
2048 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2049 appendStmt(ConfluenceBlock, C);
2053 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2054 Succ = ConfluenceBlock;
2056 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
2060 Succ = ConfluenceBlock;
2062 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
2066 Block = createBlock(false);
2067 // See if this is a known constant.
2068 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2069 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2070 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
2071 Block->setTerminator(C);
2072 return addStmt(C->getCond());
2076 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
2077 LocalScope::const_iterator scopeBeginPos = ScopePos;
2078 addLocalScopeForStmt(C);
2080 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
2081 // If the body ends with a ReturnStmt, the dtors will be added in
2083 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
2086 CFGBlock *LastBlock = Block;
2088 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2090 // If we hit a segment of code just containing ';' (NullStmts), we can
2091 // get a null block back. In such cases, just use the LastBlock
2092 if (CFGBlock *newBlock = addStmt(*I))
2093 LastBlock = newBlock;
2102 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
2103 AddStmtChoice asc) {
2104 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
2105 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
2107 // Create the confluence block that will "merge" the results of the ternary
2109 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2110 appendStmt(ConfluenceBlock, C);
2114 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2116 // Create a block for the LHS expression if there is an LHS expression. A
2117 // GCC extension allows LHS to be NULL, causing the condition to be the
2118 // value that is returned instead.
2119 // e.g: x ?: y is shorthand for: x ? x : y;
2120 Succ = ConfluenceBlock;
2122 CFGBlock *LHSBlock = nullptr;
2123 const Expr *trueExpr = C->getTrueExpr();
2124 if (trueExpr != opaqueValue) {
2125 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
2131 LHSBlock = ConfluenceBlock;
2133 // Create the block for the RHS expression.
2134 Succ = ConfluenceBlock;
2135 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
2139 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2140 if (BinaryOperator *Cond =
2141 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2142 if (Cond->isLogicalOp())
2143 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2145 // Create the block that will contain the condition.
2146 Block = createBlock(false);
2148 // See if this is a known constant.
2149 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2150 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2151 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
2152 Block->setTerminator(C);
2153 Expr *condExpr = C->getCond();
2156 // Run the condition expression if it's not trivially expressed in
2157 // terms of the opaque value (or if there is no opaque value).
2158 if (condExpr != opaqueValue)
2161 // Before that, run the common subexpression if there was one.
2162 // At least one of this or the above will be run.
2163 return addStmt(BCO->getCommon());
2166 return addStmt(condExpr);
2169 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
2170 // Check if the Decl is for an __label__. If so, elide it from the
2172 if (isa<LabelDecl>(*DS->decl_begin()))
2175 // This case also handles static_asserts.
2176 if (DS->isSingleDecl())
2177 return VisitDeclSubExpr(DS);
2179 CFGBlock *B = nullptr;
2181 // Build an individual DeclStmt for each decl.
2182 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2183 E = DS->decl_rend();
2185 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
2186 unsigned A = alignof(DeclStmt) < 8 ? 8 : alignof(DeclStmt);
2188 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2189 // automatically freed with the CFG.
2190 DeclGroupRef DG(*I);
2192 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
2193 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
2194 cfg->addSyntheticDeclStmt(DSNew, DS);
2196 // Append the fake DeclStmt to block.
2197 B = VisitDeclSubExpr(DSNew);
2203 /// VisitDeclSubExpr - Utility method to add block-level expressions for
2204 /// DeclStmts and initializers in them.
2205 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
2206 assert(DS->isSingleDecl() && "Can handle single declarations only.");
2207 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
2210 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2211 // runtime semantics.
2215 bool HasTemporaries = false;
2217 // Guard static initializers under a branch.
2218 CFGBlock *blockAfterStaticInit = nullptr;
2220 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2221 // For static variables, we need to create a branch to track
2222 // whether or not they are initialized.
2229 blockAfterStaticInit = Succ;
2232 // Destructors of temporaries in initialization expression should be called
2233 // after initialization finishes.
2234 Expr *Init = VD->getInit();
2236 HasTemporaries = isa<ExprWithCleanups>(Init);
2238 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
2239 // Generate destructors for temporaries in initialization expression.
2240 TempDtorContext Context;
2241 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2242 /*BindToTemporary=*/false, Context);
2247 appendStmt(Block, DS);
2249 // Keep track of the last non-null block, as 'Block' can be nulled out
2250 // if the initializer expression is something like a 'while' in a
2251 // statement-expression.
2252 CFGBlock *LastBlock = Block;
2255 if (HasTemporaries) {
2256 // For expression with temporaries go directly to subexpression to omit
2257 // generating destructors for the second time.
2258 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2259 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2260 LastBlock = newBlock;
2263 if (CFGBlock *newBlock = Visit(Init))
2264 LastBlock = newBlock;
2268 // If the type of VD is a VLA, then we must process its size expressions.
2269 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
2270 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
2271 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2272 LastBlock = newBlock;
2275 // Remove variable from local scope.
2276 if (ScopePos && VD == *ScopePos)
2279 CFGBlock *B = LastBlock;
2280 if (blockAfterStaticInit) {
2282 Block = createBlock(false);
2283 Block->setTerminator(DS);
2284 addSuccessor(Block, blockAfterStaticInit);
2285 addSuccessor(Block, B);
2292 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
2293 // We may see an if statement in the middle of a basic block, or it may be the
2294 // first statement we are processing. In either case, we create a new basic
2295 // block. First, we create the blocks for the then...else statements, and
2296 // then we create the block containing the if statement. If we were in the
2297 // middle of a block, we stop processing that block. That block is then the
2298 // implicit successor for the "then" and "else" clauses.
2300 // Save local scope position because in case of condition variable ScopePos
2301 // won't be restored when traversing AST.
2302 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2304 // Create local scope for C++17 if init-stmt if one exists.
2305 if (Stmt *Init = I->getInit())
2306 addLocalScopeForStmt(Init);
2308 // Create local scope for possible condition variable.
2309 // Store scope position. Add implicit destructor.
2310 if (VarDecl *VD = I->getConditionVariable())
2311 addLocalScopeForVarDecl(VD);
2313 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
2315 // The block we were processing is now finished. Make it the successor
2323 // Process the false branch.
2324 CFGBlock *ElseBlock = Succ;
2326 if (Stmt *Else = I->getElse()) {
2327 SaveAndRestore<CFGBlock*> sv(Succ);
2329 // NULL out Block so that the recursive call to Visit will
2330 // create a new basic block.
2333 // If branch is not a compound statement create implicit scope
2334 // and add destructors.
2335 if (!isa<CompoundStmt>(Else))
2336 addLocalScopeAndDtors(Else);
2338 ElseBlock = addStmt(Else);
2340 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2341 ElseBlock = sv.get();
2348 // Process the true branch.
2349 CFGBlock *ThenBlock;
2351 Stmt *Then = I->getThen();
2353 SaveAndRestore<CFGBlock*> sv(Succ);
2356 // If branch is not a compound statement create implicit scope
2357 // and add destructors.
2358 if (!isa<CompoundStmt>(Then))
2359 addLocalScopeAndDtors(Then);
2361 ThenBlock = addStmt(Then);
2364 // We can reach here if the "then" body has all NullStmts.
2365 // Create an empty block so we can distinguish between true and false
2366 // branches in path-sensitive analyses.
2367 ThenBlock = createBlock(false);
2368 addSuccessor(ThenBlock, sv.get());
2375 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2376 // having these handle the actual control-flow jump. Note that
2377 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2378 // we resort to the old control-flow behavior. This special handling
2379 // removes infeasible paths from the control-flow graph by having the
2380 // control-flow transfer of '&&' or '||' go directly into the then/else
2382 BinaryOperator *Cond =
2383 I->getConditionVariable()
2385 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
2386 CFGBlock *LastBlock;
2387 if (Cond && Cond->isLogicalOp())
2388 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2390 // Now create a new block containing the if statement.
2391 Block = createBlock(false);
2393 // Set the terminator of the new block to the If statement.
2394 Block->setTerminator(I);
2396 // See if this is a known constant.
2397 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
2399 // Add the successors. If we know that specific branches are
2400 // unreachable, inform addSuccessor() of that knowledge.
2401 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2402 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
2404 // Add the condition as the last statement in the new block. This may
2405 // create new blocks as the condition may contain control-flow. Any newly
2406 // created blocks will be pointed to be "Block".
2407 LastBlock = addStmt(I->getCond());
2409 // If the IfStmt contains a condition variable, add it and its
2410 // initializer to the CFG.
2411 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2413 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2417 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2418 if (Stmt *Init = I->getInit()) {
2420 LastBlock = addStmt(Init);
2427 CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
2428 // If we were in the middle of a block we stop processing that block.
2430 // NOTE: If a "return" appears in the middle of a block, this means that the
2431 // code afterwards is DEAD (unreachable). We still keep a basic block
2432 // for that code; a simple "mark-and-sweep" from the entry block will be
2433 // able to report such dead blocks.
2435 // Create the new block.
2436 Block = createBlock(false);
2438 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), R);
2440 // If the one of the destructors does not return, we already have the Exit
2441 // block as a successor.
2442 if (!Block->hasNoReturnElement())
2443 addSuccessor(Block, &cfg->getExit());
2445 // Add the return statement to the block. This may create new blocks if R
2446 // contains control-flow (short-circuit operations).
2447 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
2450 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
2451 // Get the block of the labeled statement. Add it to our map.
2452 addStmt(L->getSubStmt());
2453 CFGBlock *LabelBlock = Block;
2455 if (!LabelBlock) // This can happen when the body is empty, i.e.
2456 LabelBlock = createBlock(); // scopes that only contains NullStmts.
2458 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2459 "label already in map");
2460 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
2462 // Labels partition blocks, so this is the end of the basic block we were
2463 // processing (L is the block's label). Because this is label (and we have
2464 // already processed the substatement) there is no extra control-flow to worry
2466 LabelBlock->setLabel(L);
2470 // We set Block to NULL to allow lazy creation of a new block (if necessary);
2473 // This block is now the implicit successor of other blocks.
2479 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
2480 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2481 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
2482 if (Expr *CopyExpr = CI.getCopyExpr()) {
2483 CFGBlock *Tmp = Visit(CopyExpr);
2491 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2492 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2493 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2494 et = E->capture_init_end(); it != et; ++it) {
2495 if (Expr *Init = *it) {
2496 CFGBlock *Tmp = Visit(Init);
2504 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
2505 // Goto is a control-flow statement. Thus we stop processing the current
2506 // block and create a new one.
2508 Block = createBlock(false);
2509 Block->setTerminator(G);
2511 // If we already know the mapping to the label block add the successor now.
2512 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
2514 if (I == LabelMap.end())
2515 // We will need to backpatch this block later.
2516 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2518 JumpTarget JT = I->second;
2519 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
2520 addSuccessor(Block, JT.block);
2526 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
2527 CFGBlock *LoopSuccessor = nullptr;
2529 // Save local scope position because in case of condition variable ScopePos
2530 // won't be restored when traversing AST.
2531 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2533 // Create local scope for init statement and possible condition variable.
2534 // Add destructor for init statement and condition variable.
2535 // Store scope position for continue statement.
2536 if (Stmt *Init = F->getInit())
2537 addLocalScopeForStmt(Init);
2538 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2540 if (VarDecl *VD = F->getConditionVariable())
2541 addLocalScopeForVarDecl(VD);
2542 LocalScope::const_iterator ContinueScopePos = ScopePos;
2544 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
2546 // "for" is a control-flow statement. Thus we stop processing the current
2551 LoopSuccessor = Block;
2553 LoopSuccessor = Succ;
2555 // Save the current value for the break targets.
2556 // All breaks should go to the code following the loop.
2557 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2558 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2560 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
2562 // Now create the loop body.
2564 assert(F->getBody());
2566 // Save the current values for Block, Succ, continue and break targets.
2567 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2568 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
2570 // Create an empty block to represent the transition block for looping back
2571 // to the head of the loop. If we have increment code, it will
2572 // go in this block as well.
2573 Block = Succ = TransitionBlock = createBlock(false);
2574 TransitionBlock->setLoopTarget(F);
2576 if (Stmt *I = F->getInc()) {
2577 // Generate increment code in its own basic block. This is the target of
2578 // continue statements.
2582 // Finish up the increment (or empty) block if it hasn't been already.
2584 assert(Block == Succ);
2590 // The starting block for the loop increment is the block that should
2591 // represent the 'loop target' for looping back to the start of the loop.
2592 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2593 ContinueJumpTarget.block->setLoopTarget(F);
2595 // Loop body should end with destructor of Condition variable (if any).
2596 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
2598 // If body is not a compound statement create implicit scope
2599 // and add destructors.
2600 if (!isa<CompoundStmt>(F->getBody()))
2601 addLocalScopeAndDtors(F->getBody());
2603 // Now populate the body block, and in the process create new blocks as we
2604 // walk the body of the loop.
2605 BodyBlock = addStmt(F->getBody());
2608 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2609 // Use the continue jump target as the proxy for the body.
2610 BodyBlock = ContinueJumpTarget.block;
2616 // Because of short-circuit evaluation, the condition of the loop can span
2617 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2618 // evaluate the condition.
2619 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
2622 Expr *C = F->getCond();
2624 // Specially handle logical operators, which have a slightly
2625 // more optimal CFG representation.
2626 if (BinaryOperator *Cond =
2627 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
2628 if (Cond->isLogicalOp()) {
2629 std::tie(EntryConditionBlock, ExitConditionBlock) =
2630 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2634 // The default case when not handling logical operators.
2635 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2636 ExitConditionBlock->setTerminator(F);
2638 // See if this is a known constant.
2639 TryResult KnownVal(true);
2642 // Now add the actual condition to the condition block.
2643 // Because the condition itself may contain control-flow, new blocks may
2644 // be created. Thus we update "Succ" after adding the condition.
2645 Block = ExitConditionBlock;
2646 EntryConditionBlock = addStmt(C);
2648 // If this block contains a condition variable, add both the condition
2649 // variable and initializer to the CFG.
2650 if (VarDecl *VD = F->getConditionVariable()) {
2651 if (Expr *Init = VD->getInit()) {
2653 appendStmt(Block, F->getConditionVariableDeclStmt());
2654 EntryConditionBlock = addStmt(Init);
2655 assert(Block == EntryConditionBlock);
2659 if (Block && badCFG)
2662 KnownVal = tryEvaluateBool(C);
2665 // Add the loop body entry as a successor to the condition.
2666 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
2667 // Link up the condition block with the code that follows the loop. (the
2669 addSuccessor(ExitConditionBlock,
2670 KnownVal.isTrue() ? nullptr : LoopSuccessor);
2674 // Link up the loop-back block to the entry condition block.
2675 addSuccessor(TransitionBlock, EntryConditionBlock);
2677 // The condition block is the implicit successor for any code above the loop.
2678 Succ = EntryConditionBlock;
2680 // If the loop contains initialization, create a new block for those
2681 // statements. This block can also contain statements that precede the loop.
2682 if (Stmt *I = F->getInit()) {
2683 Block = createBlock();
2687 // There is no loop initialization. We are thus basically a while loop.
2688 // NULL out Block to force lazy block construction.
2690 Succ = EntryConditionBlock;
2691 return EntryConditionBlock;
2694 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
2695 if (asc.alwaysAdd(*this, M)) {
2697 appendStmt(Block, M);
2699 return Visit(M->getBase());
2702 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
2703 // Objective-C fast enumeration 'for' statements:
2704 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2706 // for ( Type newVariable in collection_expression ) { statements }
2711 // 1. collection_expression
2712 // T. jump to loop_entry
2714 // 1. side-effects of element expression
2715 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2716 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2719 // T. jump to loop_entry
2725 // Type existingItem;
2726 // for ( existingItem in expression ) { statements }
2730 // the same with newVariable replaced with existingItem; the binding works
2731 // the same except that for one ObjCForCollectionStmt::getElement() returns
2732 // a DeclStmt and the other returns a DeclRefExpr.
2735 CFGBlock *LoopSuccessor = nullptr;
2740 LoopSuccessor = Block;
2743 LoopSuccessor = Succ;
2745 // Build the condition blocks.
2746 CFGBlock *ExitConditionBlock = createBlock(false);
2748 // Set the terminator for the "exit" condition block.
2749 ExitConditionBlock->setTerminator(S);
2751 // The last statement in the block should be the ObjCForCollectionStmt, which
2752 // performs the actual binding to 'element' and determines if there are any
2753 // more items in the collection.
2754 appendStmt(ExitConditionBlock, S);
2755 Block = ExitConditionBlock;
2757 // Walk the 'element' expression to see if there are any side-effects. We
2758 // generate new blocks as necessary. We DON'T add the statement by default to
2759 // the CFG unless it contains control-flow.
2760 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2761 AddStmtChoice::NotAlwaysAdd);
2768 // The condition block is the implicit successor for the loop body as well as
2769 // any code above the loop.
2770 Succ = EntryConditionBlock;
2772 // Now create the true branch.
2774 // Save the current values for Succ, continue and break targets.
2775 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2776 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2777 save_break(BreakJumpTarget);
2779 // Add an intermediate block between the BodyBlock and the
2780 // EntryConditionBlock to represent the "loop back" transition, for looping
2781 // back to the head of the loop.
2782 CFGBlock *LoopBackBlock = nullptr;
2783 Succ = LoopBackBlock = createBlock();
2784 LoopBackBlock->setLoopTarget(S);
2786 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2787 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
2789 CFGBlock *BodyBlock = addStmt(S->getBody());
2792 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
2798 // This new body block is a successor to our "exit" condition block.
2799 addSuccessor(ExitConditionBlock, BodyBlock);
2802 // Link up the condition block with the code that follows the loop.
2803 // (the false branch).
2804 addSuccessor(ExitConditionBlock, LoopSuccessor);
2806 // Now create a prologue block to contain the collection expression.
2807 Block = createBlock();
2808 return addStmt(S->getCollection());
2811 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2813 return addStmt(S->getSubStmt());
2814 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2817 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
2818 // FIXME: Add locking 'primitives' to CFG for @synchronized.
2821 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
2823 // The sync body starts its own basic block. This makes it a little easier
2824 // for diagnostic clients.
2833 // Add the @synchronized to the CFG.
2835 appendStmt(Block, S);
2837 // Inline the sync expression.
2838 return addStmt(S->getSynchExpr());
2841 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
2846 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2849 // Add the PseudoObject as the last thing.
2850 appendStmt(Block, E);
2852 CFGBlock *lastBlock = Block;
2854 // Before that, evaluate all of the semantics in order. In
2855 // CFG-land, that means appending them in reverse order.
2856 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2857 Expr *Semantic = E->getSemanticExpr(--i);
2859 // If the semantic is an opaque value, we're being asked to bind
2860 // it to its source expression.
2861 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2862 Semantic = OVE->getSourceExpr();
2864 if (CFGBlock *B = Visit(Semantic))
2871 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
2872 CFGBlock *LoopSuccessor = nullptr;
2874 // Save local scope position because in case of condition variable ScopePos
2875 // won't be restored when traversing AST.
2876 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2878 // Create local scope for possible condition variable.
2879 // Store scope position for continue statement.
2880 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2881 if (VarDecl *VD = W->getConditionVariable()) {
2882 addLocalScopeForVarDecl(VD);
2883 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
2886 // "while" is a control-flow statement. Thus we stop processing the current
2891 LoopSuccessor = Block;
2894 LoopSuccessor = Succ;
2897 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
2899 // Process the loop body.
2901 assert(W->getBody());
2903 // Save the current values for Block, Succ, continue and break targets.
2904 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2905 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2906 save_break(BreakJumpTarget);
2908 // Create an empty block to represent the transition block for looping back
2909 // to the head of the loop.
2910 Succ = TransitionBlock = createBlock(false);
2911 TransitionBlock->setLoopTarget(W);
2912 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
2914 // All breaks should go to the code following the loop.
2915 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2917 // Loop body should end with destructor of Condition variable (if any).
2918 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
2920 // If body is not a compound statement create implicit scope
2921 // and add destructors.
2922 if (!isa<CompoundStmt>(W->getBody()))
2923 addLocalScopeAndDtors(W->getBody());
2925 // Create the body. The returned block is the entry to the loop body.
2926 BodyBlock = addStmt(W->getBody());
2929 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
2930 else if (Block && badCFG)
2934 // Because of short-circuit evaluation, the condition of the loop can span
2935 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2936 // evaluate the condition.
2937 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
2940 Expr *C = W->getCond();
2942 // Specially handle logical operators, which have a slightly
2943 // more optimal CFG representation.
2944 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
2945 if (Cond->isLogicalOp()) {
2946 std::tie(EntryConditionBlock, ExitConditionBlock) =
2947 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
2951 // The default case when not handling logical operators.
2952 ExitConditionBlock = createBlock(false);
2953 ExitConditionBlock->setTerminator(W);
2955 // Now add the actual condition to the condition block.
2956 // Because the condition itself may contain control-flow, new blocks may
2957 // be created. Thus we update "Succ" after adding the condition.
2958 Block = ExitConditionBlock;
2959 Block = EntryConditionBlock = addStmt(C);
2961 // If this block contains a condition variable, add both the condition
2962 // variable and initializer to the CFG.
2963 if (VarDecl *VD = W->getConditionVariable()) {
2964 if (Expr *Init = VD->getInit()) {
2966 appendStmt(Block, W->getConditionVariableDeclStmt());
2967 EntryConditionBlock = addStmt(Init);
2968 assert(Block == EntryConditionBlock);
2972 if (Block && badCFG)
2975 // See if this is a known constant.
2976 const TryResult& KnownVal = tryEvaluateBool(C);
2978 // Add the loop body entry as a successor to the condition.
2979 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
2980 // Link up the condition block with the code that follows the loop. (the
2982 addSuccessor(ExitConditionBlock,
2983 KnownVal.isTrue() ? nullptr : LoopSuccessor);
2987 // Link up the loop-back block to the entry condition block.
2988 addSuccessor(TransitionBlock, EntryConditionBlock);
2990 // There can be no more statements in the condition block since we loop back
2991 // to this block. NULL out Block to force lazy creation of another block.
2994 // Return the condition block, which is the dominating block for the loop.
2995 Succ = EntryConditionBlock;
2996 return EntryConditionBlock;
3000 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
3001 // FIXME: For now we pretend that @catch and the code it contains does not
3006 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
3007 // FIXME: This isn't complete. We basically treat @throw like a return
3010 // If we were in the middle of a block we stop processing that block.
3014 // Create the new block.
3015 Block = createBlock(false);
3017 // The Exit block is the only successor.
3018 addSuccessor(Block, &cfg->getExit());
3020 // Add the statement to the block. This may create new blocks if S contains
3021 // control-flow (short-circuit operations).
3022 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
3025 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
3026 // If we were in the middle of a block we stop processing that block.
3030 // Create the new block.
3031 Block = createBlock(false);
3033 if (TryTerminatedBlock)
3034 // The current try statement is the only successor.
3035 addSuccessor(Block, TryTerminatedBlock);
3037 // otherwise the Exit block is the only successor.
3038 addSuccessor(Block, &cfg->getExit());
3040 // Add the statement to the block. This may create new blocks if S contains
3041 // control-flow (short-circuit operations).
3042 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
3045 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
3046 CFGBlock *LoopSuccessor = nullptr;
3048 // "do...while" is a control-flow statement. Thus we stop processing the
3053 LoopSuccessor = Block;
3055 LoopSuccessor = Succ;
3057 // Because of short-circuit evaluation, the condition of the loop can span
3058 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3059 // evaluate the condition.
3060 CFGBlock *ExitConditionBlock = createBlock(false);
3061 CFGBlock *EntryConditionBlock = ExitConditionBlock;
3063 // Set the terminator for the "exit" condition block.
3064 ExitConditionBlock->setTerminator(D);
3066 // Now add the actual condition to the condition block. Because the condition
3067 // itself may contain control-flow, new blocks may be created.
3068 if (Stmt *C = D->getCond()) {
3069 Block = ExitConditionBlock;
3070 EntryConditionBlock = addStmt(C);
3077 // The condition block is the implicit successor for the loop body.
3078 Succ = EntryConditionBlock;
3080 // See if this is a known constant.
3081 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
3083 // Process the loop body.
3084 CFGBlock *BodyBlock = nullptr;
3086 assert(D->getBody());
3088 // Save the current values for Block, Succ, and continue and break targets
3089 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3090 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3091 save_break(BreakJumpTarget);
3093 // All continues within this loop should go to the condition block
3094 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
3096 // All breaks should go to the code following the loop.
3097 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3099 // NULL out Block to force lazy instantiation of blocks for the body.
3102 // If body is not a compound statement create implicit scope
3103 // and add destructors.
3104 if (!isa<CompoundStmt>(D->getBody()))
3105 addLocalScopeAndDtors(D->getBody());
3107 // Create the body. The returned block is the entry to the loop body.
3108 BodyBlock = addStmt(D->getBody());
3111 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
3117 // Add an intermediate block between the BodyBlock and the
3118 // ExitConditionBlock to represent the "loop back" transition. Create an
3119 // empty block to represent the transition block for looping back to the
3120 // head of the loop.
3121 // FIXME: Can we do this more efficiently without adding another block?
3124 CFGBlock *LoopBackBlock = createBlock();
3125 LoopBackBlock->setLoopTarget(D);
3127 if (!KnownVal.isFalse())
3128 // Add the loop body entry as a successor to the condition.
3129 addSuccessor(ExitConditionBlock, LoopBackBlock);
3131 addSuccessor(ExitConditionBlock, nullptr);
3134 // Link up the condition block with the code that follows the loop.
3135 // (the false branch).
3136 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
3138 // There can be no more statements in the body block(s) since we loop back to
3139 // the body. NULL out Block to force lazy creation of another block.
3142 // Return the loop body, which is the dominating block for the loop.
3147 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
3148 // "continue" is a control-flow statement. Thus we stop processing the
3153 // Now create a new block that ends with the continue statement.
3154 Block = createBlock(false);
3155 Block->setTerminator(C);
3157 // If there is no target for the continue, then we are looking at an
3158 // incomplete AST. This means the CFG cannot be constructed.
3159 if (ContinueJumpTarget.block) {
3160 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
3161 addSuccessor(Block, ContinueJumpTarget.block);
3168 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3169 AddStmtChoice asc) {
3171 if (asc.alwaysAdd(*this, E)) {
3173 appendStmt(Block, E);
3176 // VLA types have expressions that must be evaluated.
3177 CFGBlock *lastBlock = Block;
3179 if (E->isArgumentType()) {
3180 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
3181 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
3182 lastBlock = addStmt(VA->getSizeExpr());
3187 /// VisitStmtExpr - Utility method to handle (nested) statement
3188 /// expressions (a GCC extension).
3189 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
3190 if (asc.alwaysAdd(*this, SE)) {
3192 appendStmt(Block, SE);
3194 return VisitCompoundStmt(SE->getSubStmt());
3197 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
3198 // "switch" is a control-flow statement. Thus we stop processing the current
3200 CFGBlock *SwitchSuccessor = nullptr;
3202 // Save local scope position because in case of condition variable ScopePos
3203 // won't be restored when traversing AST.
3204 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3206 // Create local scope for C++17 switch init-stmt if one exists.
3207 if (Stmt *Init = Terminator->getInit())
3208 addLocalScopeForStmt(Init);
3210 // Create local scope for possible condition variable.
3211 // Store scope position. Add implicit destructor.
3212 if (VarDecl *VD = Terminator->getConditionVariable())
3213 addLocalScopeForVarDecl(VD);
3215 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
3220 SwitchSuccessor = Block;
3221 } else SwitchSuccessor = Succ;
3223 // Save the current "switch" context.
3224 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
3225 save_default(DefaultCaseBlock);
3226 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3228 // Set the "default" case to be the block after the switch statement. If the
3229 // switch statement contains a "default:", this value will be overwritten with
3230 // the block for that code.
3231 DefaultCaseBlock = SwitchSuccessor;
3233 // Create a new block that will contain the switch statement.
3234 SwitchTerminatedBlock = createBlock(false);
3236 // Now process the switch body. The code after the switch is the implicit
3238 Succ = SwitchSuccessor;
3239 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
3241 // When visiting the body, the case statements should automatically get linked
3242 // up to the switch. We also don't keep a pointer to the body, since all
3243 // control-flow from the switch goes to case/default statements.
3244 assert(Terminator->getBody() && "switch must contain a non-NULL body");
3247 // For pruning unreachable case statements, save the current state
3248 // for tracking the condition value.
3249 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3252 // Determine if the switch condition can be explicitly evaluated.
3253 assert(Terminator->getCond() && "switch condition must be non-NULL");
3254 Expr::EvalResult result;
3255 bool b = tryEvaluate(Terminator->getCond(), result);
3256 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
3257 b ? &result : nullptr);
3259 // If body is not a compound statement create implicit scope
3260 // and add destructors.
3261 if (!isa<CompoundStmt>(Terminator->getBody()))
3262 addLocalScopeAndDtors(Terminator->getBody());
3264 addStmt(Terminator->getBody());
3270 // If we have no "default:" case, the default transition is to the code
3271 // following the switch body. Moreover, take into account if all the
3272 // cases of a switch are covered (e.g., switching on an enum value).
3274 // Note: We add a successor to a switch that is considered covered yet has no
3275 // case statements if the enumeration has no enumerators.
3276 bool SwitchAlwaysHasSuccessor = false;
3277 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3278 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3279 Terminator->getSwitchCaseList();
3280 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3281 !SwitchAlwaysHasSuccessor);
3283 // Add the terminator and condition in the switch block.
3284 SwitchTerminatedBlock->setTerminator(Terminator);
3285 Block = SwitchTerminatedBlock;
3286 CFGBlock *LastBlock = addStmt(Terminator->getCond());
3288 // If the SwitchStmt contains a condition variable, add both the
3289 // SwitchStmt and the condition variable initialization to the CFG.
3290 if (VarDecl *VD = Terminator->getConditionVariable()) {
3291 if (Expr *Init = VD->getInit()) {
3293 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
3294 LastBlock = addStmt(Init);
3298 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
3299 if (Stmt *Init = Terminator->getInit()) {
3301 LastBlock = addStmt(Init);
3307 static bool shouldAddCase(bool &switchExclusivelyCovered,
3308 const Expr::EvalResult *switchCond,
3314 bool addCase = false;
3316 if (!switchExclusivelyCovered) {
3317 if (switchCond->Val.isInt()) {
3318 // Evaluate the LHS of the case value.
3319 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
3320 const llvm::APSInt &condInt = switchCond->Val.getInt();
3322 if (condInt == lhsInt) {
3324 switchExclusivelyCovered = true;
3326 else if (condInt > lhsInt) {
3327 if (const Expr *RHS = CS->getRHS()) {
3328 // Evaluate the RHS of the case value.
3329 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
3330 if (V2 >= condInt) {
3332 switchExclusivelyCovered = true;
3343 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
3344 // CaseStmts are essentially labels, so they are the first statement in a
3346 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
3348 if (Stmt *Sub = CS->getSubStmt()) {
3349 // For deeply nested chains of CaseStmts, instead of doing a recursion
3350 // (which can blow out the stack), manually unroll and create blocks
3352 while (isa<CaseStmt>(Sub)) {
3353 CFGBlock *currentBlock = createBlock(false);
3354 currentBlock->setLabel(CS);
3357 addSuccessor(LastBlock, currentBlock);
3359 TopBlock = currentBlock;
3361 addSuccessor(SwitchTerminatedBlock,
3362 shouldAddCase(switchExclusivelyCovered, switchCond,
3364 ? currentBlock : nullptr);
3366 LastBlock = currentBlock;
3367 CS = cast<CaseStmt>(Sub);
3368 Sub = CS->getSubStmt();
3374 CFGBlock *CaseBlock = Block;
3376 CaseBlock = createBlock();
3378 // Cases statements partition blocks, so this is the top of the basic block we
3379 // were processing (the "case XXX:" is the label).
3380 CaseBlock->setLabel(CS);
3385 // Add this block to the list of successors for the block with the switch
3387 assert(SwitchTerminatedBlock);
3388 addSuccessor(SwitchTerminatedBlock, CaseBlock,
3389 shouldAddCase(switchExclusivelyCovered, switchCond,
3392 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3396 addSuccessor(LastBlock, CaseBlock);
3399 // This block is now the implicit successor of other blocks.
3406 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
3407 if (Terminator->getSubStmt())
3408 addStmt(Terminator->getSubStmt());
3410 DefaultCaseBlock = Block;
3412 if (!DefaultCaseBlock)
3413 DefaultCaseBlock = createBlock();
3415 // Default statements partition blocks, so this is the top of the basic block
3416 // we were processing (the "default:" is the label).
3417 DefaultCaseBlock->setLabel(Terminator);
3422 // Unlike case statements, we don't add the default block to the successors
3423 // for the switch statement immediately. This is done when we finish
3424 // processing the switch statement. This allows for the default case
3425 // (including a fall-through to the code after the switch statement) to always
3426 // be the last successor of a switch-terminated block.
3428 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3431 // This block is now the implicit successor of other blocks.
3432 Succ = DefaultCaseBlock;
3434 return DefaultCaseBlock;
3437 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3438 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3440 CFGBlock *TrySuccessor = nullptr;
3445 TrySuccessor = Block;
3446 } else TrySuccessor = Succ;
3448 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
3450 // Create a new block that will contain the try statement.
3451 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3452 // Add the terminator in the try block.
3453 NewTryTerminatedBlock->setTerminator(Terminator);
3455 bool HasCatchAll = false;
3456 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3457 // The code after the try is the implicit successor.
3458 Succ = TrySuccessor;
3459 CXXCatchStmt *CS = Terminator->getHandler(h);
3460 if (CS->getExceptionDecl() == nullptr) {
3464 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
3467 // Add this block to the list of successors for the block with the try
3469 addSuccessor(NewTryTerminatedBlock, CatchBlock);
3472 if (PrevTryTerminatedBlock)
3473 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
3475 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3478 // The code after the try is the implicit successor.
3479 Succ = TrySuccessor;
3481 // Save the current "try" context.
3482 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3483 cfg->addTryDispatchBlock(TryTerminatedBlock);
3485 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
3487 return addStmt(Terminator->getTryBlock());
3490 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
3491 // CXXCatchStmt are treated like labels, so they are the first statement in a
3494 // Save local scope position because in case of exception variable ScopePos
3495 // won't be restored when traversing AST.
3496 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3498 // Create local scope for possible exception variable.
3499 // Store scope position. Add implicit destructor.
3500 if (VarDecl *VD = CS->getExceptionDecl()) {
3501 LocalScope::const_iterator BeginScopePos = ScopePos;
3502 addLocalScopeForVarDecl(VD);
3503 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
3506 if (CS->getHandlerBlock())
3507 addStmt(CS->getHandlerBlock());
3509 CFGBlock *CatchBlock = Block;
3511 CatchBlock = createBlock();
3513 // CXXCatchStmt is more than just a label. They have semantic meaning
3514 // as well, as they implicitly "initialize" the catch variable. Add
3515 // it to the CFG as a CFGElement so that the control-flow of these
3516 // semantics gets captured.
3517 appendStmt(CatchBlock, CS);
3519 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3521 CatchBlock->setLabel(CS);
3523 // Bail out if the CFG is bad.
3527 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3533 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
3534 // C++0x for-range statements are specified as [stmt.ranged]:
3537 // auto && __range = range-init;
3538 // for ( auto __begin = begin-expr,
3539 // __end = end-expr;
3540 // __begin != __end;
3542 // for-range-declaration = *__begin;
3547 // Save local scope position before the addition of the implicit variables.
3548 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3550 // Create local scopes and destructors for range, begin and end variables.
3551 if (Stmt *Range = S->getRangeStmt())
3552 addLocalScopeForStmt(Range);
3553 if (Stmt *Begin = S->getBeginStmt())
3554 addLocalScopeForStmt(Begin);
3555 if (Stmt *End = S->getEndStmt())
3556 addLocalScopeForStmt(End);
3557 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
3559 LocalScope::const_iterator ContinueScopePos = ScopePos;
3561 // "for" is a control-flow statement. Thus we stop processing the current
3563 CFGBlock *LoopSuccessor = nullptr;
3567 LoopSuccessor = Block;
3569 LoopSuccessor = Succ;
3571 // Save the current value for the break targets.
3572 // All breaks should go to the code following the loop.
3573 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3574 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3576 // The block for the __begin != __end expression.
3577 CFGBlock *ConditionBlock = createBlock(false);
3578 ConditionBlock->setTerminator(S);
3580 // Now add the actual condition to the condition block.
3581 if (Expr *C = S->getCond()) {
3582 Block = ConditionBlock;
3583 CFGBlock *BeginConditionBlock = addStmt(C);
3586 assert(BeginConditionBlock == ConditionBlock &&
3587 "condition block in for-range was unexpectedly complex");
3588 (void)BeginConditionBlock;
3591 // The condition block is the implicit successor for the loop body as well as
3592 // any code above the loop.
3593 Succ = ConditionBlock;
3595 // See if this is a known constant.
3596 TryResult KnownVal(true);
3599 KnownVal = tryEvaluateBool(S->getCond());
3601 // Now create the loop body.
3603 assert(S->getBody());
3605 // Save the current values for Block, Succ, and continue targets.
3606 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3607 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3609 // Generate increment code in its own basic block. This is the target of
3610 // continue statements.
3612 Succ = addStmt(S->getInc());
3615 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3617 // The starting block for the loop increment is the block that should
3618 // represent the 'loop target' for looping back to the start of the loop.
3619 ContinueJumpTarget.block->setLoopTarget(S);
3621 // Finish up the increment block and prepare to start the loop body.
3627 // Add implicit scope and dtors for loop variable.
3628 addLocalScopeAndDtors(S->getLoopVarStmt());
3630 // Populate a new block to contain the loop body and loop variable.
3631 addStmt(S->getBody());
3634 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
3638 // This new body block is a successor to our condition block.
3639 addSuccessor(ConditionBlock,
3640 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
3643 // Link up the condition block with the code that follows the loop (the
3645 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
3647 // Add the initialization statements.
3648 Block = createBlock();
3649 addStmt(S->getBeginStmt());
3650 addStmt(S->getEndStmt());
3651 return addStmt(S->getRangeStmt());
3654 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
3655 AddStmtChoice asc) {
3656 if (BuildOpts.AddTemporaryDtors) {
3657 // If adding implicit destructors visit the full expression for adding
3658 // destructors of temporaries.
3659 TempDtorContext Context;
3660 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
3662 // Full expression has to be added as CFGStmt so it will be sequenced
3663 // before destructors of it's temporaries.
3664 asc = asc.withAlwaysAdd(true);
3666 return Visit(E->getSubExpr(), asc);
3669 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3670 AddStmtChoice asc) {
3671 if (asc.alwaysAdd(*this, E)) {
3673 appendStmt(Block, E);
3675 // We do not want to propagate the AlwaysAdd property.
3676 asc = asc.withAlwaysAdd(false);
3678 return Visit(E->getSubExpr(), asc);
3681 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3682 AddStmtChoice asc) {
3684 appendStmt(Block, C);
3686 return VisitChildren(C);
3689 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3690 AddStmtChoice asc) {
3693 appendStmt(Block, NE);
3695 if (NE->getInitializer())
3696 Block = Visit(NE->getInitializer());
3697 if (BuildOpts.AddCXXNewAllocator)
3698 appendNewAllocator(Block, NE);
3700 Block = Visit(NE->getArraySize());
3701 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3702 E = NE->placement_arg_end(); I != E; ++I)
3707 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3708 AddStmtChoice asc) {
3710 appendStmt(Block, DE);
3711 QualType DTy = DE->getDestroyedType();
3712 if (!DTy.isNull()) {
3713 DTy = DTy.getNonReferenceType();
3714 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3716 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
3717 appendDeleteDtor(Block, RD, DE);
3721 return VisitChildren(DE);
3724 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3725 AddStmtChoice asc) {
3726 if (asc.alwaysAdd(*this, E)) {
3728 appendStmt(Block, E);
3729 // We do not want to propagate the AlwaysAdd property.
3730 asc = asc.withAlwaysAdd(false);
3732 return Visit(E->getSubExpr(), asc);
3735 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3736 AddStmtChoice asc) {
3738 appendStmt(Block, C);
3739 return VisitChildren(C);
3742 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3743 AddStmtChoice asc) {
3744 if (asc.alwaysAdd(*this, E)) {
3746 appendStmt(Block, E);
3748 return Visit(E->getSubExpr(), AddStmtChoice());
3751 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
3752 // Lazily create the indirect-goto dispatch block if there isn't one already.
3753 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
3756 IBlock = createBlock(false);
3757 cfg->setIndirectGotoBlock(IBlock);
3760 // IndirectGoto is a control-flow statement. Thus we stop processing the
3761 // current block and create a new one.
3765 Block = createBlock(false);
3766 Block->setTerminator(I);
3767 addSuccessor(Block, IBlock);
3768 return addStmt(I->getTarget());
3771 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
3772 TempDtorContext &Context) {
3773 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3780 switch (E->getStmtClass()) {
3782 return VisitChildrenForTemporaryDtors(E, Context);
3784 case Stmt::BinaryOperatorClass:
3785 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
3788 case Stmt::CXXBindTemporaryExprClass:
3789 return VisitCXXBindTemporaryExprForTemporaryDtors(
3790 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
3792 case Stmt::BinaryConditionalOperatorClass:
3793 case Stmt::ConditionalOperatorClass:
3794 return VisitConditionalOperatorForTemporaryDtors(
3795 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
3797 case Stmt::ImplicitCastExprClass:
3798 // For implicit cast we want BindToTemporary to be passed further.
3799 E = cast<CastExpr>(E)->getSubExpr();
3802 case Stmt::CXXFunctionalCastExprClass:
3803 // For functional cast we want BindToTemporary to be passed further.
3804 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
3807 case Stmt::ParenExprClass:
3808 E = cast<ParenExpr>(E)->getSubExpr();
3811 case Stmt::MaterializeTemporaryExprClass: {
3812 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
3813 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
3814 SmallVector<const Expr *, 2> CommaLHSs;
3815 SmallVector<SubobjectAdjustment, 2> Adjustments;
3816 // Find the expression whose lifetime needs to be extended.
3817 E = const_cast<Expr *>(
3818 cast<MaterializeTemporaryExpr>(E)
3819 ->GetTemporaryExpr()
3820 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
3821 // Visit the skipped comma operator left-hand sides for other temporaries.
3822 for (const Expr *CommaLHS : CommaLHSs) {
3823 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
3824 /*BindToTemporary=*/false, Context);
3829 case Stmt::BlockExprClass:
3830 // Don't recurse into blocks; their subexpressions don't get evaluated
3834 case Stmt::LambdaExprClass: {
3835 // For lambda expressions, only recurse into the capture initializers,
3836 // and not the body.
3837 auto *LE = cast<LambdaExpr>(E);
3838 CFGBlock *B = Block;
3839 for (Expr *Init : LE->capture_inits()) {
3840 if (CFGBlock *R = VisitForTemporaryDtors(
3841 Init, /*BindToTemporary=*/false, Context))
3847 case Stmt::CXXDefaultArgExprClass:
3848 E = cast<CXXDefaultArgExpr>(E)->getExpr();
3851 case Stmt::CXXDefaultInitExprClass:
3852 E = cast<CXXDefaultInitExpr>(E)->getExpr();
3857 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
3858 TempDtorContext &Context) {
3859 if (isa<LambdaExpr>(E)) {
3860 // Do not visit the children of lambdas; they have their own CFGs.
3864 // When visiting children for destructors we want to visit them in reverse
3865 // order that they will appear in the CFG. Because the CFG is built
3866 // bottom-up, this means we visit them in their natural order, which
3867 // reverses them in the CFG.
3868 CFGBlock *B = Block;
3869 for (Stmt *Child : E->children())
3871 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
3877 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
3878 BinaryOperator *E, TempDtorContext &Context) {
3879 if (E->isLogicalOp()) {
3880 VisitForTemporaryDtors(E->getLHS(), false, Context);
3881 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
3882 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
3883 RHSExecuted.negate();
3885 // We do not know at CFG-construction time whether the right-hand-side was
3886 // executed, thus we add a branch node that depends on the temporary
3887 // constructor call.
3888 TempDtorContext RHSContext(
3889 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
3890 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
3891 InsertTempDtorDecisionBlock(RHSContext);
3896 if (E->isAssignmentOp()) {
3897 // For assignment operator (=) LHS expression is visited
3898 // before RHS expression. For destructors visit them in reverse order.
3899 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3900 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3901 return LHSBlock ? LHSBlock : RHSBlock;
3904 // For any other binary operator RHS expression is visited before
3905 // LHS expression (order of children). For destructors visit them in reverse
3907 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3908 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3909 return RHSBlock ? RHSBlock : LHSBlock;
3912 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
3913 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
3914 // First add destructors for temporaries in subexpression.
3915 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
3916 if (!BindToTemporary) {
3917 // If lifetime of temporary is not prolonged (by assigning to constant
3918 // reference) add destructor for it.
3920 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
3922 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
3923 // If the destructor is marked as a no-return destructor, we need to
3924 // create a new block for the destructor which does not have as a
3925 // successor anything built thus far. Control won't flow out of this
3928 Block = createNoReturnBlock();
3929 } else if (Context.needsTempDtorBranch()) {
3930 // If we need to introduce a branch, we add a new block that we will hook
3931 // up to a decision block later.
3933 Block = createBlock();
3937 if (Context.needsTempDtorBranch()) {
3938 Context.setDecisionPoint(Succ, E);
3940 appendTemporaryDtor(Block, E);
3947 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
3948 CFGBlock *FalseSucc) {
3949 if (!Context.TerminatorExpr) {
3950 // If no temporary was found, we do not need to insert a decision point.
3953 assert(Context.TerminatorExpr);
3954 CFGBlock *Decision = createBlock(false);
3955 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
3956 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
3957 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
3958 !Context.KnownExecuted.isTrue());
3962 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
3963 AbstractConditionalOperator *E, bool BindToTemporary,
3964 TempDtorContext &Context) {
3965 VisitForTemporaryDtors(E->getCond(), false, Context);
3966 CFGBlock *ConditionBlock = Block;
3967 CFGBlock *ConditionSucc = Succ;
3968 TryResult ConditionVal = tryEvaluateBool(E->getCond());
3969 TryResult NegatedVal = ConditionVal;
3970 if (NegatedVal.isKnown()) NegatedVal.negate();
3972 TempDtorContext TrueContext(
3973 bothKnownTrue(Context.KnownExecuted, ConditionVal));
3974 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
3975 CFGBlock *TrueBlock = Block;
3977 Block = ConditionBlock;
3978 Succ = ConditionSucc;
3979 TempDtorContext FalseContext(
3980 bothKnownTrue(Context.KnownExecuted, NegatedVal));
3981 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
3983 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
3984 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
3985 } else if (TrueContext.TerminatorExpr) {
3987 InsertTempDtorDecisionBlock(TrueContext);
3989 InsertTempDtorDecisionBlock(FalseContext);
3994 } // end anonymous namespace
3996 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
3997 /// no successors or predecessors. If this is the first block created in the
3998 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
3999 CFGBlock *CFG::createBlock() {
4000 bool first_block = begin() == end();
4002 // Create the block.
4003 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
4004 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
4005 Blocks.push_back(Mem, BlkBVC);
4007 // If this is the first block, set it as the Entry and Exit.
4009 Entry = Exit = &back();
4011 // Return the block.
4015 /// buildCFG - Constructs a CFG from an AST.
4016 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4017 ASTContext *C, const BuildOptions &BO) {
4018 CFGBuilder Builder(C, BO);
4019 return Builder.buildCFG(D, Statement);
4022 const CXXDestructorDecl *
4023 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
4024 switch (getKind()) {
4025 case CFGElement::Statement:
4026 case CFGElement::Initializer:
4027 case CFGElement::NewAllocator:
4028 case CFGElement::LifetimeEnds:
4029 llvm_unreachable("getDestructorDecl should only be used with "
4031 case CFGElement::AutomaticObjectDtor: {
4032 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
4033 QualType ty = var->getType();
4035 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4037 // Lifetime-extending constructs are handled here. This works for a single
4038 // temporary in an initializer expression.
4039 if (ty->isReferenceType()) {
4040 if (const Expr *Init = var->getInit()) {
4041 ty = getReferenceInitTemporaryType(astContext, Init);
4045 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
4046 ty = arrayType->getElementType();
4048 const RecordType *recordType = ty->getAs<RecordType>();
4049 const CXXRecordDecl *classDecl =
4050 cast<CXXRecordDecl>(recordType->getDecl());
4051 return classDecl->getDestructor();
4053 case CFGElement::DeleteDtor: {
4054 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
4055 QualType DTy = DE->getDestroyedType();
4056 DTy = DTy.getNonReferenceType();
4057 const CXXRecordDecl *classDecl =
4058 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
4059 return classDecl->getDestructor();
4061 case CFGElement::TemporaryDtor: {
4062 const CXXBindTemporaryExpr *bindExpr =
4063 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
4064 const CXXTemporary *temp = bindExpr->getTemporary();
4065 return temp->getDestructor();
4067 case CFGElement::BaseDtor:
4068 case CFGElement::MemberDtor:
4070 // Not yet supported.
4073 llvm_unreachable("getKind() returned bogus value");
4076 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
4077 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
4078 return DD->isNoReturn();
4082 //===----------------------------------------------------------------------===//
4083 // CFGBlock operations.
4084 //===----------------------------------------------------------------------===//
4086 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
4087 : ReachableBlock(IsReachable ? B : nullptr),
4088 UnreachableBlock(!IsReachable ? B : nullptr,
4089 B && IsReachable ? AB_Normal : AB_Unreachable) {}
4091 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
4092 : ReachableBlock(B),
4093 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
4094 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
4096 void CFGBlock::addSuccessor(AdjacentBlock Succ,
4097 BumpVectorContext &C) {
4098 if (CFGBlock *B = Succ.getReachableBlock())
4099 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
4101 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
4102 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
4104 Succs.push_back(Succ, C);
4107 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
4108 const CFGBlock *From, const CFGBlock *To) {
4110 if (F.IgnoreNullPredecessors && !From)
4113 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
4114 // If the 'To' has no label or is labeled but the label isn't a
4115 // CaseStmt then filter this edge.
4116 if (const SwitchStmt *S =
4117 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
4118 if (S->isAllEnumCasesCovered()) {
4119 const Stmt *L = To->getLabel();
4120 if (!L || !isa<CaseStmt>(L))
4129 //===----------------------------------------------------------------------===//
4130 // CFG pretty printing
4131 //===----------------------------------------------------------------------===//
4135 class StmtPrinterHelper : public PrinterHelper {
4136 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
4137 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
4140 signed currentBlock;
4142 const LangOptions &LangOpts;
4145 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
4146 : currentBlock(0), currStmt(0), LangOpts(LO)
4148 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4150 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
4151 BI != BEnd; ++BI, ++j ) {
4152 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4153 const Stmt *stmt= SE->getStmt();
4154 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
4157 switch (stmt->getStmtClass()) {
4158 case Stmt::DeclStmtClass:
4159 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4161 case Stmt::IfStmtClass: {
4162 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4167 case Stmt::ForStmtClass: {
4168 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4173 case Stmt::WhileStmtClass: {
4174 const VarDecl *var =
4175 cast<WhileStmt>(stmt)->getConditionVariable();
4180 case Stmt::SwitchStmtClass: {
4181 const VarDecl *var =
4182 cast<SwitchStmt>(stmt)->getConditionVariable();
4187 case Stmt::CXXCatchStmtClass: {
4188 const VarDecl *var =
4189 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4202 ~StmtPrinterHelper() override {}
4204 const LangOptions &getLangOpts() const { return LangOpts; }
4205 void setBlockID(signed i) { currentBlock = i; }
4206 void setStmtID(unsigned i) { currStmt = i; }
4208 bool handledStmt(Stmt *S, raw_ostream &OS) override {
4209 StmtMapTy::iterator I = StmtMap.find(S);
4211 if (I == StmtMap.end())
4214 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
4215 && I->second.second == currStmt) {
4219 OS << "[B" << I->second.first << "." << I->second.second << "]";
4223 bool handleDecl(const Decl *D, raw_ostream &OS) {
4224 DeclMapTy::iterator I = DeclMap.find(D);
4226 if (I == DeclMap.end())
4229 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
4230 && I->second.second == currStmt) {
4234 OS << "[B" << I->second.first << "." << I->second.second << "]";
4238 } // end anonymous namespace
4242 class CFGBlockTerminatorPrint
4243 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
4246 StmtPrinterHelper* Helper;
4247 PrintingPolicy Policy;
4249 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
4250 const PrintingPolicy &Policy)
4251 : OS(os), Helper(helper), Policy(Policy) {
4252 this->Policy.IncludeNewlines = false;
4255 void VisitIfStmt(IfStmt *I) {
4257 if (Stmt *C = I->getCond())
4258 C->printPretty(OS, Helper, Policy);
4262 void VisitStmt(Stmt *Terminator) {
4263 Terminator->printPretty(OS, Helper, Policy);
4266 void VisitDeclStmt(DeclStmt *DS) {
4267 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4268 OS << "static init " << VD->getName();
4271 void VisitForStmt(ForStmt *F) {
4276 if (Stmt *C = F->getCond())
4277 C->printPretty(OS, Helper, Policy);
4284 void VisitWhileStmt(WhileStmt *W) {
4286 if (Stmt *C = W->getCond())
4287 C->printPretty(OS, Helper, Policy);
4290 void VisitDoStmt(DoStmt *D) {
4291 OS << "do ... while ";
4292 if (Stmt *C = D->getCond())
4293 C->printPretty(OS, Helper, Policy);
4296 void VisitSwitchStmt(SwitchStmt *Terminator) {
4298 Terminator->getCond()->printPretty(OS, Helper, Policy);
4301 void VisitCXXTryStmt(CXXTryStmt *CS) {
4305 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
4306 if (Stmt *Cond = C->getCond())
4307 Cond->printPretty(OS, Helper, Policy);
4308 OS << " ? ... : ...";
4311 void VisitChooseExpr(ChooseExpr *C) {
4312 OS << "__builtin_choose_expr( ";
4313 if (Stmt *Cond = C->getCond())
4314 Cond->printPretty(OS, Helper, Policy);
4318 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
4320 if (Stmt *T = I->getTarget())
4321 T->printPretty(OS, Helper, Policy);
4324 void VisitBinaryOperator(BinaryOperator* B) {
4325 if (!B->isLogicalOp()) {
4331 B->getLHS()->printPretty(OS, Helper, Policy);
4333 switch (B->getOpcode()) {
4341 llvm_unreachable("Invalid logical operator.");
4345 void VisitExpr(Expr *E) {
4346 E->printPretty(OS, Helper, Policy);
4350 void print(CFGTerminator T) {
4351 if (T.isTemporaryDtorsBranch())
4352 OS << "(Temp Dtor) ";
4356 } // end anonymous namespace
4358 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
4359 const CFGElement &E) {
4360 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4361 const Stmt *S = CS->getStmt();
4362 assert(S != nullptr && "Expecting non-null Stmt");
4364 // special printing for statement-expressions.
4365 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4366 const CompoundStmt *Sub = SE->getSubStmt();
4368 auto Children = Sub->children();
4369 if (Children.begin() != Children.end()) {
4371 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4376 // special printing for comma expressions.
4377 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4378 if (B->getOpcode() == BO_Comma) {
4380 Helper.handledStmt(B->getRHS(),OS);
4385 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4387 if (isa<CXXOperatorCallExpr>(S)) {
4388 OS << " (OperatorCall)";
4390 else if (isa<CXXBindTemporaryExpr>(S)) {
4391 OS << " (BindTemporary)";
4393 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4394 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
4396 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
4397 OS << " (" << CE->getStmtClassName() << ", "
4398 << CE->getCastKindName()
4399 << ", " << CE->getType().getAsString()
4403 // Expressions need a newline.
4407 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
4408 const CXXCtorInitializer *I = IE->getInitializer();
4409 if (I->isBaseInitializer())
4410 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
4411 else if (I->isDelegatingInitializer())
4412 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
4413 else OS << I->getAnyMember()->getName();
4416 if (Expr *IE = I->getInit())
4417 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4420 if (I->isBaseInitializer())
4421 OS << " (Base initializer)\n";
4422 else if (I->isDelegatingInitializer())
4423 OS << " (Delegating initializer)\n";
4424 else OS << " (Member initializer)\n";
4426 } else if (Optional<CFGAutomaticObjDtor> DE =
4427 E.getAs<CFGAutomaticObjDtor>()) {
4428 const VarDecl *VD = DE->getVarDecl();
4429 Helper.handleDecl(VD, OS);
4431 const Type* T = VD->getType().getTypePtr();
4432 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4433 T = RT->getPointeeType().getTypePtr();
4434 T = T->getBaseElementTypeUnsafe();
4436 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4437 OS << " (Implicit destructor)\n";
4439 } else if (Optional<CFGLifetimeEnds> DE = E.getAs<CFGLifetimeEnds>()) {
4440 const VarDecl *VD = DE->getVarDecl();
4441 Helper.handleDecl(VD, OS);
4443 OS << " (Lifetime ends)\n";
4445 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4446 OS << "CFGNewAllocator(";
4447 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4448 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4450 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4451 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4454 CXXDeleteExpr *DelExpr =
4455 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
4456 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
4457 OS << "->~" << RD->getName().str() << "()";
4458 OS << " (Implicit destructor)\n";
4459 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4460 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
4461 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
4462 OS << " (Base object destructor)\n";
4464 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4465 const FieldDecl *FD = ME->getFieldDecl();
4466 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
4467 OS << "this->" << FD->getName();
4468 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
4469 OS << " (Member object destructor)\n";
4471 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4472 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
4474 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4475 OS << "() (Temporary object destructor)\n";
4479 static void print_block(raw_ostream &OS, const CFG* cfg,
4481 StmtPrinterHelper &Helper, bool print_edges,
4484 Helper.setBlockID(B.getBlockID());
4486 // Print the header.
4488 OS.changeColor(raw_ostream::YELLOW, true);
4490 OS << "\n [B" << B.getBlockID();
4492 if (&B == &cfg->getEntry())
4493 OS << " (ENTRY)]\n";
4494 else if (&B == &cfg->getExit())
4496 else if (&B == cfg->getIndirectGotoBlock())
4497 OS << " (INDIRECT GOTO DISPATCH)]\n";
4498 else if (B.hasNoReturnElement())
4499 OS << " (NORETURN)]\n";
4506 // Print the label of this block.
4507 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
4512 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
4514 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
4517 C->getLHS()->printPretty(OS, &Helper,
4518 PrintingPolicy(Helper.getLangOpts()));
4521 C->getRHS()->printPretty(OS, &Helper,
4522 PrintingPolicy(Helper.getLangOpts()));
4524 } else if (isa<DefaultStmt>(Label))
4526 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
4528 if (CS->getExceptionDecl())
4529 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
4536 llvm_unreachable("Invalid label statement in CFGBlock.");
4541 // Iterate through the statements in the block and print them.
4544 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4545 I != E ; ++I, ++j ) {
4547 // Print the statement # in the basic block and the statement itself.
4551 OS << llvm::format("%3d", j) << ": ";
4553 Helper.setStmtID(j);
4555 print_elem(OS, Helper, *I);
4558 // Print the terminator of this block.
4559 if (B.getTerminator()) {
4561 OS.changeColor(raw_ostream::GREEN);
4565 Helper.setBlockID(-1);
4567 PrintingPolicy PP(Helper.getLangOpts());
4568 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
4569 TPrinter.print(B.getTerminator());
4577 // Print the predecessors of this block.
4578 if (!B.pred_empty()) {
4579 const raw_ostream::Colors Color = raw_ostream::BLUE;
4581 OS.changeColor(Color);
4585 OS << '(' << B.pred_size() << "):";
4589 OS.changeColor(Color);
4591 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4598 bool Reachable = true;
4601 B = I->getPossiblyUnreachableBlock();
4604 OS << " B" << B->getBlockID();
4606 OS << "(Unreachable)";
4615 // Print the successors of this block.
4616 if (!B.succ_empty()) {
4617 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4619 OS.changeColor(Color);
4623 OS << '(' << B.succ_size() << "):";
4627 OS.changeColor(Color);
4629 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4637 bool Reachable = true;
4640 B = I->getPossiblyUnreachableBlock();
4644 OS << " B" << B->getBlockID();
4646 OS << "(Unreachable)";
4661 /// dump - A simple pretty printer of a CFG that outputs to stderr.
4662 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4663 print(llvm::errs(), LO, ShowColors);
4666 /// print - A simple pretty printer of a CFG that outputs to an ostream.
4667 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
4668 StmtPrinterHelper Helper(this, LO);
4670 // Print the entry block.
4671 print_block(OS, this, getEntry(), Helper, true, ShowColors);
4673 // Iterate through the CFGBlocks and print them one by one.
4674 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4675 // Skip the entry block, because we already printed it.
4676 if (&(**I) == &getEntry() || &(**I) == &getExit())
4679 print_block(OS, this, **I, Helper, true, ShowColors);
4682 // Print the exit block.
4683 print_block(OS, this, getExit(), Helper, true, ShowColors);
4688 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
4689 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4690 bool ShowColors) const {
4691 print(llvm::errs(), cfg, LO, ShowColors);
4694 LLVM_DUMP_METHOD void CFGBlock::dump() const {
4695 dump(getParent(), LangOptions(), false);
4698 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4699 /// Generally this will only be called from CFG::print.
4700 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
4701 const LangOptions &LO, bool ShowColors) const {
4702 StmtPrinterHelper Helper(cfg, LO);
4703 print_block(OS, cfg, *this, Helper, true, ShowColors);
4707 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
4708 void CFGBlock::printTerminator(raw_ostream &OS,
4709 const LangOptions &LO) const {
4710 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
4711 TPrinter.print(getTerminator());
4714 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
4715 Stmt *Terminator = this->Terminator;
4721 switch (Terminator->getStmtClass()) {
4725 case Stmt::CXXForRangeStmtClass:
4726 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4729 case Stmt::ForStmtClass:
4730 E = cast<ForStmt>(Terminator)->getCond();
4733 case Stmt::WhileStmtClass:
4734 E = cast<WhileStmt>(Terminator)->getCond();
4737 case Stmt::DoStmtClass:
4738 E = cast<DoStmt>(Terminator)->getCond();
4741 case Stmt::IfStmtClass:
4742 E = cast<IfStmt>(Terminator)->getCond();
4745 case Stmt::ChooseExprClass:
4746 E = cast<ChooseExpr>(Terminator)->getCond();
4749 case Stmt::IndirectGotoStmtClass:
4750 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4753 case Stmt::SwitchStmtClass:
4754 E = cast<SwitchStmt>(Terminator)->getCond();
4757 case Stmt::BinaryConditionalOperatorClass:
4758 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4761 case Stmt::ConditionalOperatorClass:
4762 E = cast<ConditionalOperator>(Terminator)->getCond();
4765 case Stmt::BinaryOperatorClass: // '&&' and '||'
4766 E = cast<BinaryOperator>(Terminator)->getLHS();
4769 case Stmt::ObjCForCollectionStmtClass:
4776 return E ? E->IgnoreParens() : nullptr;
4779 //===----------------------------------------------------------------------===//
4780 // CFG Graphviz Visualization
4781 //===----------------------------------------------------------------------===//
4785 static StmtPrinterHelper* GraphHelper;
4788 void CFG::viewCFG(const LangOptions &LO) const {
4790 StmtPrinterHelper H(this, LO);
4792 llvm::ViewGraph(this,"CFG");
4793 GraphHelper = nullptr;
4799 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
4801 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4803 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
4806 std::string OutSStr;
4807 llvm::raw_string_ostream Out(OutSStr);
4808 print_block(Out,Graph, *Node, *GraphHelper, false, false);
4809 std::string& OutStr = Out.str();
4811 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4813 // Process string output to make it nicer...
4814 for (unsigned i = 0; i != OutStr.length(); ++i)
4815 if (OutStr[i] == '\n') { // Left justify
4817 OutStr.insert(OutStr.begin()+i+1, 'l');
4826 } // end namespace llvm