[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / Analysis / CFG.cpp
blob03ab4c6fdf29caeafdefd51c0b1291117b60defa
1 //===- CFG.cpp - Classes for representing and building CFGs ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the CFG and CFGBuilder classes for representing and
10 // building Control-Flow Graphs (CFGs) from ASTs.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Analysis/CFG.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclGroup.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/OperationKinds.h"
24 #include "clang/AST/PrettyPrinter.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/StmtObjC.h"
28 #include "clang/AST/StmtVisitor.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Analysis/ConstructionContext.h"
31 #include "clang/Analysis/Support/BumpVector.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/ExceptionSpecificationType.h"
34 #include "clang/Basic/JsonSupport.h"
35 #include "clang/Basic/LLVM.h"
36 #include "clang/Basic/LangOptions.h"
37 #include "clang/Basic/SourceLocation.h"
38 #include "clang/Basic/Specifiers.h"
39 #include "llvm/ADT/APInt.h"
40 #include "llvm/ADT/APSInt.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/SetVector.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/Support/Allocator.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/DOTGraphTraits.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/Format.h"
53 #include "llvm/Support/GraphWriter.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <cassert>
57 #include <memory>
58 #include <optional>
59 #include <string>
60 #include <tuple>
61 #include <utility>
62 #include <vector>
64 using namespace clang;
66 static SourceLocation GetEndLoc(Decl *D) {
67 if (VarDecl *VD = dyn_cast<VarDecl>(D))
68 if (Expr *Ex = VD->getInit())
69 return Ex->getSourceRange().getEnd();
70 return D->getLocation();
73 /// Returns true on constant values based around a single IntegerLiteral.
74 /// Allow for use of parentheses, integer casts, and negative signs.
75 /// FIXME: it would be good to unify this function with
76 /// getIntegerLiteralSubexpressionValue at some point given the similarity
77 /// between the functions.
79 static bool IsIntegerLiteralConstantExpr(const Expr *E) {
80 // Allow parentheses
81 E = E->IgnoreParens();
83 // Allow conversions to different integer kind.
84 if (const auto *CE = dyn_cast<CastExpr>(E)) {
85 if (CE->getCastKind() != CK_IntegralCast)
86 return false;
87 E = CE->getSubExpr();
90 // Allow negative numbers.
91 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
92 if (UO->getOpcode() != UO_Minus)
93 return false;
94 E = UO->getSubExpr();
97 return isa<IntegerLiteral>(E);
100 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
101 /// constant expression or EnumConstantDecl from the given Expr. If it fails,
102 /// returns nullptr.
103 static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
104 E = E->IgnoreParens();
105 if (IsIntegerLiteralConstantExpr(E))
106 return E;
107 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
108 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
109 return nullptr;
112 /// Tries to interpret a binary operator into `Expr Op NumExpr` form, if
113 /// NumExpr is an integer literal or an enum constant.
115 /// If this fails, at least one of the returned DeclRefExpr or Expr will be
116 /// null.
117 static std::tuple<const Expr *, BinaryOperatorKind, const Expr *>
118 tryNormalizeBinaryOperator(const BinaryOperator *B) {
119 BinaryOperatorKind Op = B->getOpcode();
121 const Expr *MaybeDecl = B->getLHS();
122 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
123 // Expr looked like `0 == Foo` instead of `Foo == 0`
124 if (Constant == nullptr) {
125 // Flip the operator
126 if (Op == BO_GT)
127 Op = BO_LT;
128 else if (Op == BO_GE)
129 Op = BO_LE;
130 else if (Op == BO_LT)
131 Op = BO_GT;
132 else if (Op == BO_LE)
133 Op = BO_GE;
135 MaybeDecl = B->getRHS();
136 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
139 return std::make_tuple(MaybeDecl, Op, Constant);
142 /// For an expression `x == Foo && x == Bar`, this determines whether the
143 /// `Foo` and `Bar` are either of the same enumeration type, or both integer
144 /// literals.
146 /// It's an error to pass this arguments that are not either IntegerLiterals
147 /// or DeclRefExprs (that have decls of type EnumConstantDecl)
148 static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
149 // User intent isn't clear if they're mixing int literals with enum
150 // constants.
151 if (isa<DeclRefExpr>(E1) != isa<DeclRefExpr>(E2))
152 return false;
154 // Integer literal comparisons, regardless of literal type, are acceptable.
155 if (!isa<DeclRefExpr>(E1))
156 return true;
158 // IntegerLiterals are handled above and only EnumConstantDecls are expected
159 // beyond this point
160 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
161 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
162 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
164 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
165 const DeclContext *DC1 = Decl1->getDeclContext();
166 const DeclContext *DC2 = Decl2->getDeclContext();
168 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
169 return DC1 == DC2;
172 namespace {
174 class CFGBuilder;
176 /// The CFG builder uses a recursive algorithm to build the CFG. When
177 /// we process an expression, sometimes we know that we must add the
178 /// subexpressions as block-level expressions. For example:
180 /// exp1 || exp2
182 /// When processing the '||' expression, we know that exp1 and exp2
183 /// need to be added as block-level expressions, even though they
184 /// might not normally need to be. AddStmtChoice records this
185 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
186 /// the builder has an option not to add a subexpression as a
187 /// block-level expression.
188 class AddStmtChoice {
189 public:
190 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
192 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
194 bool alwaysAdd(CFGBuilder &builder,
195 const Stmt *stmt) const;
197 /// Return a copy of this object, except with the 'always-add' bit
198 /// set as specified.
199 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
200 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
203 private:
204 Kind kind;
207 /// LocalScope - Node in tree of local scopes created for C++ implicit
208 /// destructor calls generation. It contains list of automatic variables
209 /// declared in the scope and link to position in previous scope this scope
210 /// began in.
212 /// The process of creating local scopes is as follows:
213 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
214 /// - Before processing statements in scope (e.g. CompoundStmt) create
215 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
216 /// and set CFGBuilder::ScopePos to the end of new scope,
217 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
218 /// at this VarDecl,
219 /// - For every normal (without jump) end of scope add to CFGBlock destructors
220 /// for objects in the current scope,
221 /// - For every jump add to CFGBlock destructors for objects
222 /// between CFGBuilder::ScopePos and local scope position saved for jump
223 /// target. Thanks to C++ restrictions on goto jumps we can be sure that
224 /// jump target position will be on the path to root from CFGBuilder::ScopePos
225 /// (adding any variable that doesn't need constructor to be called to
226 /// LocalScope can break this assumption),
228 class LocalScope {
229 public:
230 using AutomaticVarsTy = BumpVector<VarDecl *>;
232 /// const_iterator - Iterates local scope backwards and jumps to previous
233 /// scope on reaching the beginning of currently iterated scope.
234 class const_iterator {
235 const LocalScope* Scope = nullptr;
237 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
238 /// Invalid iterator (with null Scope) has VarIter equal to 0.
239 unsigned VarIter = 0;
241 public:
242 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
243 /// Incrementing invalid iterator is allowed and will result in invalid
244 /// iterator.
245 const_iterator() = default;
247 /// Create valid iterator. In case when S.Prev is an invalid iterator and
248 /// I is equal to 0, this will create invalid iterator.
249 const_iterator(const LocalScope& S, unsigned I)
250 : Scope(&S), VarIter(I) {
251 // Iterator to "end" of scope is not allowed. Handle it by going up
252 // in scopes tree possibly up to invalid iterator in the root.
253 if (VarIter == 0 && Scope)
254 *this = Scope->Prev;
257 VarDecl *const* operator->() const {
258 assert(Scope && "Dereferencing invalid iterator is not allowed");
259 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
260 return &Scope->Vars[VarIter - 1];
263 const VarDecl *getFirstVarInScope() const {
264 assert(Scope && "Dereferencing invalid iterator is not allowed");
265 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
266 return Scope->Vars[0];
269 VarDecl *operator*() const {
270 return *this->operator->();
273 const_iterator &operator++() {
274 if (!Scope)
275 return *this;
277 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
278 --VarIter;
279 if (VarIter == 0)
280 *this = Scope->Prev;
281 return *this;
283 const_iterator operator++(int) {
284 const_iterator P = *this;
285 ++*this;
286 return P;
289 bool operator==(const const_iterator &rhs) const {
290 return Scope == rhs.Scope && VarIter == rhs.VarIter;
292 bool operator!=(const const_iterator &rhs) const {
293 return !(*this == rhs);
296 explicit operator bool() const {
297 return *this != const_iterator();
300 int distance(const_iterator L);
301 const_iterator shared_parent(const_iterator L);
302 bool pointsToFirstDeclaredVar() { return VarIter == 1; }
303 bool inSameLocalScope(const_iterator rhs) { return Scope == rhs.Scope; }
306 private:
307 BumpVectorContext ctx;
309 /// Automatic variables in order of declaration.
310 AutomaticVarsTy Vars;
312 /// Iterator to variable in previous scope that was declared just before
313 /// begin of this scope.
314 const_iterator Prev;
316 public:
317 /// Constructs empty scope linked to previous scope in specified place.
318 LocalScope(BumpVectorContext ctx, const_iterator P)
319 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
321 /// Begin of scope in direction of CFG building (backwards).
322 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
324 void addVar(VarDecl *VD) {
325 Vars.push_back(VD, ctx);
329 } // namespace
331 /// distance - Calculates distance from this to L. L must be reachable from this
332 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
333 /// number of scopes between this and L.
334 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
335 int D = 0;
336 const_iterator F = *this;
337 while (F.Scope != L.Scope) {
338 assert(F != const_iterator() &&
339 "L iterator is not reachable from F iterator.");
340 D += F.VarIter;
341 F = F.Scope->Prev;
343 D += F.VarIter - L.VarIter;
344 return D;
347 /// Calculates the closest parent of this iterator
348 /// that is in a scope reachable through the parents of L.
349 /// I.e. when using 'goto' from this to L, the lifetime of all variables
350 /// between this and shared_parent(L) end.
351 LocalScope::const_iterator
352 LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
353 // one of iterators is not valid (we are not in scope), so common
354 // parent is const_iterator() (i.e. sentinel).
355 if ((*this == const_iterator()) || (L == const_iterator())) {
356 return const_iterator();
359 const_iterator F = *this;
360 if (F.inSameLocalScope(L)) {
361 // Iterators are in the same scope, get common subset of variables.
362 F.VarIter = std::min(F.VarIter, L.VarIter);
363 return F;
366 llvm::SmallDenseMap<const LocalScope *, unsigned, 4> ScopesOfL;
367 while (true) {
368 ScopesOfL.try_emplace(L.Scope, L.VarIter);
369 if (L == const_iterator())
370 break;
371 L = L.Scope->Prev;
374 while (true) {
375 if (auto LIt = ScopesOfL.find(F.Scope); LIt != ScopesOfL.end()) {
376 // Get common subset of variables in given scope
377 F.VarIter = std::min(F.VarIter, LIt->getSecond());
378 return F;
380 assert(F != const_iterator() &&
381 "L iterator is not reachable from F iterator.");
382 F = F.Scope->Prev;
386 namespace {
388 /// Structure for specifying position in CFG during its build process. It
389 /// consists of CFGBlock that specifies position in CFG and
390 /// LocalScope::const_iterator that specifies position in LocalScope graph.
391 struct BlockScopePosPair {
392 CFGBlock *block = nullptr;
393 LocalScope::const_iterator scopePosition;
395 BlockScopePosPair() = default;
396 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
397 : block(b), scopePosition(scopePos) {}
400 /// TryResult - a class representing a variant over the values
401 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
402 /// and is used by the CFGBuilder to decide if a branch condition
403 /// can be decided up front during CFG construction.
404 class TryResult {
405 int X = -1;
407 public:
408 TryResult() = default;
409 TryResult(bool b) : X(b ? 1 : 0) {}
411 bool isTrue() const { return X == 1; }
412 bool isFalse() const { return X == 0; }
413 bool isKnown() const { return X >= 0; }
415 void negate() {
416 assert(isKnown());
417 X ^= 0x1;
421 } // namespace
423 static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
424 if (!R1.isKnown() || !R2.isKnown())
425 return TryResult();
426 return TryResult(R1.isTrue() && R2.isTrue());
429 namespace {
431 class reverse_children {
432 llvm::SmallVector<Stmt *, 12> childrenBuf;
433 ArrayRef<Stmt *> children;
435 public:
436 reverse_children(Stmt *S);
438 using iterator = ArrayRef<Stmt *>::reverse_iterator;
440 iterator begin() const { return children.rbegin(); }
441 iterator end() const { return children.rend(); }
444 } // namespace
446 reverse_children::reverse_children(Stmt *S) {
447 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
448 children = CE->getRawSubExprs();
449 return;
451 switch (S->getStmtClass()) {
452 // Note: Fill in this switch with more cases we want to optimize.
453 case Stmt::InitListExprClass: {
454 InitListExpr *IE = cast<InitListExpr>(S);
455 children = llvm::ArrayRef(reinterpret_cast<Stmt **>(IE->getInits()),
456 IE->getNumInits());
457 return;
459 default:
460 break;
463 // Default case for all other statements.
464 llvm::append_range(childrenBuf, S->children());
466 // This needs to be done *after* childrenBuf has been populated.
467 children = childrenBuf;
470 namespace {
472 /// CFGBuilder - This class implements CFG construction from an AST.
473 /// The builder is stateful: an instance of the builder should be used to only
474 /// construct a single CFG.
476 /// Example usage:
478 /// CFGBuilder builder;
479 /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
481 /// CFG construction is done via a recursive walk of an AST. We actually parse
482 /// the AST in reverse order so that the successor of a basic block is
483 /// constructed prior to its predecessor. This allows us to nicely capture
484 /// implicit fall-throughs without extra basic blocks.
485 class CFGBuilder {
486 using JumpTarget = BlockScopePosPair;
487 using JumpSource = BlockScopePosPair;
489 ASTContext *Context;
490 std::unique_ptr<CFG> cfg;
492 // Current block.
493 CFGBlock *Block = nullptr;
495 // Block after the current block.
496 CFGBlock *Succ = nullptr;
498 JumpTarget ContinueJumpTarget;
499 JumpTarget BreakJumpTarget;
500 JumpTarget SEHLeaveJumpTarget;
501 CFGBlock *SwitchTerminatedBlock = nullptr;
502 CFGBlock *DefaultCaseBlock = nullptr;
504 // This can point to either a C++ try, an Objective-C @try, or an SEH __try.
505 // try and @try can be mixed and generally work the same.
506 // The frontend forbids mixing SEH __try with either try or @try.
507 // So having one for all three is enough.
508 CFGBlock *TryTerminatedBlock = nullptr;
510 // Current position in local scope.
511 LocalScope::const_iterator ScopePos;
513 // LabelMap records the mapping from Label expressions to their jump targets.
514 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
515 LabelMapTy LabelMap;
517 // A list of blocks that end with a "goto" that must be backpatched to their
518 // resolved targets upon completion of CFG construction.
519 using BackpatchBlocksTy = std::vector<JumpSource>;
520 BackpatchBlocksTy BackpatchBlocks;
522 // A list of labels whose address has been taken (for indirect gotos).
523 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
524 LabelSetTy AddressTakenLabels;
526 // Information about the currently visited C++ object construction site.
527 // This is set in the construction trigger and read when the constructor
528 // or a function that returns an object by value is being visited.
529 llvm::DenseMap<Expr *, const ConstructionContextLayer *>
530 ConstructionContextMap;
532 bool badCFG = false;
533 const CFG::BuildOptions &BuildOpts;
535 // State to track for building switch statements.
536 bool switchExclusivelyCovered = false;
537 Expr::EvalResult *switchCond = nullptr;
539 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
540 const Stmt *lastLookup = nullptr;
542 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
543 // during construction of branches for chained logical operators.
544 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
545 CachedBoolEvalsTy CachedBoolEvals;
547 public:
548 explicit CFGBuilder(ASTContext *astContext,
549 const CFG::BuildOptions &buildOpts)
550 : Context(astContext), cfg(new CFG()), BuildOpts(buildOpts) {}
552 // buildCFG - Used by external clients to construct the CFG.
553 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
555 bool alwaysAdd(const Stmt *stmt);
557 private:
558 // Visitors to walk an AST and construct the CFG.
559 CFGBlock *VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc);
560 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
561 CFGBlock *VisitAttributedStmt(AttributedStmt *A, AddStmtChoice asc);
562 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
563 CFGBlock *VisitBreakStmt(BreakStmt *B);
564 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
565 CFGBlock *VisitCaseStmt(CaseStmt *C);
566 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
567 CFGBlock *VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed);
568 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
569 AddStmtChoice asc);
570 CFGBlock *VisitContinueStmt(ContinueStmt *C);
571 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
572 AddStmtChoice asc);
573 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
574 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
575 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
576 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
577 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
578 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
579 AddStmtChoice asc);
580 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
581 AddStmtChoice asc);
582 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
583 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
584 CFGBlock *VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc);
585 CFGBlock *VisitDeclStmt(DeclStmt *DS);
586 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
587 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
588 CFGBlock *VisitDoStmt(DoStmt *D);
589 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
590 AddStmtChoice asc, bool ExternallyDestructed);
591 CFGBlock *VisitForStmt(ForStmt *F);
592 CFGBlock *VisitGotoStmt(GotoStmt *G);
593 CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc);
594 CFGBlock *VisitIfStmt(IfStmt *I);
595 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
596 CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc);
597 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
598 CFGBlock *VisitLabelStmt(LabelStmt *L);
599 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
600 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
601 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
602 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
603 Stmt *Term,
604 CFGBlock *TrueBlock,
605 CFGBlock *FalseBlock);
606 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
607 AddStmtChoice asc);
608 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
609 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
610 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
611 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
612 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
613 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
614 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
615 CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
616 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
617 CFGBlock *VisitReturnStmt(Stmt *S);
618 CFGBlock *VisitCoroutineSuspendExpr(CoroutineSuspendExpr *S,
619 AddStmtChoice asc);
620 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
621 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
622 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
623 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
624 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
625 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
626 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
627 AddStmtChoice asc);
628 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
629 CFGBlock *VisitWhileStmt(WhileStmt *W);
630 CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
632 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
633 bool ExternallyDestructed = false);
634 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
635 CFGBlock *VisitChildren(Stmt *S);
636 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
637 CFGBlock *VisitOMPExecutableDirective(OMPExecutableDirective *D,
638 AddStmtChoice asc);
640 void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
641 const Stmt *S) {
642 if (ScopePos && (VD == ScopePos.getFirstVarInScope()))
643 appendScopeBegin(B, VD, S);
646 /// When creating the CFG for temporary destructors, we want to mirror the
647 /// branch structure of the corresponding constructor calls.
648 /// Thus, while visiting a statement for temporary destructors, we keep a
649 /// context to keep track of the following information:
650 /// - whether a subexpression is executed unconditionally
651 /// - if a subexpression is executed conditionally, the first
652 /// CXXBindTemporaryExpr we encounter in that subexpression (which
653 /// corresponds to the last temporary destructor we have to call for this
654 /// subexpression) and the CFG block at that point (which will become the
655 /// successor block when inserting the decision point).
657 /// That way, we can build the branch structure for temporary destructors as
658 /// follows:
659 /// 1. If a subexpression is executed unconditionally, we add the temporary
660 /// destructor calls to the current block.
661 /// 2. If a subexpression is executed conditionally, when we encounter a
662 /// CXXBindTemporaryExpr:
663 /// a) If it is the first temporary destructor call in the subexpression,
664 /// we remember the CXXBindTemporaryExpr and the current block in the
665 /// TempDtorContext; we start a new block, and insert the temporary
666 /// destructor call.
667 /// b) Otherwise, add the temporary destructor call to the current block.
668 /// 3. When we finished visiting a conditionally executed subexpression,
669 /// and we found at least one temporary constructor during the visitation
670 /// (2.a has executed), we insert a decision block that uses the
671 /// CXXBindTemporaryExpr as terminator, and branches to the current block
672 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
673 /// branches to the stored successor.
674 struct TempDtorContext {
675 TempDtorContext() = default;
676 TempDtorContext(TryResult KnownExecuted)
677 : IsConditional(true), KnownExecuted(KnownExecuted) {}
679 /// Returns whether we need to start a new branch for a temporary destructor
680 /// call. This is the case when the temporary destructor is
681 /// conditionally executed, and it is the first one we encounter while
682 /// visiting a subexpression - other temporary destructors at the same level
683 /// will be added to the same block and are executed under the same
684 /// condition.
685 bool needsTempDtorBranch() const {
686 return IsConditional && !TerminatorExpr;
689 /// Remember the successor S of a temporary destructor decision branch for
690 /// the corresponding CXXBindTemporaryExpr E.
691 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
692 Succ = S;
693 TerminatorExpr = E;
696 const bool IsConditional = false;
697 const TryResult KnownExecuted = true;
698 CFGBlock *Succ = nullptr;
699 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
702 // Visitors to walk an AST and generate destructors of temporaries in
703 // full expression.
704 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
705 TempDtorContext &Context);
706 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
707 TempDtorContext &Context);
708 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
709 bool ExternallyDestructed,
710 TempDtorContext &Context);
711 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
712 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context);
713 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
714 AbstractConditionalOperator *E, bool ExternallyDestructed,
715 TempDtorContext &Context);
716 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
717 CFGBlock *FalseSucc = nullptr);
719 // NYS == Not Yet Supported
720 CFGBlock *NYS() {
721 badCFG = true;
722 return Block;
725 // Remember to apply the construction context based on the current \p Layer
726 // when constructing the CFG element for \p CE.
727 void consumeConstructionContext(const ConstructionContextLayer *Layer,
728 Expr *E);
730 // Scan \p Child statement to find constructors in it, while keeping in mind
731 // that its parent statement is providing a partial construction context
732 // described by \p Layer. If a constructor is found, it would be assigned
733 // the context based on the layer. If an additional construction context layer
734 // is found, the function recurses into that.
735 void findConstructionContexts(const ConstructionContextLayer *Layer,
736 Stmt *Child);
738 // Scan all arguments of a call expression for a construction context.
739 // These sorts of call expressions don't have a common superclass,
740 // hence strict duck-typing.
741 template <typename CallLikeExpr,
742 typename = std::enable_if_t<
743 std::is_base_of_v<CallExpr, CallLikeExpr> ||
744 std::is_base_of_v<CXXConstructExpr, CallLikeExpr> ||
745 std::is_base_of_v<ObjCMessageExpr, CallLikeExpr>>>
746 void findConstructionContextsForArguments(CallLikeExpr *E) {
747 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
748 Expr *Arg = E->getArg(i);
749 if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
750 findConstructionContexts(
751 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
752 ConstructionContextItem(E, i)),
753 Arg);
757 // Unset the construction context after consuming it. This is done immediately
758 // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so
759 // there's no need to do this manually in every Visit... function.
760 void cleanupConstructionContext(Expr *E);
762 void autoCreateBlock() { if (!Block) Block = createBlock(); }
763 CFGBlock *createBlock(bool add_successor = true);
764 CFGBlock *createNoReturnBlock();
766 CFGBlock *addStmt(Stmt *S) {
767 return Visit(S, AddStmtChoice::AlwaysAdd);
770 CFGBlock *addInitializer(CXXCtorInitializer *I);
771 void addLoopExit(const Stmt *LoopStmt);
772 void addAutomaticObjHandling(LocalScope::const_iterator B,
773 LocalScope::const_iterator E, Stmt *S);
774 void addAutomaticObjDestruction(LocalScope::const_iterator B,
775 LocalScope::const_iterator E, Stmt *S);
776 void addScopeExitHandling(LocalScope::const_iterator B,
777 LocalScope::const_iterator E, Stmt *S);
778 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
779 void addScopeChangesHandling(LocalScope::const_iterator SrcPos,
780 LocalScope::const_iterator DstPos,
781 Stmt *S);
782 CFGBlock *createScopeChangesHandlingBlock(LocalScope::const_iterator SrcPos,
783 CFGBlock *SrcBlk,
784 LocalScope::const_iterator DstPost,
785 CFGBlock *DstBlk);
787 // Local scopes creation.
788 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
790 void addLocalScopeForStmt(Stmt *S);
791 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
792 LocalScope* Scope = nullptr);
793 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
795 void addLocalScopeAndDtors(Stmt *S);
797 const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
798 if (!BuildOpts.AddRichCXXConstructors)
799 return nullptr;
801 const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E);
802 if (!Layer)
803 return nullptr;
805 cleanupConstructionContext(E);
806 return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(),
807 Layer);
810 // Interface to CFGBlock - adding CFGElements.
812 void appendStmt(CFGBlock *B, const Stmt *S) {
813 if (alwaysAdd(S) && cachedEntry)
814 cachedEntry->second = B;
816 // All block-level expressions should have already been IgnoreParens()ed.
817 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
818 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
821 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
822 if (const ConstructionContext *CC =
823 retrieveAndCleanupConstructionContext(CE)) {
824 B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
825 return;
828 // No valid construction context found. Fall back to statement.
829 B->appendStmt(CE, cfg->getBumpVectorContext());
832 void appendCall(CFGBlock *B, CallExpr *CE) {
833 if (alwaysAdd(CE) && cachedEntry)
834 cachedEntry->second = B;
836 if (const ConstructionContext *CC =
837 retrieveAndCleanupConstructionContext(CE)) {
838 B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
839 return;
842 // No valid construction context found. Fall back to statement.
843 B->appendStmt(CE, cfg->getBumpVectorContext());
846 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
847 B->appendInitializer(I, cfg->getBumpVectorContext());
850 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
851 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
854 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
855 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
858 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
859 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
862 void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
863 if (alwaysAdd(ME) && cachedEntry)
864 cachedEntry->second = B;
866 if (const ConstructionContext *CC =
867 retrieveAndCleanupConstructionContext(ME)) {
868 B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
869 return;
872 B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
873 cfg->getBumpVectorContext());
876 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
877 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
880 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
881 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
884 void appendCleanupFunction(CFGBlock *B, VarDecl *VD) {
885 B->appendCleanupFunction(VD, cfg->getBumpVectorContext());
888 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
889 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
892 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
893 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
896 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
897 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
900 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
901 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
902 cfg->getBumpVectorContext());
905 /// Add a reachable successor to a block, with the alternate variant that is
906 /// unreachable.
907 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
908 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
909 cfg->getBumpVectorContext());
912 void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
913 if (BuildOpts.AddScopes)
914 B->appendScopeBegin(VD, S, cfg->getBumpVectorContext());
917 void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
918 if (BuildOpts.AddScopes)
919 B->appendScopeEnd(VD, S, cfg->getBumpVectorContext());
922 /// Find a relational comparison with an expression evaluating to a
923 /// boolean and a constant other than 0 and 1.
924 /// e.g. if ((x < y) == 10)
925 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
926 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
927 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
929 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
930 const Expr *BoolExpr = RHSExpr;
931 bool IntFirst = true;
932 if (!IntLiteral) {
933 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
934 BoolExpr = LHSExpr;
935 IntFirst = false;
938 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
939 return TryResult();
941 llvm::APInt IntValue = IntLiteral->getValue();
942 if ((IntValue == 1) || (IntValue == 0))
943 return TryResult();
945 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
946 !IntValue.isNegative();
948 BinaryOperatorKind Bok = B->getOpcode();
949 if (Bok == BO_GT || Bok == BO_GE) {
950 // Always true for 10 > bool and bool > -1
951 // Always false for -1 > bool and bool > 10
952 return TryResult(IntFirst == IntLarger);
953 } else {
954 // Always true for -1 < bool and bool < 10
955 // Always false for 10 < bool and bool < -1
956 return TryResult(IntFirst != IntLarger);
960 /// Find an incorrect equality comparison. Either with an expression
961 /// evaluating to a boolean and a constant other than 0 and 1.
962 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
963 /// true/false e.q. (x & 8) == 4.
964 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
965 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
966 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
968 std::optional<llvm::APInt> IntLiteral1 =
969 getIntegerLiteralSubexpressionValue(LHSExpr);
970 const Expr *BoolExpr = RHSExpr;
972 if (!IntLiteral1) {
973 IntLiteral1 = getIntegerLiteralSubexpressionValue(RHSExpr);
974 BoolExpr = LHSExpr;
977 if (!IntLiteral1)
978 return TryResult();
980 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
981 if (BitOp && (BitOp->getOpcode() == BO_And ||
982 BitOp->getOpcode() == BO_Or)) {
983 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
984 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
986 std::optional<llvm::APInt> IntLiteral2 =
987 getIntegerLiteralSubexpressionValue(LHSExpr2);
989 if (!IntLiteral2)
990 IntLiteral2 = getIntegerLiteralSubexpressionValue(RHSExpr2);
992 if (!IntLiteral2)
993 return TryResult();
995 if ((BitOp->getOpcode() == BO_And &&
996 (*IntLiteral2 & *IntLiteral1) != *IntLiteral1) ||
997 (BitOp->getOpcode() == BO_Or &&
998 (*IntLiteral2 | *IntLiteral1) != *IntLiteral1)) {
999 if (BuildOpts.Observer)
1000 BuildOpts.Observer->compareBitwiseEquality(B,
1001 B->getOpcode() != BO_EQ);
1002 return TryResult(B->getOpcode() != BO_EQ);
1004 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
1005 if ((*IntLiteral1 == 1) || (*IntLiteral1 == 0)) {
1006 return TryResult();
1008 return TryResult(B->getOpcode() != BO_EQ);
1011 return TryResult();
1014 // Helper function to get an APInt from an expression. Supports expressions
1015 // which are an IntegerLiteral or a UnaryOperator and returns the value with
1016 // all operations performed on it.
1017 // FIXME: it would be good to unify this function with
1018 // IsIntegerLiteralConstantExpr at some point given the similarity between the
1019 // functions.
1020 std::optional<llvm::APInt>
1021 getIntegerLiteralSubexpressionValue(const Expr *E) {
1023 // If unary.
1024 if (const auto *UnOp = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1025 // Get the sub expression of the unary expression and get the Integer
1026 // Literal.
1027 const Expr *SubExpr = UnOp->getSubExpr()->IgnoreParens();
1029 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(SubExpr)) {
1031 llvm::APInt Value = IntLiteral->getValue();
1033 // Perform the operation manually.
1034 switch (UnOp->getOpcode()) {
1035 case UO_Plus:
1036 return Value;
1037 case UO_Minus:
1038 return -Value;
1039 case UO_Not:
1040 return ~Value;
1041 case UO_LNot:
1042 return llvm::APInt(Context->getTypeSize(Context->IntTy), !Value);
1043 default:
1044 assert(false && "Unexpected unary operator!");
1045 return std::nullopt;
1048 } else if (const auto *IntLiteral =
1049 dyn_cast<IntegerLiteral>(E->IgnoreParens()))
1050 return IntLiteral->getValue();
1052 return std::nullopt;
1055 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
1056 const llvm::APSInt &Value1,
1057 const llvm::APSInt &Value2) {
1058 assert(Value1.isSigned() == Value2.isSigned());
1059 switch (Relation) {
1060 default:
1061 return TryResult();
1062 case BO_EQ:
1063 return TryResult(Value1 == Value2);
1064 case BO_NE:
1065 return TryResult(Value1 != Value2);
1066 case BO_LT:
1067 return TryResult(Value1 < Value2);
1068 case BO_LE:
1069 return TryResult(Value1 <= Value2);
1070 case BO_GT:
1071 return TryResult(Value1 > Value2);
1072 case BO_GE:
1073 return TryResult(Value1 >= Value2);
1077 /// There are two checks handled by this function:
1078 /// 1. Find a law-of-excluded-middle or law-of-noncontradiction expression
1079 /// e.g. if (x || !x), if (x && !x)
1080 /// 2. Find a pair of comparison expressions with or without parentheses
1081 /// with a shared variable and constants and a logical operator between them
1082 /// that always evaluates to either true or false.
1083 /// e.g. if (x != 3 || x != 4)
1084 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
1085 assert(B->isLogicalOp());
1086 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
1087 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
1089 auto CheckLogicalOpWithNegatedVariable = [this, B](const Expr *E1,
1090 const Expr *E2) {
1091 if (const auto *Negate = dyn_cast<UnaryOperator>(E1)) {
1092 if (Negate->getOpcode() == UO_LNot &&
1093 Expr::isSameComparisonOperand(Negate->getSubExpr(), E2)) {
1094 bool AlwaysTrue = B->getOpcode() == BO_LOr;
1095 if (BuildOpts.Observer)
1096 BuildOpts.Observer->logicAlwaysTrue(B, AlwaysTrue);
1097 return TryResult(AlwaysTrue);
1100 return TryResult();
1103 TryResult Result = CheckLogicalOpWithNegatedVariable(LHSExpr, RHSExpr);
1104 if (Result.isKnown())
1105 return Result;
1106 Result = CheckLogicalOpWithNegatedVariable(RHSExpr, LHSExpr);
1107 if (Result.isKnown())
1108 return Result;
1110 const auto *LHS = dyn_cast<BinaryOperator>(LHSExpr);
1111 const auto *RHS = dyn_cast<BinaryOperator>(RHSExpr);
1112 if (!LHS || !RHS)
1113 return {};
1115 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
1116 return {};
1118 const Expr *DeclExpr1;
1119 const Expr *NumExpr1;
1120 BinaryOperatorKind BO1;
1121 std::tie(DeclExpr1, BO1, NumExpr1) = tryNormalizeBinaryOperator(LHS);
1123 if (!DeclExpr1 || !NumExpr1)
1124 return {};
1126 const Expr *DeclExpr2;
1127 const Expr *NumExpr2;
1128 BinaryOperatorKind BO2;
1129 std::tie(DeclExpr2, BO2, NumExpr2) = tryNormalizeBinaryOperator(RHS);
1131 if (!DeclExpr2 || !NumExpr2)
1132 return {};
1134 // Check that it is the same variable on both sides.
1135 if (!Expr::isSameComparisonOperand(DeclExpr1, DeclExpr2))
1136 return {};
1138 // Make sure the user's intent is clear (e.g. they're comparing against two
1139 // int literals, or two things from the same enum)
1140 if (!areExprTypesCompatible(NumExpr1, NumExpr2))
1141 return {};
1143 Expr::EvalResult L1Result, L2Result;
1144 if (!NumExpr1->EvaluateAsInt(L1Result, *Context) ||
1145 !NumExpr2->EvaluateAsInt(L2Result, *Context))
1146 return {};
1148 llvm::APSInt L1 = L1Result.Val.getInt();
1149 llvm::APSInt L2 = L2Result.Val.getInt();
1151 // Can't compare signed with unsigned or with different bit width.
1152 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
1153 return {};
1155 // Values that will be used to determine if result of logical
1156 // operator is always true/false
1157 const llvm::APSInt Values[] = {
1158 // Value less than both Value1 and Value2
1159 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
1160 // L1
1162 // Value between Value1 and Value2
1163 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
1164 L1.isUnsigned()),
1165 // L2
1167 // Value greater than both Value1 and Value2
1168 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
1171 // Check whether expression is always true/false by evaluating the following
1172 // * variable x is less than the smallest literal.
1173 // * variable x is equal to the smallest literal.
1174 // * Variable x is between smallest and largest literal.
1175 // * Variable x is equal to the largest literal.
1176 // * Variable x is greater than largest literal.
1177 bool AlwaysTrue = true, AlwaysFalse = true;
1178 // Track value of both subexpressions. If either side is always
1179 // true/false, another warning should have already been emitted.
1180 bool LHSAlwaysTrue = true, LHSAlwaysFalse = true;
1181 bool RHSAlwaysTrue = true, RHSAlwaysFalse = true;
1182 for (const llvm::APSInt &Value : Values) {
1183 TryResult Res1, Res2;
1184 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
1185 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
1187 if (!Res1.isKnown() || !Res2.isKnown())
1188 return {};
1190 if (B->getOpcode() == BO_LAnd) {
1191 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
1192 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
1193 } else {
1194 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
1195 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
1198 LHSAlwaysTrue &= Res1.isTrue();
1199 LHSAlwaysFalse &= Res1.isFalse();
1200 RHSAlwaysTrue &= Res2.isTrue();
1201 RHSAlwaysFalse &= Res2.isFalse();
1204 if (AlwaysTrue || AlwaysFalse) {
1205 if (!LHSAlwaysTrue && !LHSAlwaysFalse && !RHSAlwaysTrue &&
1206 !RHSAlwaysFalse && BuildOpts.Observer)
1207 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
1208 return TryResult(AlwaysTrue);
1210 return {};
1213 /// A bitwise-or with a non-zero constant always evaluates to true.
1214 TryResult checkIncorrectBitwiseOrOperator(const BinaryOperator *B) {
1215 const Expr *LHSConstant =
1216 tryTransformToIntOrEnumConstant(B->getLHS()->IgnoreParenImpCasts());
1217 const Expr *RHSConstant =
1218 tryTransformToIntOrEnumConstant(B->getRHS()->IgnoreParenImpCasts());
1220 if ((LHSConstant && RHSConstant) || (!LHSConstant && !RHSConstant))
1221 return {};
1223 const Expr *Constant = LHSConstant ? LHSConstant : RHSConstant;
1225 Expr::EvalResult Result;
1226 if (!Constant->EvaluateAsInt(Result, *Context))
1227 return {};
1229 if (Result.Val.getInt() == 0)
1230 return {};
1232 if (BuildOpts.Observer)
1233 BuildOpts.Observer->compareBitwiseOr(B);
1235 return TryResult(true);
1238 /// Try and evaluate an expression to an integer constant.
1239 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
1240 if (!BuildOpts.PruneTriviallyFalseEdges)
1241 return false;
1242 return !S->isTypeDependent() &&
1243 !S->isValueDependent() &&
1244 S->EvaluateAsRValue(outResult, *Context);
1247 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
1248 /// if we can evaluate to a known value, otherwise return -1.
1249 TryResult tryEvaluateBool(Expr *S) {
1250 if (!BuildOpts.PruneTriviallyFalseEdges ||
1251 S->isTypeDependent() || S->isValueDependent())
1252 return {};
1254 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1255 if (Bop->isLogicalOp() || Bop->isEqualityOp()) {
1256 // Check the cache first.
1257 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1258 if (I != CachedBoolEvals.end())
1259 return I->second; // already in map;
1261 // Retrieve result at first, or the map might be updated.
1262 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1263 CachedBoolEvals[S] = Result; // update or insert
1264 return Result;
1266 else {
1267 switch (Bop->getOpcode()) {
1268 default: break;
1269 // For 'x & 0' and 'x * 0', we can determine that
1270 // the value is always false.
1271 case BO_Mul:
1272 case BO_And: {
1273 // If either operand is zero, we know the value
1274 // must be false.
1275 Expr::EvalResult LHSResult;
1276 if (Bop->getLHS()->EvaluateAsInt(LHSResult, *Context)) {
1277 llvm::APSInt IntVal = LHSResult.Val.getInt();
1278 if (!IntVal.getBoolValue()) {
1279 return TryResult(false);
1282 Expr::EvalResult RHSResult;
1283 if (Bop->getRHS()->EvaluateAsInt(RHSResult, *Context)) {
1284 llvm::APSInt IntVal = RHSResult.Val.getInt();
1285 if (!IntVal.getBoolValue()) {
1286 return TryResult(false);
1290 break;
1295 return evaluateAsBooleanConditionNoCache(S);
1298 /// Evaluate as boolean \param E without using the cache.
1299 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1300 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1301 if (Bop->isLogicalOp()) {
1302 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1303 if (LHS.isKnown()) {
1304 // We were able to evaluate the LHS, see if we can get away with not
1305 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1306 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1307 return LHS.isTrue();
1309 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1310 if (RHS.isKnown()) {
1311 if (Bop->getOpcode() == BO_LOr)
1312 return LHS.isTrue() || RHS.isTrue();
1313 else
1314 return LHS.isTrue() && RHS.isTrue();
1316 } else {
1317 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1318 if (RHS.isKnown()) {
1319 // We can't evaluate the LHS; however, sometimes the result
1320 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1321 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1322 return RHS.isTrue();
1323 } else {
1324 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1325 if (BopRes.isKnown())
1326 return BopRes.isTrue();
1330 return {};
1331 } else if (Bop->isEqualityOp()) {
1332 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1333 if (BopRes.isKnown())
1334 return BopRes.isTrue();
1335 } else if (Bop->isRelationalOp()) {
1336 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1337 if (BopRes.isKnown())
1338 return BopRes.isTrue();
1339 } else if (Bop->getOpcode() == BO_Or) {
1340 TryResult BopRes = checkIncorrectBitwiseOrOperator(Bop);
1341 if (BopRes.isKnown())
1342 return BopRes.isTrue();
1346 bool Result;
1347 if (E->EvaluateAsBooleanCondition(Result, *Context))
1348 return Result;
1350 return {};
1353 bool hasTrivialDestructor(const VarDecl *VD) const;
1354 bool needsAutomaticDestruction(const VarDecl *VD) const;
1357 } // namespace
1359 Expr *
1360 clang::extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr *AILE) {
1361 if (!AILE)
1362 return nullptr;
1364 Expr *AILEInit = AILE->getSubExpr();
1365 while (const auto *E = dyn_cast<ArrayInitLoopExpr>(AILEInit))
1366 AILEInit = E->getSubExpr();
1368 return AILEInit;
1371 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1372 const Stmt *stmt) const {
1373 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1376 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
1377 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1379 if (!BuildOpts.forcedBlkExprs)
1380 return shouldAdd;
1382 if (lastLookup == stmt) {
1383 if (cachedEntry) {
1384 assert(cachedEntry->first == stmt);
1385 return true;
1387 return shouldAdd;
1390 lastLookup = stmt;
1392 // Perform the lookup!
1393 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1395 if (!fb) {
1396 // No need to update 'cachedEntry', since it will always be null.
1397 assert(!cachedEntry);
1398 return shouldAdd;
1401 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
1402 if (itr == fb->end()) {
1403 cachedEntry = nullptr;
1404 return shouldAdd;
1407 cachedEntry = &*itr;
1408 return true;
1411 // FIXME: Add support for dependent-sized array types in C++?
1412 // Does it even make sense to build a CFG for an uninstantiated template?
1413 static const VariableArrayType *FindVA(const Type *t) {
1414 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1415 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
1416 if (vat->getSizeExpr())
1417 return vat;
1419 t = vt->getElementType().getTypePtr();
1422 return nullptr;
1425 void CFGBuilder::consumeConstructionContext(
1426 const ConstructionContextLayer *Layer, Expr *E) {
1427 assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
1428 isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
1429 if (const ConstructionContextLayer *PreviouslyStoredLayer =
1430 ConstructionContextMap.lookup(E)) {
1431 (void)PreviouslyStoredLayer;
1432 // We might have visited this child when we were finding construction
1433 // contexts within its parents.
1434 assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
1435 "Already within a different construction context!");
1436 } else {
1437 ConstructionContextMap[E] = Layer;
1441 void CFGBuilder::findConstructionContexts(
1442 const ConstructionContextLayer *Layer, Stmt *Child) {
1443 if (!BuildOpts.AddRichCXXConstructors)
1444 return;
1446 if (!Child)
1447 return;
1449 auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) {
1450 return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item,
1451 Layer);
1454 switch(Child->getStmtClass()) {
1455 case Stmt::CXXConstructExprClass:
1456 case Stmt::CXXTemporaryObjectExprClass: {
1457 // Support pre-C++17 copy elision AST.
1458 auto *CE = cast<CXXConstructExpr>(Child);
1459 if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
1460 findConstructionContexts(withExtraLayer(CE), CE->getArg(0));
1463 consumeConstructionContext(Layer, CE);
1464 break;
1466 // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
1467 // FIXME: An isa<> would look much better but this whole switch is a
1468 // workaround for an internal compiler error in MSVC 2015 (see r326021).
1469 case Stmt::CallExprClass:
1470 case Stmt::CXXMemberCallExprClass:
1471 case Stmt::CXXOperatorCallExprClass:
1472 case Stmt::UserDefinedLiteralClass:
1473 case Stmt::ObjCMessageExprClass: {
1474 auto *E = cast<Expr>(Child);
1475 if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
1476 consumeConstructionContext(Layer, E);
1477 break;
1479 case Stmt::ExprWithCleanupsClass: {
1480 auto *Cleanups = cast<ExprWithCleanups>(Child);
1481 findConstructionContexts(Layer, Cleanups->getSubExpr());
1482 break;
1484 case Stmt::CXXFunctionalCastExprClass: {
1485 auto *Cast = cast<CXXFunctionalCastExpr>(Child);
1486 findConstructionContexts(Layer, Cast->getSubExpr());
1487 break;
1489 case Stmt::ImplicitCastExprClass: {
1490 auto *Cast = cast<ImplicitCastExpr>(Child);
1491 // Should we support other implicit cast kinds?
1492 switch (Cast->getCastKind()) {
1493 case CK_NoOp:
1494 case CK_ConstructorConversion:
1495 findConstructionContexts(Layer, Cast->getSubExpr());
1496 break;
1497 default:
1498 break;
1500 break;
1502 case Stmt::CXXBindTemporaryExprClass: {
1503 auto *BTE = cast<CXXBindTemporaryExpr>(Child);
1504 findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
1505 break;
1507 case Stmt::MaterializeTemporaryExprClass: {
1508 // Normally we don't want to search in MaterializeTemporaryExpr because
1509 // it indicates the beginning of a temporary object construction context,
1510 // so it shouldn't be found in the middle. However, if it is the beginning
1511 // of an elidable copy or move construction context, we need to include it.
1512 if (Layer->getItem().getKind() ==
1513 ConstructionContextItem::ElidableConstructorKind) {
1514 auto *MTE = cast<MaterializeTemporaryExpr>(Child);
1515 findConstructionContexts(withExtraLayer(MTE), MTE->getSubExpr());
1517 break;
1519 case Stmt::ConditionalOperatorClass: {
1520 auto *CO = cast<ConditionalOperator>(Child);
1521 if (Layer->getItem().getKind() !=
1522 ConstructionContextItem::MaterializationKind) {
1523 // If the object returned by the conditional operator is not going to be a
1524 // temporary object that needs to be immediately materialized, then
1525 // it must be C++17 with its mandatory copy elision. Do not yet promise
1526 // to support this case.
1527 assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
1528 Context->getLangOpts().CPlusPlus17);
1529 break;
1531 findConstructionContexts(Layer, CO->getLHS());
1532 findConstructionContexts(Layer, CO->getRHS());
1533 break;
1535 case Stmt::InitListExprClass: {
1536 auto *ILE = cast<InitListExpr>(Child);
1537 if (ILE->isTransparent()) {
1538 findConstructionContexts(Layer, ILE->getInit(0));
1539 break;
1541 // TODO: Handle other cases. For now, fail to find construction contexts.
1542 break;
1544 case Stmt::ParenExprClass: {
1545 // If expression is placed into parenthesis we should propagate the parent
1546 // construction context to subexpressions.
1547 auto *PE = cast<ParenExpr>(Child);
1548 findConstructionContexts(Layer, PE->getSubExpr());
1549 break;
1551 default:
1552 break;
1556 void CFGBuilder::cleanupConstructionContext(Expr *E) {
1557 assert(BuildOpts.AddRichCXXConstructors &&
1558 "We should not be managing construction contexts!");
1559 assert(ConstructionContextMap.count(E) &&
1560 "Cannot exit construction context without the context!");
1561 ConstructionContextMap.erase(E);
1564 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1565 /// arbitrary statement. Examples include a single expression or a function
1566 /// body (compound statement). The ownership of the returned CFG is
1567 /// transferred to the caller. If CFG construction fails, this method returns
1568 /// NULL.
1569 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
1570 assert(cfg.get());
1571 if (!Statement)
1572 return nullptr;
1574 // Create an empty block that will serve as the exit block for the CFG. Since
1575 // this is the first block added to the CFG, it will be implicitly registered
1576 // as the exit block.
1577 Succ = createBlock();
1578 assert(Succ == &cfg->getExit());
1579 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
1581 if (BuildOpts.AddImplicitDtors)
1582 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1583 addImplicitDtorsForDestructor(DD);
1585 // Visit the statements and create the CFG.
1586 CFGBlock *B = addStmt(Statement);
1588 if (badCFG)
1589 return nullptr;
1591 // For C++ constructor add initializers to CFG. Constructors of virtual bases
1592 // are ignored unless the object is of the most derived class.
1593 // class VBase { VBase() = default; VBase(int) {} };
1594 // class A : virtual public VBase { A() : VBase(0) {} };
1595 // class B : public A {};
1596 // B b; // Constructor calls in order: VBase(), A(), B().
1597 // // VBase(0) is ignored because A isn't the most derived class.
1598 // This may result in the virtual base(s) being already initialized at this
1599 // point, in which case we should jump right onto non-virtual bases and
1600 // fields. To handle this, make a CFG branch. We only need to add one such
1601 // branch per constructor, since the Standard states that all virtual bases
1602 // shall be initialized before non-virtual bases and direct data members.
1603 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
1604 CFGBlock *VBaseSucc = nullptr;
1605 for (auto *I : llvm::reverse(CD->inits())) {
1606 if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
1607 I->isBaseInitializer() && I->isBaseVirtual()) {
1608 // We've reached the first virtual base init while iterating in reverse
1609 // order. Make a new block for virtual base initializers so that we
1610 // could skip them.
1611 VBaseSucc = Succ = B ? B : &cfg->getExit();
1612 Block = createBlock();
1614 B = addInitializer(I);
1615 if (badCFG)
1616 return nullptr;
1618 if (VBaseSucc) {
1619 // Make a branch block for potentially skipping virtual base initializers.
1620 Succ = VBaseSucc;
1621 B = createBlock();
1622 B->setTerminator(
1623 CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch));
1624 addSuccessor(B, Block, true);
1628 if (B)
1629 Succ = B;
1631 // Backpatch the gotos whose label -> block mappings we didn't know when we
1632 // encountered them.
1633 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1634 E = BackpatchBlocks.end(); I != E; ++I ) {
1636 CFGBlock *B = I->block;
1637 if (auto *G = dyn_cast<GotoStmt>(B->getTerminator())) {
1638 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
1639 // If there is no target for the goto, then we are looking at an
1640 // incomplete AST. Handle this by not registering a successor.
1641 if (LI == LabelMap.end())
1642 continue;
1643 JumpTarget JT = LI->second;
1645 CFGBlock *SuccBlk = createScopeChangesHandlingBlock(
1646 I->scopePosition, B, JT.scopePosition, JT.block);
1647 addSuccessor(B, SuccBlk);
1648 } else if (auto *G = dyn_cast<GCCAsmStmt>(B->getTerminator())) {
1649 CFGBlock *Successor = (I+1)->block;
1650 for (auto *L : G->labels()) {
1651 LabelMapTy::iterator LI = LabelMap.find(L->getLabel());
1652 // If there is no target for the goto, then we are looking at an
1653 // incomplete AST. Handle this by not registering a successor.
1654 if (LI == LabelMap.end())
1655 continue;
1656 JumpTarget JT = LI->second;
1657 // Successor has been added, so skip it.
1658 if (JT.block == Successor)
1659 continue;
1660 addSuccessor(B, JT.block);
1662 I++;
1666 // Add successors to the Indirect Goto Dispatch block (if we have one).
1667 if (CFGBlock *B = cfg->getIndirectGotoBlock())
1668 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1669 E = AddressTakenLabels.end(); I != E; ++I ) {
1670 // Lookup the target block.
1671 LabelMapTy::iterator LI = LabelMap.find(*I);
1673 // If there is no target block that contains label, then we are looking
1674 // at an incomplete AST. Handle this by not registering a successor.
1675 if (LI == LabelMap.end()) continue;
1677 addSuccessor(B, LI->second.block);
1680 // Create an empty entry block that has no predecessors.
1681 cfg->setEntry(createBlock());
1683 if (BuildOpts.AddRichCXXConstructors)
1684 assert(ConstructionContextMap.empty() &&
1685 "Not all construction contexts were cleaned up!");
1687 return std::move(cfg);
1690 /// createBlock - Used to lazily create blocks that are connected
1691 /// to the current (global) successor.
1692 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1693 CFGBlock *B = cfg->createBlock();
1694 if (add_successor && Succ)
1695 addSuccessor(B, Succ);
1696 return B;
1699 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1700 /// CFG. It is *not* connected to the current (global) successor, and instead
1701 /// directly tied to the exit block in order to be reachable.
1702 CFGBlock *CFGBuilder::createNoReturnBlock() {
1703 CFGBlock *B = createBlock(false);
1704 B->setHasNoReturnElement();
1705 addSuccessor(B, &cfg->getExit(), Succ);
1706 return B;
1709 /// addInitializer - Add C++ base or member initializer element to CFG.
1710 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
1711 if (!BuildOpts.AddInitializers)
1712 return Block;
1714 bool HasTemporaries = false;
1716 // Destructors of temporaries in initialization expression should be called
1717 // after initialization finishes.
1718 Expr *Init = I->getInit();
1719 if (Init) {
1720 HasTemporaries = isa<ExprWithCleanups>(Init);
1722 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1723 // Generate destructors for temporaries in initialization expression.
1724 TempDtorContext Context;
1725 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1726 /*ExternallyDestructed=*/false, Context);
1730 autoCreateBlock();
1731 appendInitializer(Block, I);
1733 if (Init) {
1734 // If the initializer is an ArrayInitLoopExpr, we want to extract the
1735 // initializer, that's used for each element.
1736 auto *AILEInit = extractElementInitializerFromNestedAILE(
1737 dyn_cast<ArrayInitLoopExpr>(Init));
1739 findConstructionContexts(
1740 ConstructionContextLayer::create(cfg->getBumpVectorContext(), I),
1741 AILEInit ? AILEInit : Init);
1743 if (HasTemporaries) {
1744 // For expression with temporaries go directly to subexpression to omit
1745 // generating destructors for the second time.
1746 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1748 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1749 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1750 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1751 // may cause the same Expr to appear more than once in the CFG. Doing it
1752 // here is safe because there's only one initializer per field.
1753 autoCreateBlock();
1754 appendStmt(Block, Default);
1755 if (Stmt *Child = Default->getExpr())
1756 if (CFGBlock *R = Visit(Child))
1757 Block = R;
1758 return Block;
1761 return Visit(Init);
1764 return Block;
1767 /// Retrieve the type of the temporary object whose lifetime was
1768 /// extended by a local reference with the given initializer.
1769 static QualType getReferenceInitTemporaryType(const Expr *Init,
1770 bool *FoundMTE = nullptr) {
1771 while (true) {
1772 // Skip parentheses.
1773 Init = Init->IgnoreParens();
1775 // Skip through cleanups.
1776 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1777 Init = EWC->getSubExpr();
1778 continue;
1781 // Skip through the temporary-materialization expression.
1782 if (const MaterializeTemporaryExpr *MTE
1783 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1784 Init = MTE->getSubExpr();
1785 if (FoundMTE)
1786 *FoundMTE = true;
1787 continue;
1790 // Skip sub-object accesses into rvalues.
1791 SmallVector<const Expr *, 2> CommaLHSs;
1792 SmallVector<SubobjectAdjustment, 2> Adjustments;
1793 const Expr *SkippedInit =
1794 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1795 if (SkippedInit != Init) {
1796 Init = SkippedInit;
1797 continue;
1800 break;
1803 return Init->getType();
1806 // TODO: Support adding LoopExit element to the CFG in case where the loop is
1807 // ended by ReturnStmt, GotoStmt or ThrowExpr.
1808 void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1809 if(!BuildOpts.AddLoopExit)
1810 return;
1811 autoCreateBlock();
1812 appendLoopExit(Block, LoopStmt);
1815 /// Adds the CFG elements for leaving the scope of automatic objects in
1816 /// range [B, E). This include following:
1817 /// * AutomaticObjectDtor for variables with non-trivial destructor
1818 /// * LifetimeEnds for all variables
1819 /// * ScopeEnd for each scope left
1820 void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1821 LocalScope::const_iterator E,
1822 Stmt *S) {
1823 if (!BuildOpts.AddScopes && !BuildOpts.AddImplicitDtors &&
1824 !BuildOpts.AddLifetime)
1825 return;
1827 if (B == E)
1828 return;
1830 // Not leaving the scope, only need to handle destruction and lifetime
1831 if (B.inSameLocalScope(E)) {
1832 addAutomaticObjDestruction(B, E, S);
1833 return;
1836 // Extract information about all local scopes that are left
1837 SmallVector<LocalScope::const_iterator, 10> LocalScopeEndMarkers;
1838 LocalScopeEndMarkers.push_back(B);
1839 for (LocalScope::const_iterator I = B; I != E; ++I) {
1840 if (!I.inSameLocalScope(LocalScopeEndMarkers.back()))
1841 LocalScopeEndMarkers.push_back(I);
1843 LocalScopeEndMarkers.push_back(E);
1845 // We need to leave the scope in reverse order, so we reverse the end
1846 // markers
1847 std::reverse(LocalScopeEndMarkers.begin(), LocalScopeEndMarkers.end());
1848 auto Pairwise =
1849 llvm::zip(LocalScopeEndMarkers, llvm::drop_begin(LocalScopeEndMarkers));
1850 for (auto [E, B] : Pairwise) {
1851 if (!B.inSameLocalScope(E))
1852 addScopeExitHandling(B, E, S);
1853 addAutomaticObjDestruction(B, E, S);
1857 /// Add CFG elements corresponding to call destructor and end of lifetime
1858 /// of all automatic variables with non-trivial destructor in range [B, E).
1859 /// This include AutomaticObjectDtor and LifetimeEnds elements.
1860 void CFGBuilder::addAutomaticObjDestruction(LocalScope::const_iterator B,
1861 LocalScope::const_iterator E,
1862 Stmt *S) {
1863 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
1864 return;
1866 if (B == E)
1867 return;
1869 SmallVector<VarDecl *, 10> DeclsNeedDestruction;
1870 DeclsNeedDestruction.reserve(B.distance(E));
1872 for (VarDecl* D : llvm::make_range(B, E))
1873 if (needsAutomaticDestruction(D))
1874 DeclsNeedDestruction.push_back(D);
1876 for (VarDecl *VD : llvm::reverse(DeclsNeedDestruction)) {
1877 if (BuildOpts.AddImplicitDtors) {
1878 // If this destructor is marked as a no-return destructor, we need to
1879 // create a new block for the destructor which does not have as a
1880 // successor anything built thus far: control won't flow out of this
1881 // block.
1882 QualType Ty = VD->getType();
1883 if (Ty->isReferenceType())
1884 Ty = getReferenceInitTemporaryType(VD->getInit());
1885 Ty = Context->getBaseElementType(Ty);
1887 const CXXRecordDecl *CRD = Ty->getAsCXXRecordDecl();
1888 if (CRD && CRD->isAnyDestructorNoReturn())
1889 Block = createNoReturnBlock();
1892 autoCreateBlock();
1894 // Add LifetimeEnd after automatic obj with non-trivial destructors,
1895 // as they end their lifetime when the destructor returns. For trivial
1896 // objects, we end lifetime with scope end.
1897 if (BuildOpts.AddLifetime)
1898 appendLifetimeEnds(Block, VD, S);
1899 if (BuildOpts.AddImplicitDtors && !hasTrivialDestructor(VD))
1900 appendAutomaticObjDtor(Block, VD, S);
1901 if (VD->hasAttr<CleanupAttr>())
1902 appendCleanupFunction(Block, VD);
1906 /// Add CFG elements corresponding to leaving a scope.
1907 /// Assumes that range [B, E) corresponds to single scope.
1908 /// This add following elements:
1909 /// * LifetimeEnds for all variables with non-trivial destructor
1910 /// * ScopeEnd for each scope left
1911 void CFGBuilder::addScopeExitHandling(LocalScope::const_iterator B,
1912 LocalScope::const_iterator E, Stmt *S) {
1913 assert(!B.inSameLocalScope(E));
1914 if (!BuildOpts.AddLifetime && !BuildOpts.AddScopes)
1915 return;
1917 if (BuildOpts.AddScopes) {
1918 autoCreateBlock();
1919 appendScopeEnd(Block, B.getFirstVarInScope(), S);
1922 if (!BuildOpts.AddLifetime)
1923 return;
1925 // We need to perform the scope leaving in reverse order
1926 SmallVector<VarDecl *, 10> DeclsTrivial;
1927 DeclsTrivial.reserve(B.distance(E));
1929 // Objects with trivial destructor ends their lifetime when their storage
1930 // is destroyed, for automatic variables, this happens when the end of the
1931 // scope is added.
1932 for (VarDecl* D : llvm::make_range(B, E))
1933 if (!needsAutomaticDestruction(D))
1934 DeclsTrivial.push_back(D);
1936 if (DeclsTrivial.empty())
1937 return;
1939 autoCreateBlock();
1940 for (VarDecl *VD : llvm::reverse(DeclsTrivial))
1941 appendLifetimeEnds(Block, VD, S);
1944 /// addScopeChangesHandling - appends information about destruction, lifetime
1945 /// and cfgScopeEnd for variables in the scope that was left by the jump, and
1946 /// appends cfgScopeBegin for all scopes that where entered.
1947 /// We insert the cfgScopeBegin at the end of the jump node, as depending on
1948 /// the sourceBlock, each goto, may enter different amount of scopes.
1949 void CFGBuilder::addScopeChangesHandling(LocalScope::const_iterator SrcPos,
1950 LocalScope::const_iterator DstPos,
1951 Stmt *S) {
1952 assert(Block && "Source block should be always crated");
1953 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1954 !BuildOpts.AddScopes) {
1955 return;
1958 if (SrcPos == DstPos)
1959 return;
1961 // Get common scope, the jump leaves all scopes [SrcPos, BasePos), and
1962 // enter all scopes between [DstPos, BasePos)
1963 LocalScope::const_iterator BasePos = SrcPos.shared_parent(DstPos);
1965 // Append scope begins for scopes entered by goto
1966 if (BuildOpts.AddScopes && !DstPos.inSameLocalScope(BasePos)) {
1967 for (LocalScope::const_iterator I = DstPos; I != BasePos; ++I)
1968 if (I.pointsToFirstDeclaredVar())
1969 appendScopeBegin(Block, *I, S);
1972 // Append scopeEnds, destructor and lifetime with the terminator for
1973 // block left by goto.
1974 addAutomaticObjHandling(SrcPos, BasePos, S);
1977 /// createScopeChangesHandlingBlock - Creates a block with cfgElements
1978 /// corresponding to changing the scope from the source scope of the GotoStmt,
1979 /// to destination scope. Add destructor, lifetime and cfgScopeEnd
1980 /// CFGElements to newly created CFGBlock, that will have the CFG terminator
1981 /// transferred.
1982 CFGBlock *CFGBuilder::createScopeChangesHandlingBlock(
1983 LocalScope::const_iterator SrcPos, CFGBlock *SrcBlk,
1984 LocalScope::const_iterator DstPos, CFGBlock *DstBlk) {
1985 if (SrcPos == DstPos)
1986 return DstBlk;
1988 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1989 (!BuildOpts.AddScopes || SrcPos.inSameLocalScope(DstPos)))
1990 return DstBlk;
1992 // We will update CFBBuilder when creating new block, restore the
1993 // previous state at exit.
1994 SaveAndRestore save_Block(Block), save_Succ(Succ);
1996 // Create a new block, and transfer terminator
1997 Block = createBlock(false);
1998 Block->setTerminator(SrcBlk->getTerminator());
1999 SrcBlk->setTerminator(CFGTerminator());
2000 addSuccessor(Block, DstBlk);
2002 // Fill the created Block with the required elements.
2003 addScopeChangesHandling(SrcPos, DstPos, Block->getTerminatorStmt());
2005 assert(Block && "There should be at least one scope changing Block");
2006 return Block;
2009 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
2010 /// base and member objects in destructor.
2011 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
2012 assert(BuildOpts.AddImplicitDtors &&
2013 "Can be called only when dtors should be added");
2014 const CXXRecordDecl *RD = DD->getParent();
2016 // At the end destroy virtual base objects.
2017 for (const auto &VI : RD->vbases()) {
2018 // TODO: Add a VirtualBaseBranch to see if the most derived class
2019 // (which is different from the current class) is responsible for
2020 // destroying them.
2021 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
2022 if (CD && !CD->hasTrivialDestructor()) {
2023 autoCreateBlock();
2024 appendBaseDtor(Block, &VI);
2028 // Before virtual bases destroy direct base objects.
2029 for (const auto &BI : RD->bases()) {
2030 if (!BI.isVirtual()) {
2031 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
2032 if (CD && !CD->hasTrivialDestructor()) {
2033 autoCreateBlock();
2034 appendBaseDtor(Block, &BI);
2039 // First destroy member objects.
2040 for (auto *FI : RD->fields()) {
2041 // Check for constant size array. Set type to array element type.
2042 QualType QT = FI->getType();
2043 // It may be a multidimensional array.
2044 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
2045 if (AT->getSize() == 0)
2046 break;
2047 QT = AT->getElementType();
2050 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
2051 if (!CD->hasTrivialDestructor()) {
2052 autoCreateBlock();
2053 appendMemberDtor(Block, FI);
2058 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
2059 /// way return valid LocalScope object.
2060 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
2061 if (Scope)
2062 return Scope;
2063 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
2064 return new (alloc) LocalScope(BumpVectorContext(alloc), ScopePos);
2067 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
2068 /// that should create implicit scope (e.g. if/else substatements).
2069 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
2070 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2071 !BuildOpts.AddScopes)
2072 return;
2074 LocalScope *Scope = nullptr;
2076 // For compound statement we will be creating explicit scope.
2077 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
2078 for (auto *BI : CS->body()) {
2079 Stmt *SI = BI->stripLabelLikeStatements();
2080 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
2081 Scope = addLocalScopeForDeclStmt(DS, Scope);
2083 return;
2086 // For any other statement scope will be implicit and as such will be
2087 // interesting only for DeclStmt.
2088 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
2089 addLocalScopeForDeclStmt(DS);
2092 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
2093 /// reuse Scope if not NULL.
2094 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
2095 LocalScope* Scope) {
2096 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2097 !BuildOpts.AddScopes)
2098 return Scope;
2100 for (auto *DI : DS->decls())
2101 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
2102 Scope = addLocalScopeForVarDecl(VD, Scope);
2103 return Scope;
2106 bool CFGBuilder::needsAutomaticDestruction(const VarDecl *VD) const {
2107 return !hasTrivialDestructor(VD) || VD->hasAttr<CleanupAttr>();
2110 bool CFGBuilder::hasTrivialDestructor(const VarDecl *VD) const {
2111 // Check for const references bound to temporary. Set type to pointee.
2112 QualType QT = VD->getType();
2113 if (QT->isReferenceType()) {
2114 // Attempt to determine whether this declaration lifetime-extends a
2115 // temporary.
2117 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
2118 // temporaries, and a single declaration can extend multiple temporaries.
2119 // We should look at the storage duration on each nested
2120 // MaterializeTemporaryExpr instead.
2122 const Expr *Init = VD->getInit();
2123 if (!Init) {
2124 // Probably an exception catch-by-reference variable.
2125 // FIXME: It doesn't really mean that the object has a trivial destructor.
2126 // Also are there other cases?
2127 return true;
2130 // Lifetime-extending a temporary?
2131 bool FoundMTE = false;
2132 QT = getReferenceInitTemporaryType(Init, &FoundMTE);
2133 if (!FoundMTE)
2134 return true;
2137 // Check for constant size array. Set type to array element type.
2138 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
2139 if (AT->getSize() == 0)
2140 return true;
2141 QT = AT->getElementType();
2144 // Check if type is a C++ class with non-trivial destructor.
2145 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
2146 return !CD->hasDefinition() || CD->hasTrivialDestructor();
2147 return true;
2150 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
2151 /// create add scope for automatic objects and temporary objects bound to
2152 /// const reference. Will reuse Scope if not NULL.
2153 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
2154 LocalScope* Scope) {
2155 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2156 !BuildOpts.AddScopes)
2157 return Scope;
2159 // Check if variable is local.
2160 if (!VD->hasLocalStorage())
2161 return Scope;
2163 if (!BuildOpts.AddLifetime && !BuildOpts.AddScopes &&
2164 !needsAutomaticDestruction(VD)) {
2165 assert(BuildOpts.AddImplicitDtors);
2166 return Scope;
2169 // Add the variable to scope
2170 Scope = createOrReuseLocalScope(Scope);
2171 Scope->addVar(VD);
2172 ScopePos = Scope->begin();
2173 return Scope;
2176 /// addLocalScopeAndDtors - For given statement add local scope for it and
2177 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
2178 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
2179 LocalScope::const_iterator scopeBeginPos = ScopePos;
2180 addLocalScopeForStmt(S);
2181 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
2184 /// Visit - Walk the subtree of a statement and add extra
2185 /// blocks for ternary operators, &&, and ||. We also process "," and
2186 /// DeclStmts (which may contain nested control-flow).
2187 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
2188 bool ExternallyDestructed) {
2189 if (!S) {
2190 badCFG = true;
2191 return nullptr;
2194 if (Expr *E = dyn_cast<Expr>(S))
2195 S = E->IgnoreParens();
2197 if (Context->getLangOpts().OpenMP)
2198 if (auto *D = dyn_cast<OMPExecutableDirective>(S))
2199 return VisitOMPExecutableDirective(D, asc);
2201 switch (S->getStmtClass()) {
2202 default:
2203 return VisitStmt(S, asc);
2205 case Stmt::ImplicitValueInitExprClass:
2206 if (BuildOpts.OmitImplicitValueInitializers)
2207 return Block;
2208 return VisitStmt(S, asc);
2210 case Stmt::InitListExprClass:
2211 return VisitInitListExpr(cast<InitListExpr>(S), asc);
2213 case Stmt::AttributedStmtClass:
2214 return VisitAttributedStmt(cast<AttributedStmt>(S), asc);
2216 case Stmt::AddrLabelExprClass:
2217 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
2219 case Stmt::BinaryConditionalOperatorClass:
2220 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
2222 case Stmt::BinaryOperatorClass:
2223 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
2225 case Stmt::BlockExprClass:
2226 return VisitBlockExpr(cast<BlockExpr>(S), asc);
2228 case Stmt::BreakStmtClass:
2229 return VisitBreakStmt(cast<BreakStmt>(S));
2231 case Stmt::CallExprClass:
2232 case Stmt::CXXOperatorCallExprClass:
2233 case Stmt::CXXMemberCallExprClass:
2234 case Stmt::UserDefinedLiteralClass:
2235 return VisitCallExpr(cast<CallExpr>(S), asc);
2237 case Stmt::CaseStmtClass:
2238 return VisitCaseStmt(cast<CaseStmt>(S));
2240 case Stmt::ChooseExprClass:
2241 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
2243 case Stmt::CompoundStmtClass:
2244 return VisitCompoundStmt(cast<CompoundStmt>(S), ExternallyDestructed);
2246 case Stmt::ConditionalOperatorClass:
2247 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
2249 case Stmt::ContinueStmtClass:
2250 return VisitContinueStmt(cast<ContinueStmt>(S));
2252 case Stmt::CXXCatchStmtClass:
2253 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
2255 case Stmt::ExprWithCleanupsClass:
2256 return VisitExprWithCleanups(cast<ExprWithCleanups>(S),
2257 asc, ExternallyDestructed);
2259 case Stmt::CXXDefaultArgExprClass:
2260 case Stmt::CXXDefaultInitExprClass:
2261 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
2262 // called function's declaration, not by the caller. If we simply add
2263 // this expression to the CFG, we could end up with the same Expr
2264 // appearing multiple times (PR13385).
2266 // It's likewise possible for multiple CXXDefaultInitExprs for the same
2267 // expression to be used in the same function (through aggregate
2268 // initialization).
2269 return VisitStmt(S, asc);
2271 case Stmt::CXXBindTemporaryExprClass:
2272 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
2274 case Stmt::CXXConstructExprClass:
2275 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
2277 case Stmt::CXXNewExprClass:
2278 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
2280 case Stmt::CXXDeleteExprClass:
2281 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
2283 case Stmt::CXXFunctionalCastExprClass:
2284 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
2286 case Stmt::CXXTemporaryObjectExprClass:
2287 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
2289 case Stmt::CXXThrowExprClass:
2290 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
2292 case Stmt::CXXTryStmtClass:
2293 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
2295 case Stmt::CXXTypeidExprClass:
2296 return VisitCXXTypeidExpr(cast<CXXTypeidExpr>(S), asc);
2298 case Stmt::CXXForRangeStmtClass:
2299 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
2301 case Stmt::DeclStmtClass:
2302 return VisitDeclStmt(cast<DeclStmt>(S));
2304 case Stmt::DefaultStmtClass:
2305 return VisitDefaultStmt(cast<DefaultStmt>(S));
2307 case Stmt::DoStmtClass:
2308 return VisitDoStmt(cast<DoStmt>(S));
2310 case Stmt::ForStmtClass:
2311 return VisitForStmt(cast<ForStmt>(S));
2313 case Stmt::GotoStmtClass:
2314 return VisitGotoStmt(cast<GotoStmt>(S));
2316 case Stmt::GCCAsmStmtClass:
2317 return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc);
2319 case Stmt::IfStmtClass:
2320 return VisitIfStmt(cast<IfStmt>(S));
2322 case Stmt::ImplicitCastExprClass:
2323 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
2325 case Stmt::ConstantExprClass:
2326 return VisitConstantExpr(cast<ConstantExpr>(S), asc);
2328 case Stmt::IndirectGotoStmtClass:
2329 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
2331 case Stmt::LabelStmtClass:
2332 return VisitLabelStmt(cast<LabelStmt>(S));
2334 case Stmt::LambdaExprClass:
2335 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
2337 case Stmt::MaterializeTemporaryExprClass:
2338 return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
2339 asc);
2341 case Stmt::MemberExprClass:
2342 return VisitMemberExpr(cast<MemberExpr>(S), asc);
2344 case Stmt::NullStmtClass:
2345 return Block;
2347 case Stmt::ObjCAtCatchStmtClass:
2348 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
2350 case Stmt::ObjCAutoreleasePoolStmtClass:
2351 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
2353 case Stmt::ObjCAtSynchronizedStmtClass:
2354 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
2356 case Stmt::ObjCAtThrowStmtClass:
2357 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
2359 case Stmt::ObjCAtTryStmtClass:
2360 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
2362 case Stmt::ObjCForCollectionStmtClass:
2363 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
2365 case Stmt::ObjCMessageExprClass:
2366 return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc);
2368 case Stmt::OpaqueValueExprClass:
2369 return Block;
2371 case Stmt::PseudoObjectExprClass:
2372 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
2374 case Stmt::ReturnStmtClass:
2375 case Stmt::CoreturnStmtClass:
2376 return VisitReturnStmt(S);
2378 case Stmt::CoyieldExprClass:
2379 case Stmt::CoawaitExprClass:
2380 return VisitCoroutineSuspendExpr(cast<CoroutineSuspendExpr>(S), asc);
2382 case Stmt::SEHExceptStmtClass:
2383 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
2385 case Stmt::SEHFinallyStmtClass:
2386 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
2388 case Stmt::SEHLeaveStmtClass:
2389 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
2391 case Stmt::SEHTryStmtClass:
2392 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
2394 case Stmt::UnaryExprOrTypeTraitExprClass:
2395 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
2396 asc);
2398 case Stmt::StmtExprClass:
2399 return VisitStmtExpr(cast<StmtExpr>(S), asc);
2401 case Stmt::SwitchStmtClass:
2402 return VisitSwitchStmt(cast<SwitchStmt>(S));
2404 case Stmt::UnaryOperatorClass:
2405 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
2407 case Stmt::WhileStmtClass:
2408 return VisitWhileStmt(cast<WhileStmt>(S));
2410 case Stmt::ArrayInitLoopExprClass:
2411 return VisitArrayInitLoopExpr(cast<ArrayInitLoopExpr>(S), asc);
2415 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
2416 if (asc.alwaysAdd(*this, S)) {
2417 autoCreateBlock();
2418 appendStmt(Block, S);
2421 return VisitChildren(S);
2424 /// VisitChildren - Visit the children of a Stmt.
2425 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
2426 CFGBlock *B = Block;
2428 // Visit the children in their reverse order so that they appear in
2429 // left-to-right (natural) order in the CFG.
2430 reverse_children RChildren(S);
2431 for (Stmt *Child : RChildren) {
2432 if (Child)
2433 if (CFGBlock *R = Visit(Child))
2434 B = R;
2436 return B;
2439 CFGBlock *CFGBuilder::VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc) {
2440 if (asc.alwaysAdd(*this, ILE)) {
2441 autoCreateBlock();
2442 appendStmt(Block, ILE);
2444 CFGBlock *B = Block;
2446 reverse_children RChildren(ILE);
2447 for (Stmt *Child : RChildren) {
2448 if (!Child)
2449 continue;
2450 if (CFGBlock *R = Visit(Child))
2451 B = R;
2452 if (BuildOpts.AddCXXDefaultInitExprInAggregates) {
2453 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Child))
2454 if (Stmt *Child = DIE->getExpr())
2455 if (CFGBlock *R = Visit(Child))
2456 B = R;
2459 return B;
2462 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
2463 AddStmtChoice asc) {
2464 AddressTakenLabels.insert(A->getLabel());
2466 if (asc.alwaysAdd(*this, A)) {
2467 autoCreateBlock();
2468 appendStmt(Block, A);
2471 return Block;
2474 static bool isFallthroughStatement(const AttributedStmt *A) {
2475 bool isFallthrough = hasSpecificAttr<FallThroughAttr>(A->getAttrs());
2476 assert((!isFallthrough || isa<NullStmt>(A->getSubStmt())) &&
2477 "expected fallthrough not to have children");
2478 return isFallthrough;
2481 CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt *A,
2482 AddStmtChoice asc) {
2483 // AttributedStmts for [[likely]] can have arbitrary statements as children,
2484 // and the current visitation order here would add the AttributedStmts
2485 // for [[likely]] after the child nodes, which is undesirable: For example,
2486 // if the child contains an unconditional return, the [[likely]] would be
2487 // considered unreachable.
2488 // So only add the AttributedStmt for FallThrough, which has CFG effects and
2489 // also no children, and omit the others. None of the other current StmtAttrs
2490 // have semantic meaning for the CFG.
2491 if (isFallthroughStatement(A) && asc.alwaysAdd(*this, A)) {
2492 autoCreateBlock();
2493 appendStmt(Block, A);
2496 return VisitChildren(A);
2499 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc) {
2500 if (asc.alwaysAdd(*this, U)) {
2501 autoCreateBlock();
2502 appendStmt(Block, U);
2505 if (U->getOpcode() == UO_LNot)
2506 tryEvaluateBool(U->getSubExpr()->IgnoreParens());
2508 return Visit(U->getSubExpr(), AddStmtChoice());
2511 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
2512 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2513 appendStmt(ConfluenceBlock, B);
2515 if (badCFG)
2516 return nullptr;
2518 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
2519 ConfluenceBlock).first;
2522 std::pair<CFGBlock*, CFGBlock*>
2523 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
2524 Stmt *Term,
2525 CFGBlock *TrueBlock,
2526 CFGBlock *FalseBlock) {
2527 // Introspect the RHS. If it is a nested logical operation, we recursively
2528 // build the CFG using this function. Otherwise, resort to default
2529 // CFG construction behavior.
2530 Expr *RHS = B->getRHS()->IgnoreParens();
2531 CFGBlock *RHSBlock, *ExitBlock;
2533 do {
2534 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
2535 if (B_RHS->isLogicalOp()) {
2536 std::tie(RHSBlock, ExitBlock) =
2537 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
2538 break;
2541 // The RHS is not a nested logical operation. Don't push the terminator
2542 // down further, but instead visit RHS and construct the respective
2543 // pieces of the CFG, and link up the RHSBlock with the terminator
2544 // we have been provided.
2545 ExitBlock = RHSBlock = createBlock(false);
2547 // Even though KnownVal is only used in the else branch of the next
2548 // conditional, tryEvaluateBool performs additional checking on the
2549 // Expr, so it should be called unconditionally.
2550 TryResult KnownVal = tryEvaluateBool(RHS);
2551 if (!KnownVal.isKnown())
2552 KnownVal = tryEvaluateBool(B);
2554 if (!Term) {
2555 assert(TrueBlock == FalseBlock);
2556 addSuccessor(RHSBlock, TrueBlock);
2558 else {
2559 RHSBlock->setTerminator(Term);
2560 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
2561 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
2564 Block = RHSBlock;
2565 RHSBlock = addStmt(RHS);
2567 while (false);
2569 if (badCFG)
2570 return std::make_pair(nullptr, nullptr);
2572 // Generate the blocks for evaluating the LHS.
2573 Expr *LHS = B->getLHS()->IgnoreParens();
2575 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
2576 if (B_LHS->isLogicalOp()) {
2577 if (B->getOpcode() == BO_LOr)
2578 FalseBlock = RHSBlock;
2579 else
2580 TrueBlock = RHSBlock;
2582 // For the LHS, treat 'B' as the terminator that we want to sink
2583 // into the nested branch. The RHS always gets the top-most
2584 // terminator.
2585 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
2588 // Create the block evaluating the LHS.
2589 // This contains the '&&' or '||' as the terminator.
2590 CFGBlock *LHSBlock = createBlock(false);
2591 LHSBlock->setTerminator(B);
2593 Block = LHSBlock;
2594 CFGBlock *EntryLHSBlock = addStmt(LHS);
2596 if (badCFG)
2597 return std::make_pair(nullptr, nullptr);
2599 // See if this is a known constant.
2600 TryResult KnownVal = tryEvaluateBool(LHS);
2602 // Now link the LHSBlock with RHSBlock.
2603 if (B->getOpcode() == BO_LOr) {
2604 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2605 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
2606 } else {
2607 assert(B->getOpcode() == BO_LAnd);
2608 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2609 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
2612 return std::make_pair(EntryLHSBlock, ExitBlock);
2615 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2616 AddStmtChoice asc) {
2617 // && or ||
2618 if (B->isLogicalOp())
2619 return VisitLogicalOperator(B);
2621 if (B->getOpcode() == BO_Comma) { // ,
2622 autoCreateBlock();
2623 appendStmt(Block, B);
2624 addStmt(B->getRHS());
2625 return addStmt(B->getLHS());
2628 if (B->isAssignmentOp()) {
2629 if (asc.alwaysAdd(*this, B)) {
2630 autoCreateBlock();
2631 appendStmt(Block, B);
2633 Visit(B->getLHS());
2634 return Visit(B->getRHS());
2637 if (asc.alwaysAdd(*this, B)) {
2638 autoCreateBlock();
2639 appendStmt(Block, B);
2642 if (B->isEqualityOp() || B->isRelationalOp())
2643 tryEvaluateBool(B);
2645 CFGBlock *RBlock = Visit(B->getRHS());
2646 CFGBlock *LBlock = Visit(B->getLHS());
2647 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2648 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2649 // return RBlock. Otherwise we'll incorrectly return NULL.
2650 return (LBlock ? LBlock : RBlock);
2653 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
2654 if (asc.alwaysAdd(*this, E)) {
2655 autoCreateBlock();
2656 appendStmt(Block, E);
2658 return Block;
2661 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2662 // "break" is a control-flow statement. Thus we stop processing the current
2663 // block.
2664 if (badCFG)
2665 return nullptr;
2667 // Now create a new block that ends with the break statement.
2668 Block = createBlock(false);
2669 Block->setTerminator(B);
2671 // If there is no target for the break, then we are looking at an incomplete
2672 // AST. This means that the CFG cannot be constructed.
2673 if (BreakJumpTarget.block) {
2674 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
2675 addSuccessor(Block, BreakJumpTarget.block);
2676 } else
2677 badCFG = true;
2679 return Block;
2682 static bool CanThrow(Expr *E, ASTContext &Ctx) {
2683 QualType Ty = E->getType();
2684 if (Ty->isFunctionPointerType() || Ty->isBlockPointerType())
2685 Ty = Ty->getPointeeType();
2687 const FunctionType *FT = Ty->getAs<FunctionType>();
2688 if (FT) {
2689 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
2690 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
2691 Proto->isNothrow())
2692 return false;
2694 return true;
2697 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
2698 // Compute the callee type.
2699 QualType calleeType = C->getCallee()->getType();
2700 if (calleeType == Context->BoundMemberTy) {
2701 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2703 // We should only get a null bound type if processing a dependent
2704 // CFG. Recover by assuming nothing.
2705 if (!boundType.isNull()) calleeType = boundType;
2708 // If this is a call to a no-return function, this stops the block here.
2709 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2711 bool AddEHEdge = false;
2713 // Languages without exceptions are assumed to not throw.
2714 if (Context->getLangOpts().Exceptions) {
2715 if (BuildOpts.AddEHEdges)
2716 AddEHEdge = true;
2719 // If this is a call to a builtin function, it might not actually evaluate
2720 // its arguments. Don't add them to the CFG if this is the case.
2721 bool OmitArguments = false;
2723 if (FunctionDecl *FD = C->getDirectCallee()) {
2724 // TODO: Support construction contexts for variadic function arguments.
2725 // These are a bit problematic and not very useful because passing
2726 // C++ objects as C-style variadic arguments doesn't work in general
2727 // (see [expr.call]).
2728 if (!FD->isVariadic())
2729 findConstructionContextsForArguments(C);
2731 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
2732 NoReturn = true;
2733 if (FD->hasAttr<NoThrowAttr>())
2734 AddEHEdge = false;
2735 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size ||
2736 FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size)
2737 OmitArguments = true;
2740 if (!CanThrow(C->getCallee(), *Context))
2741 AddEHEdge = false;
2743 if (OmitArguments) {
2744 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2745 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2746 autoCreateBlock();
2747 appendStmt(Block, C);
2748 return Visit(C->getCallee());
2751 if (!NoReturn && !AddEHEdge) {
2752 autoCreateBlock();
2753 appendCall(Block, C);
2755 return VisitChildren(C);
2758 if (Block) {
2759 Succ = Block;
2760 if (badCFG)
2761 return nullptr;
2764 if (NoReturn)
2765 Block = createNoReturnBlock();
2766 else
2767 Block = createBlock();
2769 appendCall(Block, C);
2771 if (AddEHEdge) {
2772 // Add exceptional edges.
2773 if (TryTerminatedBlock)
2774 addSuccessor(Block, TryTerminatedBlock);
2775 else
2776 addSuccessor(Block, &cfg->getExit());
2779 return VisitChildren(C);
2782 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2783 AddStmtChoice asc) {
2784 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2785 appendStmt(ConfluenceBlock, C);
2786 if (badCFG)
2787 return nullptr;
2789 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2790 Succ = ConfluenceBlock;
2791 Block = nullptr;
2792 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
2793 if (badCFG)
2794 return nullptr;
2796 Succ = ConfluenceBlock;
2797 Block = nullptr;
2798 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
2799 if (badCFG)
2800 return nullptr;
2802 Block = createBlock(false);
2803 // See if this is a known constant.
2804 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2805 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2806 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
2807 Block->setTerminator(C);
2808 return addStmt(C->getCond());
2811 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C,
2812 bool ExternallyDestructed) {
2813 LocalScope::const_iterator scopeBeginPos = ScopePos;
2814 addLocalScopeForStmt(C);
2816 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
2817 // If the body ends with a ReturnStmt, the dtors will be added in
2818 // VisitReturnStmt.
2819 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
2822 CFGBlock *LastBlock = Block;
2824 for (Stmt *S : llvm::reverse(C->body())) {
2825 // If we hit a segment of code just containing ';' (NullStmts), we can
2826 // get a null block back. In such cases, just use the LastBlock
2827 CFGBlock *newBlock = Visit(S, AddStmtChoice::AlwaysAdd,
2828 ExternallyDestructed);
2830 if (newBlock)
2831 LastBlock = newBlock;
2833 if (badCFG)
2834 return nullptr;
2836 ExternallyDestructed = false;
2839 return LastBlock;
2842 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
2843 AddStmtChoice asc) {
2844 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
2845 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
2847 // Create the confluence block that will "merge" the results of the ternary
2848 // expression.
2849 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2850 appendStmt(ConfluenceBlock, C);
2851 if (badCFG)
2852 return nullptr;
2854 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2856 // Create a block for the LHS expression if there is an LHS expression. A
2857 // GCC extension allows LHS to be NULL, causing the condition to be the
2858 // value that is returned instead.
2859 // e.g: x ?: y is shorthand for: x ? x : y;
2860 Succ = ConfluenceBlock;
2861 Block = nullptr;
2862 CFGBlock *LHSBlock = nullptr;
2863 const Expr *trueExpr = C->getTrueExpr();
2864 if (trueExpr != opaqueValue) {
2865 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
2866 if (badCFG)
2867 return nullptr;
2868 Block = nullptr;
2870 else
2871 LHSBlock = ConfluenceBlock;
2873 // Create the block for the RHS expression.
2874 Succ = ConfluenceBlock;
2875 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
2876 if (badCFG)
2877 return nullptr;
2879 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2880 if (BinaryOperator *Cond =
2881 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2882 if (Cond->isLogicalOp())
2883 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2885 // Create the block that will contain the condition.
2886 Block = createBlock(false);
2888 // See if this is a known constant.
2889 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2890 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2891 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
2892 Block->setTerminator(C);
2893 Expr *condExpr = C->getCond();
2895 if (opaqueValue) {
2896 // Run the condition expression if it's not trivially expressed in
2897 // terms of the opaque value (or if there is no opaque value).
2898 if (condExpr != opaqueValue)
2899 addStmt(condExpr);
2901 // Before that, run the common subexpression if there was one.
2902 // At least one of this or the above will be run.
2903 return addStmt(BCO->getCommon());
2906 return addStmt(condExpr);
2909 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
2910 // Check if the Decl is for an __label__. If so, elide it from the
2911 // CFG entirely.
2912 if (isa<LabelDecl>(*DS->decl_begin()))
2913 return Block;
2915 // This case also handles static_asserts.
2916 if (DS->isSingleDecl())
2917 return VisitDeclSubExpr(DS);
2919 CFGBlock *B = nullptr;
2921 // Build an individual DeclStmt for each decl.
2922 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2923 E = DS->decl_rend();
2924 I != E; ++I) {
2926 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2927 // automatically freed with the CFG.
2928 DeclGroupRef DG(*I);
2929 Decl *D = *I;
2930 DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
2931 cfg->addSyntheticDeclStmt(DSNew, DS);
2933 // Append the fake DeclStmt to block.
2934 B = VisitDeclSubExpr(DSNew);
2937 return B;
2940 /// VisitDeclSubExpr - Utility method to add block-level expressions for
2941 /// DeclStmts and initializers in them.
2942 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
2943 assert(DS->isSingleDecl() && "Can handle single declarations only.");
2945 if (const auto *TND = dyn_cast<TypedefNameDecl>(DS->getSingleDecl())) {
2946 // If we encounter a VLA, process its size expressions.
2947 const Type *T = TND->getUnderlyingType().getTypePtr();
2948 if (!T->isVariablyModifiedType())
2949 return Block;
2951 autoCreateBlock();
2952 appendStmt(Block, DS);
2954 CFGBlock *LastBlock = Block;
2955 for (const VariableArrayType *VA = FindVA(T); VA != nullptr;
2956 VA = FindVA(VA->getElementType().getTypePtr())) {
2957 if (CFGBlock *NewBlock = addStmt(VA->getSizeExpr()))
2958 LastBlock = NewBlock;
2960 return LastBlock;
2963 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
2965 if (!VD) {
2966 // Of everything that can be declared in a DeclStmt, only VarDecls and the
2967 // exceptions above impact runtime semantics.
2968 return Block;
2971 bool HasTemporaries = false;
2973 // Guard static initializers under a branch.
2974 CFGBlock *blockAfterStaticInit = nullptr;
2976 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2977 // For static variables, we need to create a branch to track
2978 // whether or not they are initialized.
2979 if (Block) {
2980 Succ = Block;
2981 Block = nullptr;
2982 if (badCFG)
2983 return nullptr;
2985 blockAfterStaticInit = Succ;
2988 // Destructors of temporaries in initialization expression should be called
2989 // after initialization finishes.
2990 Expr *Init = VD->getInit();
2991 if (Init) {
2992 HasTemporaries = isa<ExprWithCleanups>(Init);
2994 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
2995 // Generate destructors for temporaries in initialization expression.
2996 TempDtorContext Context;
2997 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2998 /*ExternallyDestructed=*/true, Context);
3002 // If we bind to a tuple-like type, we iterate over the HoldingVars, and
3003 // create a DeclStmt for each of them.
3004 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
3005 for (auto *BD : llvm::reverse(DD->bindings())) {
3006 if (auto *VD = BD->getHoldingVar()) {
3007 DeclGroupRef DG(VD);
3008 DeclStmt *DSNew =
3009 new (Context) DeclStmt(DG, VD->getLocation(), GetEndLoc(VD));
3010 cfg->addSyntheticDeclStmt(DSNew, DS);
3011 Block = VisitDeclSubExpr(DSNew);
3016 autoCreateBlock();
3017 appendStmt(Block, DS);
3019 // If the initializer is an ArrayInitLoopExpr, we want to extract the
3020 // initializer, that's used for each element.
3021 const auto *AILE = dyn_cast_or_null<ArrayInitLoopExpr>(Init);
3023 findConstructionContexts(
3024 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
3025 AILE ? AILE->getSubExpr() : Init);
3027 // Keep track of the last non-null block, as 'Block' can be nulled out
3028 // if the initializer expression is something like a 'while' in a
3029 // statement-expression.
3030 CFGBlock *LastBlock = Block;
3032 if (Init) {
3033 if (HasTemporaries) {
3034 // For expression with temporaries go directly to subexpression to omit
3035 // generating destructors for the second time.
3036 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
3037 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
3038 LastBlock = newBlock;
3040 else {
3041 if (CFGBlock *newBlock = Visit(Init))
3042 LastBlock = newBlock;
3046 // If the type of VD is a VLA, then we must process its size expressions.
3047 // FIXME: This does not find the VLA if it is embedded in other types,
3048 // like here: `int (*p_vla)[x];`
3049 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
3050 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
3051 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
3052 LastBlock = newBlock;
3055 maybeAddScopeBeginForVarDecl(Block, VD, DS);
3057 // Remove variable from local scope.
3058 if (ScopePos && VD == *ScopePos)
3059 ++ScopePos;
3061 CFGBlock *B = LastBlock;
3062 if (blockAfterStaticInit) {
3063 Succ = B;
3064 Block = createBlock(false);
3065 Block->setTerminator(DS);
3066 addSuccessor(Block, blockAfterStaticInit);
3067 addSuccessor(Block, B);
3068 B = Block;
3071 return B;
3074 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
3075 // We may see an if statement in the middle of a basic block, or it may be the
3076 // first statement we are processing. In either case, we create a new basic
3077 // block. First, we create the blocks for the then...else statements, and
3078 // then we create the block containing the if statement. If we were in the
3079 // middle of a block, we stop processing that block. That block is then the
3080 // implicit successor for the "then" and "else" clauses.
3082 // Save local scope position because in case of condition variable ScopePos
3083 // won't be restored when traversing AST.
3084 SaveAndRestore save_scope_pos(ScopePos);
3086 // Create local scope for C++17 if init-stmt if one exists.
3087 if (Stmt *Init = I->getInit())
3088 addLocalScopeForStmt(Init);
3090 // Create local scope for possible condition variable.
3091 // Store scope position. Add implicit destructor.
3092 if (VarDecl *VD = I->getConditionVariable())
3093 addLocalScopeForVarDecl(VD);
3095 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
3097 // The block we were processing is now finished. Make it the successor
3098 // block.
3099 if (Block) {
3100 Succ = Block;
3101 if (badCFG)
3102 return nullptr;
3105 // Process the false branch.
3106 CFGBlock *ElseBlock = Succ;
3108 if (Stmt *Else = I->getElse()) {
3109 SaveAndRestore sv(Succ);
3111 // NULL out Block so that the recursive call to Visit will
3112 // create a new basic block.
3113 Block = nullptr;
3115 // If branch is not a compound statement create implicit scope
3116 // and add destructors.
3117 if (!isa<CompoundStmt>(Else))
3118 addLocalScopeAndDtors(Else);
3120 ElseBlock = addStmt(Else);
3122 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
3123 ElseBlock = sv.get();
3124 else if (Block) {
3125 if (badCFG)
3126 return nullptr;
3130 // Process the true branch.
3131 CFGBlock *ThenBlock;
3133 Stmt *Then = I->getThen();
3134 assert(Then);
3135 SaveAndRestore sv(Succ);
3136 Block = nullptr;
3138 // If branch is not a compound statement create implicit scope
3139 // and add destructors.
3140 if (!isa<CompoundStmt>(Then))
3141 addLocalScopeAndDtors(Then);
3143 ThenBlock = addStmt(Then);
3145 if (!ThenBlock) {
3146 // We can reach here if the "then" body has all NullStmts.
3147 // Create an empty block so we can distinguish between true and false
3148 // branches in path-sensitive analyses.
3149 ThenBlock = createBlock(false);
3150 addSuccessor(ThenBlock, sv.get());
3151 } else if (Block) {
3152 if (badCFG)
3153 return nullptr;
3157 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
3158 // having these handle the actual control-flow jump. Note that
3159 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
3160 // we resort to the old control-flow behavior. This special handling
3161 // removes infeasible paths from the control-flow graph by having the
3162 // control-flow transfer of '&&' or '||' go directly into the then/else
3163 // blocks directly.
3164 BinaryOperator *Cond =
3165 (I->isConsteval() || I->getConditionVariable())
3166 ? nullptr
3167 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
3168 CFGBlock *LastBlock;
3169 if (Cond && Cond->isLogicalOp())
3170 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
3171 else {
3172 // Now create a new block containing the if statement.
3173 Block = createBlock(false);
3175 // Set the terminator of the new block to the If statement.
3176 Block->setTerminator(I);
3178 // See if this is a known constant.
3179 TryResult KnownVal;
3180 if (!I->isConsteval())
3181 KnownVal = tryEvaluateBool(I->getCond());
3183 // Add the successors. If we know that specific branches are
3184 // unreachable, inform addSuccessor() of that knowledge.
3185 addSuccessor(Block, ThenBlock, /* IsReachable = */ !KnownVal.isFalse());
3186 addSuccessor(Block, ElseBlock, /* IsReachable = */ !KnownVal.isTrue());
3188 // Add the condition as the last statement in the new block. This may
3189 // create new blocks as the condition may contain control-flow. Any newly
3190 // created blocks will be pointed to be "Block".
3191 LastBlock = addStmt(I->getCond());
3193 // If the IfStmt contains a condition variable, add it and its
3194 // initializer to the CFG.
3195 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
3196 autoCreateBlock();
3197 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
3201 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
3202 if (Stmt *Init = I->getInit()) {
3203 autoCreateBlock();
3204 LastBlock = addStmt(Init);
3207 return LastBlock;
3210 CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
3211 // If we were in the middle of a block we stop processing that block.
3213 // NOTE: If a "return" or "co_return" appears in the middle of a block, this
3214 // means that the code afterwards is DEAD (unreachable). We still keep
3215 // a basic block for that code; a simple "mark-and-sweep" from the entry
3216 // block will be able to report such dead blocks.
3217 assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S));
3219 // Create the new block.
3220 Block = createBlock(false);
3222 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), S);
3224 if (auto *R = dyn_cast<ReturnStmt>(S))
3225 findConstructionContexts(
3226 ConstructionContextLayer::create(cfg->getBumpVectorContext(), R),
3227 R->getRetValue());
3229 // If the one of the destructors does not return, we already have the Exit
3230 // block as a successor.
3231 if (!Block->hasNoReturnElement())
3232 addSuccessor(Block, &cfg->getExit());
3234 // Add the return statement to the block.
3235 appendStmt(Block, S);
3237 // Visit children
3238 if (ReturnStmt *RS = dyn_cast<ReturnStmt>(S)) {
3239 if (Expr *O = RS->getRetValue())
3240 return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true);
3241 return Block;
3244 CoreturnStmt *CRS = cast<CoreturnStmt>(S);
3245 auto *B = Block;
3246 if (CFGBlock *R = Visit(CRS->getPromiseCall()))
3247 B = R;
3249 if (Expr *RV = CRS->getOperand())
3250 if (RV->getType()->isVoidType() && !isa<InitListExpr>(RV))
3251 // A non-initlist void expression.
3252 if (CFGBlock *R = Visit(RV))
3253 B = R;
3255 return B;
3258 CFGBlock *CFGBuilder::VisitCoroutineSuspendExpr(CoroutineSuspendExpr *E,
3259 AddStmtChoice asc) {
3260 // We're modelling the pre-coro-xform CFG. Thus just evalate the various
3261 // active components of the co_await or co_yield. Note we do not model the
3262 // edge from the builtin_suspend to the exit node.
3263 if (asc.alwaysAdd(*this, E)) {
3264 autoCreateBlock();
3265 appendStmt(Block, E);
3267 CFGBlock *B = Block;
3268 if (auto *R = Visit(E->getResumeExpr()))
3269 B = R;
3270 if (auto *R = Visit(E->getSuspendExpr()))
3271 B = R;
3272 if (auto *R = Visit(E->getReadyExpr()))
3273 B = R;
3274 if (auto *R = Visit(E->getCommonExpr()))
3275 B = R;
3276 return B;
3279 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
3280 // SEHExceptStmt are treated like labels, so they are the first statement in a
3281 // block.
3283 // Save local scope position because in case of exception variable ScopePos
3284 // won't be restored when traversing AST.
3285 SaveAndRestore save_scope_pos(ScopePos);
3287 addStmt(ES->getBlock());
3288 CFGBlock *SEHExceptBlock = Block;
3289 if (!SEHExceptBlock)
3290 SEHExceptBlock = createBlock();
3292 appendStmt(SEHExceptBlock, ES);
3294 // Also add the SEHExceptBlock as a label, like with regular labels.
3295 SEHExceptBlock->setLabel(ES);
3297 // Bail out if the CFG is bad.
3298 if (badCFG)
3299 return nullptr;
3301 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3302 Block = nullptr;
3304 return SEHExceptBlock;
3307 CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
3308 return VisitCompoundStmt(FS->getBlock(), /*ExternallyDestructed=*/false);
3311 CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
3312 // "__leave" is a control-flow statement. Thus we stop processing the current
3313 // block.
3314 if (badCFG)
3315 return nullptr;
3317 // Now create a new block that ends with the __leave statement.
3318 Block = createBlock(false);
3319 Block->setTerminator(LS);
3321 // If there is no target for the __leave, then we are looking at an incomplete
3322 // AST. This means that the CFG cannot be constructed.
3323 if (SEHLeaveJumpTarget.block) {
3324 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
3325 addSuccessor(Block, SEHLeaveJumpTarget.block);
3326 } else
3327 badCFG = true;
3329 return Block;
3332 CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
3333 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
3334 // processing the current block.
3335 CFGBlock *SEHTrySuccessor = nullptr;
3337 if (Block) {
3338 if (badCFG)
3339 return nullptr;
3340 SEHTrySuccessor = Block;
3341 } else SEHTrySuccessor = Succ;
3343 // FIXME: Implement __finally support.
3344 if (Terminator->getFinallyHandler())
3345 return NYS();
3347 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
3349 // Create a new block that will contain the __try statement.
3350 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3352 // Add the terminator in the __try block.
3353 NewTryTerminatedBlock->setTerminator(Terminator);
3355 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
3356 // The code after the try is the implicit successor if there's an __except.
3357 Succ = SEHTrySuccessor;
3358 Block = nullptr;
3359 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
3360 if (!ExceptBlock)
3361 return nullptr;
3362 // Add this block to the list of successors for the block with the try
3363 // statement.
3364 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
3366 if (PrevSEHTryTerminatedBlock)
3367 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
3368 else
3369 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3371 // The code after the try is the implicit successor.
3372 Succ = SEHTrySuccessor;
3374 // Save the current "__try" context.
3375 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
3376 cfg->addTryDispatchBlock(TryTerminatedBlock);
3378 // Save the current value for the __leave target.
3379 // All __leaves should go to the code following the __try
3380 // (FIXME: or if the __try has a __finally, to the __finally.)
3381 SaveAndRestore save_break(SEHLeaveJumpTarget);
3382 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
3384 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
3385 Block = nullptr;
3386 return addStmt(Terminator->getTryBlock());
3389 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
3390 // Get the block of the labeled statement. Add it to our map.
3391 addStmt(L->getSubStmt());
3392 CFGBlock *LabelBlock = Block;
3394 if (!LabelBlock) // This can happen when the body is empty, i.e.
3395 LabelBlock = createBlock(); // scopes that only contains NullStmts.
3397 assert(!LabelMap.contains(L->getDecl()) && "label already in map");
3398 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
3400 // Labels partition blocks, so this is the end of the basic block we were
3401 // processing (L is the block's label). Because this is label (and we have
3402 // already processed the substatement) there is no extra control-flow to worry
3403 // about.
3404 LabelBlock->setLabel(L);
3405 if (badCFG)
3406 return nullptr;
3408 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3409 Block = nullptr;
3411 // This block is now the implicit successor of other blocks.
3412 Succ = LabelBlock;
3414 return LabelBlock;
3417 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
3418 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3419 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
3420 if (Expr *CopyExpr = CI.getCopyExpr()) {
3421 CFGBlock *Tmp = Visit(CopyExpr);
3422 if (Tmp)
3423 LastBlock = Tmp;
3426 return LastBlock;
3429 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
3430 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3432 unsigned Idx = 0;
3433 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
3434 et = E->capture_init_end();
3435 it != et; ++it, ++Idx) {
3436 if (Expr *Init = *it) {
3437 // If the initializer is an ArrayInitLoopExpr, we want to extract the
3438 // initializer, that's used for each element.
3439 auto *AILEInit = extractElementInitializerFromNestedAILE(
3440 dyn_cast<ArrayInitLoopExpr>(Init));
3442 findConstructionContexts(ConstructionContextLayer::create(
3443 cfg->getBumpVectorContext(), {E, Idx}),
3444 AILEInit ? AILEInit : Init);
3446 CFGBlock *Tmp = Visit(Init);
3447 if (Tmp)
3448 LastBlock = Tmp;
3451 return LastBlock;
3454 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
3455 // Goto is a control-flow statement. Thus we stop processing the current
3456 // block and create a new one.
3458 Block = createBlock(false);
3459 Block->setTerminator(G);
3461 // If we already know the mapping to the label block add the successor now.
3462 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
3464 if (I == LabelMap.end())
3465 // We will need to backpatch this block later.
3466 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3467 else {
3468 JumpTarget JT = I->second;
3469 addSuccessor(Block, JT.block);
3470 addScopeChangesHandling(ScopePos, JT.scopePosition, G);
3473 return Block;
3476 CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
3477 // Goto is a control-flow statement. Thus we stop processing the current
3478 // block and create a new one.
3480 if (!G->isAsmGoto())
3481 return VisitStmt(G, asc);
3483 if (Block) {
3484 Succ = Block;
3485 if (badCFG)
3486 return nullptr;
3488 Block = createBlock();
3489 Block->setTerminator(G);
3490 // We will backpatch this block later for all the labels.
3491 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3492 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
3493 // used to avoid adding "Succ" again.
3494 BackpatchBlocks.push_back(JumpSource(Succ, ScopePos));
3495 return VisitChildren(G);
3498 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
3499 CFGBlock *LoopSuccessor = nullptr;
3501 // Save local scope position because in case of condition variable ScopePos
3502 // won't be restored when traversing AST.
3503 SaveAndRestore save_scope_pos(ScopePos);
3505 // Create local scope for init statement and possible condition variable.
3506 // Add destructor for init statement and condition variable.
3507 // Store scope position for continue statement.
3508 if (Stmt *Init = F->getInit())
3509 addLocalScopeForStmt(Init);
3510 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3512 if (VarDecl *VD = F->getConditionVariable())
3513 addLocalScopeForVarDecl(VD);
3514 LocalScope::const_iterator ContinueScopePos = ScopePos;
3516 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
3518 addLoopExit(F);
3520 // "for" is a control-flow statement. Thus we stop processing the current
3521 // block.
3522 if (Block) {
3523 if (badCFG)
3524 return nullptr;
3525 LoopSuccessor = Block;
3526 } else
3527 LoopSuccessor = Succ;
3529 // Save the current value for the break targets.
3530 // All breaks should go to the code following the loop.
3531 SaveAndRestore save_break(BreakJumpTarget);
3532 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3534 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3536 // Now create the loop body.
3538 assert(F->getBody());
3540 // Save the current values for Block, Succ, continue and break targets.
3541 SaveAndRestore save_Block(Block), save_Succ(Succ);
3542 SaveAndRestore save_continue(ContinueJumpTarget);
3544 // Create an empty block to represent the transition block for looping back
3545 // to the head of the loop. If we have increment code, it will
3546 // go in this block as well.
3547 Block = Succ = TransitionBlock = createBlock(false);
3548 TransitionBlock->setLoopTarget(F);
3551 // Loop iteration (after increment) should end with destructor of Condition
3552 // variable (if any).
3553 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
3555 if (Stmt *I = F->getInc()) {
3556 // Generate increment code in its own basic block. This is the target of
3557 // continue statements.
3558 Succ = addStmt(I);
3561 // Finish up the increment (or empty) block if it hasn't been already.
3562 if (Block) {
3563 assert(Block == Succ);
3564 if (badCFG)
3565 return nullptr;
3566 Block = nullptr;
3569 // The starting block for the loop increment is the block that should
3570 // represent the 'loop target' for looping back to the start of the loop.
3571 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3572 ContinueJumpTarget.block->setLoopTarget(F);
3575 // If body is not a compound statement create implicit scope
3576 // and add destructors.
3577 if (!isa<CompoundStmt>(F->getBody()))
3578 addLocalScopeAndDtors(F->getBody());
3580 // Now populate the body block, and in the process create new blocks as we
3581 // walk the body of the loop.
3582 BodyBlock = addStmt(F->getBody());
3584 if (!BodyBlock) {
3585 // In the case of "for (...;...;...);" we can have a null BodyBlock.
3586 // Use the continue jump target as the proxy for the body.
3587 BodyBlock = ContinueJumpTarget.block;
3589 else if (badCFG)
3590 return nullptr;
3593 // Because of short-circuit evaluation, the condition of the loop can span
3594 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3595 // evaluate the condition.
3596 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3598 do {
3599 Expr *C = F->getCond();
3600 SaveAndRestore save_scope_pos(ScopePos);
3602 // Specially handle logical operators, which have a slightly
3603 // more optimal CFG representation.
3604 if (BinaryOperator *Cond =
3605 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
3606 if (Cond->isLogicalOp()) {
3607 std::tie(EntryConditionBlock, ExitConditionBlock) =
3608 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
3609 break;
3612 // The default case when not handling logical operators.
3613 EntryConditionBlock = ExitConditionBlock = createBlock(false);
3614 ExitConditionBlock->setTerminator(F);
3616 // See if this is a known constant.
3617 TryResult KnownVal(true);
3619 if (C) {
3620 // Now add the actual condition to the condition block.
3621 // Because the condition itself may contain control-flow, new blocks may
3622 // be created. Thus we update "Succ" after adding the condition.
3623 Block = ExitConditionBlock;
3624 EntryConditionBlock = addStmt(C);
3626 // If this block contains a condition variable, add both the condition
3627 // variable and initializer to the CFG.
3628 if (VarDecl *VD = F->getConditionVariable()) {
3629 if (Expr *Init = VD->getInit()) {
3630 autoCreateBlock();
3631 const DeclStmt *DS = F->getConditionVariableDeclStmt();
3632 assert(DS->isSingleDecl());
3633 findConstructionContexts(
3634 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
3635 Init);
3636 appendStmt(Block, DS);
3637 EntryConditionBlock = addStmt(Init);
3638 assert(Block == EntryConditionBlock);
3639 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
3643 if (Block && badCFG)
3644 return nullptr;
3646 KnownVal = tryEvaluateBool(C);
3649 // Add the loop body entry as a successor to the condition.
3650 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
3651 // Link up the condition block with the code that follows the loop. (the
3652 // false branch).
3653 addSuccessor(ExitConditionBlock,
3654 KnownVal.isTrue() ? nullptr : LoopSuccessor);
3655 } while (false);
3657 // Link up the loop-back block to the entry condition block.
3658 addSuccessor(TransitionBlock, EntryConditionBlock);
3660 // The condition block is the implicit successor for any code above the loop.
3661 Succ = EntryConditionBlock;
3663 // If the loop contains initialization, create a new block for those
3664 // statements. This block can also contain statements that precede the loop.
3665 if (Stmt *I = F->getInit()) {
3666 SaveAndRestore save_scope_pos(ScopePos);
3667 ScopePos = LoopBeginScopePos;
3668 Block = createBlock();
3669 return addStmt(I);
3672 // There is no loop initialization. We are thus basically a while loop.
3673 // NULL out Block to force lazy block construction.
3674 Block = nullptr;
3675 Succ = EntryConditionBlock;
3676 return EntryConditionBlock;
3679 CFGBlock *
3680 CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
3681 AddStmtChoice asc) {
3682 findConstructionContexts(
3683 ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
3684 MTE->getSubExpr());
3686 return VisitStmt(MTE, asc);
3689 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
3690 if (asc.alwaysAdd(*this, M)) {
3691 autoCreateBlock();
3692 appendStmt(Block, M);
3694 return Visit(M->getBase());
3697 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
3698 // Objective-C fast enumeration 'for' statements:
3699 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3701 // for ( Type newVariable in collection_expression ) { statements }
3703 // becomes:
3705 // prologue:
3706 // 1. collection_expression
3707 // T. jump to loop_entry
3708 // loop_entry:
3709 // 1. side-effects of element expression
3710 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3711 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3712 // TB:
3713 // statements
3714 // T. jump to loop_entry
3715 // FB:
3716 // what comes after
3718 // and
3720 // Type existingItem;
3721 // for ( existingItem in expression ) { statements }
3723 // becomes:
3725 // the same with newVariable replaced with existingItem; the binding works
3726 // the same except that for one ObjCForCollectionStmt::getElement() returns
3727 // a DeclStmt and the other returns a DeclRefExpr.
3729 CFGBlock *LoopSuccessor = nullptr;
3731 if (Block) {
3732 if (badCFG)
3733 return nullptr;
3734 LoopSuccessor = Block;
3735 Block = nullptr;
3736 } else
3737 LoopSuccessor = Succ;
3739 // Build the condition blocks.
3740 CFGBlock *ExitConditionBlock = createBlock(false);
3742 // Set the terminator for the "exit" condition block.
3743 ExitConditionBlock->setTerminator(S);
3745 // The last statement in the block should be the ObjCForCollectionStmt, which
3746 // performs the actual binding to 'element' and determines if there are any
3747 // more items in the collection.
3748 appendStmt(ExitConditionBlock, S);
3749 Block = ExitConditionBlock;
3751 // Walk the 'element' expression to see if there are any side-effects. We
3752 // generate new blocks as necessary. We DON'T add the statement by default to
3753 // the CFG unless it contains control-flow.
3754 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3755 AddStmtChoice::NotAlwaysAdd);
3756 if (Block) {
3757 if (badCFG)
3758 return nullptr;
3759 Block = nullptr;
3762 // The condition block is the implicit successor for the loop body as well as
3763 // any code above the loop.
3764 Succ = EntryConditionBlock;
3766 // Now create the true branch.
3768 // Save the current values for Succ, continue and break targets.
3769 SaveAndRestore save_Block(Block), save_Succ(Succ);
3770 SaveAndRestore save_continue(ContinueJumpTarget),
3771 save_break(BreakJumpTarget);
3773 // Add an intermediate block between the BodyBlock and the
3774 // EntryConditionBlock to represent the "loop back" transition, for looping
3775 // back to the head of the loop.
3776 CFGBlock *LoopBackBlock = nullptr;
3777 Succ = LoopBackBlock = createBlock();
3778 LoopBackBlock->setLoopTarget(S);
3780 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3781 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
3783 CFGBlock *BodyBlock = addStmt(S->getBody());
3785 if (!BodyBlock)
3786 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
3787 else if (Block) {
3788 if (badCFG)
3789 return nullptr;
3792 // This new body block is a successor to our "exit" condition block.
3793 addSuccessor(ExitConditionBlock, BodyBlock);
3796 // Link up the condition block with the code that follows the loop.
3797 // (the false branch).
3798 addSuccessor(ExitConditionBlock, LoopSuccessor);
3800 // Now create a prologue block to contain the collection expression.
3801 Block = createBlock();
3802 return addStmt(S->getCollection());
3805 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3806 // Inline the body.
3807 return addStmt(S->getSubStmt());
3808 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3811 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
3812 // FIXME: Add locking 'primitives' to CFG for @synchronized.
3814 // Inline the body.
3815 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
3817 // The sync body starts its own basic block. This makes it a little easier
3818 // for diagnostic clients.
3819 if (SyncBlock) {
3820 if (badCFG)
3821 return nullptr;
3823 Block = nullptr;
3824 Succ = SyncBlock;
3827 // Add the @synchronized to the CFG.
3828 autoCreateBlock();
3829 appendStmt(Block, S);
3831 // Inline the sync expression.
3832 return addStmt(S->getSynchExpr());
3835 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3836 autoCreateBlock();
3838 // Add the PseudoObject as the last thing.
3839 appendStmt(Block, E);
3841 CFGBlock *lastBlock = Block;
3843 // Before that, evaluate all of the semantics in order. In
3844 // CFG-land, that means appending them in reverse order.
3845 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3846 Expr *Semantic = E->getSemanticExpr(--i);
3848 // If the semantic is an opaque value, we're being asked to bind
3849 // it to its source expression.
3850 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3851 Semantic = OVE->getSourceExpr();
3853 if (CFGBlock *B = Visit(Semantic))
3854 lastBlock = B;
3857 return lastBlock;
3860 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
3861 CFGBlock *LoopSuccessor = nullptr;
3863 // Save local scope position because in case of condition variable ScopePos
3864 // won't be restored when traversing AST.
3865 SaveAndRestore save_scope_pos(ScopePos);
3867 // Create local scope for possible condition variable.
3868 // Store scope position for continue statement.
3869 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3870 if (VarDecl *VD = W->getConditionVariable()) {
3871 addLocalScopeForVarDecl(VD);
3872 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3874 addLoopExit(W);
3876 // "while" is a control-flow statement. Thus we stop processing the current
3877 // block.
3878 if (Block) {
3879 if (badCFG)
3880 return nullptr;
3881 LoopSuccessor = Block;
3882 Block = nullptr;
3883 } else {
3884 LoopSuccessor = Succ;
3887 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3889 // Process the loop body.
3891 assert(W->getBody());
3893 // Save the current values for Block, Succ, continue and break targets.
3894 SaveAndRestore save_Block(Block), save_Succ(Succ);
3895 SaveAndRestore save_continue(ContinueJumpTarget),
3896 save_break(BreakJumpTarget);
3898 // Create an empty block to represent the transition block for looping back
3899 // to the head of the loop.
3900 Succ = TransitionBlock = createBlock(false);
3901 TransitionBlock->setLoopTarget(W);
3902 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
3904 // All breaks should go to the code following the loop.
3905 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3907 // Loop body should end with destructor of Condition variable (if any).
3908 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3910 // If body is not a compound statement create implicit scope
3911 // and add destructors.
3912 if (!isa<CompoundStmt>(W->getBody()))
3913 addLocalScopeAndDtors(W->getBody());
3915 // Create the body. The returned block is the entry to the loop body.
3916 BodyBlock = addStmt(W->getBody());
3918 if (!BodyBlock)
3919 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
3920 else if (Block && badCFG)
3921 return nullptr;
3924 // Because of short-circuit evaluation, the condition of the loop can span
3925 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3926 // evaluate the condition.
3927 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3929 do {
3930 Expr *C = W->getCond();
3932 // Specially handle logical operators, which have a slightly
3933 // more optimal CFG representation.
3934 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
3935 if (Cond->isLogicalOp()) {
3936 std::tie(EntryConditionBlock, ExitConditionBlock) =
3937 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
3938 break;
3941 // The default case when not handling logical operators.
3942 ExitConditionBlock = createBlock(false);
3943 ExitConditionBlock->setTerminator(W);
3945 // Now add the actual condition to the condition block.
3946 // Because the condition itself may contain control-flow, new blocks may
3947 // be created. Thus we update "Succ" after adding the condition.
3948 Block = ExitConditionBlock;
3949 Block = EntryConditionBlock = addStmt(C);
3951 // If this block contains a condition variable, add both the condition
3952 // variable and initializer to the CFG.
3953 if (VarDecl *VD = W->getConditionVariable()) {
3954 if (Expr *Init = VD->getInit()) {
3955 autoCreateBlock();
3956 const DeclStmt *DS = W->getConditionVariableDeclStmt();
3957 assert(DS->isSingleDecl());
3958 findConstructionContexts(
3959 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
3960 const_cast<DeclStmt *>(DS)),
3961 Init);
3962 appendStmt(Block, DS);
3963 EntryConditionBlock = addStmt(Init);
3964 assert(Block == EntryConditionBlock);
3965 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
3969 if (Block && badCFG)
3970 return nullptr;
3972 // See if this is a known constant.
3973 const TryResult& KnownVal = tryEvaluateBool(C);
3975 // Add the loop body entry as a successor to the condition.
3976 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
3977 // Link up the condition block with the code that follows the loop. (the
3978 // false branch).
3979 addSuccessor(ExitConditionBlock,
3980 KnownVal.isTrue() ? nullptr : LoopSuccessor);
3981 } while(false);
3983 // Link up the loop-back block to the entry condition block.
3984 addSuccessor(TransitionBlock, EntryConditionBlock);
3986 // There can be no more statements in the condition block since we loop back
3987 // to this block. NULL out Block to force lazy creation of another block.
3988 Block = nullptr;
3990 // Return the condition block, which is the dominating block for the loop.
3991 Succ = EntryConditionBlock;
3992 return EntryConditionBlock;
3995 CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
3996 AddStmtChoice asc) {
3997 if (asc.alwaysAdd(*this, A)) {
3998 autoCreateBlock();
3999 appendStmt(Block, A);
4002 CFGBlock *B = Block;
4004 if (CFGBlock *R = Visit(A->getSubExpr()))
4005 B = R;
4007 auto *OVE = dyn_cast<OpaqueValueExpr>(A->getCommonExpr());
4008 assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
4009 "OpaqueValueExpr!");
4010 if (CFGBlock *R = Visit(OVE->getSourceExpr()))
4011 B = R;
4013 return B;
4016 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
4017 // ObjCAtCatchStmt are treated like labels, so they are the first statement
4018 // in a block.
4020 // Save local scope position because in case of exception variable ScopePos
4021 // won't be restored when traversing AST.
4022 SaveAndRestore save_scope_pos(ScopePos);
4024 if (CS->getCatchBody())
4025 addStmt(CS->getCatchBody());
4027 CFGBlock *CatchBlock = Block;
4028 if (!CatchBlock)
4029 CatchBlock = createBlock();
4031 appendStmt(CatchBlock, CS);
4033 // Also add the ObjCAtCatchStmt as a label, like with regular labels.
4034 CatchBlock->setLabel(CS);
4036 // Bail out if the CFG is bad.
4037 if (badCFG)
4038 return nullptr;
4040 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4041 Block = nullptr;
4043 return CatchBlock;
4046 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
4047 // If we were in the middle of a block we stop processing that block.
4048 if (badCFG)
4049 return nullptr;
4051 // Create the new block.
4052 Block = createBlock(false);
4054 if (TryTerminatedBlock)
4055 // The current try statement is the only successor.
4056 addSuccessor(Block, TryTerminatedBlock);
4057 else
4058 // otherwise the Exit block is the only successor.
4059 addSuccessor(Block, &cfg->getExit());
4061 // Add the statement to the block. This may create new blocks if S contains
4062 // control-flow (short-circuit operations).
4063 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
4066 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
4067 // "@try"/"@catch" is a control-flow statement. Thus we stop processing the
4068 // current block.
4069 CFGBlock *TrySuccessor = nullptr;
4071 if (Block) {
4072 if (badCFG)
4073 return nullptr;
4074 TrySuccessor = Block;
4075 } else
4076 TrySuccessor = Succ;
4078 // FIXME: Implement @finally support.
4079 if (Terminator->getFinallyStmt())
4080 return NYS();
4082 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
4084 // Create a new block that will contain the try statement.
4085 CFGBlock *NewTryTerminatedBlock = createBlock(false);
4086 // Add the terminator in the try block.
4087 NewTryTerminatedBlock->setTerminator(Terminator);
4089 bool HasCatchAll = false;
4090 for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
4091 // The code after the try is the implicit successor.
4092 Succ = TrySuccessor;
4093 if (CS->hasEllipsis()) {
4094 HasCatchAll = true;
4096 Block = nullptr;
4097 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
4098 if (!CatchBlock)
4099 return nullptr;
4100 // Add this block to the list of successors for the block with the try
4101 // statement.
4102 addSuccessor(NewTryTerminatedBlock, CatchBlock);
4105 // FIXME: This needs updating when @finally support is added.
4106 if (!HasCatchAll) {
4107 if (PrevTryTerminatedBlock)
4108 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
4109 else
4110 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
4113 // The code after the try is the implicit successor.
4114 Succ = TrySuccessor;
4116 // Save the current "try" context.
4117 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
4118 cfg->addTryDispatchBlock(TryTerminatedBlock);
4120 assert(Terminator->getTryBody() && "try must contain a non-NULL body");
4121 Block = nullptr;
4122 return addStmt(Terminator->getTryBody());
4125 CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
4126 AddStmtChoice asc) {
4127 findConstructionContextsForArguments(ME);
4129 autoCreateBlock();
4130 appendObjCMessage(Block, ME);
4132 return VisitChildren(ME);
4135 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
4136 // If we were in the middle of a block we stop processing that block.
4137 if (badCFG)
4138 return nullptr;
4140 // Create the new block.
4141 Block = createBlock(false);
4143 if (TryTerminatedBlock)
4144 // The current try statement is the only successor.
4145 addSuccessor(Block, TryTerminatedBlock);
4146 else
4147 // otherwise the Exit block is the only successor.
4148 addSuccessor(Block, &cfg->getExit());
4150 // Add the statement to the block. This may create new blocks if S contains
4151 // control-flow (short-circuit operations).
4152 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
4155 CFGBlock *CFGBuilder::VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc) {
4156 if (asc.alwaysAdd(*this, S)) {
4157 autoCreateBlock();
4158 appendStmt(Block, S);
4161 // C++ [expr.typeid]p3:
4162 // When typeid is applied to an expression other than an glvalue of a
4163 // polymorphic class type [...] [the] expression is an unevaluated
4164 // operand. [...]
4165 // We add only potentially evaluated statements to the block to avoid
4166 // CFG generation for unevaluated operands.
4167 if (!S->isTypeDependent() && S->isPotentiallyEvaluated())
4168 return VisitChildren(S);
4170 // Return block without CFG for unevaluated operands.
4171 return Block;
4174 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
4175 CFGBlock *LoopSuccessor = nullptr;
4177 addLoopExit(D);
4179 // "do...while" is a control-flow statement. Thus we stop processing the
4180 // current block.
4181 if (Block) {
4182 if (badCFG)
4183 return nullptr;
4184 LoopSuccessor = Block;
4185 } else
4186 LoopSuccessor = Succ;
4188 // Because of short-circuit evaluation, the condition of the loop can span
4189 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
4190 // evaluate the condition.
4191 CFGBlock *ExitConditionBlock = createBlock(false);
4192 CFGBlock *EntryConditionBlock = ExitConditionBlock;
4194 // Set the terminator for the "exit" condition block.
4195 ExitConditionBlock->setTerminator(D);
4197 // Now add the actual condition to the condition block. Because the condition
4198 // itself may contain control-flow, new blocks may be created.
4199 if (Stmt *C = D->getCond()) {
4200 Block = ExitConditionBlock;
4201 EntryConditionBlock = addStmt(C);
4202 if (Block) {
4203 if (badCFG)
4204 return nullptr;
4208 // The condition block is the implicit successor for the loop body.
4209 Succ = EntryConditionBlock;
4211 // See if this is a known constant.
4212 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
4214 // Process the loop body.
4215 CFGBlock *BodyBlock = nullptr;
4217 assert(D->getBody());
4219 // Save the current values for Block, Succ, and continue and break targets
4220 SaveAndRestore save_Block(Block), save_Succ(Succ);
4221 SaveAndRestore save_continue(ContinueJumpTarget),
4222 save_break(BreakJumpTarget);
4224 // All continues within this loop should go to the condition block
4225 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
4227 // All breaks should go to the code following the loop.
4228 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4230 // NULL out Block to force lazy instantiation of blocks for the body.
4231 Block = nullptr;
4233 // If body is not a compound statement create implicit scope
4234 // and add destructors.
4235 if (!isa<CompoundStmt>(D->getBody()))
4236 addLocalScopeAndDtors(D->getBody());
4238 // Create the body. The returned block is the entry to the loop body.
4239 BodyBlock = addStmt(D->getBody());
4241 if (!BodyBlock)
4242 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
4243 else if (Block) {
4244 if (badCFG)
4245 return nullptr;
4248 // Add an intermediate block between the BodyBlock and the
4249 // ExitConditionBlock to represent the "loop back" transition. Create an
4250 // empty block to represent the transition block for looping back to the
4251 // head of the loop.
4252 // FIXME: Can we do this more efficiently without adding another block?
4253 Block = nullptr;
4254 Succ = BodyBlock;
4255 CFGBlock *LoopBackBlock = createBlock();
4256 LoopBackBlock->setLoopTarget(D);
4258 if (!KnownVal.isFalse())
4259 // Add the loop body entry as a successor to the condition.
4260 addSuccessor(ExitConditionBlock, LoopBackBlock);
4261 else
4262 addSuccessor(ExitConditionBlock, nullptr);
4265 // Link up the condition block with the code that follows the loop.
4266 // (the false branch).
4267 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
4269 // There can be no more statements in the body block(s) since we loop back to
4270 // the body. NULL out Block to force lazy creation of another block.
4271 Block = nullptr;
4273 // Return the loop body, which is the dominating block for the loop.
4274 Succ = BodyBlock;
4275 return BodyBlock;
4278 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
4279 // "continue" is a control-flow statement. Thus we stop processing the
4280 // current block.
4281 if (badCFG)
4282 return nullptr;
4284 // Now create a new block that ends with the continue statement.
4285 Block = createBlock(false);
4286 Block->setTerminator(C);
4288 // If there is no target for the continue, then we are looking at an
4289 // incomplete AST. This means the CFG cannot be constructed.
4290 if (ContinueJumpTarget.block) {
4291 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
4292 addSuccessor(Block, ContinueJumpTarget.block);
4293 } else
4294 badCFG = true;
4296 return Block;
4299 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
4300 AddStmtChoice asc) {
4301 if (asc.alwaysAdd(*this, E)) {
4302 autoCreateBlock();
4303 appendStmt(Block, E);
4306 // VLA types have expressions that must be evaluated.
4307 // Evaluation is done only for `sizeof`.
4309 if (E->getKind() != UETT_SizeOf)
4310 return Block;
4312 CFGBlock *lastBlock = Block;
4314 if (E->isArgumentType()) {
4315 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
4316 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
4317 lastBlock = addStmt(VA->getSizeExpr());
4319 return lastBlock;
4322 /// VisitStmtExpr - Utility method to handle (nested) statement
4323 /// expressions (a GCC extension).
4324 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
4325 if (asc.alwaysAdd(*this, SE)) {
4326 autoCreateBlock();
4327 appendStmt(Block, SE);
4329 return VisitCompoundStmt(SE->getSubStmt(), /*ExternallyDestructed=*/true);
4332 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
4333 // "switch" is a control-flow statement. Thus we stop processing the current
4334 // block.
4335 CFGBlock *SwitchSuccessor = nullptr;
4337 // Save local scope position because in case of condition variable ScopePos
4338 // won't be restored when traversing AST.
4339 SaveAndRestore save_scope_pos(ScopePos);
4341 // Create local scope for C++17 switch init-stmt if one exists.
4342 if (Stmt *Init = Terminator->getInit())
4343 addLocalScopeForStmt(Init);
4345 // Create local scope for possible condition variable.
4346 // Store scope position. Add implicit destructor.
4347 if (VarDecl *VD = Terminator->getConditionVariable())
4348 addLocalScopeForVarDecl(VD);
4350 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
4352 if (Block) {
4353 if (badCFG)
4354 return nullptr;
4355 SwitchSuccessor = Block;
4356 } else SwitchSuccessor = Succ;
4358 // Save the current "switch" context.
4359 SaveAndRestore save_switch(SwitchTerminatedBlock),
4360 save_default(DefaultCaseBlock);
4361 SaveAndRestore save_break(BreakJumpTarget);
4363 // Set the "default" case to be the block after the switch statement. If the
4364 // switch statement contains a "default:", this value will be overwritten with
4365 // the block for that code.
4366 DefaultCaseBlock = SwitchSuccessor;
4368 // Create a new block that will contain the switch statement.
4369 SwitchTerminatedBlock = createBlock(false);
4371 // Now process the switch body. The code after the switch is the implicit
4372 // successor.
4373 Succ = SwitchSuccessor;
4374 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
4376 // When visiting the body, the case statements should automatically get linked
4377 // up to the switch. We also don't keep a pointer to the body, since all
4378 // control-flow from the switch goes to case/default statements.
4379 assert(Terminator->getBody() && "switch must contain a non-NULL body");
4380 Block = nullptr;
4382 // For pruning unreachable case statements, save the current state
4383 // for tracking the condition value.
4384 SaveAndRestore save_switchExclusivelyCovered(switchExclusivelyCovered, false);
4386 // Determine if the switch condition can be explicitly evaluated.
4387 assert(Terminator->getCond() && "switch condition must be non-NULL");
4388 Expr::EvalResult result;
4389 bool b = tryEvaluate(Terminator->getCond(), result);
4390 SaveAndRestore save_switchCond(switchCond, b ? &result : nullptr);
4392 // If body is not a compound statement create implicit scope
4393 // and add destructors.
4394 if (!isa<CompoundStmt>(Terminator->getBody()))
4395 addLocalScopeAndDtors(Terminator->getBody());
4397 addStmt(Terminator->getBody());
4398 if (Block) {
4399 if (badCFG)
4400 return nullptr;
4403 // If we have no "default:" case, the default transition is to the code
4404 // following the switch body. Moreover, take into account if all the
4405 // cases of a switch are covered (e.g., switching on an enum value).
4407 // Note: We add a successor to a switch that is considered covered yet has no
4408 // case statements if the enumeration has no enumerators.
4409 bool SwitchAlwaysHasSuccessor = false;
4410 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
4411 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
4412 Terminator->getSwitchCaseList();
4413 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
4414 !SwitchAlwaysHasSuccessor);
4416 // Add the terminator and condition in the switch block.
4417 SwitchTerminatedBlock->setTerminator(Terminator);
4418 Block = SwitchTerminatedBlock;
4419 CFGBlock *LastBlock = addStmt(Terminator->getCond());
4421 // If the SwitchStmt contains a condition variable, add both the
4422 // SwitchStmt and the condition variable initialization to the CFG.
4423 if (VarDecl *VD = Terminator->getConditionVariable()) {
4424 if (Expr *Init = VD->getInit()) {
4425 autoCreateBlock();
4426 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
4427 LastBlock = addStmt(Init);
4428 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
4432 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
4433 if (Stmt *Init = Terminator->getInit()) {
4434 autoCreateBlock();
4435 LastBlock = addStmt(Init);
4438 return LastBlock;
4441 static bool shouldAddCase(bool &switchExclusivelyCovered,
4442 const Expr::EvalResult *switchCond,
4443 const CaseStmt *CS,
4444 ASTContext &Ctx) {
4445 if (!switchCond)
4446 return true;
4448 bool addCase = false;
4450 if (!switchExclusivelyCovered) {
4451 if (switchCond->Val.isInt()) {
4452 // Evaluate the LHS of the case value.
4453 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
4454 const llvm::APSInt &condInt = switchCond->Val.getInt();
4456 if (condInt == lhsInt) {
4457 addCase = true;
4458 switchExclusivelyCovered = true;
4460 else if (condInt > lhsInt) {
4461 if (const Expr *RHS = CS->getRHS()) {
4462 // Evaluate the RHS of the case value.
4463 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
4464 if (V2 >= condInt) {
4465 addCase = true;
4466 switchExclusivelyCovered = true;
4471 else
4472 addCase = true;
4474 return addCase;
4477 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
4478 // CaseStmts are essentially labels, so they are the first statement in a
4479 // block.
4480 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
4482 if (Stmt *Sub = CS->getSubStmt()) {
4483 // For deeply nested chains of CaseStmts, instead of doing a recursion
4484 // (which can blow out the stack), manually unroll and create blocks
4485 // along the way.
4486 while (isa<CaseStmt>(Sub)) {
4487 CFGBlock *currentBlock = createBlock(false);
4488 currentBlock->setLabel(CS);
4490 if (TopBlock)
4491 addSuccessor(LastBlock, currentBlock);
4492 else
4493 TopBlock = currentBlock;
4495 addSuccessor(SwitchTerminatedBlock,
4496 shouldAddCase(switchExclusivelyCovered, switchCond,
4497 CS, *Context)
4498 ? currentBlock : nullptr);
4500 LastBlock = currentBlock;
4501 CS = cast<CaseStmt>(Sub);
4502 Sub = CS->getSubStmt();
4505 addStmt(Sub);
4508 CFGBlock *CaseBlock = Block;
4509 if (!CaseBlock)
4510 CaseBlock = createBlock();
4512 // Cases statements partition blocks, so this is the top of the basic block we
4513 // were processing (the "case XXX:" is the label).
4514 CaseBlock->setLabel(CS);
4516 if (badCFG)
4517 return nullptr;
4519 // Add this block to the list of successors for the block with the switch
4520 // statement.
4521 assert(SwitchTerminatedBlock);
4522 addSuccessor(SwitchTerminatedBlock, CaseBlock,
4523 shouldAddCase(switchExclusivelyCovered, switchCond,
4524 CS, *Context));
4526 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4527 Block = nullptr;
4529 if (TopBlock) {
4530 addSuccessor(LastBlock, CaseBlock);
4531 Succ = TopBlock;
4532 } else {
4533 // This block is now the implicit successor of other blocks.
4534 Succ = CaseBlock;
4537 return Succ;
4540 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
4541 if (Terminator->getSubStmt())
4542 addStmt(Terminator->getSubStmt());
4544 DefaultCaseBlock = Block;
4546 if (!DefaultCaseBlock)
4547 DefaultCaseBlock = createBlock();
4549 // Default statements partition blocks, so this is the top of the basic block
4550 // we were processing (the "default:" is the label).
4551 DefaultCaseBlock->setLabel(Terminator);
4553 if (badCFG)
4554 return nullptr;
4556 // Unlike case statements, we don't add the default block to the successors
4557 // for the switch statement immediately. This is done when we finish
4558 // processing the switch statement. This allows for the default case
4559 // (including a fall-through to the code after the switch statement) to always
4560 // be the last successor of a switch-terminated block.
4562 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4563 Block = nullptr;
4565 // This block is now the implicit successor of other blocks.
4566 Succ = DefaultCaseBlock;
4568 return DefaultCaseBlock;
4571 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
4572 // "try"/"catch" is a control-flow statement. Thus we stop processing the
4573 // current block.
4574 CFGBlock *TrySuccessor = nullptr;
4576 if (Block) {
4577 if (badCFG)
4578 return nullptr;
4579 TrySuccessor = Block;
4580 } else
4581 TrySuccessor = Succ;
4583 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
4585 // Create a new block that will contain the try statement.
4586 CFGBlock *NewTryTerminatedBlock = createBlock(false);
4587 // Add the terminator in the try block.
4588 NewTryTerminatedBlock->setTerminator(Terminator);
4590 bool HasCatchAll = false;
4591 for (unsigned I = 0, E = Terminator->getNumHandlers(); I != E; ++I) {
4592 // The code after the try is the implicit successor.
4593 Succ = TrySuccessor;
4594 CXXCatchStmt *CS = Terminator->getHandler(I);
4595 if (CS->getExceptionDecl() == nullptr) {
4596 HasCatchAll = true;
4598 Block = nullptr;
4599 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
4600 if (!CatchBlock)
4601 return nullptr;
4602 // Add this block to the list of successors for the block with the try
4603 // statement.
4604 addSuccessor(NewTryTerminatedBlock, CatchBlock);
4606 if (!HasCatchAll) {
4607 if (PrevTryTerminatedBlock)
4608 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
4609 else
4610 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
4613 // The code after the try is the implicit successor.
4614 Succ = TrySuccessor;
4616 // Save the current "try" context.
4617 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
4618 cfg->addTryDispatchBlock(TryTerminatedBlock);
4620 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
4621 Block = nullptr;
4622 return addStmt(Terminator->getTryBlock());
4625 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
4626 // CXXCatchStmt are treated like labels, so they are the first statement in a
4627 // block.
4629 // Save local scope position because in case of exception variable ScopePos
4630 // won't be restored when traversing AST.
4631 SaveAndRestore save_scope_pos(ScopePos);
4633 // Create local scope for possible exception variable.
4634 // Store scope position. Add implicit destructor.
4635 if (VarDecl *VD = CS->getExceptionDecl()) {
4636 LocalScope::const_iterator BeginScopePos = ScopePos;
4637 addLocalScopeForVarDecl(VD);
4638 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
4641 if (CS->getHandlerBlock())
4642 addStmt(CS->getHandlerBlock());
4644 CFGBlock *CatchBlock = Block;
4645 if (!CatchBlock)
4646 CatchBlock = createBlock();
4648 // CXXCatchStmt is more than just a label. They have semantic meaning
4649 // as well, as they implicitly "initialize" the catch variable. Add
4650 // it to the CFG as a CFGElement so that the control-flow of these
4651 // semantics gets captured.
4652 appendStmt(CatchBlock, CS);
4654 // Also add the CXXCatchStmt as a label, to mirror handling of regular
4655 // labels.
4656 CatchBlock->setLabel(CS);
4658 // Bail out if the CFG is bad.
4659 if (badCFG)
4660 return nullptr;
4662 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4663 Block = nullptr;
4665 return CatchBlock;
4668 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4669 // C++0x for-range statements are specified as [stmt.ranged]:
4671 // {
4672 // auto && __range = range-init;
4673 // for ( auto __begin = begin-expr,
4674 // __end = end-expr;
4675 // __begin != __end;
4676 // ++__begin ) {
4677 // for-range-declaration = *__begin;
4678 // statement
4679 // }
4680 // }
4682 // Save local scope position before the addition of the implicit variables.
4683 SaveAndRestore save_scope_pos(ScopePos);
4685 // Create local scopes and destructors for range, begin and end variables.
4686 if (Stmt *Range = S->getRangeStmt())
4687 addLocalScopeForStmt(Range);
4688 if (Stmt *Begin = S->getBeginStmt())
4689 addLocalScopeForStmt(Begin);
4690 if (Stmt *End = S->getEndStmt())
4691 addLocalScopeForStmt(End);
4692 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
4694 LocalScope::const_iterator ContinueScopePos = ScopePos;
4696 // "for" is a control-flow statement. Thus we stop processing the current
4697 // block.
4698 CFGBlock *LoopSuccessor = nullptr;
4699 if (Block) {
4700 if (badCFG)
4701 return nullptr;
4702 LoopSuccessor = Block;
4703 } else
4704 LoopSuccessor = Succ;
4706 // Save the current value for the break targets.
4707 // All breaks should go to the code following the loop.
4708 SaveAndRestore save_break(BreakJumpTarget);
4709 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4711 // The block for the __begin != __end expression.
4712 CFGBlock *ConditionBlock = createBlock(false);
4713 ConditionBlock->setTerminator(S);
4715 // Now add the actual condition to the condition block.
4716 if (Expr *C = S->getCond()) {
4717 Block = ConditionBlock;
4718 CFGBlock *BeginConditionBlock = addStmt(C);
4719 if (badCFG)
4720 return nullptr;
4721 assert(BeginConditionBlock == ConditionBlock &&
4722 "condition block in for-range was unexpectedly complex");
4723 (void)BeginConditionBlock;
4726 // The condition block is the implicit successor for the loop body as well as
4727 // any code above the loop.
4728 Succ = ConditionBlock;
4730 // See if this is a known constant.
4731 TryResult KnownVal(true);
4733 if (S->getCond())
4734 KnownVal = tryEvaluateBool(S->getCond());
4736 // Now create the loop body.
4738 assert(S->getBody());
4740 // Save the current values for Block, Succ, and continue targets.
4741 SaveAndRestore save_Block(Block), save_Succ(Succ);
4742 SaveAndRestore save_continue(ContinueJumpTarget);
4744 // Generate increment code in its own basic block. This is the target of
4745 // continue statements.
4746 Block = nullptr;
4747 Succ = addStmt(S->getInc());
4748 if (badCFG)
4749 return nullptr;
4750 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
4752 // The starting block for the loop increment is the block that should
4753 // represent the 'loop target' for looping back to the start of the loop.
4754 ContinueJumpTarget.block->setLoopTarget(S);
4756 // Finish up the increment block and prepare to start the loop body.
4757 assert(Block);
4758 if (badCFG)
4759 return nullptr;
4760 Block = nullptr;
4762 // Add implicit scope and dtors for loop variable.
4763 addLocalScopeAndDtors(S->getLoopVarStmt());
4765 // If body is not a compound statement create implicit scope
4766 // and add destructors.
4767 if (!isa<CompoundStmt>(S->getBody()))
4768 addLocalScopeAndDtors(S->getBody());
4770 // Populate a new block to contain the loop body and loop variable.
4771 addStmt(S->getBody());
4773 if (badCFG)
4774 return nullptr;
4775 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
4776 if (badCFG)
4777 return nullptr;
4779 // This new body block is a successor to our condition block.
4780 addSuccessor(ConditionBlock,
4781 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
4784 // Link up the condition block with the code that follows the loop (the
4785 // false branch).
4786 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
4788 // Add the initialization statements.
4789 Block = createBlock();
4790 addStmt(S->getBeginStmt());
4791 addStmt(S->getEndStmt());
4792 CFGBlock *Head = addStmt(S->getRangeStmt());
4793 if (S->getInit())
4794 Head = addStmt(S->getInit());
4795 return Head;
4798 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
4799 AddStmtChoice asc, bool ExternallyDestructed) {
4800 if (BuildOpts.AddTemporaryDtors) {
4801 // If adding implicit destructors visit the full expression for adding
4802 // destructors of temporaries.
4803 TempDtorContext Context;
4804 VisitForTemporaryDtors(E->getSubExpr(), ExternallyDestructed, Context);
4806 // Full expression has to be added as CFGStmt so it will be sequenced
4807 // before destructors of it's temporaries.
4808 asc = asc.withAlwaysAdd(true);
4810 return Visit(E->getSubExpr(), asc);
4813 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
4814 AddStmtChoice asc) {
4815 if (asc.alwaysAdd(*this, E)) {
4816 autoCreateBlock();
4817 appendStmt(Block, E);
4819 findConstructionContexts(
4820 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
4821 E->getSubExpr());
4823 // We do not want to propagate the AlwaysAdd property.
4824 asc = asc.withAlwaysAdd(false);
4826 return Visit(E->getSubExpr(), asc);
4829 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
4830 AddStmtChoice asc) {
4831 // If the constructor takes objects as arguments by value, we need to properly
4832 // construct these objects. Construction contexts we find here aren't for the
4833 // constructor C, they're for its arguments only.
4834 findConstructionContextsForArguments(C);
4836 autoCreateBlock();
4837 appendConstructor(Block, C);
4839 return VisitChildren(C);
4842 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
4843 AddStmtChoice asc) {
4844 autoCreateBlock();
4845 appendStmt(Block, NE);
4847 findConstructionContexts(
4848 ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
4849 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
4851 if (NE->getInitializer())
4852 Block = Visit(NE->getInitializer());
4854 if (BuildOpts.AddCXXNewAllocator)
4855 appendNewAllocator(Block, NE);
4857 if (NE->isArray() && *NE->getArraySize())
4858 Block = Visit(*NE->getArraySize());
4860 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
4861 E = NE->placement_arg_end(); I != E; ++I)
4862 Block = Visit(*I);
4864 return Block;
4867 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
4868 AddStmtChoice asc) {
4869 autoCreateBlock();
4870 appendStmt(Block, DE);
4871 QualType DTy = DE->getDestroyedType();
4872 if (!DTy.isNull()) {
4873 DTy = DTy.getNonReferenceType();
4874 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
4875 if (RD) {
4876 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
4877 appendDeleteDtor(Block, RD, DE);
4881 return VisitChildren(DE);
4884 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
4885 AddStmtChoice asc) {
4886 if (asc.alwaysAdd(*this, E)) {
4887 autoCreateBlock();
4888 appendStmt(Block, E);
4889 // We do not want to propagate the AlwaysAdd property.
4890 asc = asc.withAlwaysAdd(false);
4892 return Visit(E->getSubExpr(), asc);
4895 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
4896 AddStmtChoice asc) {
4897 // If the constructor takes objects as arguments by value, we need to properly
4898 // construct these objects. Construction contexts we find here aren't for the
4899 // constructor C, they're for its arguments only.
4900 findConstructionContextsForArguments(C);
4902 autoCreateBlock();
4903 appendConstructor(Block, C);
4904 return VisitChildren(C);
4907 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
4908 AddStmtChoice asc) {
4909 if (asc.alwaysAdd(*this, E)) {
4910 autoCreateBlock();
4911 appendStmt(Block, E);
4914 if (E->getCastKind() == CK_IntegralToBoolean)
4915 tryEvaluateBool(E->getSubExpr()->IgnoreParens());
4917 return Visit(E->getSubExpr(), AddStmtChoice());
4920 CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
4921 return Visit(E->getSubExpr(), AddStmtChoice());
4924 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
4925 // Lazily create the indirect-goto dispatch block if there isn't one already.
4926 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
4928 if (!IBlock) {
4929 IBlock = createBlock(false);
4930 cfg->setIndirectGotoBlock(IBlock);
4933 // IndirectGoto is a control-flow statement. Thus we stop processing the
4934 // current block and create a new one.
4935 if (badCFG)
4936 return nullptr;
4938 Block = createBlock(false);
4939 Block->setTerminator(I);
4940 addSuccessor(Block, IBlock);
4941 return addStmt(I->getTarget());
4944 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
4945 TempDtorContext &Context) {
4946 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4948 tryAgain:
4949 if (!E) {
4950 badCFG = true;
4951 return nullptr;
4953 switch (E->getStmtClass()) {
4954 default:
4955 return VisitChildrenForTemporaryDtors(E, false, Context);
4957 case Stmt::InitListExprClass:
4958 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
4960 case Stmt::BinaryOperatorClass:
4961 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4962 ExternallyDestructed,
4963 Context);
4965 case Stmt::CXXBindTemporaryExprClass:
4966 return VisitCXXBindTemporaryExprForTemporaryDtors(
4967 cast<CXXBindTemporaryExpr>(E), ExternallyDestructed, Context);
4969 case Stmt::BinaryConditionalOperatorClass:
4970 case Stmt::ConditionalOperatorClass:
4971 return VisitConditionalOperatorForTemporaryDtors(
4972 cast<AbstractConditionalOperator>(E), ExternallyDestructed, Context);
4974 case Stmt::ImplicitCastExprClass:
4975 // For implicit cast we want ExternallyDestructed to be passed further.
4976 E = cast<CastExpr>(E)->getSubExpr();
4977 goto tryAgain;
4979 case Stmt::CXXFunctionalCastExprClass:
4980 // For functional cast we want ExternallyDestructed to be passed further.
4981 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4982 goto tryAgain;
4984 case Stmt::ConstantExprClass:
4985 E = cast<ConstantExpr>(E)->getSubExpr();
4986 goto tryAgain;
4988 case Stmt::ParenExprClass:
4989 E = cast<ParenExpr>(E)->getSubExpr();
4990 goto tryAgain;
4992 case Stmt::MaterializeTemporaryExprClass: {
4993 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4994 ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression);
4995 SmallVector<const Expr *, 2> CommaLHSs;
4996 SmallVector<SubobjectAdjustment, 2> Adjustments;
4997 // Find the expression whose lifetime needs to be extended.
4998 E = const_cast<Expr *>(
4999 cast<MaterializeTemporaryExpr>(E)
5000 ->getSubExpr()
5001 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5002 // Visit the skipped comma operator left-hand sides for other temporaries.
5003 for (const Expr *CommaLHS : CommaLHSs) {
5004 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
5005 /*ExternallyDestructed=*/false, Context);
5007 goto tryAgain;
5010 case Stmt::BlockExprClass:
5011 // Don't recurse into blocks; their subexpressions don't get evaluated
5012 // here.
5013 return Block;
5015 case Stmt::LambdaExprClass: {
5016 // For lambda expressions, only recurse into the capture initializers,
5017 // and not the body.
5018 auto *LE = cast<LambdaExpr>(E);
5019 CFGBlock *B = Block;
5020 for (Expr *Init : LE->capture_inits()) {
5021 if (Init) {
5022 if (CFGBlock *R = VisitForTemporaryDtors(
5023 Init, /*ExternallyDestructed=*/true, Context))
5024 B = R;
5027 return B;
5030 case Stmt::StmtExprClass:
5031 // Don't recurse into statement expressions; any cleanups inside them
5032 // will be wrapped in their own ExprWithCleanups.
5033 return Block;
5035 case Stmt::CXXDefaultArgExprClass:
5036 E = cast<CXXDefaultArgExpr>(E)->getExpr();
5037 goto tryAgain;
5039 case Stmt::CXXDefaultInitExprClass:
5040 E = cast<CXXDefaultInitExpr>(E)->getExpr();
5041 goto tryAgain;
5045 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
5046 bool ExternallyDestructed,
5047 TempDtorContext &Context) {
5048 if (isa<LambdaExpr>(E)) {
5049 // Do not visit the children of lambdas; they have their own CFGs.
5050 return Block;
5053 // When visiting children for destructors we want to visit them in reverse
5054 // order that they will appear in the CFG. Because the CFG is built
5055 // bottom-up, this means we visit them in their natural order, which
5056 // reverses them in the CFG.
5057 CFGBlock *B = Block;
5058 for (Stmt *Child : E->children())
5059 if (Child)
5060 if (CFGBlock *R = VisitForTemporaryDtors(Child, ExternallyDestructed, Context))
5061 B = R;
5063 return B;
5066 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
5067 BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) {
5068 if (E->isCommaOp()) {
5069 // For the comma operator, the LHS expression is evaluated before the RHS
5070 // expression, so prepend temporary destructors for the LHS first.
5071 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
5072 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), ExternallyDestructed, Context);
5073 return RHSBlock ? RHSBlock : LHSBlock;
5076 if (E->isLogicalOp()) {
5077 VisitForTemporaryDtors(E->getLHS(), false, Context);
5078 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
5079 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
5080 RHSExecuted.negate();
5082 // We do not know at CFG-construction time whether the right-hand-side was
5083 // executed, thus we add a branch node that depends on the temporary
5084 // constructor call.
5085 TempDtorContext RHSContext(
5086 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
5087 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
5088 InsertTempDtorDecisionBlock(RHSContext);
5090 return Block;
5093 if (E->isAssignmentOp()) {
5094 // For assignment operators, the RHS expression is evaluated before the LHS
5095 // expression, so prepend temporary destructors for the RHS first.
5096 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
5097 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
5098 return LHSBlock ? LHSBlock : RHSBlock;
5101 // Any other operator is visited normally.
5102 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
5105 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
5106 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) {
5107 // First add destructors for temporaries in subexpression.
5108 // Because VisitCXXBindTemporaryExpr calls setDestructed:
5109 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), true, Context);
5110 if (!ExternallyDestructed) {
5111 // If lifetime of temporary is not prolonged (by assigning to constant
5112 // reference) add destructor for it.
5114 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
5116 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
5117 // If the destructor is marked as a no-return destructor, we need to
5118 // create a new block for the destructor which does not have as a
5119 // successor anything built thus far. Control won't flow out of this
5120 // block.
5121 if (B) Succ = B;
5122 Block = createNoReturnBlock();
5123 } else if (Context.needsTempDtorBranch()) {
5124 // If we need to introduce a branch, we add a new block that we will hook
5125 // up to a decision block later.
5126 if (B) Succ = B;
5127 Block = createBlock();
5128 } else {
5129 autoCreateBlock();
5131 if (Context.needsTempDtorBranch()) {
5132 Context.setDecisionPoint(Succ, E);
5134 appendTemporaryDtor(Block, E);
5136 B = Block;
5138 return B;
5141 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
5142 CFGBlock *FalseSucc) {
5143 if (!Context.TerminatorExpr) {
5144 // If no temporary was found, we do not need to insert a decision point.
5145 return;
5147 assert(Context.TerminatorExpr);
5148 CFGBlock *Decision = createBlock(false);
5149 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
5150 CFGTerminator::TemporaryDtorsBranch));
5151 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
5152 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
5153 !Context.KnownExecuted.isTrue());
5154 Block = Decision;
5157 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
5158 AbstractConditionalOperator *E, bool ExternallyDestructed,
5159 TempDtorContext &Context) {
5160 VisitForTemporaryDtors(E->getCond(), false, Context);
5161 CFGBlock *ConditionBlock = Block;
5162 CFGBlock *ConditionSucc = Succ;
5163 TryResult ConditionVal = tryEvaluateBool(E->getCond());
5164 TryResult NegatedVal = ConditionVal;
5165 if (NegatedVal.isKnown()) NegatedVal.negate();
5167 TempDtorContext TrueContext(
5168 bothKnownTrue(Context.KnownExecuted, ConditionVal));
5169 VisitForTemporaryDtors(E->getTrueExpr(), ExternallyDestructed, TrueContext);
5170 CFGBlock *TrueBlock = Block;
5172 Block = ConditionBlock;
5173 Succ = ConditionSucc;
5174 TempDtorContext FalseContext(
5175 bothKnownTrue(Context.KnownExecuted, NegatedVal));
5176 VisitForTemporaryDtors(E->getFalseExpr(), ExternallyDestructed, FalseContext);
5178 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
5179 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
5180 } else if (TrueContext.TerminatorExpr) {
5181 Block = TrueBlock;
5182 InsertTempDtorDecisionBlock(TrueContext);
5183 } else {
5184 InsertTempDtorDecisionBlock(FalseContext);
5186 return Block;
5189 CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D,
5190 AddStmtChoice asc) {
5191 if (asc.alwaysAdd(*this, D)) {
5192 autoCreateBlock();
5193 appendStmt(Block, D);
5196 // Iterate over all used expression in clauses.
5197 CFGBlock *B = Block;
5199 // Reverse the elements to process them in natural order. Iterators are not
5200 // bidirectional, so we need to create temp vector.
5201 SmallVector<Stmt *, 8> Used(
5202 OMPExecutableDirective::used_clauses_children(D->clauses()));
5203 for (Stmt *S : llvm::reverse(Used)) {
5204 assert(S && "Expected non-null used-in-clause child.");
5205 if (CFGBlock *R = Visit(S))
5206 B = R;
5208 // Visit associated structured block if any.
5209 if (!D->isStandaloneDirective()) {
5210 Stmt *S = D->getRawStmt();
5211 if (!isa<CompoundStmt>(S))
5212 addLocalScopeAndDtors(S);
5213 if (CFGBlock *R = addStmt(S))
5214 B = R;
5217 return B;
5220 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
5221 /// no successors or predecessors. If this is the first block created in the
5222 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
5223 CFGBlock *CFG::createBlock() {
5224 bool first_block = begin() == end();
5226 // Create the block.
5227 CFGBlock *Mem = new (getAllocator()) CFGBlock(NumBlockIDs++, BlkBVC, this);
5228 Blocks.push_back(Mem, BlkBVC);
5230 // If this is the first block, set it as the Entry and Exit.
5231 if (first_block)
5232 Entry = Exit = &back();
5234 // Return the block.
5235 return &back();
5238 /// buildCFG - Constructs a CFG from an AST.
5239 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
5240 ASTContext *C, const BuildOptions &BO) {
5241 CFGBuilder Builder(C, BO);
5242 return Builder.buildCFG(D, Statement);
5245 bool CFG::isLinear() const {
5246 // Quick path: if we only have the ENTRY block, the EXIT block, and some code
5247 // in between, then we have no room for control flow.
5248 if (size() <= 3)
5249 return true;
5251 // Traverse the CFG until we find a branch.
5252 // TODO: While this should still be very fast,
5253 // maybe we should cache the answer.
5254 llvm::SmallPtrSet<const CFGBlock *, 4> Visited;
5255 const CFGBlock *B = Entry;
5256 while (B != Exit) {
5257 auto IteratorAndFlag = Visited.insert(B);
5258 if (!IteratorAndFlag.second) {
5259 // We looped back to a block that we've already visited. Not linear.
5260 return false;
5263 // Iterate over reachable successors.
5264 const CFGBlock *FirstReachableB = nullptr;
5265 for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
5266 if (!AB.isReachable())
5267 continue;
5269 if (FirstReachableB == nullptr) {
5270 FirstReachableB = &*AB;
5271 } else {
5272 // We've encountered a branch. It's not a linear CFG.
5273 return false;
5277 if (!FirstReachableB) {
5278 // We reached a dead end. EXIT is unreachable. This is linear enough.
5279 return true;
5282 // There's only one way to move forward. Proceed.
5283 B = FirstReachableB;
5286 // We reached EXIT and found no branches.
5287 return true;
5290 const CXXDestructorDecl *
5291 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
5292 switch (getKind()) {
5293 case CFGElement::Initializer:
5294 case CFGElement::NewAllocator:
5295 case CFGElement::LoopExit:
5296 case CFGElement::LifetimeEnds:
5297 case CFGElement::Statement:
5298 case CFGElement::Constructor:
5299 case CFGElement::CXXRecordTypedCall:
5300 case CFGElement::ScopeBegin:
5301 case CFGElement::ScopeEnd:
5302 case CFGElement::CleanupFunction:
5303 llvm_unreachable("getDestructorDecl should only be used with "
5304 "ImplicitDtors");
5305 case CFGElement::AutomaticObjectDtor: {
5306 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
5307 QualType ty = var->getType();
5309 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
5311 // Lifetime-extending constructs are handled here. This works for a single
5312 // temporary in an initializer expression.
5313 if (ty->isReferenceType()) {
5314 if (const Expr *Init = var->getInit()) {
5315 ty = getReferenceInitTemporaryType(Init);
5319 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
5320 ty = arrayType->getElementType();
5323 // The situation when the type of the lifetime-extending reference
5324 // does not correspond to the type of the object is supposed
5325 // to be handled by now. In particular, 'ty' is now the unwrapped
5326 // record type.
5327 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
5328 assert(classDecl);
5329 return classDecl->getDestructor();
5331 case CFGElement::DeleteDtor: {
5332 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
5333 QualType DTy = DE->getDestroyedType();
5334 DTy = DTy.getNonReferenceType();
5335 const CXXRecordDecl *classDecl =
5336 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
5337 return classDecl->getDestructor();
5339 case CFGElement::TemporaryDtor: {
5340 const CXXBindTemporaryExpr *bindExpr =
5341 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
5342 const CXXTemporary *temp = bindExpr->getTemporary();
5343 return temp->getDestructor();
5345 case CFGElement::MemberDtor: {
5346 const FieldDecl *field = castAs<CFGMemberDtor>().getFieldDecl();
5347 QualType ty = field->getType();
5349 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
5350 ty = arrayType->getElementType();
5353 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
5354 assert(classDecl);
5355 return classDecl->getDestructor();
5357 case CFGElement::BaseDtor:
5358 // Not yet supported.
5359 return nullptr;
5361 llvm_unreachable("getKind() returned bogus value");
5364 //===----------------------------------------------------------------------===//
5365 // CFGBlock operations.
5366 //===----------------------------------------------------------------------===//
5368 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
5369 : ReachableBlock(IsReachable ? B : nullptr),
5370 UnreachableBlock(!IsReachable ? B : nullptr,
5371 B && IsReachable ? AB_Normal : AB_Unreachable) {}
5373 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
5374 : ReachableBlock(B),
5375 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
5376 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
5378 void CFGBlock::addSuccessor(AdjacentBlock Succ,
5379 BumpVectorContext &C) {
5380 if (CFGBlock *B = Succ.getReachableBlock())
5381 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
5383 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
5384 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
5386 Succs.push_back(Succ, C);
5389 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
5390 const CFGBlock *From, const CFGBlock *To) {
5391 if (F.IgnoreNullPredecessors && !From)
5392 return true;
5394 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
5395 // If the 'To' has no label or is labeled but the label isn't a
5396 // CaseStmt then filter this edge.
5397 if (const SwitchStmt *S =
5398 dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) {
5399 if (S->isAllEnumCasesCovered()) {
5400 const Stmt *L = To->getLabel();
5401 if (!L || !isa<CaseStmt>(L))
5402 return true;
5407 return false;
5410 //===----------------------------------------------------------------------===//
5411 // CFG pretty printing
5412 //===----------------------------------------------------------------------===//
5414 namespace {
5416 class StmtPrinterHelper : public PrinterHelper {
5417 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
5418 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
5420 StmtMapTy StmtMap;
5421 DeclMapTy DeclMap;
5422 signed currentBlock = 0;
5423 unsigned currStmt = 0;
5424 const LangOptions &LangOpts;
5426 public:
5427 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
5428 : LangOpts(LO) {
5429 if (!cfg)
5430 return;
5431 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
5432 unsigned j = 1;
5433 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
5434 BI != BEnd; ++BI, ++j ) {
5435 if (std::optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
5436 const Stmt *stmt= SE->getStmt();
5437 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
5438 StmtMap[stmt] = P;
5440 switch (stmt->getStmtClass()) {
5441 case Stmt::DeclStmtClass:
5442 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
5443 break;
5444 case Stmt::IfStmtClass: {
5445 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
5446 if (var)
5447 DeclMap[var] = P;
5448 break;
5450 case Stmt::ForStmtClass: {
5451 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
5452 if (var)
5453 DeclMap[var] = P;
5454 break;
5456 case Stmt::WhileStmtClass: {
5457 const VarDecl *var =
5458 cast<WhileStmt>(stmt)->getConditionVariable();
5459 if (var)
5460 DeclMap[var] = P;
5461 break;
5463 case Stmt::SwitchStmtClass: {
5464 const VarDecl *var =
5465 cast<SwitchStmt>(stmt)->getConditionVariable();
5466 if (var)
5467 DeclMap[var] = P;
5468 break;
5470 case Stmt::CXXCatchStmtClass: {
5471 const VarDecl *var =
5472 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
5473 if (var)
5474 DeclMap[var] = P;
5475 break;
5477 default:
5478 break;
5485 ~StmtPrinterHelper() override = default;
5487 const LangOptions &getLangOpts() const { return LangOpts; }
5488 void setBlockID(signed i) { currentBlock = i; }
5489 void setStmtID(unsigned i) { currStmt = i; }
5491 bool handledStmt(Stmt *S, raw_ostream &OS) override {
5492 StmtMapTy::iterator I = StmtMap.find(S);
5494 if (I == StmtMap.end())
5495 return false;
5497 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5498 && I->second.second == currStmt) {
5499 return false;
5502 OS << "[B" << I->second.first << "." << I->second.second << "]";
5503 return true;
5506 bool handleDecl(const Decl *D, raw_ostream &OS) {
5507 DeclMapTy::iterator I = DeclMap.find(D);
5509 if (I == DeclMap.end())
5510 return false;
5512 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5513 && I->second.second == currStmt) {
5514 return false;
5517 OS << "[B" << I->second.first << "." << I->second.second << "]";
5518 return true;
5522 class CFGBlockTerminatorPrint
5523 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
5524 raw_ostream &OS;
5525 StmtPrinterHelper* Helper;
5526 PrintingPolicy Policy;
5528 public:
5529 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
5530 const PrintingPolicy &Policy)
5531 : OS(os), Helper(helper), Policy(Policy) {
5532 this->Policy.IncludeNewlines = false;
5535 void VisitIfStmt(IfStmt *I) {
5536 OS << "if ";
5537 if (Stmt *C = I->getCond())
5538 C->printPretty(OS, Helper, Policy);
5541 // Default case.
5542 void VisitStmt(Stmt *Terminator) {
5543 Terminator->printPretty(OS, Helper, Policy);
5546 void VisitDeclStmt(DeclStmt *DS) {
5547 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
5548 OS << "static init " << VD->getName();
5551 void VisitForStmt(ForStmt *F) {
5552 OS << "for (" ;
5553 if (F->getInit())
5554 OS << "...";
5555 OS << "; ";
5556 if (Stmt *C = F->getCond())
5557 C->printPretty(OS, Helper, Policy);
5558 OS << "; ";
5559 if (F->getInc())
5560 OS << "...";
5561 OS << ")";
5564 void VisitWhileStmt(WhileStmt *W) {
5565 OS << "while " ;
5566 if (Stmt *C = W->getCond())
5567 C->printPretty(OS, Helper, Policy);
5570 void VisitDoStmt(DoStmt *D) {
5571 OS << "do ... while ";
5572 if (Stmt *C = D->getCond())
5573 C->printPretty(OS, Helper, Policy);
5576 void VisitSwitchStmt(SwitchStmt *Terminator) {
5577 OS << "switch ";
5578 Terminator->getCond()->printPretty(OS, Helper, Policy);
5581 void VisitCXXTryStmt(CXXTryStmt *) { OS << "try ..."; }
5583 void VisitObjCAtTryStmt(ObjCAtTryStmt *) { OS << "@try ..."; }
5585 void VisitSEHTryStmt(SEHTryStmt *CS) { OS << "__try ..."; }
5587 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
5588 if (Stmt *Cond = C->getCond())
5589 Cond->printPretty(OS, Helper, Policy);
5590 OS << " ? ... : ...";
5593 void VisitChooseExpr(ChooseExpr *C) {
5594 OS << "__builtin_choose_expr( ";
5595 if (Stmt *Cond = C->getCond())
5596 Cond->printPretty(OS, Helper, Policy);
5597 OS << " )";
5600 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
5601 OS << "goto *";
5602 if (Stmt *T = I->getTarget())
5603 T->printPretty(OS, Helper, Policy);
5606 void VisitBinaryOperator(BinaryOperator* B) {
5607 if (!B->isLogicalOp()) {
5608 VisitExpr(B);
5609 return;
5612 if (B->getLHS())
5613 B->getLHS()->printPretty(OS, Helper, Policy);
5615 switch (B->getOpcode()) {
5616 case BO_LOr:
5617 OS << " || ...";
5618 return;
5619 case BO_LAnd:
5620 OS << " && ...";
5621 return;
5622 default:
5623 llvm_unreachable("Invalid logical operator.");
5627 void VisitExpr(Expr *E) {
5628 E->printPretty(OS, Helper, Policy);
5631 public:
5632 void print(CFGTerminator T) {
5633 switch (T.getKind()) {
5634 case CFGTerminator::StmtBranch:
5635 Visit(T.getStmt());
5636 break;
5637 case CFGTerminator::TemporaryDtorsBranch:
5638 OS << "(Temp Dtor) ";
5639 Visit(T.getStmt());
5640 break;
5641 case CFGTerminator::VirtualBaseBranch:
5642 OS << "(See if most derived ctor has already initialized vbases)";
5643 break;
5648 } // namespace
5650 static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
5651 const CXXCtorInitializer *I) {
5652 if (I->isBaseInitializer())
5653 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
5654 else if (I->isDelegatingInitializer())
5655 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
5656 else
5657 OS << I->getAnyMember()->getName();
5658 OS << "(";
5659 if (Expr *IE = I->getInit())
5660 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5661 OS << ")";
5663 if (I->isBaseInitializer())
5664 OS << " (Base initializer)";
5665 else if (I->isDelegatingInitializer())
5666 OS << " (Delegating initializer)";
5667 else
5668 OS << " (Member initializer)";
5671 static void print_construction_context(raw_ostream &OS,
5672 StmtPrinterHelper &Helper,
5673 const ConstructionContext *CC) {
5674 SmallVector<const Stmt *, 3> Stmts;
5675 switch (CC->getKind()) {
5676 case ConstructionContext::SimpleConstructorInitializerKind: {
5677 OS << ", ";
5678 const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC);
5679 print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
5680 return;
5682 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
5683 OS << ", ";
5684 const auto *CICC =
5685 cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC);
5686 print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
5687 Stmts.push_back(CICC->getCXXBindTemporaryExpr());
5688 break;
5690 case ConstructionContext::SimpleVariableKind: {
5691 const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
5692 Stmts.push_back(SDSCC->getDeclStmt());
5693 break;
5695 case ConstructionContext::CXX17ElidedCopyVariableKind: {
5696 const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC);
5697 Stmts.push_back(CDSCC->getDeclStmt());
5698 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
5699 break;
5701 case ConstructionContext::NewAllocatedObjectKind: {
5702 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
5703 Stmts.push_back(NECC->getCXXNewExpr());
5704 break;
5706 case ConstructionContext::SimpleReturnedValueKind: {
5707 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
5708 Stmts.push_back(RSCC->getReturnStmt());
5709 break;
5711 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
5712 const auto *RSCC =
5713 cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC);
5714 Stmts.push_back(RSCC->getReturnStmt());
5715 Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
5716 break;
5718 case ConstructionContext::SimpleTemporaryObjectKind: {
5719 const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC);
5720 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5721 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5722 break;
5724 case ConstructionContext::ElidedTemporaryObjectKind: {
5725 const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
5726 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5727 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5728 Stmts.push_back(TOCC->getConstructorAfterElision());
5729 break;
5731 case ConstructionContext::LambdaCaptureKind: {
5732 const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
5733 Helper.handledStmt(const_cast<LambdaExpr *>(LCC->getLambdaExpr()), OS);
5734 OS << "+" << LCC->getIndex();
5735 return;
5737 case ConstructionContext::ArgumentKind: {
5738 const auto *ACC = cast<ArgumentConstructionContext>(CC);
5739 if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
5740 OS << ", ";
5741 Helper.handledStmt(const_cast<Stmt *>(BTE), OS);
5743 OS << ", ";
5744 Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
5745 OS << "+" << ACC->getIndex();
5746 return;
5749 for (auto I: Stmts)
5750 if (I) {
5751 OS << ", ";
5752 Helper.handledStmt(const_cast<Stmt *>(I), OS);
5756 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5757 const CFGElement &E);
5759 void CFGElement::dumpToStream(llvm::raw_ostream &OS) const {
5760 LangOptions LangOpts;
5761 StmtPrinterHelper Helper(nullptr, LangOpts);
5762 print_elem(OS, Helper, *this);
5765 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5766 const CFGElement &E) {
5767 switch (E.getKind()) {
5768 case CFGElement::Kind::Statement:
5769 case CFGElement::Kind::CXXRecordTypedCall:
5770 case CFGElement::Kind::Constructor: {
5771 CFGStmt CS = E.castAs<CFGStmt>();
5772 const Stmt *S = CS.getStmt();
5773 assert(S != nullptr && "Expecting non-null Stmt");
5775 // special printing for statement-expressions.
5776 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
5777 const CompoundStmt *Sub = SE->getSubStmt();
5779 auto Children = Sub->children();
5780 if (Children.begin() != Children.end()) {
5781 OS << "({ ... ; ";
5782 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
5783 OS << " })\n";
5784 return;
5787 // special printing for comma expressions.
5788 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
5789 if (B->getOpcode() == BO_Comma) {
5790 OS << "... , ";
5791 Helper.handledStmt(B->getRHS(),OS);
5792 OS << '\n';
5793 return;
5796 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5798 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
5799 if (isa<CXXOperatorCallExpr>(S))
5800 OS << " (OperatorCall)";
5801 OS << " (CXXRecordTypedCall";
5802 print_construction_context(OS, Helper, VTC->getConstructionContext());
5803 OS << ")";
5804 } else if (isa<CXXOperatorCallExpr>(S)) {
5805 OS << " (OperatorCall)";
5806 } else if (isa<CXXBindTemporaryExpr>(S)) {
5807 OS << " (BindTemporary)";
5808 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
5809 OS << " (CXXConstructExpr";
5810 if (std::optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
5811 print_construction_context(OS, Helper, CE->getConstructionContext());
5813 OS << ", " << CCE->getType() << ")";
5814 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
5815 OS << " (" << CE->getStmtClassName() << ", " << CE->getCastKindName()
5816 << ", " << CE->getType() << ")";
5819 // Expressions need a newline.
5820 if (isa<Expr>(S))
5821 OS << '\n';
5823 break;
5826 case CFGElement::Kind::Initializer:
5827 print_initializer(OS, Helper, E.castAs<CFGInitializer>().getInitializer());
5828 OS << '\n';
5829 break;
5831 case CFGElement::Kind::AutomaticObjectDtor: {
5832 CFGAutomaticObjDtor DE = E.castAs<CFGAutomaticObjDtor>();
5833 const VarDecl *VD = DE.getVarDecl();
5834 Helper.handleDecl(VD, OS);
5836 QualType T = VD->getType();
5837 if (T->isReferenceType())
5838 T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
5840 OS << ".~";
5841 T.getUnqualifiedType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5842 OS << "() (Implicit destructor)\n";
5843 break;
5846 case CFGElement::Kind::CleanupFunction:
5847 OS << "CleanupFunction ("
5848 << E.castAs<CFGCleanupFunction>().getFunctionDecl()->getName() << ")\n";
5849 break;
5851 case CFGElement::Kind::LifetimeEnds:
5852 Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS);
5853 OS << " (Lifetime ends)\n";
5854 break;
5856 case CFGElement::Kind::LoopExit:
5857 OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName() << " (LoopExit)\n";
5858 break;
5860 case CFGElement::Kind::ScopeBegin:
5861 OS << "CFGScopeBegin(";
5862 if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl())
5863 OS << VD->getQualifiedNameAsString();
5864 OS << ")\n";
5865 break;
5867 case CFGElement::Kind::ScopeEnd:
5868 OS << "CFGScopeEnd(";
5869 if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl())
5870 OS << VD->getQualifiedNameAsString();
5871 OS << ")\n";
5872 break;
5874 case CFGElement::Kind::NewAllocator:
5875 OS << "CFGNewAllocator(";
5876 if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr())
5877 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5878 OS << ")\n";
5879 break;
5881 case CFGElement::Kind::DeleteDtor: {
5882 CFGDeleteDtor DE = E.castAs<CFGDeleteDtor>();
5883 const CXXRecordDecl *RD = DE.getCXXRecordDecl();
5884 if (!RD)
5885 return;
5886 CXXDeleteExpr *DelExpr =
5887 const_cast<CXXDeleteExpr*>(DE.getDeleteExpr());
5888 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
5889 OS << "->~" << RD->getName().str() << "()";
5890 OS << " (Implicit destructor)\n";
5891 break;
5894 case CFGElement::Kind::BaseDtor: {
5895 const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier();
5896 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
5897 OS << " (Base object destructor)\n";
5898 break;
5901 case CFGElement::Kind::MemberDtor: {
5902 const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl();
5903 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
5904 OS << "this->" << FD->getName();
5905 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
5906 OS << " (Member object destructor)\n";
5907 break;
5910 case CFGElement::Kind::TemporaryDtor: {
5911 const CXXBindTemporaryExpr *BT =
5912 E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
5913 OS << "~";
5914 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5915 OS << "() (Temporary object destructor)\n";
5916 break;
5921 static void print_block(raw_ostream &OS, const CFG* cfg,
5922 const CFGBlock &B,
5923 StmtPrinterHelper &Helper, bool print_edges,
5924 bool ShowColors) {
5925 Helper.setBlockID(B.getBlockID());
5927 // Print the header.
5928 if (ShowColors)
5929 OS.changeColor(raw_ostream::YELLOW, true);
5931 OS << "\n [B" << B.getBlockID();
5933 if (&B == &cfg->getEntry())
5934 OS << " (ENTRY)]\n";
5935 else if (&B == &cfg->getExit())
5936 OS << " (EXIT)]\n";
5937 else if (&B == cfg->getIndirectGotoBlock())
5938 OS << " (INDIRECT GOTO DISPATCH)]\n";
5939 else if (B.hasNoReturnElement())
5940 OS << " (NORETURN)]\n";
5941 else
5942 OS << "]\n";
5944 if (ShowColors)
5945 OS.resetColor();
5947 // Print the label of this block.
5948 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
5949 if (print_edges)
5950 OS << " ";
5952 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
5953 OS << L->getName();
5954 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
5955 OS << "case ";
5956 if (const Expr *LHS = C->getLHS())
5957 LHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5958 if (const Expr *RHS = C->getRHS()) {
5959 OS << " ... ";
5960 RHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5962 } else if (isa<DefaultStmt>(Label))
5963 OS << "default";
5964 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
5965 OS << "catch (";
5966 if (const VarDecl *ED = CS->getExceptionDecl())
5967 ED->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
5968 else
5969 OS << "...";
5970 OS << ")";
5971 } else if (ObjCAtCatchStmt *CS = dyn_cast<ObjCAtCatchStmt>(Label)) {
5972 OS << "@catch (";
5973 if (const VarDecl *PD = CS->getCatchParamDecl())
5974 PD->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
5975 else
5976 OS << "...";
5977 OS << ")";
5978 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
5979 OS << "__except (";
5980 ES->getFilterExpr()->printPretty(OS, &Helper,
5981 PrintingPolicy(Helper.getLangOpts()), 0);
5982 OS << ")";
5983 } else
5984 llvm_unreachable("Invalid label statement in CFGBlock.");
5986 OS << ":\n";
5989 // Iterate through the statements in the block and print them.
5990 unsigned j = 1;
5992 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
5993 I != E ; ++I, ++j ) {
5994 // Print the statement # in the basic block and the statement itself.
5995 if (print_edges)
5996 OS << " ";
5998 OS << llvm::format("%3d", j) << ": ";
6000 Helper.setStmtID(j);
6002 print_elem(OS, Helper, *I);
6005 // Print the terminator of this block.
6006 if (B.getTerminator().isValid()) {
6007 if (ShowColors)
6008 OS.changeColor(raw_ostream::GREEN);
6010 OS << " T: ";
6012 Helper.setBlockID(-1);
6014 PrintingPolicy PP(Helper.getLangOpts());
6015 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
6016 TPrinter.print(B.getTerminator());
6017 OS << '\n';
6019 if (ShowColors)
6020 OS.resetColor();
6023 if (print_edges) {
6024 // Print the predecessors of this block.
6025 if (!B.pred_empty()) {
6026 const raw_ostream::Colors Color = raw_ostream::BLUE;
6027 if (ShowColors)
6028 OS.changeColor(Color);
6029 OS << " Preds " ;
6030 if (ShowColors)
6031 OS.resetColor();
6032 OS << '(' << B.pred_size() << "):";
6033 unsigned i = 0;
6035 if (ShowColors)
6036 OS.changeColor(Color);
6038 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
6039 I != E; ++I, ++i) {
6040 if (i % 10 == 8)
6041 OS << "\n ";
6043 CFGBlock *B = *I;
6044 bool Reachable = true;
6045 if (!B) {
6046 Reachable = false;
6047 B = I->getPossiblyUnreachableBlock();
6050 OS << " B" << B->getBlockID();
6051 if (!Reachable)
6052 OS << "(Unreachable)";
6055 if (ShowColors)
6056 OS.resetColor();
6058 OS << '\n';
6061 // Print the successors of this block.
6062 if (!B.succ_empty()) {
6063 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
6064 if (ShowColors)
6065 OS.changeColor(Color);
6066 OS << " Succs ";
6067 if (ShowColors)
6068 OS.resetColor();
6069 OS << '(' << B.succ_size() << "):";
6070 unsigned i = 0;
6072 if (ShowColors)
6073 OS.changeColor(Color);
6075 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
6076 I != E; ++I, ++i) {
6077 if (i % 10 == 8)
6078 OS << "\n ";
6080 CFGBlock *B = *I;
6082 bool Reachable = true;
6083 if (!B) {
6084 Reachable = false;
6085 B = I->getPossiblyUnreachableBlock();
6088 if (B) {
6089 OS << " B" << B->getBlockID();
6090 if (!Reachable)
6091 OS << "(Unreachable)";
6093 else {
6094 OS << " NULL";
6098 if (ShowColors)
6099 OS.resetColor();
6100 OS << '\n';
6105 /// dump - A simple pretty printer of a CFG that outputs to stderr.
6106 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
6107 print(llvm::errs(), LO, ShowColors);
6110 /// print - A simple pretty printer of a CFG that outputs to an ostream.
6111 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
6112 StmtPrinterHelper Helper(this, LO);
6114 // Print the entry block.
6115 print_block(OS, this, getEntry(), Helper, true, ShowColors);
6117 // Iterate through the CFGBlocks and print them one by one.
6118 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
6119 // Skip the entry block, because we already printed it.
6120 if (&(**I) == &getEntry() || &(**I) == &getExit())
6121 continue;
6123 print_block(OS, this, **I, Helper, true, ShowColors);
6126 // Print the exit block.
6127 print_block(OS, this, getExit(), Helper, true, ShowColors);
6128 OS << '\n';
6129 OS.flush();
6132 size_t CFGBlock::getIndexInCFG() const {
6133 return llvm::find(*getParent(), this) - getParent()->begin();
6136 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
6137 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
6138 bool ShowColors) const {
6139 print(llvm::errs(), cfg, LO, ShowColors);
6142 LLVM_DUMP_METHOD void CFGBlock::dump() const {
6143 dump(getParent(), LangOptions(), false);
6146 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
6147 /// Generally this will only be called from CFG::print.
6148 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
6149 const LangOptions &LO, bool ShowColors) const {
6150 StmtPrinterHelper Helper(cfg, LO);
6151 print_block(OS, cfg, *this, Helper, true, ShowColors);
6152 OS << '\n';
6155 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
6156 void CFGBlock::printTerminator(raw_ostream &OS,
6157 const LangOptions &LO) const {
6158 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
6159 TPrinter.print(getTerminator());
6162 /// printTerminatorJson - Pretty-prints the terminator in JSON format.
6163 void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
6164 bool AddQuotes) const {
6165 std::string Buf;
6166 llvm::raw_string_ostream TempOut(Buf);
6168 printTerminator(TempOut, LO);
6170 Out << JsonFormat(TempOut.str(), AddQuotes);
6173 // Returns true if by simply looking at the block, we can be sure that it
6174 // results in a sink during analysis. This is useful to know when the analysis
6175 // was interrupted, and we try to figure out if it would sink eventually.
6176 // There may be many more reasons why a sink would appear during analysis
6177 // (eg. checkers may generate sinks arbitrarily), but here we only consider
6178 // sinks that would be obvious by looking at the CFG.
6179 static bool isImmediateSinkBlock(const CFGBlock *Blk) {
6180 if (Blk->hasNoReturnElement())
6181 return true;
6183 // FIXME: Throw-expressions are currently generating sinks during analysis:
6184 // they're not supported yet, and also often used for actually terminating
6185 // the program. So we should treat them as sinks in this analysis as well,
6186 // at least for now, but once we have better support for exceptions,
6187 // we'd need to carefully handle the case when the throw is being
6188 // immediately caught.
6189 if (llvm::any_of(*Blk, [](const CFGElement &Elm) {
6190 if (std::optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
6191 if (isa<CXXThrowExpr>(StmtElm->getStmt()))
6192 return true;
6193 return false;
6195 return true;
6197 return false;
6200 bool CFGBlock::isInevitablySinking() const {
6201 const CFG &Cfg = *getParent();
6203 const CFGBlock *StartBlk = this;
6204 if (isImmediateSinkBlock(StartBlk))
6205 return true;
6207 llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
6208 llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
6210 DFSWorkList.push_back(StartBlk);
6211 while (!DFSWorkList.empty()) {
6212 const CFGBlock *Blk = DFSWorkList.back();
6213 DFSWorkList.pop_back();
6214 Visited.insert(Blk);
6216 // If at least one path reaches the CFG exit, it means that control is
6217 // returned to the caller. For now, say that we are not sure what
6218 // happens next. If necessary, this can be improved to analyze
6219 // the parent StackFrameContext's call site in a similar manner.
6220 if (Blk == &Cfg.getExit())
6221 return false;
6223 for (const auto &Succ : Blk->succs()) {
6224 if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
6225 if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
6226 // If the block has reachable child blocks that aren't no-return,
6227 // add them to the worklist.
6228 DFSWorkList.push_back(SuccBlk);
6234 // Nothing reached the exit. It can only mean one thing: there's no return.
6235 return true;
6238 const Expr *CFGBlock::getLastCondition() const {
6239 // If the terminator is a temporary dtor or a virtual base, etc, we can't
6240 // retrieve a meaningful condition, bail out.
6241 if (Terminator.getKind() != CFGTerminator::StmtBranch)
6242 return nullptr;
6244 // Also, if this method was called on a block that doesn't have 2 successors,
6245 // this block doesn't have retrievable condition.
6246 if (succ_size() < 2)
6247 return nullptr;
6249 // FIXME: Is there a better condition expression we can return in this case?
6250 if (size() == 0)
6251 return nullptr;
6253 auto StmtElem = rbegin()->getAs<CFGStmt>();
6254 if (!StmtElem)
6255 return nullptr;
6257 const Stmt *Cond = StmtElem->getStmt();
6258 if (isa<ObjCForCollectionStmt>(Cond) || isa<DeclStmt>(Cond))
6259 return nullptr;
6261 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
6262 // the cast<>.
6263 return cast<Expr>(Cond)->IgnoreParens();
6266 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
6267 Stmt *Terminator = getTerminatorStmt();
6268 if (!Terminator)
6269 return nullptr;
6271 Expr *E = nullptr;
6273 switch (Terminator->getStmtClass()) {
6274 default:
6275 break;
6277 case Stmt::CXXForRangeStmtClass:
6278 E = cast<CXXForRangeStmt>(Terminator)->getCond();
6279 break;
6281 case Stmt::ForStmtClass:
6282 E = cast<ForStmt>(Terminator)->getCond();
6283 break;
6285 case Stmt::WhileStmtClass:
6286 E = cast<WhileStmt>(Terminator)->getCond();
6287 break;
6289 case Stmt::DoStmtClass:
6290 E = cast<DoStmt>(Terminator)->getCond();
6291 break;
6293 case Stmt::IfStmtClass:
6294 E = cast<IfStmt>(Terminator)->getCond();
6295 break;
6297 case Stmt::ChooseExprClass:
6298 E = cast<ChooseExpr>(Terminator)->getCond();
6299 break;
6301 case Stmt::IndirectGotoStmtClass:
6302 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
6303 break;
6305 case Stmt::SwitchStmtClass:
6306 E = cast<SwitchStmt>(Terminator)->getCond();
6307 break;
6309 case Stmt::BinaryConditionalOperatorClass:
6310 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
6311 break;
6313 case Stmt::ConditionalOperatorClass:
6314 E = cast<ConditionalOperator>(Terminator)->getCond();
6315 break;
6317 case Stmt::BinaryOperatorClass: // '&&' and '||'
6318 E = cast<BinaryOperator>(Terminator)->getLHS();
6319 break;
6321 case Stmt::ObjCForCollectionStmtClass:
6322 return Terminator;
6325 if (!StripParens)
6326 return E;
6328 return E ? E->IgnoreParens() : nullptr;
6331 //===----------------------------------------------------------------------===//
6332 // CFG Graphviz Visualization
6333 //===----------------------------------------------------------------------===//
6335 static StmtPrinterHelper *GraphHelper;
6337 void CFG::viewCFG(const LangOptions &LO) const {
6338 StmtPrinterHelper H(this, LO);
6339 GraphHelper = &H;
6340 llvm::ViewGraph(this,"CFG");
6341 GraphHelper = nullptr;
6344 namespace llvm {
6346 template<>
6347 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
6348 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
6350 static std::string getNodeLabel(const CFGBlock *Node, const CFG *Graph) {
6351 std::string OutSStr;
6352 llvm::raw_string_ostream Out(OutSStr);
6353 print_block(Out,Graph, *Node, *GraphHelper, false, false);
6354 std::string& OutStr = Out.str();
6356 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
6358 // Process string output to make it nicer...
6359 for (unsigned i = 0; i != OutStr.length(); ++i)
6360 if (OutStr[i] == '\n') { // Left justify
6361 OutStr[i] = '\\';
6362 OutStr.insert(OutStr.begin()+i+1, 'l');
6365 return OutStr;
6369 } // namespace llvm