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.
11//
12//===----------------------------------------------------------------------===//
13
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/APFloat.h"
40#include "llvm/ADT/APInt.h"
41#include "llvm/ADT/APSInt.h"
42#include "llvm/ADT/ArrayRef.h"
43#include "llvm/ADT/DenseMap.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/SetVector.h"
46#include "llvm/ADT/SmallPtrSet.h"
47#include "llvm/ADT/SmallVector.h"
48#include "llvm/Support/Allocator.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>
63
64using namespace clang;
65
66static SourceLocation GetEndLoc(Decl *D) {
67 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
68 if (Expr *Ex = VD->getInit())
69 return Ex->getSourceRange().getEnd();
70 return D->getLocation();
71}
72
73/// Returns true on constant values based around a single IntegerLiteral,
74/// CharacterLiteral, or FloatingLiteral. Allow for use of parentheses, integer
75/// casts, and negative signs.
76
77static bool IsLiteralConstantExpr(const Expr *E) {
78 // Allow parentheses
79 E = E->IgnoreParens();
80
81 // Allow conversions to different integer kind, and integer to floating point
82 // (to account for float comparing with int).
83 if (const auto *CE = dyn_cast<CastExpr>(Val: E)) {
84 if (CE->getCastKind() != CK_IntegralCast &&
85 CE->getCastKind() != CK_IntegralToFloating)
86 return false;
87 E = CE->getSubExpr();
88 }
89
90 // Allow negative numbers.
91 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
92 if (UO->getOpcode() != UO_Minus)
93 return false;
94 E = UO->getSubExpr();
95 }
96 return isa<IntegerLiteral, CharacterLiteral, FloatingLiteral>(Val: E);
97}
98
99/// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
100/// FloatingLiteral, CharacterLiteral or EnumConstantDecl from the given Expr.
101/// If it fails, returns nullptr.
102static const Expr *tryTransformToLiteralConstant(const Expr *E) {
103 E = E->IgnoreParens();
104 if (IsLiteralConstantExpr(E))
105 return E;
106 if (auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
107 return isa<EnumConstantDecl>(Val: DR->getDecl()) ? DR : nullptr;
108 return nullptr;
109}
110
111/// Tries to interpret a binary operator into `Expr Op NumExpr` form, if
112/// NumExpr is an integer literal or an enum constant.
113///
114/// If this fails, at least one of the returned DeclRefExpr or Expr will be
115/// null.
116static std::tuple<const Expr *, BinaryOperatorKind, const Expr *>
117tryNormalizeBinaryOperator(const BinaryOperator *B) {
118 BinaryOperatorKind Op = B->getOpcode();
119
120 const Expr *MaybeDecl = B->getLHS();
121 const Expr *Constant = tryTransformToLiteralConstant(E: B->getRHS());
122 // Expr looked like `0 == Foo` instead of `Foo == 0`
123 if (Constant == nullptr) {
124 // Flip the operator
125 if (Op == BO_GT)
126 Op = BO_LT;
127 else if (Op == BO_GE)
128 Op = BO_LE;
129 else if (Op == BO_LT)
130 Op = BO_GT;
131 else if (Op == BO_LE)
132 Op = BO_GE;
133
134 MaybeDecl = B->getRHS();
135 Constant = tryTransformToLiteralConstant(E: B->getLHS());
136 }
137
138 return std::make_tuple(args&: MaybeDecl, args&: Op, args&: Constant);
139}
140
141/// For an expression `x == Foo && x == Bar`, this determines whether the
142/// `Foo` and `Bar` are either of the same enumeration type, or both integer
143/// literals.
144///
145/// It's an error to pass this arguments that are not either IntegerLiterals
146/// or DeclRefExprs (that have decls of type EnumConstantDecl)
147static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
148 // User intent isn't clear if they're mixing int literals with enum
149 // constants.
150 if (isa<DeclRefExpr>(Val: E1) != isa<DeclRefExpr>(Val: E2))
151 return false;
152
153 // Integer literal comparisons, regardless of literal type, are acceptable.
154 if (!isa<DeclRefExpr>(Val: E1))
155 return true;
156
157 // IntegerLiterals are handled above and only EnumConstantDecls are expected
158 // beyond this point
159 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
160 auto *Decl1 = cast<DeclRefExpr>(Val: E1)->getDecl();
161 auto *Decl2 = cast<DeclRefExpr>(Val: E2)->getDecl();
162
163 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
164 const DeclContext *DC1 = Decl1->getDeclContext();
165 const DeclContext *DC2 = Decl2->getDeclContext();
166
167 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
168 return DC1 == DC2;
169}
170
171namespace {
172
173class CFGBuilder;
174
175/// The CFG builder uses a recursive algorithm to build the CFG. When
176/// we process an expression, sometimes we know that we must add the
177/// subexpressions as block-level expressions. For example:
178///
179/// exp1 || exp2
180///
181/// When processing the '||' expression, we know that exp1 and exp2
182/// need to be added as block-level expressions, even though they
183/// might not normally need to be. AddStmtChoice records this
184/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
185/// the builder has an option not to add a subexpression as a
186/// block-level expression.
187class AddStmtChoice {
188public:
189 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
190
191 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
192
193 bool alwaysAdd(CFGBuilder &builder,
194 const Stmt *stmt) const;
195
196 /// Return a copy of this object, except with the 'always-add' bit
197 /// set as specified.
198 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
199 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
200 }
201
202private:
203 Kind kind;
204};
205
206/// LocalScope - Node in tree of local scopes created for C++ implicit
207/// destructor calls generation. It contains list of automatic variables
208/// declared in the scope and link to position in previous scope this scope
209/// began in.
210///
211/// The process of creating local scopes is as follows:
212/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
213/// - Before processing statements in scope (e.g. CompoundStmt) create
214/// LocalScope object using CFGBuilder::ScopePos as link to previous scope
215/// and set CFGBuilder::ScopePos to the end of new scope,
216/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
217/// at this VarDecl,
218/// - For every normal (without jump) end of scope add to CFGBlock destructors
219/// for objects in the current scope,
220/// - For every jump add to CFGBlock destructors for objects
221/// between CFGBuilder::ScopePos and local scope position saved for jump
222/// target. Thanks to C++ restrictions on goto jumps we can be sure that
223/// jump target position will be on the path to root from CFGBuilder::ScopePos
224/// (adding any variable that doesn't need constructor to be called to
225/// LocalScope can break this assumption),
226///
227class LocalScope {
228public:
229 using AutomaticVarsTy = BumpVector<VarDecl *>;
230
231 /// const_iterator - Iterates local scope backwards and jumps to previous
232 /// scope on reaching the beginning of currently iterated scope.
233 class const_iterator {
234 const LocalScope* Scope = nullptr;
235
236 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
237 /// Invalid iterator (with null Scope) has VarIter equal to 0.
238 unsigned VarIter = 0;
239
240 public:
241 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
242 /// Incrementing invalid iterator is allowed and will result in invalid
243 /// iterator.
244 const_iterator() = default;
245
246 /// Create valid iterator. In case when S.Prev is an invalid iterator and
247 /// I is equal to 0, this will create invalid iterator.
248 const_iterator(const LocalScope& S, unsigned I)
249 : Scope(&S), VarIter(I) {
250 // Iterator to "end" of scope is not allowed. Handle it by going up
251 // in scopes tree possibly up to invalid iterator in the root.
252 if (VarIter == 0 && Scope)
253 *this = Scope->Prev;
254 }
255
256 VarDecl *const* operator->() const {
257 assert(Scope && "Dereferencing invalid iterator is not allowed");
258 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
259 return &Scope->Vars[VarIter - 1];
260 }
261
262 const VarDecl *getFirstVarInScope() const {
263 assert(Scope && "Dereferencing invalid iterator is not allowed");
264 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
265 return Scope->Vars[0];
266 }
267
268 VarDecl *operator*() const {
269 return *this->operator->();
270 }
271
272 const_iterator &operator++() {
273 if (!Scope)
274 return *this;
275
276 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
277 --VarIter;
278 if (VarIter == 0)
279 *this = Scope->Prev;
280 return *this;
281 }
282 const_iterator operator++(int) {
283 const_iterator P = *this;
284 ++*this;
285 return P;
286 }
287
288 bool operator==(const const_iterator &rhs) const {
289 return Scope == rhs.Scope && VarIter == rhs.VarIter;
290 }
291 bool operator!=(const const_iterator &rhs) const {
292 return !(*this == rhs);
293 }
294
295 explicit operator bool() const {
296 return *this != const_iterator();
297 }
298
299 int distance(const_iterator L);
300 const_iterator shared_parent(const_iterator L);
301 bool pointsToFirstDeclaredVar() { return VarIter == 1; }
302 bool inSameLocalScope(const_iterator rhs) { return Scope == rhs.Scope; }
303 };
304
305private:
306 BumpVectorContext ctx;
307
308 /// Automatic variables in order of declaration.
309 AutomaticVarsTy Vars;
310
311 /// Iterator to variable in previous scope that was declared just before
312 /// begin of this scope.
313 const_iterator Prev;
314
315public:
316 /// Constructs empty scope linked to previous scope in specified place.
317 LocalScope(BumpVectorContext ctx, const_iterator P)
318 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
319
320 /// Begin of scope in direction of CFG building (backwards).
321 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
322
323 void addVar(VarDecl *VD) {
324 Vars.push_back(Elt: VD, C&: ctx);
325 }
326};
327
328} // namespace
329
330/// distance - Calculates distance from this to L. L must be reachable from this
331/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
332/// number of scopes between this and L.
333int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
334 int D = 0;
335 const_iterator F = *this;
336 while (F.Scope != L.Scope) {
337 assert(F != const_iterator() &&
338 "L iterator is not reachable from F iterator.");
339 D += F.VarIter;
340 F = F.Scope->Prev;
341 }
342 D += F.VarIter - L.VarIter;
343 return D;
344}
345
346/// Calculates the closest parent of this iterator
347/// that is in a scope reachable through the parents of L.
348/// I.e. when using 'goto' from this to L, the lifetime of all variables
349/// between this and shared_parent(L) end.
350LocalScope::const_iterator
351LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
352 // one of iterators is not valid (we are not in scope), so common
353 // parent is const_iterator() (i.e. sentinel).
354 if ((*this == const_iterator()) || (L == const_iterator())) {
355 return const_iterator();
356 }
357
358 const_iterator F = *this;
359 if (F.inSameLocalScope(rhs: L)) {
360 // Iterators are in the same scope, get common subset of variables.
361 F.VarIter = std::min(a: F.VarIter, b: L.VarIter);
362 return F;
363 }
364
365 llvm::SmallDenseMap<const LocalScope *, unsigned, 4> ScopesOfL;
366 while (true) {
367 ScopesOfL.try_emplace(Key: L.Scope, Args&: L.VarIter);
368 if (L == const_iterator())
369 break;
370 L = L.Scope->Prev;
371 }
372
373 while (true) {
374 if (auto LIt = ScopesOfL.find(Val: F.Scope); LIt != ScopesOfL.end()) {
375 // Get common subset of variables in given scope
376 F.VarIter = std::min(a: F.VarIter, b: LIt->getSecond());
377 return F;
378 }
379 assert(F != const_iterator() &&
380 "L iterator is not reachable from F iterator.");
381 F = F.Scope->Prev;
382 }
383}
384
385namespace {
386
387/// Structure for specifying position in CFG during its build process. It
388/// consists of CFGBlock that specifies position in CFG and
389/// LocalScope::const_iterator that specifies position in LocalScope graph.
390struct BlockScopePosPair {
391 CFGBlock *block = nullptr;
392 LocalScope::const_iterator scopePosition;
393
394 BlockScopePosPair() = default;
395 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
396 : block(b), scopePosition(scopePos) {}
397};
398
399/// TryResult - a class representing a variant over the values
400/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
401/// and is used by the CFGBuilder to decide if a branch condition
402/// can be decided up front during CFG construction.
403class TryResult {
404 int X = -1;
405
406public:
407 TryResult() = default;
408 TryResult(bool b) : X(b ? 1 : 0) {}
409
410 bool isTrue() const { return X == 1; }
411 bool isFalse() const { return X == 0; }
412 bool isKnown() const { return X >= 0; }
413
414 void negate() {
415 assert(isKnown());
416 X ^= 0x1;
417 }
418};
419
420} // namespace
421
422static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
423 if (!R1.isKnown() || !R2.isKnown())
424 return TryResult();
425 return TryResult(R1.isTrue() && R2.isTrue());
426}
427
428namespace {
429
430class reverse_children {
431 llvm::SmallVector<Stmt *, 12> childrenBuf;
432 ArrayRef<Stmt *> children;
433
434public:
435 reverse_children(Stmt *S, ASTContext &Ctx);
436
437 using iterator = ArrayRef<Stmt *>::reverse_iterator;
438
439 iterator begin() const { return children.rbegin(); }
440 iterator end() const { return children.rend(); }
441};
442
443} // namespace
444
445reverse_children::reverse_children(Stmt *S, ASTContext &Ctx) {
446 if (CallExpr *CE = dyn_cast<CallExpr>(Val: S)) {
447 children = CE->getRawSubExprs();
448 return;
449 }
450
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>(Val: S);
455 children = llvm::ArrayRef(reinterpret_cast<Stmt **>(IE->getInits()),
456 IE->getNumInits());
457 return;
458 }
459
460 case Stmt::AttributedStmtClass: {
461 // For an attributed stmt, the "children()" returns only the NullStmt
462 // (;) but semantically the "children" are supposed to be the
463 // expressions _within_ i.e. the two square brackets i.e. [[ HERE ]]
464 // so we add the subexpressions first, _then_ add the "children"
465 auto *AS = cast<AttributedStmt>(Val: S);
466 for (const auto *Attr : AS->getAttrs()) {
467 if (const auto *AssumeAttr = dyn_cast<CXXAssumeAttr>(Attr)) {
468 Expr *AssumeExpr = AssumeAttr->getAssumption();
469 if (!AssumeExpr->HasSideEffects(Ctx)) {
470 childrenBuf.push_back(AssumeExpr);
471 }
472 }
473 }
474
475 // Visit the actual children AST nodes.
476 // For CXXAssumeAttrs, this is always a NullStmt.
477 llvm::append_range(C&: childrenBuf, R: AS->children());
478 children = childrenBuf;
479 return;
480 }
481 default:
482 break;
483 }
484
485 // Default case for all other statements.
486 llvm::append_range(C&: childrenBuf, R: S->children());
487
488 // This needs to be done *after* childrenBuf has been populated.
489 children = childrenBuf;
490}
491
492namespace {
493
494/// CFGBuilder - This class implements CFG construction from an AST.
495/// The builder is stateful: an instance of the builder should be used to only
496/// construct a single CFG.
497///
498/// Example usage:
499///
500/// CFGBuilder builder;
501/// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
502///
503/// CFG construction is done via a recursive walk of an AST. We actually parse
504/// the AST in reverse order so that the successor of a basic block is
505/// constructed prior to its predecessor. This allows us to nicely capture
506/// implicit fall-throughs without extra basic blocks.
507class CFGBuilder {
508 using JumpTarget = BlockScopePosPair;
509 using JumpSource = BlockScopePosPair;
510
511 ASTContext *Context;
512 std::unique_ptr<CFG> cfg;
513
514 // Current block.
515 CFGBlock *Block = nullptr;
516
517 // Block after the current block.
518 CFGBlock *Succ = nullptr;
519
520 JumpTarget ContinueJumpTarget;
521 JumpTarget BreakJumpTarget;
522 JumpTarget SEHLeaveJumpTarget;
523 CFGBlock *SwitchTerminatedBlock = nullptr;
524 CFGBlock *DefaultCaseBlock = nullptr;
525
526 // This can point to either a C++ try, an Objective-C @try, or an SEH __try.
527 // try and @try can be mixed and generally work the same.
528 // The frontend forbids mixing SEH __try with either try or @try.
529 // So having one for all three is enough.
530 CFGBlock *TryTerminatedBlock = nullptr;
531
532 // Current position in local scope.
533 LocalScope::const_iterator ScopePos;
534
535 // LabelMap records the mapping from Label expressions to their jump targets.
536 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
537 LabelMapTy LabelMap;
538
539 // A list of blocks that end with a "goto" that must be backpatched to their
540 // resolved targets upon completion of CFG construction.
541 using BackpatchBlocksTy = std::vector<JumpSource>;
542 BackpatchBlocksTy BackpatchBlocks;
543
544 // A list of labels whose address has been taken (for indirect gotos).
545 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
546 LabelSetTy AddressTakenLabels;
547
548 // Information about the currently visited C++ object construction site.
549 // This is set in the construction trigger and read when the constructor
550 // or a function that returns an object by value is being visited.
551 llvm::DenseMap<Expr *, const ConstructionContextLayer *>
552 ConstructionContextMap;
553
554 bool badCFG = false;
555 const CFG::BuildOptions &BuildOpts;
556
557 // State to track for building switch statements.
558 bool switchExclusivelyCovered = false;
559 Expr::EvalResult *switchCond = nullptr;
560
561 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
562 const Stmt *lastLookup = nullptr;
563
564 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
565 // during construction of branches for chained logical operators.
566 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
567 CachedBoolEvalsTy CachedBoolEvals;
568
569public:
570 explicit CFGBuilder(ASTContext *astContext,
571 const CFG::BuildOptions &buildOpts)
572 : Context(astContext), cfg(new CFG()), BuildOpts(buildOpts) {}
573
574 // buildCFG - Used by external clients to construct the CFG.
575 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
576
577 bool alwaysAdd(const Stmt *stmt);
578
579private:
580 // Visitors to walk an AST and construct the CFG.
581 CFGBlock *VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc);
582 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
583 CFGBlock *VisitAttributedStmt(AttributedStmt *A, AddStmtChoice asc);
584 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
585 CFGBlock *VisitBreakStmt(BreakStmt *B);
586 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
587 CFGBlock *VisitCaseStmt(CaseStmt *C);
588 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
589 CFGBlock *VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed);
590 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
591 AddStmtChoice asc);
592 CFGBlock *VisitContinueStmt(ContinueStmt *C);
593 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
594 AddStmtChoice asc);
595 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
596 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
597 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
598 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
599 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
600 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
601 AddStmtChoice asc);
602 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
603 AddStmtChoice asc);
604 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
605 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
606 CFGBlock *VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc);
607 CFGBlock *VisitDeclStmt(DeclStmt *DS);
608 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
609 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
610 CFGBlock *VisitDoStmt(DoStmt *D);
611 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
612 AddStmtChoice asc, bool ExternallyDestructed);
613 CFGBlock *VisitForStmt(ForStmt *F);
614 CFGBlock *VisitGotoStmt(GotoStmt *G);
615 CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc);
616 CFGBlock *VisitIfStmt(IfStmt *I);
617 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
618 CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc);
619 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
620 CFGBlock *VisitLabelStmt(LabelStmt *L);
621 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
622 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
623 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
624 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
625 Stmt *Term,
626 CFGBlock *TrueBlock,
627 CFGBlock *FalseBlock);
628 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
629 AddStmtChoice asc);
630 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
631 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
632 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
633 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
634 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
635 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
636 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
637 CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
638 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
639 CFGBlock *VisitReturnStmt(Stmt *S);
640 CFGBlock *VisitCoroutineSuspendExpr(CoroutineSuspendExpr *S,
641 AddStmtChoice asc);
642 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
643 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
644 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
645 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
646 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
647 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
648 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
649 AddStmtChoice asc);
650 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
651 CFGBlock *VisitWhileStmt(WhileStmt *W);
652 CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
653
654 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
655 bool ExternallyDestructed = false);
656 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
657 CFGBlock *VisitChildren(Stmt *S);
658 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
659 CFGBlock *VisitOMPExecutableDirective(OMPExecutableDirective *D,
660 AddStmtChoice asc);
661
662 void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
663 const Stmt *S) {
664 if (ScopePos && (VD == ScopePos.getFirstVarInScope()))
665 appendScopeBegin(B, VD, S);
666 }
667
668 /// When creating the CFG for temporary destructors, we want to mirror the
669 /// branch structure of the corresponding constructor calls.
670 /// Thus, while visiting a statement for temporary destructors, we keep a
671 /// context to keep track of the following information:
672 /// - whether a subexpression is executed unconditionally
673 /// - if a subexpression is executed conditionally, the first
674 /// CXXBindTemporaryExpr we encounter in that subexpression (which
675 /// corresponds to the last temporary destructor we have to call for this
676 /// subexpression) and the CFG block at that point (which will become the
677 /// successor block when inserting the decision point).
678 ///
679 /// That way, we can build the branch structure for temporary destructors as
680 /// follows:
681 /// 1. If a subexpression is executed unconditionally, we add the temporary
682 /// destructor calls to the current block.
683 /// 2. If a subexpression is executed conditionally, when we encounter a
684 /// CXXBindTemporaryExpr:
685 /// a) If it is the first temporary destructor call in the subexpression,
686 /// we remember the CXXBindTemporaryExpr and the current block in the
687 /// TempDtorContext; we start a new block, and insert the temporary
688 /// destructor call.
689 /// b) Otherwise, add the temporary destructor call to the current block.
690 /// 3. When we finished visiting a conditionally executed subexpression,
691 /// and we found at least one temporary constructor during the visitation
692 /// (2.a has executed), we insert a decision block that uses the
693 /// CXXBindTemporaryExpr as terminator, and branches to the current block
694 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
695 /// branches to the stored successor.
696 struct TempDtorContext {
697 TempDtorContext() = default;
698 TempDtorContext(TryResult KnownExecuted)
699 : IsConditional(true), KnownExecuted(KnownExecuted) {}
700
701 /// Returns whether we need to start a new branch for a temporary destructor
702 /// call. This is the case when the temporary destructor is
703 /// conditionally executed, and it is the first one we encounter while
704 /// visiting a subexpression - other temporary destructors at the same level
705 /// will be added to the same block and are executed under the same
706 /// condition.
707 bool needsTempDtorBranch() const {
708 return IsConditional && !TerminatorExpr;
709 }
710
711 /// Remember the successor S of a temporary destructor decision branch for
712 /// the corresponding CXXBindTemporaryExpr E.
713 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
714 Succ = S;
715 TerminatorExpr = E;
716 }
717
718 const bool IsConditional = false;
719 const TryResult KnownExecuted = true;
720 CFGBlock *Succ = nullptr;
721 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
722 };
723
724 // Visitors to walk an AST and generate destructors of temporaries in
725 // full expression.
726 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
727 TempDtorContext &Context);
728 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
729 TempDtorContext &Context);
730 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
731 bool ExternallyDestructed,
732 TempDtorContext &Context);
733 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
734 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context);
735 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
736 AbstractConditionalOperator *E, bool ExternallyDestructed,
737 TempDtorContext &Context);
738 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
739 CFGBlock *FalseSucc = nullptr);
740
741 // NYS == Not Yet Supported
742 CFGBlock *NYS() {
743 badCFG = true;
744 return Block;
745 }
746
747 // Remember to apply the construction context based on the current \p Layer
748 // when constructing the CFG element for \p CE.
749 void consumeConstructionContext(const ConstructionContextLayer *Layer,
750 Expr *E);
751
752 // Scan \p Child statement to find constructors in it, while keeping in mind
753 // that its parent statement is providing a partial construction context
754 // described by \p Layer. If a constructor is found, it would be assigned
755 // the context based on the layer. If an additional construction context layer
756 // is found, the function recurses into that.
757 void findConstructionContexts(const ConstructionContextLayer *Layer,
758 Stmt *Child);
759
760 // Scan all arguments of a call expression for a construction context.
761 // These sorts of call expressions don't have a common superclass,
762 // hence strict duck-typing.
763 template <typename CallLikeExpr,
764 typename = std::enable_if_t<
765 std::is_base_of_v<CallExpr, CallLikeExpr> ||
766 std::is_base_of_v<CXXConstructExpr, CallLikeExpr> ||
767 std::is_base_of_v<ObjCMessageExpr, CallLikeExpr>>>
768 void findConstructionContextsForArguments(CallLikeExpr *E) {
769 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
770 Expr *Arg = E->getArg(i);
771 if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
772 findConstructionContexts(
773 ConstructionContextLayer::create(C&: cfg->getBumpVectorContext(),
774 Item: ConstructionContextItem(E, i)),
775 Arg);
776 }
777 }
778
779 // Unset the construction context after consuming it. This is done immediately
780 // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so
781 // there's no need to do this manually in every Visit... function.
782 void cleanupConstructionContext(Expr *E);
783
784 void autoCreateBlock() { if (!Block) Block = createBlock(); }
785
786 CFGBlock *createBlock(bool add_successor = true);
787 CFGBlock *createNoReturnBlock();
788
789 CFGBlock *addStmt(Stmt *S) {
790 return Visit(S, asc: AddStmtChoice::AlwaysAdd);
791 }
792
793 CFGBlock *addInitializer(CXXCtorInitializer *I);
794 void addLoopExit(const Stmt *LoopStmt);
795 void addAutomaticObjHandling(LocalScope::const_iterator B,
796 LocalScope::const_iterator E, Stmt *S);
797 void addAutomaticObjDestruction(LocalScope::const_iterator B,
798 LocalScope::const_iterator E, Stmt *S);
799 void addScopeExitHandling(LocalScope::const_iterator B,
800 LocalScope::const_iterator E, Stmt *S);
801 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
802 void addScopeChangesHandling(LocalScope::const_iterator SrcPos,
803 LocalScope::const_iterator DstPos,
804 Stmt *S);
805 CFGBlock *createScopeChangesHandlingBlock(LocalScope::const_iterator SrcPos,
806 CFGBlock *SrcBlk,
807 LocalScope::const_iterator DstPost,
808 CFGBlock *DstBlk);
809
810 // Local scopes creation.
811 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
812
813 void addLocalScopeForStmt(Stmt *S);
814 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
815 LocalScope* Scope = nullptr);
816 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
817
818 void addLocalScopeAndDtors(Stmt *S);
819
820 const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
821 if (!BuildOpts.AddRichCXXConstructors)
822 return nullptr;
823
824 const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(Val: E);
825 if (!Layer)
826 return nullptr;
827
828 cleanupConstructionContext(E);
829 return ConstructionContext::createFromLayers(C&: cfg->getBumpVectorContext(),
830 TopLayer: Layer);
831 }
832
833 // Interface to CFGBlock - adding CFGElements.
834
835 void appendStmt(CFGBlock *B, const Stmt *S) {
836 if (alwaysAdd(stmt: S) && cachedEntry)
837 cachedEntry->second = B;
838
839 // All block-level expressions should have already been IgnoreParens()ed.
840 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
841 B->appendStmt(statement: const_cast<Stmt*>(S), C&: cfg->getBumpVectorContext());
842 }
843
844 void appendConstructor(CXXConstructExpr *CE) {
845 CXXConstructorDecl *C = CE->getConstructor();
846 if (C && C->isNoReturn())
847 Block = createNoReturnBlock();
848 else
849 autoCreateBlock();
850
851 if (const ConstructionContext *CC =
852 retrieveAndCleanupConstructionContext(CE)) {
853 Block->appendConstructor(CE, CC, C&: cfg->getBumpVectorContext());
854 return;
855 }
856
857 // No valid construction context found. Fall back to statement.
858 Block->appendStmt(CE, cfg->getBumpVectorContext());
859 }
860
861 void appendCall(CFGBlock *B, CallExpr *CE) {
862 if (alwaysAdd(CE) && cachedEntry)
863 cachedEntry->second = B;
864
865 if (const ConstructionContext *CC =
866 retrieveAndCleanupConstructionContext(CE)) {
867 B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
868 return;
869 }
870
871 // No valid construction context found. Fall back to statement.
872 B->appendStmt(CE, cfg->getBumpVectorContext());
873 }
874
875 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
876 B->appendInitializer(initializer: I, C&: cfg->getBumpVectorContext());
877 }
878
879 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
880 B->appendNewAllocator(NE, C&: cfg->getBumpVectorContext());
881 }
882
883 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
884 B->appendBaseDtor(BS, C&: cfg->getBumpVectorContext());
885 }
886
887 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
888 B->appendMemberDtor(FD, C&: cfg->getBumpVectorContext());
889 }
890
891 void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
892 if (alwaysAdd(ME) && cachedEntry)
893 cachedEntry->second = B;
894
895 if (const ConstructionContext *CC =
896 retrieveAndCleanupConstructionContext(ME)) {
897 B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
898 return;
899 }
900
901 B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
902 cfg->getBumpVectorContext());
903 }
904
905 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
906 B->appendTemporaryDtor(E, C&: cfg->getBumpVectorContext());
907 }
908
909 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
910 B->appendAutomaticObjDtor(VD, S, C&: cfg->getBumpVectorContext());
911 }
912
913 void appendCleanupFunction(CFGBlock *B, VarDecl *VD) {
914 B->appendCleanupFunction(VD, C&: cfg->getBumpVectorContext());
915 }
916
917 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
918 B->appendLifetimeEnds(VD, S, C&: cfg->getBumpVectorContext());
919 }
920
921 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
922 B->appendLoopExit(LoopStmt, C&: cfg->getBumpVectorContext());
923 }
924
925 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
926 B->appendDeleteDtor(RD, DE, C&: cfg->getBumpVectorContext());
927 }
928
929 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
930 B->addSuccessor(Succ: CFGBlock::AdjacentBlock(S, IsReachable),
931 C&: cfg->getBumpVectorContext());
932 }
933
934 /// Add a reachable successor to a block, with the alternate variant that is
935 /// unreachable.
936 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
937 B->addSuccessor(Succ: CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
938 C&: cfg->getBumpVectorContext());
939 }
940
941 void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
942 if (BuildOpts.AddScopes)
943 B->appendScopeBegin(VD, S, C&: cfg->getBumpVectorContext());
944 }
945
946 void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
947 if (BuildOpts.AddScopes)
948 B->appendScopeEnd(VD, S, C&: cfg->getBumpVectorContext());
949 }
950
951 /// Find a relational comparison with an expression evaluating to a
952 /// boolean and a constant other than 0 and 1.
953 /// e.g. if ((x < y) == 10)
954 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
955 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
956 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
957
958 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHSExpr);
959 const Expr *BoolExpr = RHSExpr;
960 bool IntFirst = true;
961 if (!IntLiteral) {
962 IntLiteral = dyn_cast<IntegerLiteral>(Val: RHSExpr);
963 BoolExpr = LHSExpr;
964 IntFirst = false;
965 }
966
967 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
968 return TryResult();
969
970 llvm::APInt IntValue = IntLiteral->getValue();
971 if ((IntValue == 1) || (IntValue == 0))
972 return TryResult();
973
974 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
975 !IntValue.isNegative();
976
977 BinaryOperatorKind Bok = B->getOpcode();
978 if (Bok == BO_GT || Bok == BO_GE) {
979 // Always true for 10 > bool and bool > -1
980 // Always false for -1 > bool and bool > 10
981 return TryResult(IntFirst == IntLarger);
982 } else {
983 // Always true for -1 < bool and bool < 10
984 // Always false for 10 < bool and bool < -1
985 return TryResult(IntFirst != IntLarger);
986 }
987 }
988
989 /// Find an incorrect equality comparison. Either with an expression
990 /// evaluating to a boolean and a constant other than 0 and 1.
991 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
992 /// true/false e.q. (x & 8) == 4.
993 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
994 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
995 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
996
997 std::optional<llvm::APInt> IntLiteral1 =
998 getIntegerLiteralSubexpressionValue(E: LHSExpr);
999 const Expr *BoolExpr = RHSExpr;
1000
1001 if (!IntLiteral1) {
1002 IntLiteral1 = getIntegerLiteralSubexpressionValue(E: RHSExpr);
1003 BoolExpr = LHSExpr;
1004 }
1005
1006 if (!IntLiteral1)
1007 return TryResult();
1008
1009 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(Val: BoolExpr);
1010 if (BitOp && (BitOp->getOpcode() == BO_And ||
1011 BitOp->getOpcode() == BO_Or)) {
1012 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
1013 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
1014
1015 std::optional<llvm::APInt> IntLiteral2 =
1016 getIntegerLiteralSubexpressionValue(E: LHSExpr2);
1017
1018 if (!IntLiteral2)
1019 IntLiteral2 = getIntegerLiteralSubexpressionValue(E: RHSExpr2);
1020
1021 if (!IntLiteral2)
1022 return TryResult();
1023
1024 if ((BitOp->getOpcode() == BO_And &&
1025 (*IntLiteral2 & *IntLiteral1) != *IntLiteral1) ||
1026 (BitOp->getOpcode() == BO_Or &&
1027 (*IntLiteral2 | *IntLiteral1) != *IntLiteral1)) {
1028 if (BuildOpts.Observer)
1029 BuildOpts.Observer->compareBitwiseEquality(B,
1030 isAlwaysTrue: B->getOpcode() != BO_EQ);
1031 return TryResult(B->getOpcode() != BO_EQ);
1032 }
1033 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
1034 if ((*IntLiteral1 == 1) || (*IntLiteral1 == 0)) {
1035 return TryResult();
1036 }
1037 return TryResult(B->getOpcode() != BO_EQ);
1038 }
1039
1040 return TryResult();
1041 }
1042
1043 // Helper function to get an APInt from an expression. Supports expressions
1044 // which are an IntegerLiteral or a UnaryOperator and returns the value with
1045 // all operations performed on it.
1046 // FIXME: it would be good to unify this function with
1047 // IsIntegerLiteralConstantExpr at some point given the similarity between the
1048 // functions.
1049 std::optional<llvm::APInt>
1050 getIntegerLiteralSubexpressionValue(const Expr *E) {
1051
1052 // If unary.
1053 if (const auto *UnOp = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
1054 // Get the sub expression of the unary expression and get the Integer
1055 // Literal.
1056 const Expr *SubExpr = UnOp->getSubExpr()->IgnoreParens();
1057
1058 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: SubExpr)) {
1059
1060 llvm::APInt Value = IntLiteral->getValue();
1061
1062 // Perform the operation manually.
1063 switch (UnOp->getOpcode()) {
1064 case UO_Plus:
1065 return Value;
1066 case UO_Minus:
1067 return -Value;
1068 case UO_Not:
1069 return ~Value;
1070 case UO_LNot:
1071 return llvm::APInt(Context->getTypeSize(Context->IntTy), !Value);
1072 default:
1073 assert(false && "Unexpected unary operator!");
1074 return std::nullopt;
1075 }
1076 }
1077 } else if (const auto *IntLiteral =
1078 dyn_cast<IntegerLiteral>(Val: E->IgnoreParens()))
1079 return IntLiteral->getValue();
1080
1081 return std::nullopt;
1082 }
1083
1084 template <typename APFloatOrInt>
1085 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
1086 const APFloatOrInt &Value1,
1087 const APFloatOrInt &Value2) {
1088 switch (Relation) {
1089 default:
1090 return TryResult();
1091 case BO_EQ:
1092 return TryResult(Value1 == Value2);
1093 case BO_NE:
1094 return TryResult(Value1 != Value2);
1095 case BO_LT:
1096 return TryResult(Value1 < Value2);
1097 case BO_LE:
1098 return TryResult(Value1 <= Value2);
1099 case BO_GT:
1100 return TryResult(Value1 > Value2);
1101 case BO_GE:
1102 return TryResult(Value1 >= Value2);
1103 }
1104 }
1105
1106 /// There are two checks handled by this function:
1107 /// 1. Find a law-of-excluded-middle or law-of-noncontradiction expression
1108 /// e.g. if (x || !x), if (x && !x)
1109 /// 2. Find a pair of comparison expressions with or without parentheses
1110 /// with a shared variable and constants and a logical operator between them
1111 /// that always evaluates to either true or false.
1112 /// e.g. if (x != 3 || x != 4)
1113 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
1114 assert(B->isLogicalOp());
1115 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
1116 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
1117
1118 auto CheckLogicalOpWithNegatedVariable = [this, B](const Expr *E1,
1119 const Expr *E2) {
1120 if (const auto *Negate = dyn_cast<UnaryOperator>(Val: E1)) {
1121 if (Negate->getOpcode() == UO_LNot &&
1122 Expr::isSameComparisonOperand(E1: Negate->getSubExpr(), E2)) {
1123 bool AlwaysTrue = B->getOpcode() == BO_LOr;
1124 if (BuildOpts.Observer)
1125 BuildOpts.Observer->logicAlwaysTrue(B, isAlwaysTrue: AlwaysTrue);
1126 return TryResult(AlwaysTrue);
1127 }
1128 }
1129 return TryResult();
1130 };
1131
1132 TryResult Result = CheckLogicalOpWithNegatedVariable(LHSExpr, RHSExpr);
1133 if (Result.isKnown())
1134 return Result;
1135 Result = CheckLogicalOpWithNegatedVariable(RHSExpr, LHSExpr);
1136 if (Result.isKnown())
1137 return Result;
1138
1139 const auto *LHS = dyn_cast<BinaryOperator>(Val: LHSExpr);
1140 const auto *RHS = dyn_cast<BinaryOperator>(Val: RHSExpr);
1141 if (!LHS || !RHS)
1142 return {};
1143
1144 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
1145 return {};
1146
1147 const Expr *DeclExpr1;
1148 const Expr *NumExpr1;
1149 BinaryOperatorKind BO1;
1150 std::tie(args&: DeclExpr1, args&: BO1, args&: NumExpr1) = tryNormalizeBinaryOperator(B: LHS);
1151
1152 if (!DeclExpr1 || !NumExpr1)
1153 return {};
1154
1155 const Expr *DeclExpr2;
1156 const Expr *NumExpr2;
1157 BinaryOperatorKind BO2;
1158 std::tie(args&: DeclExpr2, args&: BO2, args&: NumExpr2) = tryNormalizeBinaryOperator(B: RHS);
1159
1160 if (!DeclExpr2 || !NumExpr2)
1161 return {};
1162
1163 // Check that it is the same variable on both sides.
1164 if (!Expr::isSameComparisonOperand(E1: DeclExpr1, E2: DeclExpr2))
1165 return {};
1166
1167 // Make sure the user's intent is clear (e.g. they're comparing against two
1168 // int literals, or two things from the same enum)
1169 if (!areExprTypesCompatible(E1: NumExpr1, E2: NumExpr2))
1170 return {};
1171
1172 // Check that the two expressions are of the same type.
1173 Expr::EvalResult L1Result, L2Result;
1174 if (!NumExpr1->EvaluateAsRValue(Result&: L1Result, Ctx: *Context) ||
1175 !NumExpr2->EvaluateAsRValue(Result&: L2Result, Ctx: *Context))
1176 return {};
1177
1178 // Check whether expression is always true/false by evaluating the
1179 // following
1180 // * variable x is less than the smallest literal.
1181 // * variable x is equal to the smallest literal.
1182 // * Variable x is between smallest and largest literal.
1183 // * Variable x is equal to the largest literal.
1184 // * Variable x is greater than largest literal.
1185 // This isn't technically correct, as it doesn't take into account the
1186 // possibility that the variable could be NaN. However, this is a very rare
1187 // case.
1188 auto AnalyzeConditions = [&](const auto &Values,
1189 const BinaryOperatorKind *BO1,
1190 const BinaryOperatorKind *BO2) -> TryResult {
1191 bool AlwaysTrue = true, AlwaysFalse = true;
1192 // Track value of both subexpressions. If either side is always
1193 // true/false, another warning should have already been emitted.
1194 bool LHSAlwaysTrue = true, LHSAlwaysFalse = true;
1195 bool RHSAlwaysTrue = true, RHSAlwaysFalse = true;
1196
1197 for (const auto &Value : Values) {
1198 TryResult Res1 =
1199 analyzeLogicOperatorCondition(*BO1, Value, Values[1] /* L1 */);
1200 TryResult Res2 =
1201 analyzeLogicOperatorCondition(*BO2, Value, Values[3] /* L2 */);
1202
1203 if (!Res1.isKnown() || !Res2.isKnown())
1204 return {};
1205
1206 const bool IsAnd = B->getOpcode() == BO_LAnd;
1207 const bool Combine = IsAnd ? (Res1.isTrue() && Res2.isTrue())
1208 : (Res1.isTrue() || Res2.isTrue());
1209
1210 AlwaysTrue &= Combine;
1211 AlwaysFalse &= !Combine;
1212
1213 LHSAlwaysTrue &= Res1.isTrue();
1214 LHSAlwaysFalse &= Res1.isFalse();
1215 RHSAlwaysTrue &= Res2.isTrue();
1216 RHSAlwaysFalse &= Res2.isFalse();
1217 }
1218
1219 if (AlwaysTrue || AlwaysFalse) {
1220 if (!LHSAlwaysTrue && !LHSAlwaysFalse && !RHSAlwaysTrue &&
1221 !RHSAlwaysFalse && BuildOpts.Observer) {
1222 BuildOpts.Observer->compareAlwaysTrue(B, isAlwaysTrue: AlwaysTrue);
1223 }
1224 return TryResult(AlwaysTrue);
1225 }
1226 return {};
1227 };
1228
1229 // Handle integer comparison.
1230 if (L1Result.Val.getKind() == APValue::Int &&
1231 L2Result.Val.getKind() == APValue::Int) {
1232 llvm::APSInt L1 = L1Result.Val.getInt();
1233 llvm::APSInt L2 = L2Result.Val.getInt();
1234
1235 // Can't compare signed with unsigned or with different bit width.
1236 if (L1.isSigned() != L2.isSigned() ||
1237 L1.getBitWidth() != L2.getBitWidth())
1238 return {};
1239
1240 // Values that will be used to determine if result of logical
1241 // operator is always true/false
1242 const llvm::APSInt Values[] = {
1243 // Value less than both Value1 and Value2
1244 llvm::APSInt::getMinValue(numBits: L1.getBitWidth(), Unsigned: L1.isUnsigned()),
1245 // L1
1246 L1,
1247 // Value between Value1 and Value2
1248 ((L1 < L2) ? L1 : L2) +
1249 llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1), L1.isUnsigned()),
1250 // L2
1251 L2,
1252 // Value greater than both Value1 and Value2
1253 llvm::APSInt::getMaxValue(numBits: L1.getBitWidth(), Unsigned: L1.isUnsigned()),
1254 };
1255
1256 return AnalyzeConditions(Values, &BO1, &BO2);
1257 }
1258
1259 // Handle float comparison.
1260 if (L1Result.Val.getKind() == APValue::Float &&
1261 L2Result.Val.getKind() == APValue::Float) {
1262 llvm::APFloat L1 = L1Result.Val.getFloat();
1263 llvm::APFloat L2 = L2Result.Val.getFloat();
1264 // Note that L1 and L2 do not necessarily have the same type. For example
1265 // `x != 0 || x != 1.0`, if `x` is a float16, the two literals `0` and
1266 // `1.0` are float16 and double respectively. In this case, we should do
1267 // a conversion before comparing L1 and L2. Their types must be
1268 // compatible since they are comparing with the same DRE.
1269 int Order = Context->getFloatingTypeSemanticOrder(LHS: NumExpr1->getType(),
1270 RHS: NumExpr2->getType());
1271 bool Ignored = false;
1272
1273 if (Order > 0) {
1274 // type rank L1 > L2:
1275 if (llvm::APFloat::opOK !=
1276 L2.convert(ToSemantics: L1.getSemantics(), RM: llvm::APFloat::rmNearestTiesToEven,
1277 losesInfo: &Ignored))
1278 return {};
1279 } else if (Order < 0)
1280 // type rank L1 < L2:
1281 if (llvm::APFloat::opOK !=
1282 L1.convert(ToSemantics: L2.getSemantics(), RM: llvm::APFloat::rmNearestTiesToEven,
1283 losesInfo: &Ignored))
1284 return {};
1285
1286 llvm::APFloat MidValue = L1;
1287 MidValue.add(RHS: L2, RM: llvm::APFloat::rmNearestTiesToEven);
1288 MidValue.divide(RHS: llvm::APFloat(MidValue.getSemantics(), "2.0"),
1289 RM: llvm::APFloat::rmNearestTiesToEven);
1290
1291 const llvm::APFloat Values[] = {
1292 llvm::APFloat::getSmallest(Sem: L1.getSemantics(), Negative: true), L1, MidValue, L2,
1293 llvm::APFloat::getLargest(Sem: L2.getSemantics(), Negative: false),
1294 };
1295
1296 return AnalyzeConditions(Values, &BO1, &BO2);
1297 }
1298
1299 return {};
1300 }
1301
1302 /// A bitwise-or with a non-zero constant always evaluates to true.
1303 TryResult checkIncorrectBitwiseOrOperator(const BinaryOperator *B) {
1304 const Expr *LHSConstant =
1305 tryTransformToLiteralConstant(E: B->getLHS()->IgnoreParenImpCasts());
1306 const Expr *RHSConstant =
1307 tryTransformToLiteralConstant(E: B->getRHS()->IgnoreParenImpCasts());
1308
1309 if ((LHSConstant && RHSConstant) || (!LHSConstant && !RHSConstant))
1310 return {};
1311
1312 const Expr *Constant = LHSConstant ? LHSConstant : RHSConstant;
1313
1314 Expr::EvalResult Result;
1315 if (!Constant->EvaluateAsInt(Result, Ctx: *Context))
1316 return {};
1317
1318 if (Result.Val.getInt() == 0)
1319 return {};
1320
1321 if (BuildOpts.Observer)
1322 BuildOpts.Observer->compareBitwiseOr(B);
1323
1324 return TryResult(true);
1325 }
1326
1327 /// Try and evaluate an expression to an integer constant.
1328 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
1329 if (!BuildOpts.PruneTriviallyFalseEdges)
1330 return false;
1331 return !S->isTypeDependent() &&
1332 !S->isValueDependent() &&
1333 S->EvaluateAsRValue(Result&: outResult, Ctx: *Context);
1334 }
1335
1336 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
1337 /// if we can evaluate to a known value, otherwise return -1.
1338 TryResult tryEvaluateBool(Expr *S) {
1339 if (!BuildOpts.PruneTriviallyFalseEdges ||
1340 S->isTypeDependent() || S->isValueDependent())
1341 return {};
1342
1343 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: S)) {
1344 if (Bop->isLogicalOp() || Bop->isEqualityOp()) {
1345 // Check the cache first.
1346 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(Val: S);
1347 if (I != CachedBoolEvals.end())
1348 return I->second; // already in map;
1349
1350 // Retrieve result at first, or the map might be updated.
1351 TryResult Result = evaluateAsBooleanConditionNoCache(E: S);
1352 CachedBoolEvals[S] = Result; // update or insert
1353 return Result;
1354 }
1355 else {
1356 switch (Bop->getOpcode()) {
1357 default: break;
1358 // For 'x & 0' and 'x * 0', we can determine that
1359 // the value is always false.
1360 case BO_Mul:
1361 case BO_And: {
1362 // If either operand is zero, we know the value
1363 // must be false.
1364 Expr::EvalResult LHSResult;
1365 if (Bop->getLHS()->EvaluateAsInt(Result&: LHSResult, Ctx: *Context)) {
1366 llvm::APSInt IntVal = LHSResult.Val.getInt();
1367 if (!IntVal.getBoolValue()) {
1368 return TryResult(false);
1369 }
1370 }
1371 Expr::EvalResult RHSResult;
1372 if (Bop->getRHS()->EvaluateAsInt(Result&: RHSResult, Ctx: *Context)) {
1373 llvm::APSInt IntVal = RHSResult.Val.getInt();
1374 if (!IntVal.getBoolValue()) {
1375 return TryResult(false);
1376 }
1377 }
1378 }
1379 break;
1380 }
1381 }
1382 }
1383
1384 return evaluateAsBooleanConditionNoCache(E: S);
1385 }
1386
1387 /// Evaluate as boolean \param E without using the cache.
1388 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1389 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: E)) {
1390 if (Bop->isLogicalOp()) {
1391 TryResult LHS = tryEvaluateBool(S: Bop->getLHS());
1392 if (LHS.isKnown()) {
1393 // We were able to evaluate the LHS, see if we can get away with not
1394 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1395 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1396 return LHS.isTrue();
1397
1398 TryResult RHS = tryEvaluateBool(S: Bop->getRHS());
1399 if (RHS.isKnown()) {
1400 if (Bop->getOpcode() == BO_LOr)
1401 return LHS.isTrue() || RHS.isTrue();
1402 else
1403 return LHS.isTrue() && RHS.isTrue();
1404 }
1405 } else {
1406 TryResult RHS = tryEvaluateBool(S: Bop->getRHS());
1407 if (RHS.isKnown()) {
1408 // We can't evaluate the LHS; however, sometimes the result
1409 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1410 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1411 return RHS.isTrue();
1412 } else {
1413 TryResult BopRes = checkIncorrectLogicOperator(B: Bop);
1414 if (BopRes.isKnown())
1415 return BopRes.isTrue();
1416 }
1417 }
1418
1419 return {};
1420 } else if (Bop->isEqualityOp()) {
1421 TryResult BopRes = checkIncorrectEqualityOperator(B: Bop);
1422 if (BopRes.isKnown())
1423 return BopRes.isTrue();
1424 } else if (Bop->isRelationalOp()) {
1425 TryResult BopRes = checkIncorrectRelationalOperator(B: Bop);
1426 if (BopRes.isKnown())
1427 return BopRes.isTrue();
1428 } else if (Bop->getOpcode() == BO_Or) {
1429 TryResult BopRes = checkIncorrectBitwiseOrOperator(B: Bop);
1430 if (BopRes.isKnown())
1431 return BopRes.isTrue();
1432 }
1433 }
1434
1435 bool Result;
1436 if (E->EvaluateAsBooleanCondition(Result, Ctx: *Context))
1437 return Result;
1438
1439 return {};
1440 }
1441
1442 bool hasTrivialDestructor(const VarDecl *VD) const;
1443 bool needsAutomaticDestruction(const VarDecl *VD) const;
1444};
1445
1446} // namespace
1447
1448Expr *
1449clang::extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr *AILE) {
1450 if (!AILE)
1451 return nullptr;
1452
1453 Expr *AILEInit = AILE->getSubExpr();
1454 while (const auto *E = dyn_cast<ArrayInitLoopExpr>(Val: AILEInit))
1455 AILEInit = E->getSubExpr();
1456
1457 return AILEInit;
1458}
1459
1460inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1461 const Stmt *stmt) const {
1462 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1463}
1464
1465bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
1466 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1467
1468 if (!BuildOpts.forcedBlkExprs)
1469 return shouldAdd;
1470
1471 if (lastLookup == stmt) {
1472 if (cachedEntry) {
1473 assert(cachedEntry->first == stmt);
1474 return true;
1475 }
1476 return shouldAdd;
1477 }
1478
1479 lastLookup = stmt;
1480
1481 // Perform the lookup!
1482 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1483
1484 if (!fb) {
1485 // No need to update 'cachedEntry', since it will always be null.
1486 assert(!cachedEntry);
1487 return shouldAdd;
1488 }
1489
1490 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(Val: stmt);
1491 if (itr == fb->end()) {
1492 cachedEntry = nullptr;
1493 return shouldAdd;
1494 }
1495
1496 cachedEntry = &*itr;
1497 return true;
1498}
1499
1500// FIXME: Add support for dependent-sized array types in C++?
1501// Does it even make sense to build a CFG for an uninstantiated template?
1502static const VariableArrayType *FindVA(const Type *t) {
1503 while (const ArrayType *vt = dyn_cast<ArrayType>(Val: t)) {
1504 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(Val: vt))
1505 if (vat->getSizeExpr())
1506 return vat;
1507
1508 t = vt->getElementType().getTypePtr();
1509 }
1510
1511 return nullptr;
1512}
1513
1514void CFGBuilder::consumeConstructionContext(
1515 const ConstructionContextLayer *Layer, Expr *E) {
1516 assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
1517 isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
1518 if (const ConstructionContextLayer *PreviouslyStoredLayer =
1519 ConstructionContextMap.lookup(Val: E)) {
1520 (void)PreviouslyStoredLayer;
1521 // We might have visited this child when we were finding construction
1522 // contexts within its parents.
1523 assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
1524 "Already within a different construction context!");
1525 } else {
1526 ConstructionContextMap[E] = Layer;
1527 }
1528}
1529
1530void CFGBuilder::findConstructionContexts(
1531 const ConstructionContextLayer *Layer, Stmt *Child) {
1532 if (!BuildOpts.AddRichCXXConstructors)
1533 return;
1534
1535 if (!Child)
1536 return;
1537
1538 auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) {
1539 return ConstructionContextLayer::create(C&: cfg->getBumpVectorContext(), Item,
1540 Parent: Layer);
1541 };
1542
1543 switch(Child->getStmtClass()) {
1544 case Stmt::CXXConstructExprClass:
1545 case Stmt::CXXTemporaryObjectExprClass: {
1546 // Support pre-C++17 copy elision AST.
1547 auto *CE = cast<CXXConstructExpr>(Val: Child);
1548 if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
1549 findConstructionContexts(withExtraLayer(CE), CE->getArg(Arg: 0));
1550 }
1551
1552 consumeConstructionContext(Layer, CE);
1553 break;
1554 }
1555 // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
1556 // FIXME: An isa<> would look much better but this whole switch is a
1557 // workaround for an internal compiler error in MSVC 2015 (see r326021).
1558 case Stmt::CallExprClass:
1559 case Stmt::CXXMemberCallExprClass:
1560 case Stmt::CXXOperatorCallExprClass:
1561 case Stmt::UserDefinedLiteralClass:
1562 case Stmt::ObjCMessageExprClass: {
1563 auto *E = cast<Expr>(Val: Child);
1564 if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
1565 consumeConstructionContext(Layer, E);
1566 break;
1567 }
1568 case Stmt::ExprWithCleanupsClass: {
1569 auto *Cleanups = cast<ExprWithCleanups>(Val: Child);
1570 findConstructionContexts(Layer, Child: Cleanups->getSubExpr());
1571 break;
1572 }
1573 case Stmt::CXXFunctionalCastExprClass: {
1574 auto *Cast = cast<CXXFunctionalCastExpr>(Val: Child);
1575 findConstructionContexts(Layer, Child: Cast->getSubExpr());
1576 break;
1577 }
1578 case Stmt::ImplicitCastExprClass: {
1579 auto *Cast = cast<ImplicitCastExpr>(Val: Child);
1580 // Should we support other implicit cast kinds?
1581 switch (Cast->getCastKind()) {
1582 case CK_NoOp:
1583 case CK_ConstructorConversion:
1584 findConstructionContexts(Layer, Child: Cast->getSubExpr());
1585 break;
1586 default:
1587 break;
1588 }
1589 break;
1590 }
1591 case Stmt::CXXBindTemporaryExprClass: {
1592 auto *BTE = cast<CXXBindTemporaryExpr>(Val: Child);
1593 findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
1594 break;
1595 }
1596 case Stmt::MaterializeTemporaryExprClass: {
1597 // Normally we don't want to search in MaterializeTemporaryExpr because
1598 // it indicates the beginning of a temporary object construction context,
1599 // so it shouldn't be found in the middle. However, if it is the beginning
1600 // of an elidable copy or move construction context, we need to include it.
1601 if (Layer->getItem().getKind() ==
1602 ConstructionContextItem::ElidableConstructorKind) {
1603 auto *MTE = cast<MaterializeTemporaryExpr>(Val: Child);
1604 findConstructionContexts(withExtraLayer(MTE), MTE->getSubExpr());
1605 }
1606 break;
1607 }
1608 case Stmt::ConditionalOperatorClass: {
1609 auto *CO = cast<ConditionalOperator>(Val: Child);
1610 if (Layer->getItem().getKind() !=
1611 ConstructionContextItem::MaterializationKind) {
1612 // If the object returned by the conditional operator is not going to be a
1613 // temporary object that needs to be immediately materialized, then
1614 // it must be C++17 with its mandatory copy elision. Do not yet promise
1615 // to support this case.
1616 assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
1617 Context->getLangOpts().CPlusPlus17);
1618 break;
1619 }
1620 findConstructionContexts(Layer, CO->getLHS());
1621 findConstructionContexts(Layer, CO->getRHS());
1622 break;
1623 }
1624 case Stmt::InitListExprClass: {
1625 auto *ILE = cast<InitListExpr>(Val: Child);
1626 if (ILE->isTransparent()) {
1627 findConstructionContexts(Layer, ILE->getInit(Init: 0));
1628 break;
1629 }
1630 // TODO: Handle other cases. For now, fail to find construction contexts.
1631 break;
1632 }
1633 case Stmt::ParenExprClass: {
1634 // If expression is placed into parenthesis we should propagate the parent
1635 // construction context to subexpressions.
1636 auto *PE = cast<ParenExpr>(Val: Child);
1637 findConstructionContexts(Layer, PE->getSubExpr());
1638 break;
1639 }
1640 default:
1641 break;
1642 }
1643}
1644
1645void CFGBuilder::cleanupConstructionContext(Expr *E) {
1646 assert(BuildOpts.AddRichCXXConstructors &&
1647 "We should not be managing construction contexts!");
1648 assert(ConstructionContextMap.count(E) &&
1649 "Cannot exit construction context without the context!");
1650 ConstructionContextMap.erase(Val: E);
1651}
1652
1653/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1654/// arbitrary statement. Examples include a single expression or a function
1655/// body (compound statement). The ownership of the returned CFG is
1656/// transferred to the caller. If CFG construction fails, this method returns
1657/// NULL.
1658std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
1659 assert(cfg.get());
1660 if (!Statement)
1661 return nullptr;
1662
1663 // Create an empty block that will serve as the exit block for the CFG. Since
1664 // this is the first block added to the CFG, it will be implicitly registered
1665 // as the exit block.
1666 Succ = createBlock();
1667 assert(Succ == &cfg->getExit());
1668 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
1669
1670 if (BuildOpts.AddImplicitDtors)
1671 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(Val: D))
1672 addImplicitDtorsForDestructor(DD);
1673
1674 // Visit the statements and create the CFG.
1675 CFGBlock *B = addStmt(S: Statement);
1676
1677 if (badCFG)
1678 return nullptr;
1679
1680 // For C++ constructor add initializers to CFG. Constructors of virtual bases
1681 // are ignored unless the object is of the most derived class.
1682 // class VBase { VBase() = default; VBase(int) {} };
1683 // class A : virtual public VBase { A() : VBase(0) {} };
1684 // class B : public A {};
1685 // B b; // Constructor calls in order: VBase(), A(), B().
1686 // // VBase(0) is ignored because A isn't the most derived class.
1687 // This may result in the virtual base(s) being already initialized at this
1688 // point, in which case we should jump right onto non-virtual bases and
1689 // fields. To handle this, make a CFG branch. We only need to add one such
1690 // branch per constructor, since the Standard states that all virtual bases
1691 // shall be initialized before non-virtual bases and direct data members.
1692 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Val: D)) {
1693 CFGBlock *VBaseSucc = nullptr;
1694 for (auto *I : llvm::reverse(C: CD->inits())) {
1695 if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
1696 I->isBaseInitializer() && I->isBaseVirtual()) {
1697 // We've reached the first virtual base init while iterating in reverse
1698 // order. Make a new block for virtual base initializers so that we
1699 // could skip them.
1700 VBaseSucc = Succ = B ? B : &cfg->getExit();
1701 Block = createBlock();
1702 }
1703 B = addInitializer(I);
1704 if (badCFG)
1705 return nullptr;
1706 }
1707 if (VBaseSucc) {
1708 // Make a branch block for potentially skipping virtual base initializers.
1709 Succ = VBaseSucc;
1710 B = createBlock();
1711 B->setTerminator(
1712 CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch));
1713 addSuccessor(B, S: Block, IsReachable: true);
1714 }
1715 }
1716
1717 if (B)
1718 Succ = B;
1719
1720 // Backpatch the gotos whose label -> block mappings we didn't know when we
1721 // encountered them.
1722 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1723 E = BackpatchBlocks.end(); I != E; ++I ) {
1724
1725 CFGBlock *B = I->block;
1726 if (auto *G = dyn_cast<GotoStmt>(Val: B->getTerminator())) {
1727 LabelMapTy::iterator LI = LabelMap.find(Val: G->getLabel());
1728 // If there is no target for the goto, then we are looking at an
1729 // incomplete AST. Handle this by not registering a successor.
1730 if (LI == LabelMap.end())
1731 continue;
1732 JumpTarget JT = LI->second;
1733
1734 CFGBlock *SuccBlk = createScopeChangesHandlingBlock(
1735 SrcPos: I->scopePosition, SrcBlk: B, DstPost: JT.scopePosition, DstBlk: JT.block);
1736 addSuccessor(B, S: SuccBlk);
1737 } else if (auto *G = dyn_cast<GCCAsmStmt>(Val: B->getTerminator())) {
1738 CFGBlock *Successor = (I+1)->block;
1739 for (auto *L : G->labels()) {
1740 LabelMapTy::iterator LI = LabelMap.find(L->getLabel());
1741 // If there is no target for the goto, then we are looking at an
1742 // incomplete AST. Handle this by not registering a successor.
1743 if (LI == LabelMap.end())
1744 continue;
1745 JumpTarget JT = LI->second;
1746 // Successor has been added, so skip it.
1747 if (JT.block == Successor)
1748 continue;
1749 addSuccessor(B, JT.block);
1750 }
1751 I++;
1752 }
1753 }
1754
1755 // Add successors to the Indirect Goto Dispatch block (if we have one).
1756 if (CFGBlock *B = cfg->getIndirectGotoBlock())
1757 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1758 E = AddressTakenLabels.end(); I != E; ++I ) {
1759 // Lookup the target block.
1760 LabelMapTy::iterator LI = LabelMap.find(Val: *I);
1761
1762 // If there is no target block that contains label, then we are looking
1763 // at an incomplete AST. Handle this by not registering a successor.
1764 if (LI == LabelMap.end()) continue;
1765
1766 addSuccessor(B, S: LI->second.block);
1767 }
1768
1769 // Create an empty entry block that has no predecessors.
1770 cfg->setEntry(createBlock());
1771
1772 if (BuildOpts.AddRichCXXConstructors)
1773 assert(ConstructionContextMap.empty() &&
1774 "Not all construction contexts were cleaned up!");
1775
1776 return std::move(cfg);
1777}
1778
1779/// createBlock - Used to lazily create blocks that are connected
1780/// to the current (global) successor.
1781CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1782 CFGBlock *B = cfg->createBlock();
1783 if (add_successor && Succ)
1784 addSuccessor(B, S: Succ);
1785 return B;
1786}
1787
1788/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1789/// CFG. It is *not* connected to the current (global) successor, and instead
1790/// directly tied to the exit block in order to be reachable.
1791CFGBlock *CFGBuilder::createNoReturnBlock() {
1792 CFGBlock *B = createBlock(add_successor: false);
1793 B->setHasNoReturnElement();
1794 addSuccessor(B, ReachableBlock: &cfg->getExit(), AltBlock: Succ);
1795 return B;
1796}
1797
1798/// addInitializer - Add C++ base or member initializer element to CFG.
1799CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
1800 if (!BuildOpts.AddInitializers)
1801 return Block;
1802
1803 bool HasTemporaries = false;
1804
1805 // Destructors of temporaries in initialization expression should be called
1806 // after initialization finishes.
1807 Expr *Init = I->getInit();
1808 if (Init) {
1809 HasTemporaries = isa<ExprWithCleanups>(Val: Init);
1810
1811 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1812 // Generate destructors for temporaries in initialization expression.
1813 TempDtorContext Context;
1814 VisitForTemporaryDtors(E: cast<ExprWithCleanups>(Val: Init)->getSubExpr(),
1815 /*ExternallyDestructed=*/false, Context);
1816 }
1817 }
1818
1819 autoCreateBlock();
1820 appendInitializer(B: Block, I);
1821
1822 if (Init) {
1823 // If the initializer is an ArrayInitLoopExpr, we want to extract the
1824 // initializer, that's used for each element.
1825 auto *AILEInit = extractElementInitializerFromNestedAILE(
1826 AILE: dyn_cast<ArrayInitLoopExpr>(Val: Init));
1827
1828 findConstructionContexts(
1829 ConstructionContextLayer::create(C&: cfg->getBumpVectorContext(), Item: I),
1830 AILEInit ? AILEInit : Init);
1831
1832 if (HasTemporaries) {
1833 // For expression with temporaries go directly to subexpression to omit
1834 // generating destructors for the second time.
1835 return Visit(S: cast<ExprWithCleanups>(Val: Init)->getSubExpr());
1836 }
1837 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1838 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Val: Init)) {
1839 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1840 // may cause the same Expr to appear more than once in the CFG. Doing it
1841 // here is safe because there's only one initializer per field.
1842 autoCreateBlock();
1843 appendStmt(Block, Default);
1844 if (Stmt *Child = Default->getExpr())
1845 if (CFGBlock *R = Visit(S: Child))
1846 Block = R;
1847 return Block;
1848 }
1849 }
1850 return Visit(Init);
1851 }
1852
1853 return Block;
1854}
1855
1856/// Retrieve the type of the temporary object whose lifetime was
1857/// extended by a local reference with the given initializer.
1858static QualType getReferenceInitTemporaryType(const Expr *Init,
1859 bool *FoundMTE = nullptr) {
1860 while (true) {
1861 // Skip parentheses.
1862 Init = Init->IgnoreParens();
1863
1864 // Skip through cleanups.
1865 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Val: Init)) {
1866 Init = EWC->getSubExpr();
1867 continue;
1868 }
1869
1870 // Skip through the temporary-materialization expression.
1871 if (const MaterializeTemporaryExpr *MTE
1872 = dyn_cast<MaterializeTemporaryExpr>(Val: Init)) {
1873 Init = MTE->getSubExpr();
1874 if (FoundMTE)
1875 *FoundMTE = true;
1876 continue;
1877 }
1878
1879 // Skip sub-object accesses into rvalues.
1880 const Expr *SkippedInit = Init->skipRValueSubobjectAdjustments();
1881 if (SkippedInit != Init) {
1882 Init = SkippedInit;
1883 continue;
1884 }
1885
1886 break;
1887 }
1888
1889 return Init->getType();
1890}
1891
1892// TODO: Support adding LoopExit element to the CFG in case where the loop is
1893// ended by ReturnStmt, GotoStmt or ThrowExpr.
1894void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1895 if(!BuildOpts.AddLoopExit)
1896 return;
1897 autoCreateBlock();
1898 appendLoopExit(B: Block, LoopStmt);
1899}
1900
1901/// Adds the CFG elements for leaving the scope of automatic objects in
1902/// range [B, E). This include following:
1903/// * AutomaticObjectDtor for variables with non-trivial destructor
1904/// * LifetimeEnds for all variables
1905/// * ScopeEnd for each scope left
1906void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1907 LocalScope::const_iterator E,
1908 Stmt *S) {
1909 if (!BuildOpts.AddScopes && !BuildOpts.AddImplicitDtors &&
1910 !BuildOpts.AddLifetime)
1911 return;
1912
1913 if (B == E)
1914 return;
1915
1916 // Not leaving the scope, only need to handle destruction and lifetime
1917 if (B.inSameLocalScope(rhs: E)) {
1918 addAutomaticObjDestruction(B, E, S);
1919 return;
1920 }
1921
1922 // Extract information about all local scopes that are left
1923 SmallVector<LocalScope::const_iterator, 10> LocalScopeEndMarkers;
1924 LocalScopeEndMarkers.push_back(Elt: B);
1925 for (LocalScope::const_iterator I = B; I != E; ++I) {
1926 if (!I.inSameLocalScope(rhs: LocalScopeEndMarkers.back()))
1927 LocalScopeEndMarkers.push_back(Elt: I);
1928 }
1929 LocalScopeEndMarkers.push_back(Elt: E);
1930
1931 // We need to leave the scope in reverse order, so we reverse the end
1932 // markers
1933 std::reverse(first: LocalScopeEndMarkers.begin(), last: LocalScopeEndMarkers.end());
1934 auto Pairwise =
1935 llvm::zip(t&: LocalScopeEndMarkers, u: llvm::drop_begin(RangeOrContainer&: LocalScopeEndMarkers));
1936 for (auto [E, B] : Pairwise) {
1937 if (!B.inSameLocalScope(rhs: E))
1938 addScopeExitHandling(B, E, S);
1939 addAutomaticObjDestruction(B, E, S);
1940 }
1941}
1942
1943/// Add CFG elements corresponding to call destructor and end of lifetime
1944/// of all automatic variables with non-trivial destructor in range [B, E).
1945/// This include AutomaticObjectDtor and LifetimeEnds elements.
1946void CFGBuilder::addAutomaticObjDestruction(LocalScope::const_iterator B,
1947 LocalScope::const_iterator E,
1948 Stmt *S) {
1949 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
1950 return;
1951
1952 if (B == E)
1953 return;
1954
1955 SmallVector<VarDecl *, 10> DeclsNeedDestruction;
1956 DeclsNeedDestruction.reserve(N: B.distance(L: E));
1957
1958 for (VarDecl* D : llvm::make_range(x: B, y: E))
1959 if (needsAutomaticDestruction(VD: D))
1960 DeclsNeedDestruction.push_back(Elt: D);
1961
1962 for (VarDecl *VD : llvm::reverse(C&: DeclsNeedDestruction)) {
1963 if (BuildOpts.AddImplicitDtors) {
1964 // If this destructor is marked as a no-return destructor, we need to
1965 // create a new block for the destructor which does not have as a
1966 // successor anything built thus far: control won't flow out of this
1967 // block.
1968 QualType Ty = VD->getType();
1969 if (Ty->isReferenceType())
1970 Ty = getReferenceInitTemporaryType(Init: VD->getInit());
1971 Ty = Context->getBaseElementType(QT: Ty);
1972
1973 const CXXRecordDecl *CRD = Ty->getAsCXXRecordDecl();
1974 if (CRD && CRD->isAnyDestructorNoReturn())
1975 Block = createNoReturnBlock();
1976 }
1977
1978 autoCreateBlock();
1979
1980 // Add LifetimeEnd after automatic obj with non-trivial destructors,
1981 // as they end their lifetime when the destructor returns. For trivial
1982 // objects, we end lifetime with scope end.
1983 if (BuildOpts.AddLifetime)
1984 appendLifetimeEnds(B: Block, VD, S);
1985 if (BuildOpts.AddImplicitDtors && !hasTrivialDestructor(VD))
1986 appendAutomaticObjDtor(B: Block, VD, S);
1987 if (VD->hasAttr<CleanupAttr>())
1988 appendCleanupFunction(B: Block, VD);
1989 }
1990}
1991
1992/// Add CFG elements corresponding to leaving a scope.
1993/// Assumes that range [B, E) corresponds to single scope.
1994/// This add following elements:
1995/// * LifetimeEnds for all variables with non-trivial destructor
1996/// * ScopeEnd for each scope left
1997void CFGBuilder::addScopeExitHandling(LocalScope::const_iterator B,
1998 LocalScope::const_iterator E, Stmt *S) {
1999 assert(!B.inSameLocalScope(E));
2000 if (!BuildOpts.AddLifetime && !BuildOpts.AddScopes)
2001 return;
2002
2003 if (BuildOpts.AddScopes) {
2004 autoCreateBlock();
2005 appendScopeEnd(B: Block, VD: B.getFirstVarInScope(), S);
2006 }
2007
2008 if (!BuildOpts.AddLifetime)
2009 return;
2010
2011 // We need to perform the scope leaving in reverse order
2012 SmallVector<VarDecl *, 10> DeclsTrivial;
2013 DeclsTrivial.reserve(N: B.distance(L: E));
2014
2015 // Objects with trivial destructor ends their lifetime when their storage
2016 // is destroyed, for automatic variables, this happens when the end of the
2017 // scope is added.
2018 for (VarDecl* D : llvm::make_range(x: B, y: E))
2019 if (!needsAutomaticDestruction(VD: D))
2020 DeclsTrivial.push_back(Elt: D);
2021
2022 if (DeclsTrivial.empty())
2023 return;
2024
2025 autoCreateBlock();
2026 for (VarDecl *VD : llvm::reverse(C&: DeclsTrivial))
2027 appendLifetimeEnds(B: Block, VD, S);
2028}
2029
2030/// addScopeChangesHandling - appends information about destruction, lifetime
2031/// and cfgScopeEnd for variables in the scope that was left by the jump, and
2032/// appends cfgScopeBegin for all scopes that where entered.
2033/// We insert the cfgScopeBegin at the end of the jump node, as depending on
2034/// the sourceBlock, each goto, may enter different amount of scopes.
2035void CFGBuilder::addScopeChangesHandling(LocalScope::const_iterator SrcPos,
2036 LocalScope::const_iterator DstPos,
2037 Stmt *S) {
2038 assert(Block && "Source block should be always crated");
2039 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2040 !BuildOpts.AddScopes) {
2041 return;
2042 }
2043
2044 if (SrcPos == DstPos)
2045 return;
2046
2047 // Get common scope, the jump leaves all scopes [SrcPos, BasePos), and
2048 // enter all scopes between [DstPos, BasePos)
2049 LocalScope::const_iterator BasePos = SrcPos.shared_parent(L: DstPos);
2050
2051 // Append scope begins for scopes entered by goto
2052 if (BuildOpts.AddScopes && !DstPos.inSameLocalScope(rhs: BasePos)) {
2053 for (LocalScope::const_iterator I = DstPos; I != BasePos; ++I)
2054 if (I.pointsToFirstDeclaredVar())
2055 appendScopeBegin(B: Block, VD: *I, S);
2056 }
2057
2058 // Append scopeEnds, destructor and lifetime with the terminator for
2059 // block left by goto.
2060 addAutomaticObjHandling(B: SrcPos, E: BasePos, S);
2061}
2062
2063/// createScopeChangesHandlingBlock - Creates a block with cfgElements
2064/// corresponding to changing the scope from the source scope of the GotoStmt,
2065/// to destination scope. Add destructor, lifetime and cfgScopeEnd
2066/// CFGElements to newly created CFGBlock, that will have the CFG terminator
2067/// transferred.
2068CFGBlock *CFGBuilder::createScopeChangesHandlingBlock(
2069 LocalScope::const_iterator SrcPos, CFGBlock *SrcBlk,
2070 LocalScope::const_iterator DstPos, CFGBlock *DstBlk) {
2071 if (SrcPos == DstPos)
2072 return DstBlk;
2073
2074 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2075 (!BuildOpts.AddScopes || SrcPos.inSameLocalScope(rhs: DstPos)))
2076 return DstBlk;
2077
2078 // We will update CFBBuilder when creating new block, restore the
2079 // previous state at exit.
2080 SaveAndRestore save_Block(Block), save_Succ(Succ);
2081
2082 // Create a new block, and transfer terminator
2083 Block = createBlock(add_successor: false);
2084 Block->setTerminator(SrcBlk->getTerminator());
2085 SrcBlk->setTerminator(CFGTerminator());
2086 addSuccessor(B: Block, S: DstBlk);
2087
2088 // Fill the created Block with the required elements.
2089 addScopeChangesHandling(SrcPos, DstPos, S: Block->getTerminatorStmt());
2090
2091 assert(Block && "There should be at least one scope changing Block");
2092 return Block;
2093}
2094
2095/// addImplicitDtorsForDestructor - Add implicit destructors generated for
2096/// base and member objects in destructor.
2097void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
2098 assert(BuildOpts.AddImplicitDtors &&
2099 "Can be called only when dtors should be added");
2100 const CXXRecordDecl *RD = DD->getParent();
2101
2102 // At the end destroy virtual base objects.
2103 for (const auto &VI : RD->vbases()) {
2104 // TODO: Add a VirtualBaseBranch to see if the most derived class
2105 // (which is different from the current class) is responsible for
2106 // destroying them.
2107 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
2108 if (CD && !CD->hasTrivialDestructor()) {
2109 autoCreateBlock();
2110 appendBaseDtor(Block, &VI);
2111 }
2112 }
2113
2114 // Before virtual bases destroy direct base objects.
2115 for (const auto &BI : RD->bases()) {
2116 if (!BI.isVirtual()) {
2117 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
2118 if (CD && !CD->hasTrivialDestructor()) {
2119 autoCreateBlock();
2120 appendBaseDtor(Block, &BI);
2121 }
2122 }
2123 }
2124
2125 // First destroy member objects.
2126 if (RD->isUnion())
2127 return;
2128 for (auto *FI : RD->fields()) {
2129 // Check for constant size array. Set type to array element type.
2130 QualType QT = FI->getType();
2131 // It may be a multidimensional array.
2132 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
2133 if (AT->isZeroSize())
2134 break;
2135 QT = AT->getElementType();
2136 }
2137
2138 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
2139 if (!CD->hasTrivialDestructor()) {
2140 autoCreateBlock();
2141 appendMemberDtor(Block, FI);
2142 }
2143 }
2144}
2145
2146/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
2147/// way return valid LocalScope object.
2148LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
2149 if (Scope)
2150 return Scope;
2151 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
2152 return new (alloc) LocalScope(BumpVectorContext(alloc), ScopePos);
2153}
2154
2155/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
2156/// that should create implicit scope (e.g. if/else substatements).
2157void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
2158 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2159 !BuildOpts.AddScopes)
2160 return;
2161
2162 LocalScope *Scope = nullptr;
2163
2164 // For compound statement we will be creating explicit scope.
2165 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Val: S)) {
2166 for (auto *BI : CS->body()) {
2167 Stmt *SI = BI->stripLabelLikeStatements();
2168 if (DeclStmt *DS = dyn_cast<DeclStmt>(Val: SI))
2169 Scope = addLocalScopeForDeclStmt(DS, Scope);
2170 }
2171 return;
2172 }
2173
2174 // For any other statement scope will be implicit and as such will be
2175 // interesting only for DeclStmt.
2176 if (DeclStmt *DS = dyn_cast<DeclStmt>(Val: S->stripLabelLikeStatements()))
2177 addLocalScopeForDeclStmt(DS);
2178}
2179
2180/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
2181/// reuse Scope if not NULL.
2182LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
2183 LocalScope* Scope) {
2184 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2185 !BuildOpts.AddScopes)
2186 return Scope;
2187
2188 for (auto *DI : DS->decls())
2189 if (VarDecl *VD = dyn_cast<VarDecl>(Val: DI))
2190 Scope = addLocalScopeForVarDecl(VD, Scope);
2191 return Scope;
2192}
2193
2194bool CFGBuilder::needsAutomaticDestruction(const VarDecl *VD) const {
2195 return !hasTrivialDestructor(VD) || VD->hasAttr<CleanupAttr>();
2196}
2197
2198bool CFGBuilder::hasTrivialDestructor(const VarDecl *VD) const {
2199 // Check for const references bound to temporary. Set type to pointee.
2200 QualType QT = VD->getType();
2201 if (QT->isReferenceType()) {
2202 // Attempt to determine whether this declaration lifetime-extends a
2203 // temporary.
2204 //
2205 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
2206 // temporaries, and a single declaration can extend multiple temporaries.
2207 // We should look at the storage duration on each nested
2208 // MaterializeTemporaryExpr instead.
2209
2210 const Expr *Init = VD->getInit();
2211 if (!Init) {
2212 // Probably an exception catch-by-reference variable.
2213 // FIXME: It doesn't really mean that the object has a trivial destructor.
2214 // Also are there other cases?
2215 return true;
2216 }
2217
2218 // Lifetime-extending a temporary?
2219 bool FoundMTE = false;
2220 QT = getReferenceInitTemporaryType(Init, FoundMTE: &FoundMTE);
2221 if (!FoundMTE)
2222 return true;
2223 }
2224
2225 // Check for constant size array. Set type to array element type.
2226 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(T: QT)) {
2227 if (AT->isZeroSize())
2228 return true;
2229 QT = AT->getElementType();
2230 }
2231
2232 // Check if type is a C++ class with non-trivial destructor.
2233 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
2234 return !CD->hasDefinition() || CD->hasTrivialDestructor();
2235 return true;
2236}
2237
2238/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
2239/// create add scope for automatic objects and temporary objects bound to
2240/// const reference. Will reuse Scope if not NULL.
2241LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
2242 LocalScope* Scope) {
2243 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2244 !BuildOpts.AddScopes)
2245 return Scope;
2246
2247 // Check if variable is local.
2248 if (!VD->hasLocalStorage())
2249 return Scope;
2250
2251 if (!BuildOpts.AddLifetime && !BuildOpts.AddScopes &&
2252 !needsAutomaticDestruction(VD)) {
2253 assert(BuildOpts.AddImplicitDtors);
2254 return Scope;
2255 }
2256
2257 // Add the variable to scope
2258 Scope = createOrReuseLocalScope(Scope);
2259 Scope->addVar(VD);
2260 ScopePos = Scope->begin();
2261 return Scope;
2262}
2263
2264/// addLocalScopeAndDtors - For given statement add local scope for it and
2265/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
2266void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
2267 LocalScope::const_iterator scopeBeginPos = ScopePos;
2268 addLocalScopeForStmt(S);
2269 addAutomaticObjHandling(B: ScopePos, E: scopeBeginPos, S);
2270}
2271
2272/// Visit - Walk the subtree of a statement and add extra
2273/// blocks for ternary operators, &&, and ||. We also process "," and
2274/// DeclStmts (which may contain nested control-flow).
2275CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
2276 bool ExternallyDestructed) {
2277 if (!S) {
2278 badCFG = true;
2279 return nullptr;
2280 }
2281
2282 if (Expr *E = dyn_cast<Expr>(Val: S))
2283 S = E->IgnoreParens();
2284
2285 if (Context->getLangOpts().OpenMP)
2286 if (auto *D = dyn_cast<OMPExecutableDirective>(Val: S))
2287 return VisitOMPExecutableDirective(D, asc);
2288
2289 switch (S->getStmtClass()) {
2290 default:
2291 return VisitStmt(S, asc);
2292
2293 case Stmt::ImplicitValueInitExprClass:
2294 if (BuildOpts.OmitImplicitValueInitializers)
2295 return Block;
2296 return VisitStmt(S, asc);
2297
2298 case Stmt::InitListExprClass:
2299 return VisitInitListExpr(ILE: cast<InitListExpr>(Val: S), asc);
2300
2301 case Stmt::AttributedStmtClass:
2302 return VisitAttributedStmt(A: cast<AttributedStmt>(Val: S), asc);
2303
2304 case Stmt::AddrLabelExprClass:
2305 return VisitAddrLabelExpr(A: cast<AddrLabelExpr>(Val: S), asc);
2306
2307 case Stmt::BinaryConditionalOperatorClass:
2308 return VisitConditionalOperator(cast<BinaryConditionalOperator>(Val: S), asc);
2309
2310 case Stmt::BinaryOperatorClass:
2311 return VisitBinaryOperator(B: cast<BinaryOperator>(Val: S), asc);
2312
2313 case Stmt::BlockExprClass:
2314 return VisitBlockExpr(E: cast<BlockExpr>(Val: S), asc);
2315
2316 case Stmt::BreakStmtClass:
2317 return VisitBreakStmt(B: cast<BreakStmt>(Val: S));
2318
2319 case Stmt::CallExprClass:
2320 case Stmt::CXXOperatorCallExprClass:
2321 case Stmt::CXXMemberCallExprClass:
2322 case Stmt::UserDefinedLiteralClass:
2323 return VisitCallExpr(C: cast<CallExpr>(Val: S), asc);
2324
2325 case Stmt::CaseStmtClass:
2326 return VisitCaseStmt(C: cast<CaseStmt>(Val: S));
2327
2328 case Stmt::ChooseExprClass:
2329 return VisitChooseExpr(C: cast<ChooseExpr>(Val: S), asc);
2330
2331 case Stmt::CompoundStmtClass:
2332 return VisitCompoundStmt(C: cast<CompoundStmt>(Val: S), ExternallyDestructed);
2333
2334 case Stmt::ConditionalOperatorClass:
2335 return VisitConditionalOperator(cast<ConditionalOperator>(Val: S), asc);
2336
2337 case Stmt::ContinueStmtClass:
2338 return VisitContinueStmt(C: cast<ContinueStmt>(Val: S));
2339
2340 case Stmt::CXXCatchStmtClass:
2341 return VisitCXXCatchStmt(S: cast<CXXCatchStmt>(Val: S));
2342
2343 case Stmt::ExprWithCleanupsClass:
2344 return VisitExprWithCleanups(E: cast<ExprWithCleanups>(Val: S),
2345 asc, ExternallyDestructed);
2346
2347 case Stmt::CXXDefaultArgExprClass:
2348 case Stmt::CXXDefaultInitExprClass:
2349 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
2350 // called function's declaration, not by the caller. If we simply add
2351 // this expression to the CFG, we could end up with the same Expr
2352 // appearing multiple times (PR13385).
2353 //
2354 // It's likewise possible for multiple CXXDefaultInitExprs for the same
2355 // expression to be used in the same function (through aggregate
2356 // initialization).
2357 return VisitStmt(S, asc);
2358
2359 case Stmt::CXXBindTemporaryExprClass:
2360 return VisitCXXBindTemporaryExpr(E: cast<CXXBindTemporaryExpr>(Val: S), asc);
2361
2362 case Stmt::CXXConstructExprClass:
2363 return VisitCXXConstructExpr(C: cast<CXXConstructExpr>(Val: S), asc);
2364
2365 case Stmt::CXXNewExprClass:
2366 return VisitCXXNewExpr(DE: cast<CXXNewExpr>(Val: S), asc);
2367
2368 case Stmt::CXXDeleteExprClass:
2369 return VisitCXXDeleteExpr(DE: cast<CXXDeleteExpr>(Val: S), asc);
2370
2371 case Stmt::CXXFunctionalCastExprClass:
2372 return VisitCXXFunctionalCastExpr(E: cast<CXXFunctionalCastExpr>(Val: S), asc);
2373
2374 case Stmt::CXXTemporaryObjectExprClass:
2375 return VisitCXXTemporaryObjectExpr(C: cast<CXXTemporaryObjectExpr>(Val: S), asc);
2376
2377 case Stmt::CXXThrowExprClass:
2378 return VisitCXXThrowExpr(T: cast<CXXThrowExpr>(Val: S));
2379
2380 case Stmt::CXXTryStmtClass:
2381 return VisitCXXTryStmt(S: cast<CXXTryStmt>(Val: S));
2382
2383 case Stmt::CXXTypeidExprClass:
2384 return VisitCXXTypeidExpr(S: cast<CXXTypeidExpr>(Val: S), asc);
2385
2386 case Stmt::CXXForRangeStmtClass:
2387 return VisitCXXForRangeStmt(S: cast<CXXForRangeStmt>(Val: S));
2388
2389 case Stmt::DeclStmtClass:
2390 return VisitDeclStmt(DS: cast<DeclStmt>(Val: S));
2391
2392 case Stmt::DefaultStmtClass:
2393 return VisitDefaultStmt(D: cast<DefaultStmt>(Val: S));
2394
2395 case Stmt::DoStmtClass:
2396 return VisitDoStmt(D: cast<DoStmt>(Val: S));
2397
2398 case Stmt::ForStmtClass:
2399 return VisitForStmt(F: cast<ForStmt>(Val: S));
2400
2401 case Stmt::GotoStmtClass:
2402 return VisitGotoStmt(G: cast<GotoStmt>(Val: S));
2403
2404 case Stmt::GCCAsmStmtClass:
2405 return VisitGCCAsmStmt(G: cast<GCCAsmStmt>(Val: S), asc);
2406
2407 case Stmt::IfStmtClass:
2408 return VisitIfStmt(I: cast<IfStmt>(Val: S));
2409
2410 case Stmt::ImplicitCastExprClass:
2411 return VisitImplicitCastExpr(E: cast<ImplicitCastExpr>(Val: S), asc);
2412
2413 case Stmt::ConstantExprClass:
2414 return VisitConstantExpr(E: cast<ConstantExpr>(Val: S), asc);
2415
2416 case Stmt::IndirectGotoStmtClass:
2417 return VisitIndirectGotoStmt(I: cast<IndirectGotoStmt>(Val: S));
2418
2419 case Stmt::LabelStmtClass:
2420 return VisitLabelStmt(L: cast<LabelStmt>(Val: S));
2421
2422 case Stmt::LambdaExprClass:
2423 return VisitLambdaExpr(E: cast<LambdaExpr>(Val: S), asc);
2424
2425 case Stmt::MaterializeTemporaryExprClass:
2426 return VisitMaterializeTemporaryExpr(MTE: cast<MaterializeTemporaryExpr>(Val: S),
2427 asc);
2428
2429 case Stmt::MemberExprClass:
2430 return VisitMemberExpr(M: cast<MemberExpr>(Val: S), asc);
2431
2432 case Stmt::NullStmtClass:
2433 return Block;
2434
2435 case Stmt::ObjCAtCatchStmtClass:
2436 return VisitObjCAtCatchStmt(S: cast<ObjCAtCatchStmt>(Val: S));
2437
2438 case Stmt::ObjCAutoreleasePoolStmtClass:
2439 return VisitObjCAutoreleasePoolStmt(S: cast<ObjCAutoreleasePoolStmt>(Val: S));
2440
2441 case Stmt::ObjCAtSynchronizedStmtClass:
2442 return VisitObjCAtSynchronizedStmt(S: cast<ObjCAtSynchronizedStmt>(Val: S));
2443
2444 case Stmt::ObjCAtThrowStmtClass:
2445 return VisitObjCAtThrowStmt(S: cast<ObjCAtThrowStmt>(Val: S));
2446
2447 case Stmt::ObjCAtTryStmtClass:
2448 return VisitObjCAtTryStmt(S: cast<ObjCAtTryStmt>(Val: S));
2449
2450 case Stmt::ObjCForCollectionStmtClass:
2451 return VisitObjCForCollectionStmt(S: cast<ObjCForCollectionStmt>(Val: S));
2452
2453 case Stmt::ObjCMessageExprClass:
2454 return VisitObjCMessageExpr(E: cast<ObjCMessageExpr>(Val: S), asc);
2455
2456 case Stmt::OpaqueValueExprClass:
2457 return Block;
2458
2459 case Stmt::PseudoObjectExprClass:
2460 return VisitPseudoObjectExpr(E: cast<PseudoObjectExpr>(Val: S));
2461
2462 case Stmt::ReturnStmtClass:
2463 case Stmt::CoreturnStmtClass:
2464 return VisitReturnStmt(S);
2465
2466 case Stmt::CoyieldExprClass:
2467 case Stmt::CoawaitExprClass:
2468 return VisitCoroutineSuspendExpr(S: cast<CoroutineSuspendExpr>(Val: S), asc);
2469
2470 case Stmt::SEHExceptStmtClass:
2471 return VisitSEHExceptStmt(S: cast<SEHExceptStmt>(Val: S));
2472
2473 case Stmt::SEHFinallyStmtClass:
2474 return VisitSEHFinallyStmt(S: cast<SEHFinallyStmt>(Val: S));
2475
2476 case Stmt::SEHLeaveStmtClass:
2477 return VisitSEHLeaveStmt(S: cast<SEHLeaveStmt>(Val: S));
2478
2479 case Stmt::SEHTryStmtClass:
2480 return VisitSEHTryStmt(S: cast<SEHTryStmt>(Val: S));
2481
2482 case Stmt::UnaryExprOrTypeTraitExprClass:
2483 return VisitUnaryExprOrTypeTraitExpr(E: cast<UnaryExprOrTypeTraitExpr>(Val: S),
2484 asc);
2485
2486 case Stmt::StmtExprClass:
2487 return VisitStmtExpr(S: cast<StmtExpr>(Val: S), asc);
2488
2489 case Stmt::SwitchStmtClass:
2490 return VisitSwitchStmt(S: cast<SwitchStmt>(Val: S));
2491
2492 case Stmt::UnaryOperatorClass:
2493 return VisitUnaryOperator(U: cast<UnaryOperator>(Val: S), asc);
2494
2495 case Stmt::WhileStmtClass:
2496 return VisitWhileStmt(W: cast<WhileStmt>(Val: S));
2497
2498 case Stmt::ArrayInitLoopExprClass:
2499 return VisitArrayInitLoopExpr(A: cast<ArrayInitLoopExpr>(Val: S), asc);
2500 }
2501}
2502
2503CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
2504 if (asc.alwaysAdd(builder&: *this, stmt: S)) {
2505 autoCreateBlock();
2506 appendStmt(B: Block, S);
2507 }
2508
2509 return VisitChildren(S);
2510}
2511
2512/// VisitChildren - Visit the children of a Stmt.
2513CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
2514 CFGBlock *B = Block;
2515
2516 // Visit the children in their reverse order so that they appear in
2517 // left-to-right (natural) order in the CFG.
2518 reverse_children RChildren(S, *Context);
2519 for (Stmt *Child : RChildren) {
2520 if (Child)
2521 if (CFGBlock *R = Visit(S: Child))
2522 B = R;
2523 }
2524 return B;
2525}
2526
2527CFGBlock *CFGBuilder::VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc) {
2528 if (asc.alwaysAdd(*this, ILE)) {
2529 autoCreateBlock();
2530 appendStmt(Block, ILE);
2531 }
2532 CFGBlock *B = Block;
2533
2534 reverse_children RChildren(ILE, *Context);
2535 for (Stmt *Child : RChildren) {
2536 if (!Child)
2537 continue;
2538 if (CFGBlock *R = Visit(Child))
2539 B = R;
2540 if (BuildOpts.AddCXXDefaultInitExprInAggregates) {
2541 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Child))
2542 if (Stmt *Child = DIE->getExpr())
2543 if (CFGBlock *R = Visit(Child))
2544 B = R;
2545 }
2546 }
2547 return B;
2548}
2549
2550CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
2551 AddStmtChoice asc) {
2552 AddressTakenLabels.insert(X: A->getLabel());
2553
2554 if (asc.alwaysAdd(*this, A)) {
2555 autoCreateBlock();
2556 appendStmt(Block, A);
2557 }
2558
2559 return Block;
2560}
2561
2562static bool isFallthroughStatement(const AttributedStmt *A) {
2563 bool isFallthrough = hasSpecificAttr<FallThroughAttr>(A->getAttrs());
2564 assert((!isFallthrough || isa<NullStmt>(A->getSubStmt())) &&
2565 "expected fallthrough not to have children");
2566 return isFallthrough;
2567}
2568
2569static bool isCXXAssumeAttr(const AttributedStmt *A) {
2570 bool hasAssumeAttr = hasSpecificAttr<CXXAssumeAttr>(A->getAttrs());
2571
2572 assert((!hasAssumeAttr || isa<NullStmt>(A->getSubStmt())) &&
2573 "expected [[assume]] not to have children");
2574 return hasAssumeAttr;
2575}
2576
2577CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt *A,
2578 AddStmtChoice asc) {
2579 // AttributedStmts for [[likely]] can have arbitrary statements as children,
2580 // and the current visitation order here would add the AttributedStmts
2581 // for [[likely]] after the child nodes, which is undesirable: For example,
2582 // if the child contains an unconditional return, the [[likely]] would be
2583 // considered unreachable.
2584 // So only add the AttributedStmt for FallThrough, which has CFG effects and
2585 // also no children, and omit the others. None of the other current StmtAttrs
2586 // have semantic meaning for the CFG.
2587 bool isInterestingAttribute = isFallthroughStatement(A) || isCXXAssumeAttr(A);
2588 if (isInterestingAttribute && asc.alwaysAdd(*this, A)) {
2589 autoCreateBlock();
2590 appendStmt(Block, A);
2591 }
2592
2593 return VisitChildren(A);
2594}
2595
2596CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc) {
2597 if (asc.alwaysAdd(*this, U)) {
2598 autoCreateBlock();
2599 appendStmt(Block, U);
2600 }
2601
2602 if (U->getOpcode() == UO_LNot)
2603 tryEvaluateBool(S: U->getSubExpr()->IgnoreParens());
2604
2605 return Visit(U->getSubExpr(), AddStmtChoice());
2606}
2607
2608CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
2609 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2610 appendStmt(ConfluenceBlock, B);
2611
2612 if (badCFG)
2613 return nullptr;
2614
2615 return VisitLogicalOperator(B, Term: nullptr, TrueBlock: ConfluenceBlock,
2616 FalseBlock: ConfluenceBlock).first;
2617}
2618
2619std::pair<CFGBlock*, CFGBlock*>
2620CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
2621 Stmt *Term,
2622 CFGBlock *TrueBlock,
2623 CFGBlock *FalseBlock) {
2624 // Introspect the RHS. If it is a nested logical operation, we recursively
2625 // build the CFG using this function. Otherwise, resort to default
2626 // CFG construction behavior.
2627 Expr *RHS = B->getRHS()->IgnoreParens();
2628 CFGBlock *RHSBlock, *ExitBlock;
2629
2630 do {
2631 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(Val: RHS))
2632 if (B_RHS->isLogicalOp()) {
2633 std::tie(args&: RHSBlock, args&: ExitBlock) =
2634 VisitLogicalOperator(B: B_RHS, Term, TrueBlock, FalseBlock);
2635 break;
2636 }
2637
2638 // The RHS is not a nested logical operation. Don't push the terminator
2639 // down further, but instead visit RHS and construct the respective
2640 // pieces of the CFG, and link up the RHSBlock with the terminator
2641 // we have been provided.
2642 ExitBlock = RHSBlock = createBlock(add_successor: false);
2643
2644 // Even though KnownVal is only used in the else branch of the next
2645 // conditional, tryEvaluateBool performs additional checking on the
2646 // Expr, so it should be called unconditionally.
2647 TryResult KnownVal = tryEvaluateBool(S: RHS);
2648 if (!KnownVal.isKnown())
2649 KnownVal = tryEvaluateBool(B);
2650
2651 if (!Term) {
2652 assert(TrueBlock == FalseBlock);
2653 addSuccessor(B: RHSBlock, S: TrueBlock);
2654 }
2655 else {
2656 RHSBlock->setTerminator(Term);
2657 addSuccessor(B: RHSBlock, S: TrueBlock, IsReachable: !KnownVal.isFalse());
2658 addSuccessor(B: RHSBlock, S: FalseBlock, IsReachable: !KnownVal.isTrue());
2659 }
2660
2661 Block = RHSBlock;
2662 RHSBlock = addStmt(RHS);
2663 }
2664 while (false);
2665
2666 if (badCFG)
2667 return std::make_pair(x: nullptr, y: nullptr);
2668
2669 // Generate the blocks for evaluating the LHS.
2670 Expr *LHS = B->getLHS()->IgnoreParens();
2671
2672 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(Val: LHS))
2673 if (B_LHS->isLogicalOp()) {
2674 if (B->getOpcode() == BO_LOr)
2675 FalseBlock = RHSBlock;
2676 else
2677 TrueBlock = RHSBlock;
2678
2679 // For the LHS, treat 'B' as the terminator that we want to sink
2680 // into the nested branch. The RHS always gets the top-most
2681 // terminator.
2682 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
2683 }
2684
2685 // Create the block evaluating the LHS.
2686 // This contains the '&&' or '||' as the terminator.
2687 CFGBlock *LHSBlock = createBlock(add_successor: false);
2688 LHSBlock->setTerminator(B);
2689
2690 Block = LHSBlock;
2691 CFGBlock *EntryLHSBlock = addStmt(LHS);
2692
2693 if (badCFG)
2694 return std::make_pair(x: nullptr, y: nullptr);
2695
2696 // See if this is a known constant.
2697 TryResult KnownVal = tryEvaluateBool(S: LHS);
2698
2699 // Now link the LHSBlock with RHSBlock.
2700 if (B->getOpcode() == BO_LOr) {
2701 addSuccessor(B: LHSBlock, S: TrueBlock, IsReachable: !KnownVal.isFalse());
2702 addSuccessor(B: LHSBlock, S: RHSBlock, IsReachable: !KnownVal.isTrue());
2703 } else {
2704 assert(B->getOpcode() == BO_LAnd);
2705 addSuccessor(B: LHSBlock, S: RHSBlock, IsReachable: !KnownVal.isFalse());
2706 addSuccessor(B: LHSBlock, S: FalseBlock, IsReachable: !KnownVal.isTrue());
2707 }
2708
2709 return std::make_pair(x&: EntryLHSBlock, y&: ExitBlock);
2710}
2711
2712CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2713 AddStmtChoice asc) {
2714 // && or ||
2715 if (B->isLogicalOp())
2716 return VisitLogicalOperator(B);
2717
2718 if (B->getOpcode() == BO_Comma) { // ,
2719 autoCreateBlock();
2720 appendStmt(Block, B);
2721 addStmt(B->getRHS());
2722 return addStmt(B->getLHS());
2723 }
2724
2725 if (B->isAssignmentOp()) {
2726 if (asc.alwaysAdd(*this, B)) {
2727 autoCreateBlock();
2728 appendStmt(Block, B);
2729 }
2730 Visit(B->getLHS());
2731 return Visit(B->getRHS());
2732 }
2733
2734 if (asc.alwaysAdd(*this, B)) {
2735 autoCreateBlock();
2736 appendStmt(Block, B);
2737 }
2738
2739 if (B->isEqualityOp() || B->isRelationalOp())
2740 tryEvaluateBool(B);
2741
2742 CFGBlock *RBlock = Visit(B->getRHS());
2743 CFGBlock *LBlock = Visit(B->getLHS());
2744 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2745 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2746 // return RBlock. Otherwise we'll incorrectly return NULL.
2747 return (LBlock ? LBlock : RBlock);
2748}
2749
2750CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
2751 if (asc.alwaysAdd(*this, E)) {
2752 autoCreateBlock();
2753 appendStmt(Block, E);
2754 }
2755 return Block;
2756}
2757
2758CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2759 // "break" is a control-flow statement. Thus we stop processing the current
2760 // block.
2761 if (badCFG)
2762 return nullptr;
2763
2764 // Now create a new block that ends with the break statement.
2765 Block = createBlock(add_successor: false);
2766 Block->setTerminator(B);
2767
2768 // If there is no target for the break, then we are looking at an incomplete
2769 // AST. This means that the CFG cannot be constructed.
2770 if (BreakJumpTarget.block) {
2771 addAutomaticObjHandling(B: ScopePos, E: BreakJumpTarget.scopePosition, S: B);
2772 addSuccessor(B: Block, S: BreakJumpTarget.block);
2773 } else
2774 badCFG = true;
2775
2776 return Block;
2777}
2778
2779static bool CanThrow(Expr *E, ASTContext &Ctx) {
2780 QualType Ty = E->getType();
2781 if (Ty->isFunctionPointerType() || Ty->isBlockPointerType())
2782 Ty = Ty->getPointeeType();
2783
2784 const FunctionType *FT = Ty->getAs<FunctionType>();
2785 if (FT) {
2786 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(Val: FT))
2787 if (!isUnresolvedExceptionSpec(ESpecType: Proto->getExceptionSpecType()) &&
2788 Proto->isNothrow())
2789 return false;
2790 }
2791 return true;
2792}
2793
2794static bool isBuiltinAssumeWithSideEffects(const ASTContext &Ctx,
2795 const CallExpr *CE) {
2796 unsigned BuiltinID = CE->getBuiltinCallee();
2797 if (BuiltinID != Builtin::BI__assume &&
2798 BuiltinID != Builtin::BI__builtin_assume)
2799 return false;
2800
2801 return CE->getArg(Arg: 0)->HasSideEffects(Ctx);
2802}
2803
2804CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
2805 // Compute the callee type.
2806 QualType calleeType = C->getCallee()->getType();
2807 if (calleeType == Context->BoundMemberTy) {
2808 QualType boundType = Expr::findBoundMemberType(expr: C->getCallee());
2809
2810 // We should only get a null bound type if processing a dependent
2811 // CFG. Recover by assuming nothing.
2812 if (!boundType.isNull()) calleeType = boundType;
2813 }
2814
2815 // If this is a call to a no-return function, this stops the block here.
2816 bool NoReturn = getFunctionExtInfo(t: *calleeType).getNoReturn();
2817
2818 bool AddEHEdge = false;
2819
2820 // Languages without exceptions are assumed to not throw.
2821 if (Context->getLangOpts().Exceptions) {
2822 if (BuildOpts.AddEHEdges)
2823 AddEHEdge = true;
2824 }
2825
2826 // If this is a call to a builtin function, it might not actually evaluate
2827 // its arguments. Don't add them to the CFG if this is the case.
2828 bool OmitArguments = false;
2829
2830 if (FunctionDecl *FD = C->getDirectCallee()) {
2831 // TODO: Support construction contexts for variadic function arguments.
2832 // These are a bit problematic and not very useful because passing
2833 // C++ objects as C-style variadic arguments doesn't work in general
2834 // (see [expr.call]).
2835 if (!FD->isVariadic())
2836 findConstructionContextsForArguments(E: C);
2837
2838 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(Ctx: *Context))
2839 NoReturn = true;
2840 if (FD->hasAttr<NoThrowAttr>())
2841 AddEHEdge = false;
2842 if (isBuiltinAssumeWithSideEffects(FD->getASTContext(), C) ||
2843 FD->getBuiltinID() == Builtin::BI__builtin_object_size ||
2844 FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size)
2845 OmitArguments = true;
2846 }
2847
2848 if (!CanThrow(E: C->getCallee(), Ctx&: *Context))
2849 AddEHEdge = false;
2850
2851 if (OmitArguments) {
2852 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2853 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2854 autoCreateBlock();
2855 appendStmt(Block, C);
2856 return Visit(C->getCallee());
2857 }
2858
2859 if (!NoReturn && !AddEHEdge) {
2860 autoCreateBlock();
2861 appendCall(B: Block, CE: C);
2862
2863 return VisitChildren(C);
2864 }
2865
2866 if (Block) {
2867 Succ = Block;
2868 if (badCFG)
2869 return nullptr;
2870 }
2871
2872 if (NoReturn)
2873 Block = createNoReturnBlock();
2874 else
2875 Block = createBlock();
2876
2877 appendCall(B: Block, CE: C);
2878
2879 if (AddEHEdge) {
2880 // Add exceptional edges.
2881 if (TryTerminatedBlock)
2882 addSuccessor(B: Block, S: TryTerminatedBlock);
2883 else
2884 addSuccessor(B: Block, S: &cfg->getExit());
2885 }
2886
2887 return VisitChildren(C);
2888}
2889
2890CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2891 AddStmtChoice asc) {
2892 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2893 appendStmt(ConfluenceBlock, C);
2894 if (badCFG)
2895 return nullptr;
2896
2897 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(alwaysAdd: true);
2898 Succ = ConfluenceBlock;
2899 Block = nullptr;
2900 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
2901 if (badCFG)
2902 return nullptr;
2903
2904 Succ = ConfluenceBlock;
2905 Block = nullptr;
2906 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
2907 if (badCFG)
2908 return nullptr;
2909
2910 Block = createBlock(add_successor: false);
2911 // See if this is a known constant.
2912 const TryResult& KnownVal = tryEvaluateBool(S: C->getCond());
2913 addSuccessor(B: Block, S: KnownVal.isFalse() ? nullptr : LHSBlock);
2914 addSuccessor(B: Block, S: KnownVal.isTrue() ? nullptr : RHSBlock);
2915 Block->setTerminator(C);
2916 return addStmt(C->getCond());
2917}
2918
2919CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C,
2920 bool ExternallyDestructed) {
2921 LocalScope::const_iterator scopeBeginPos = ScopePos;
2922 addLocalScopeForStmt(C);
2923
2924 if (!C->body_empty() && !isa<ReturnStmt>(Val: *C->body_rbegin())) {
2925 // If the body ends with a ReturnStmt, the dtors will be added in
2926 // VisitReturnStmt.
2927 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
2928 }
2929
2930 CFGBlock *LastBlock = Block;
2931
2932 for (Stmt *S : llvm::reverse(C: C->body())) {
2933 // If we hit a segment of code just containing ';' (NullStmts), we can
2934 // get a null block back. In such cases, just use the LastBlock
2935 CFGBlock *newBlock = Visit(S, asc: AddStmtChoice::AlwaysAdd,
2936 ExternallyDestructed);
2937
2938 if (newBlock)
2939 LastBlock = newBlock;
2940
2941 if (badCFG)
2942 return nullptr;
2943
2944 ExternallyDestructed = false;
2945 }
2946
2947 return LastBlock;
2948}
2949
2950CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
2951 AddStmtChoice asc) {
2952 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(Val: C);
2953 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
2954
2955 // Create the confluence block that will "merge" the results of the ternary
2956 // expression.
2957 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2958 appendStmt(ConfluenceBlock, C);
2959 if (badCFG)
2960 return nullptr;
2961
2962 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(alwaysAdd: true);
2963
2964 // Create a block for the LHS expression if there is an LHS expression. A
2965 // GCC extension allows LHS to be NULL, causing the condition to be the
2966 // value that is returned instead.
2967 // e.g: x ?: y is shorthand for: x ? x : y;
2968 Succ = ConfluenceBlock;
2969 Block = nullptr;
2970 CFGBlock *LHSBlock = nullptr;
2971 const Expr *trueExpr = C->getTrueExpr();
2972 if (trueExpr != opaqueValue) {
2973 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
2974 if (badCFG)
2975 return nullptr;
2976 Block = nullptr;
2977 }
2978 else
2979 LHSBlock = ConfluenceBlock;
2980
2981 // Create the block for the RHS expression.
2982 Succ = ConfluenceBlock;
2983 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
2984 if (badCFG)
2985 return nullptr;
2986
2987 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2988 if (BinaryOperator *Cond =
2989 dyn_cast<BinaryOperator>(Val: C->getCond()->IgnoreParens()))
2990 if (Cond->isLogicalOp())
2991 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2992
2993 // Create the block that will contain the condition.
2994 Block = createBlock(add_successor: false);
2995
2996 // See if this is a known constant.
2997 const TryResult& KnownVal = tryEvaluateBool(S: C->getCond());
2998 addSuccessor(B: Block, S: LHSBlock, IsReachable: !KnownVal.isFalse());
2999 addSuccessor(B: Block, S: RHSBlock, IsReachable: !KnownVal.isTrue());
3000 Block->setTerminator(C);
3001 Expr *condExpr = C->getCond();
3002
3003 if (opaqueValue) {
3004 // Run the condition expression if it's not trivially expressed in
3005 // terms of the opaque value (or if there is no opaque value).
3006 if (condExpr != opaqueValue)
3007 addStmt(condExpr);
3008
3009 // Before that, run the common subexpression if there was one.
3010 // At least one of this or the above will be run.
3011 return addStmt(BCO->getCommon());
3012 }
3013
3014 return addStmt(condExpr);
3015}
3016
3017CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
3018 // Check if the Decl is for an __label__. If so, elide it from the
3019 // CFG entirely.
3020 if (isa<LabelDecl>(Val: *DS->decl_begin()))
3021 return Block;
3022
3023 // This case also handles static_asserts.
3024 if (DS->isSingleDecl())
3025 return VisitDeclSubExpr(DS);
3026
3027 CFGBlock *B = nullptr;
3028
3029 // Build an individual DeclStmt for each decl.
3030 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
3031 E = DS->decl_rend();
3032 I != E; ++I) {
3033
3034 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
3035 // automatically freed with the CFG.
3036 DeclGroupRef DG(*I);
3037 Decl *D = *I;
3038 DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
3039 cfg->addSyntheticDeclStmt(Synthetic: DSNew, Source: DS);
3040
3041 // Append the fake DeclStmt to block.
3042 B = VisitDeclSubExpr(DS: DSNew);
3043 }
3044
3045 return B;
3046}
3047
3048/// VisitDeclSubExpr - Utility method to add block-level expressions for
3049/// DeclStmts and initializers in them.
3050CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
3051 assert(DS->isSingleDecl() && "Can handle single declarations only.");
3052
3053 if (const auto *TND = dyn_cast<TypedefNameDecl>(Val: DS->getSingleDecl())) {
3054 // If we encounter a VLA, process its size expressions.
3055 const Type *T = TND->getUnderlyingType().getTypePtr();
3056 if (!T->isVariablyModifiedType())
3057 return Block;
3058
3059 autoCreateBlock();
3060 appendStmt(B: Block, S: DS);
3061
3062 CFGBlock *LastBlock = Block;
3063 for (const VariableArrayType *VA = FindVA(t: T); VA != nullptr;
3064 VA = FindVA(VA->getElementType().getTypePtr())) {
3065 if (CFGBlock *NewBlock = addStmt(VA->getSizeExpr()))
3066 LastBlock = NewBlock;
3067 }
3068 return LastBlock;
3069 }
3070
3071 VarDecl *VD = dyn_cast<VarDecl>(Val: DS->getSingleDecl());
3072
3073 if (!VD) {
3074 // Of everything that can be declared in a DeclStmt, only VarDecls and the
3075 // exceptions above impact runtime semantics.
3076 return Block;
3077 }
3078
3079 bool HasTemporaries = false;
3080
3081 // Guard static initializers under a branch.
3082 CFGBlock *blockAfterStaticInit = nullptr;
3083
3084 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
3085 // For static variables, we need to create a branch to track
3086 // whether or not they are initialized.
3087 if (Block) {
3088 Succ = Block;
3089 Block = nullptr;
3090 if (badCFG)
3091 return nullptr;
3092 }
3093 blockAfterStaticInit = Succ;
3094 }
3095
3096 // Destructors of temporaries in initialization expression should be called
3097 // after initialization finishes.
3098 Expr *Init = VD->getInit();
3099 if (Init) {
3100 HasTemporaries = isa<ExprWithCleanups>(Val: Init);
3101
3102 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
3103 // Generate destructors for temporaries in initialization expression.
3104 TempDtorContext Context;
3105 VisitForTemporaryDtors(E: cast<ExprWithCleanups>(Val: Init)->getSubExpr(),
3106 /*ExternallyDestructed=*/true, Context);
3107 }
3108 }
3109
3110 // If we bind to a tuple-like type, we iterate over the HoldingVars, and
3111 // create a DeclStmt for each of them.
3112 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) {
3113 for (auto *BD : llvm::reverse(C: DD->bindings())) {
3114 if (auto *VD = BD->getHoldingVar()) {
3115 DeclGroupRef DG(VD);
3116 DeclStmt *DSNew =
3117 new (Context) DeclStmt(DG, VD->getLocation(), GetEndLoc(VD));
3118 cfg->addSyntheticDeclStmt(Synthetic: DSNew, Source: DS);
3119 Block = VisitDeclSubExpr(DS: DSNew);
3120 }
3121 }
3122 }
3123
3124 autoCreateBlock();
3125 appendStmt(B: Block, S: DS);
3126
3127 // If the initializer is an ArrayInitLoopExpr, we want to extract the
3128 // initializer, that's used for each element.
3129 const auto *AILE = dyn_cast_or_null<ArrayInitLoopExpr>(Val: Init);
3130
3131 findConstructionContexts(
3132 ConstructionContextLayer::create(C&: cfg->getBumpVectorContext(), Item: DS),
3133 AILE ? AILE->getSubExpr() : Init);
3134
3135 // Keep track of the last non-null block, as 'Block' can be nulled out
3136 // if the initializer expression is something like a 'while' in a
3137 // statement-expression.
3138 CFGBlock *LastBlock = Block;
3139
3140 if (Init) {
3141 if (HasTemporaries) {
3142 // For expression with temporaries go directly to subexpression to omit
3143 // generating destructors for the second time.
3144 ExprWithCleanups *EC = cast<ExprWithCleanups>(Val: Init);
3145 if (CFGBlock *newBlock = Visit(S: EC->getSubExpr()))
3146 LastBlock = newBlock;
3147 }
3148 else {
3149 if (CFGBlock *newBlock = Visit(Init))
3150 LastBlock = newBlock;
3151 }
3152 }
3153
3154 // If the type of VD is a VLA, then we must process its size expressions.
3155 // FIXME: This does not find the VLA if it is embedded in other types,
3156 // like here: `int (*p_vla)[x];`
3157 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
3158 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
3159 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
3160 LastBlock = newBlock;
3161 }
3162
3163 maybeAddScopeBeginForVarDecl(B: Block, VD, S: DS);
3164
3165 // Remove variable from local scope.
3166 if (ScopePos && VD == *ScopePos)
3167 ++ScopePos;
3168
3169 CFGBlock *B = LastBlock;
3170 if (blockAfterStaticInit) {
3171 Succ = B;
3172 Block = createBlock(add_successor: false);
3173 Block->setTerminator(DS);
3174 addSuccessor(B: Block, S: blockAfterStaticInit);
3175 addSuccessor(B: Block, S: B);
3176 B = Block;
3177 }
3178
3179 return B;
3180}
3181
3182CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
3183 // We may see an if statement in the middle of a basic block, or it may be the
3184 // first statement we are processing. In either case, we create a new basic
3185 // block. First, we create the blocks for the then...else statements, and
3186 // then we create the block containing the if statement. If we were in the
3187 // middle of a block, we stop processing that block. That block is then the
3188 // implicit successor for the "then" and "else" clauses.
3189
3190 // Save local scope position because in case of condition variable ScopePos
3191 // won't be restored when traversing AST.
3192 SaveAndRestore save_scope_pos(ScopePos);
3193
3194 // Create local scope for C++17 if init-stmt if one exists.
3195 if (Stmt *Init = I->getInit())
3196 addLocalScopeForStmt(S: Init);
3197
3198 // Create local scope for possible condition variable.
3199 // Store scope position. Add implicit destructor.
3200 if (VarDecl *VD = I->getConditionVariable())
3201 addLocalScopeForVarDecl(VD);
3202
3203 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
3204
3205 // The block we were processing is now finished. Make it the successor
3206 // block.
3207 if (Block) {
3208 Succ = Block;
3209 if (badCFG)
3210 return nullptr;
3211 }
3212
3213 // Process the false branch.
3214 CFGBlock *ElseBlock = Succ;
3215
3216 if (Stmt *Else = I->getElse()) {
3217 SaveAndRestore sv(Succ);
3218
3219 // NULL out Block so that the recursive call to Visit will
3220 // create a new basic block.
3221 Block = nullptr;
3222
3223 // If branch is not a compound statement create implicit scope
3224 // and add destructors.
3225 if (!isa<CompoundStmt>(Val: Else))
3226 addLocalScopeAndDtors(S: Else);
3227
3228 ElseBlock = addStmt(S: Else);
3229
3230 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
3231 ElseBlock = sv.get();
3232 else if (Block) {
3233 if (badCFG)
3234 return nullptr;
3235 }
3236 }
3237
3238 // Process the true branch.
3239 CFGBlock *ThenBlock;
3240 {
3241 Stmt *Then = I->getThen();
3242 assert(Then);
3243 SaveAndRestore sv(Succ);
3244 Block = nullptr;
3245
3246 // If branch is not a compound statement create implicit scope
3247 // and add destructors.
3248 if (!isa<CompoundStmt>(Val: Then))
3249 addLocalScopeAndDtors(S: Then);
3250
3251 ThenBlock = addStmt(S: Then);
3252
3253 if (!ThenBlock) {
3254 // We can reach here if the "then" body has all NullStmts.
3255 // Create an empty block so we can distinguish between true and false
3256 // branches in path-sensitive analyses.
3257 ThenBlock = createBlock(add_successor: false);
3258 addSuccessor(B: ThenBlock, S: sv.get());
3259 } else if (Block) {
3260 if (badCFG)
3261 return nullptr;
3262 }
3263 }
3264
3265 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
3266 // having these handle the actual control-flow jump. Note that
3267 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
3268 // we resort to the old control-flow behavior. This special handling
3269 // removes infeasible paths from the control-flow graph by having the
3270 // control-flow transfer of '&&' or '||' go directly into the then/else
3271 // blocks directly.
3272 BinaryOperator *Cond =
3273 (I->isConsteval() || I->getConditionVariable())
3274 ? nullptr
3275 : dyn_cast<BinaryOperator>(Val: I->getCond()->IgnoreParens());
3276 CFGBlock *LastBlock;
3277 if (Cond && Cond->isLogicalOp())
3278 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
3279 else {
3280 // Now create a new block containing the if statement.
3281 Block = createBlock(add_successor: false);
3282
3283 // Set the terminator of the new block to the If statement.
3284 Block->setTerminator(I);
3285
3286 // See if this is a known constant.
3287 TryResult KnownVal;
3288 if (!I->isConsteval())
3289 KnownVal = tryEvaluateBool(S: I->getCond());
3290
3291 // Add the successors. If we know that specific branches are
3292 // unreachable, inform addSuccessor() of that knowledge.
3293 addSuccessor(B: Block, S: ThenBlock, /* IsReachable = */ !KnownVal.isFalse());
3294 addSuccessor(B: Block, S: ElseBlock, /* IsReachable = */ !KnownVal.isTrue());
3295
3296 if (I->isConsteval())
3297 return Block;
3298
3299 // Add the condition as the last statement in the new block. This may
3300 // create new blocks as the condition may contain control-flow. Any newly
3301 // created blocks will be pointed to be "Block".
3302 LastBlock = addStmt(I->getCond());
3303
3304 // If the IfStmt contains a condition variable, add it and its
3305 // initializer to the CFG.
3306 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
3307 autoCreateBlock();
3308 LastBlock = addStmt(S: const_cast<DeclStmt *>(DS));
3309 }
3310 }
3311
3312 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
3313 if (Stmt *Init = I->getInit()) {
3314 autoCreateBlock();
3315 LastBlock = addStmt(S: Init);
3316 }
3317
3318 return LastBlock;
3319}
3320
3321CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
3322 // If we were in the middle of a block we stop processing that block.
3323 //
3324 // NOTE: If a "return" or "co_return" appears in the middle of a block, this
3325 // means that the code afterwards is DEAD (unreachable). We still keep
3326 // a basic block for that code; a simple "mark-and-sweep" from the entry
3327 // block will be able to report such dead blocks.
3328 assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S));
3329
3330 // Create the new block.
3331 Block = createBlock(add_successor: false);
3332
3333 addAutomaticObjHandling(B: ScopePos, E: LocalScope::const_iterator(), S);
3334
3335 if (auto *R = dyn_cast<ReturnStmt>(Val: S))
3336 findConstructionContexts(
3337 ConstructionContextLayer::create(C&: cfg->getBumpVectorContext(), Item: R),
3338 R->getRetValue());
3339
3340 // If the one of the destructors does not return, we already have the Exit
3341 // block as a successor.
3342 if (!Block->hasNoReturnElement())
3343 addSuccessor(B: Block, S: &cfg->getExit());
3344
3345 // Add the return statement to the block.
3346 appendStmt(B: Block, S);
3347
3348 // Visit children
3349 if (ReturnStmt *RS = dyn_cast<ReturnStmt>(Val: S)) {
3350 if (Expr *O = RS->getRetValue())
3351 return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true);
3352 return Block;
3353 }
3354
3355 CoreturnStmt *CRS = cast<CoreturnStmt>(Val: S);
3356 auto *B = Block;
3357 if (CFGBlock *R = Visit(CRS->getPromiseCall()))
3358 B = R;
3359
3360 if (Expr *RV = CRS->getOperand())
3361 if (RV->getType()->isVoidType() && !isa<InitListExpr>(Val: RV))
3362 // A non-initlist void expression.
3363 if (CFGBlock *R = Visit(RV))
3364 B = R;
3365
3366 return B;
3367}
3368
3369CFGBlock *CFGBuilder::VisitCoroutineSuspendExpr(CoroutineSuspendExpr *E,
3370 AddStmtChoice asc) {
3371 // We're modelling the pre-coro-xform CFG. Thus just evalate the various
3372 // active components of the co_await or co_yield. Note we do not model the
3373 // edge from the builtin_suspend to the exit node.
3374 if (asc.alwaysAdd(*this, E)) {
3375 autoCreateBlock();
3376 appendStmt(Block, E);
3377 }
3378 CFGBlock *B = Block;
3379 if (auto *R = Visit(E->getResumeExpr()))
3380 B = R;
3381 if (auto *R = Visit(E->getSuspendExpr()))
3382 B = R;
3383 if (auto *R = Visit(E->getReadyExpr()))
3384 B = R;
3385 if (auto *R = Visit(E->getCommonExpr()))
3386 B = R;
3387 return B;
3388}
3389
3390CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
3391 // SEHExceptStmt are treated like labels, so they are the first statement in a
3392 // block.
3393
3394 // Save local scope position because in case of exception variable ScopePos
3395 // won't be restored when traversing AST.
3396 SaveAndRestore save_scope_pos(ScopePos);
3397
3398 addStmt(ES->getBlock());
3399 CFGBlock *SEHExceptBlock = Block;
3400 if (!SEHExceptBlock)
3401 SEHExceptBlock = createBlock();
3402
3403 appendStmt(B: SEHExceptBlock, S: ES);
3404
3405 // Also add the SEHExceptBlock as a label, like with regular labels.
3406 SEHExceptBlock->setLabel(ES);
3407
3408 // Bail out if the CFG is bad.
3409 if (badCFG)
3410 return nullptr;
3411
3412 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3413 Block = nullptr;
3414
3415 return SEHExceptBlock;
3416}
3417
3418CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
3419 return VisitCompoundStmt(C: FS->getBlock(), /*ExternallyDestructed=*/false);
3420}
3421
3422CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
3423 // "__leave" is a control-flow statement. Thus we stop processing the current
3424 // block.
3425 if (badCFG)
3426 return nullptr;
3427
3428 // Now create a new block that ends with the __leave statement.
3429 Block = createBlock(add_successor: false);
3430 Block->setTerminator(LS);
3431
3432 // If there is no target for the __leave, then we are looking at an incomplete
3433 // AST. This means that the CFG cannot be constructed.
3434 if (SEHLeaveJumpTarget.block) {
3435 addAutomaticObjHandling(B: ScopePos, E: SEHLeaveJumpTarget.scopePosition, S: LS);
3436 addSuccessor(B: Block, S: SEHLeaveJumpTarget.block);
3437 } else
3438 badCFG = true;
3439
3440 return Block;
3441}
3442
3443CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
3444 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
3445 // processing the current block.
3446 CFGBlock *SEHTrySuccessor = nullptr;
3447
3448 if (Block) {
3449 if (badCFG)
3450 return nullptr;
3451 SEHTrySuccessor = Block;
3452 } else SEHTrySuccessor = Succ;
3453
3454 // FIXME: Implement __finally support.
3455 if (Terminator->getFinallyHandler())
3456 return NYS();
3457
3458 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
3459
3460 // Create a new block that will contain the __try statement.
3461 CFGBlock *NewTryTerminatedBlock = createBlock(add_successor: false);
3462
3463 // Add the terminator in the __try block.
3464 NewTryTerminatedBlock->setTerminator(Terminator);
3465
3466 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
3467 // The code after the try is the implicit successor if there's an __except.
3468 Succ = SEHTrySuccessor;
3469 Block = nullptr;
3470 CFGBlock *ExceptBlock = VisitSEHExceptStmt(ES: Except);
3471 if (!ExceptBlock)
3472 return nullptr;
3473 // Add this block to the list of successors for the block with the try
3474 // statement.
3475 addSuccessor(B: NewTryTerminatedBlock, S: ExceptBlock);
3476 }
3477 if (PrevSEHTryTerminatedBlock)
3478 addSuccessor(B: NewTryTerminatedBlock, S: PrevSEHTryTerminatedBlock);
3479 else
3480 addSuccessor(B: NewTryTerminatedBlock, S: &cfg->getExit());
3481
3482 // The code after the try is the implicit successor.
3483 Succ = SEHTrySuccessor;
3484
3485 // Save the current "__try" context.
3486 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
3487 cfg->addTryDispatchBlock(block: TryTerminatedBlock);
3488
3489 // Save the current value for the __leave target.
3490 // All __leaves should go to the code following the __try
3491 // (FIXME: or if the __try has a __finally, to the __finally.)
3492 SaveAndRestore save_break(SEHLeaveJumpTarget);
3493 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
3494
3495 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
3496 Block = nullptr;
3497 return addStmt(Terminator->getTryBlock());
3498}
3499
3500CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
3501 // Get the block of the labeled statement. Add it to our map.
3502 addStmt(S: L->getSubStmt());
3503 CFGBlock *LabelBlock = Block;
3504
3505 if (!LabelBlock) // This can happen when the body is empty, i.e.
3506 LabelBlock = createBlock(); // scopes that only contains NullStmts.
3507
3508 assert(!LabelMap.contains(L->getDecl()) && "label already in map");
3509 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
3510
3511 // Labels partition blocks, so this is the end of the basic block we were
3512 // processing (L is the block's label). Because this is label (and we have
3513 // already processed the substatement) there is no extra control-flow to worry
3514 // about.
3515 LabelBlock->setLabel(L);
3516 if (badCFG)
3517 return nullptr;
3518
3519 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3520 Block = nullptr;
3521
3522 // This block is now the implicit successor of other blocks.
3523 Succ = LabelBlock;
3524
3525 return LabelBlock;
3526}
3527
3528CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
3529 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3530 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
3531 if (Expr *CopyExpr = CI.getCopyExpr()) {
3532 CFGBlock *Tmp = Visit(CopyExpr);
3533 if (Tmp)
3534 LastBlock = Tmp;
3535 }
3536 }
3537 return LastBlock;
3538}
3539
3540CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
3541 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3542
3543 unsigned Idx = 0;
3544 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
3545 et = E->capture_init_end();
3546 it != et; ++it, ++Idx) {
3547 if (Expr *Init = *it) {
3548 // If the initializer is an ArrayInitLoopExpr, we want to extract the
3549 // initializer, that's used for each element.
3550 auto *AILEInit = extractElementInitializerFromNestedAILE(
3551 AILE: dyn_cast<ArrayInitLoopExpr>(Val: Init));
3552
3553 findConstructionContexts(ConstructionContextLayer::create(
3554 C&: cfg->getBumpVectorContext(), Item: {E, Idx}),
3555 AILEInit ? AILEInit : Init);
3556
3557 CFGBlock *Tmp = Visit(Init);
3558 if (Tmp)
3559 LastBlock = Tmp;
3560 }
3561 }
3562 return LastBlock;
3563}
3564
3565CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
3566 // Goto is a control-flow statement. Thus we stop processing the current
3567 // block and create a new one.
3568
3569 Block = createBlock(add_successor: false);
3570 Block->setTerminator(G);
3571
3572 // If we already know the mapping to the label block add the successor now.
3573 LabelMapTy::iterator I = LabelMap.find(Val: G->getLabel());
3574
3575 if (I == LabelMap.end())
3576 // We will need to backpatch this block later.
3577 BackpatchBlocks.push_back(x: JumpSource(Block, ScopePos));
3578 else {
3579 JumpTarget JT = I->second;
3580 addSuccessor(B: Block, S: JT.block);
3581 addScopeChangesHandling(SrcPos: ScopePos, DstPos: JT.scopePosition, S: G);
3582 }
3583
3584 return Block;
3585}
3586
3587CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
3588 // Goto is a control-flow statement. Thus we stop processing the current
3589 // block and create a new one.
3590
3591 if (!G->isAsmGoto())
3592 return VisitStmt(S: G, asc);
3593
3594 if (Block) {
3595 Succ = Block;
3596 if (badCFG)
3597 return nullptr;
3598 }
3599 Block = createBlock();
3600 Block->setTerminator(G);
3601 // We will backpatch this block later for all the labels.
3602 BackpatchBlocks.push_back(x: JumpSource(Block, ScopePos));
3603 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
3604 // used to avoid adding "Succ" again.
3605 BackpatchBlocks.push_back(x: JumpSource(Succ, ScopePos));
3606 return VisitChildren(S: G);
3607}
3608
3609CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
3610 CFGBlock *LoopSuccessor = nullptr;
3611
3612 // Save local scope position because in case of condition variable ScopePos
3613 // won't be restored when traversing AST.
3614 SaveAndRestore save_scope_pos(ScopePos);
3615
3616 // Create local scope for init statement and possible condition variable.
3617 // Add destructor for init statement and condition variable.
3618 // Store scope position for continue statement.
3619 if (Stmt *Init = F->getInit())
3620 addLocalScopeForStmt(S: Init);
3621 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3622
3623 if (VarDecl *VD = F->getConditionVariable())
3624 addLocalScopeForVarDecl(VD);
3625 LocalScope::const_iterator ContinueScopePos = ScopePos;
3626
3627 addAutomaticObjHandling(B: ScopePos, E: save_scope_pos.get(), S: F);
3628
3629 addLoopExit(LoopStmt: F);
3630
3631 // "for" is a control-flow statement. Thus we stop processing the current
3632 // block.
3633 if (Block) {
3634 if (badCFG)
3635 return nullptr;
3636 LoopSuccessor = Block;
3637 } else
3638 LoopSuccessor = Succ;
3639
3640 // Save the current value for the break targets.
3641 // All breaks should go to the code following the loop.
3642 SaveAndRestore save_break(BreakJumpTarget);
3643 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3644
3645 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3646
3647 // Now create the loop body.
3648 {
3649 assert(F->getBody());
3650
3651 // Save the current values for Block, Succ, continue and break targets.
3652 SaveAndRestore save_Block(Block), save_Succ(Succ);
3653 SaveAndRestore save_continue(ContinueJumpTarget);
3654
3655 // Create an empty block to represent the transition block for looping back
3656 // to the head of the loop. If we have increment code, it will
3657 // go in this block as well.
3658 Block = Succ = TransitionBlock = createBlock(add_successor: false);
3659 TransitionBlock->setLoopTarget(F);
3660
3661
3662 // Loop iteration (after increment) should end with destructor of Condition
3663 // variable (if any).
3664 addAutomaticObjHandling(B: ScopePos, E: LoopBeginScopePos, S: F);
3665
3666 if (Stmt *I = F->getInc()) {
3667 // Generate increment code in its own basic block. This is the target of
3668 // continue statements.
3669 Succ = addStmt(S: I);
3670 }
3671
3672 // Finish up the increment (or empty) block if it hasn't been already.
3673 if (Block) {
3674 assert(Block == Succ);
3675 if (badCFG)
3676 return nullptr;
3677 Block = nullptr;
3678 }
3679
3680 // The starting block for the loop increment is the block that should
3681 // represent the 'loop target' for looping back to the start of the loop.
3682 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3683 ContinueJumpTarget.block->setLoopTarget(F);
3684
3685
3686 // If body is not a compound statement create implicit scope
3687 // and add destructors.
3688 if (!isa<CompoundStmt>(Val: F->getBody()))
3689 addLocalScopeAndDtors(S: F->getBody());
3690
3691 // Now populate the body block, and in the process create new blocks as we
3692 // walk the body of the loop.
3693 BodyBlock = addStmt(S: F->getBody());
3694
3695 if (!BodyBlock) {
3696 // In the case of "for (...;...;...);" we can have a null BodyBlock.
3697 // Use the continue jump target as the proxy for the body.
3698 BodyBlock = ContinueJumpTarget.block;
3699 }
3700 else if (badCFG)
3701 return nullptr;
3702 }
3703
3704 // Because of short-circuit evaluation, the condition of the loop can span
3705 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3706 // evaluate the condition.
3707 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3708
3709 do {
3710 Expr *C = F->getCond();
3711 SaveAndRestore save_scope_pos(ScopePos);
3712
3713 // Specially handle logical operators, which have a slightly
3714 // more optimal CFG representation.
3715 if (BinaryOperator *Cond =
3716 dyn_cast_or_null<BinaryOperator>(Val: C ? C->IgnoreParens() : nullptr))
3717 if (Cond->isLogicalOp()) {
3718 std::tie(args&: EntryConditionBlock, args&: ExitConditionBlock) =
3719 VisitLogicalOperator(B: Cond, Term: F, TrueBlock: BodyBlock, FalseBlock: LoopSuccessor);
3720 break;
3721 }
3722
3723 // The default case when not handling logical operators.
3724 EntryConditionBlock = ExitConditionBlock = createBlock(add_successor: false);
3725 ExitConditionBlock->setTerminator(F);
3726
3727 // See if this is a known constant.
3728 TryResult KnownVal(true);
3729
3730 if (C) {
3731 // Now add the actual condition to the condition block.
3732 // Because the condition itself may contain control-flow, new blocks may
3733 // be created. Thus we update "Succ" after adding the condition.
3734 Block = ExitConditionBlock;
3735 EntryConditionBlock = addStmt(C);
3736
3737 // If this block contains a condition variable, add both the condition
3738 // variable and initializer to the CFG.
3739 if (VarDecl *VD = F->getConditionVariable()) {
3740 if (Expr *Init = VD->getInit()) {
3741 autoCreateBlock();
3742 const DeclStmt *DS = F->getConditionVariableDeclStmt();
3743 assert(DS->isSingleDecl());
3744 findConstructionContexts(
3745 ConstructionContextLayer::create(C&: cfg->getBumpVectorContext(), Item: DS),
3746 Init);
3747 appendStmt(B: Block, S: DS);
3748 EntryConditionBlock = addStmt(Init);
3749 assert(Block == EntryConditionBlock);
3750 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
3751 }
3752 }
3753
3754 if (Block && badCFG)
3755 return nullptr;
3756
3757 KnownVal = tryEvaluateBool(S: C);
3758 }
3759
3760 // Add the loop body entry as a successor to the condition.
3761 addSuccessor(B: ExitConditionBlock, S: KnownVal.isFalse() ? nullptr : BodyBlock);
3762 // Link up the condition block with the code that follows the loop. (the
3763 // false branch).
3764 addSuccessor(B: ExitConditionBlock,
3765 S: KnownVal.isTrue() ? nullptr : LoopSuccessor);
3766 } while (false);
3767
3768 // Link up the loop-back block to the entry condition block.
3769 addSuccessor(B: TransitionBlock, S: EntryConditionBlock);
3770
3771 // The condition block is the implicit successor for any code above the loop.
3772 Succ = EntryConditionBlock;
3773
3774 // If the loop contains initialization, create a new block for those
3775 // statements. This block can also contain statements that precede the loop.
3776 if (Stmt *I = F->getInit()) {
3777 SaveAndRestore save_scope_pos(ScopePos);
3778 ScopePos = LoopBeginScopePos;
3779 Block = createBlock();
3780 return addStmt(S: I);
3781 }
3782
3783 // There is no loop initialization. We are thus basically a while loop.
3784 // NULL out Block to force lazy block construction.
3785 Block = nullptr;
3786 Succ = EntryConditionBlock;
3787 return EntryConditionBlock;
3788}
3789
3790CFGBlock *
3791CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
3792 AddStmtChoice asc) {
3793 findConstructionContexts(
3794 ConstructionContextLayer::create(C&: cfg->getBumpVectorContext(), Item: MTE),
3795 MTE->getSubExpr());
3796
3797 return VisitStmt(MTE, asc);
3798}
3799
3800CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
3801 if (asc.alwaysAdd(*this, M)) {
3802 autoCreateBlock();
3803 appendStmt(Block, M);
3804 }
3805 return Visit(M->getBase());
3806}
3807
3808CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
3809 // Objective-C fast enumeration 'for' statements:
3810 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3811 //
3812 // for ( Type newVariable in collection_expression ) { statements }
3813 //
3814 // becomes:
3815 //
3816 // prologue:
3817 // 1. collection_expression
3818 // T. jump to loop_entry
3819 // loop_entry:
3820 // 1. side-effects of element expression
3821 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3822 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3823 // TB:
3824 // statements
3825 // T. jump to loop_entry
3826 // FB:
3827 // what comes after
3828 //
3829 // and
3830 //
3831 // Type existingItem;
3832 // for ( existingItem in expression ) { statements }
3833 //
3834 // becomes:
3835 //
3836 // the same with newVariable replaced with existingItem; the binding works
3837 // the same except that for one ObjCForCollectionStmt::getElement() returns
3838 // a DeclStmt and the other returns a DeclRefExpr.
3839
3840 CFGBlock *LoopSuccessor = nullptr;
3841
3842 if (Block) {
3843 if (badCFG)
3844 return nullptr;
3845 LoopSuccessor = Block;
3846 Block = nullptr;
3847 } else
3848 LoopSuccessor = Succ;
3849
3850 // Build the condition blocks.
3851 CFGBlock *ExitConditionBlock = createBlock(add_successor: false);
3852
3853 // Set the terminator for the "exit" condition block.
3854 ExitConditionBlock->setTerminator(S);
3855
3856 // The last statement in the block should be the ObjCForCollectionStmt, which
3857 // performs the actual binding to 'element' and determines if there are any
3858 // more items in the collection.
3859 appendStmt(B: ExitConditionBlock, S);
3860 Block = ExitConditionBlock;
3861
3862 // Walk the 'element' expression to see if there are any side-effects. We
3863 // generate new blocks as necessary. We DON'T add the statement by default to
3864 // the CFG unless it contains control-flow.
3865 CFGBlock *EntryConditionBlock = Visit(S: S->getElement(),
3866 asc: AddStmtChoice::NotAlwaysAdd);
3867 if (Block) {
3868 if (badCFG)
3869 return nullptr;
3870 Block = nullptr;
3871 }
3872
3873 // The condition block is the implicit successor for the loop body as well as
3874 // any code above the loop.
3875 Succ = EntryConditionBlock;
3876
3877 // Now create the true branch.
3878 {
3879 // Save the current values for Succ, continue and break targets.
3880 SaveAndRestore save_Block(Block), save_Succ(Succ);
3881 SaveAndRestore save_continue(ContinueJumpTarget),
3882 save_break(BreakJumpTarget);
3883
3884 // Add an intermediate block between the BodyBlock and the
3885 // EntryConditionBlock to represent the "loop back" transition, for looping
3886 // back to the head of the loop.
3887 CFGBlock *LoopBackBlock = nullptr;
3888 Succ = LoopBackBlock = createBlock();
3889 LoopBackBlock->setLoopTarget(S);
3890
3891 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3892 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
3893
3894 CFGBlock *BodyBlock = addStmt(S: S->getBody());
3895
3896 if (!BodyBlock)
3897 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
3898 else if (Block) {
3899 if (badCFG)
3900 return nullptr;
3901 }
3902
3903 // This new body block is a successor to our "exit" condition block.
3904 addSuccessor(B: ExitConditionBlock, S: BodyBlock);
3905 }
3906
3907 // Link up the condition block with the code that follows the loop.
3908 // (the false branch).
3909 addSuccessor(B: ExitConditionBlock, S: LoopSuccessor);
3910
3911 // Now create a prologue block to contain the collection expression.
3912 Block = createBlock();
3913 return addStmt(S->getCollection());
3914}
3915
3916CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3917 // Inline the body.
3918 return addStmt(S: S->getSubStmt());
3919 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3920}
3921
3922CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
3923 // FIXME: Add locking 'primitives' to CFG for @synchronized.
3924
3925 // Inline the body.
3926 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
3927
3928 // The sync body starts its own basic block. This makes it a little easier
3929 // for diagnostic clients.
3930 if (SyncBlock) {
3931 if (badCFG)
3932 return nullptr;
3933
3934 Block = nullptr;
3935 Succ = SyncBlock;
3936 }
3937
3938 // Add the @synchronized to the CFG.
3939 autoCreateBlock();
3940 appendStmt(B: Block, S);
3941
3942 // Inline the sync expression.
3943 return addStmt(S->getSynchExpr());
3944}
3945
3946CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3947 autoCreateBlock();
3948
3949 // Add the PseudoObject as the last thing.
3950 appendStmt(Block, E);
3951
3952 CFGBlock *lastBlock = Block;
3953
3954 // Before that, evaluate all of the semantics in order. In
3955 // CFG-land, that means appending them in reverse order.
3956 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3957 Expr *Semantic = E->getSemanticExpr(index: --i);
3958
3959 // If the semantic is an opaque value, we're being asked to bind
3960 // it to its source expression.
3961 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: Semantic))
3962 Semantic = OVE->getSourceExpr();
3963
3964 if (CFGBlock *B = Visit(Semantic))
3965 lastBlock = B;
3966 }
3967
3968 return lastBlock;
3969}
3970
3971CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
3972 CFGBlock *LoopSuccessor = nullptr;
3973
3974 // Save local scope position because in case of condition variable ScopePos
3975 // won't be restored when traversing AST.
3976 SaveAndRestore save_scope_pos(ScopePos);
3977
3978 // Create local scope for possible condition variable.
3979 // Store scope position for continue statement.
3980 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3981 if (VarDecl *VD = W->getConditionVariable()) {
3982 addLocalScopeForVarDecl(VD);
3983 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3984 }
3985 addLoopExit(W);
3986
3987 // "while" is a control-flow statement. Thus we stop processing the current
3988 // block.
3989 if (Block) {
3990 if (badCFG)
3991 return nullptr;
3992 LoopSuccessor = Block;
3993 Block = nullptr;
3994 } else {
3995 LoopSuccessor = Succ;
3996 }
3997
3998 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3999
4000 // Process the loop body.
4001 {
4002 assert(W->getBody());
4003
4004 // Save the current values for Block, Succ, continue and break targets.
4005 SaveAndRestore save_Block(Block), save_Succ(Succ);
4006 SaveAndRestore save_continue(ContinueJumpTarget),
4007 save_break(BreakJumpTarget);
4008
4009 // Create an empty block to represent the transition block for looping back
4010 // to the head of the loop.
4011 Succ = TransitionBlock = createBlock(add_successor: false);
4012 TransitionBlock->setLoopTarget(W);
4013 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
4014
4015 // All breaks should go to the code following the loop.
4016 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4017
4018 // Loop body should end with destructor of Condition variable (if any).
4019 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
4020
4021 // If body is not a compound statement create implicit scope
4022 // and add destructors.
4023 if (!isa<CompoundStmt>(Val: W->getBody()))
4024 addLocalScopeAndDtors(S: W->getBody());
4025
4026 // Create the body. The returned block is the entry to the loop body.
4027 BodyBlock = addStmt(S: W->getBody());
4028
4029 if (!BodyBlock)
4030 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
4031 else if (Block && badCFG)
4032 return nullptr;
4033 }
4034
4035 // Because of short-circuit evaluation, the condition of the loop can span
4036 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
4037 // evaluate the condition.
4038 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
4039
4040 do {
4041 Expr *C = W->getCond();
4042
4043 // Specially handle logical operators, which have a slightly
4044 // more optimal CFG representation.
4045 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(Val: C->IgnoreParens()))
4046 if (Cond->isLogicalOp()) {
4047 std::tie(args&: EntryConditionBlock, args&: ExitConditionBlock) =
4048 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
4049 break;
4050 }
4051
4052 // The default case when not handling logical operators.
4053 ExitConditionBlock = createBlock(add_successor: false);
4054 ExitConditionBlock->setTerminator(W);
4055
4056 // Now add the actual condition to the condition block.
4057 // Because the condition itself may contain control-flow, new blocks may
4058 // be created. Thus we update "Succ" after adding the condition.
4059 Block = ExitConditionBlock;
4060 Block = EntryConditionBlock = addStmt(C);
4061
4062 // If this block contains a condition variable, add both the condition
4063 // variable and initializer to the CFG.
4064 if (VarDecl *VD = W->getConditionVariable()) {
4065 if (Expr *Init = VD->getInit()) {
4066 autoCreateBlock();
4067 const DeclStmt *DS = W->getConditionVariableDeclStmt();
4068 assert(DS->isSingleDecl());
4069 findConstructionContexts(
4070 ConstructionContextLayer::create(C&: cfg->getBumpVectorContext(),
4071 Item: const_cast<DeclStmt *>(DS)),
4072 Init);
4073 appendStmt(B: Block, S: DS);
4074 EntryConditionBlock = addStmt(Init);
4075 assert(Block == EntryConditionBlock);
4076 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
4077 }
4078 }
4079
4080 if (Block && badCFG)
4081 return nullptr;
4082
4083 // See if this is a known constant.
4084 const TryResult& KnownVal = tryEvaluateBool(S: C);
4085
4086 // Add the loop body entry as a successor to the condition.
4087 addSuccessor(B: ExitConditionBlock, S: KnownVal.isFalse() ? nullptr : BodyBlock);
4088 // Link up the condition block with the code that follows the loop. (the
4089 // false branch).
4090 addSuccessor(B: ExitConditionBlock,
4091 S: KnownVal.isTrue() ? nullptr : LoopSuccessor);
4092 } while(false);
4093
4094 // Link up the loop-back block to the entry condition block.
4095 addSuccessor(B: TransitionBlock, S: EntryConditionBlock);
4096
4097 // There can be no more statements in the condition block since we loop back
4098 // to this block. NULL out Block to force lazy creation of another block.
4099 Block = nullptr;
4100
4101 // Return the condition block, which is the dominating block for the loop.
4102 Succ = EntryConditionBlock;
4103 return EntryConditionBlock;
4104}
4105
4106CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
4107 AddStmtChoice asc) {
4108 if (asc.alwaysAdd(*this, A)) {
4109 autoCreateBlock();
4110 appendStmt(Block, A);
4111 }
4112
4113 CFGBlock *B = Block;
4114
4115 if (CFGBlock *R = Visit(A->getSubExpr()))
4116 B = R;
4117
4118 auto *OVE = dyn_cast<OpaqueValueExpr>(Val: A->getCommonExpr());
4119 assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
4120 "OpaqueValueExpr!");
4121 if (CFGBlock *R = Visit(OVE->getSourceExpr()))
4122 B = R;
4123
4124 return B;
4125}
4126
4127CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
4128 // ObjCAtCatchStmt are treated like labels, so they are the first statement
4129 // in a block.
4130
4131 // Save local scope position because in case of exception variable ScopePos
4132 // won't be restored when traversing AST.
4133 SaveAndRestore save_scope_pos(ScopePos);
4134
4135 if (CS->getCatchBody())
4136 addStmt(S: CS->getCatchBody());
4137
4138 CFGBlock *CatchBlock = Block;
4139 if (!CatchBlock)
4140 CatchBlock = createBlock();
4141
4142 appendStmt(B: CatchBlock, S: CS);
4143
4144 // Also add the ObjCAtCatchStmt as a label, like with regular labels.
4145 CatchBlock->setLabel(CS);
4146
4147 // Bail out if the CFG is bad.
4148 if (badCFG)
4149 return nullptr;
4150
4151 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4152 Block = nullptr;
4153
4154 return CatchBlock;
4155}
4156
4157CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
4158 // If we were in the middle of a block we stop processing that block.
4159 if (badCFG)
4160 return nullptr;
4161
4162 // Create the new block.
4163 Block = createBlock(add_successor: false);
4164
4165 if (TryTerminatedBlock)
4166 // The current try statement is the only successor.
4167 addSuccessor(B: Block, S: TryTerminatedBlock);
4168 else
4169 // otherwise the Exit block is the only successor.
4170 addSuccessor(B: Block, S: &cfg->getExit());
4171
4172 // Add the statement to the block. This may create new blocks if S contains
4173 // control-flow (short-circuit operations).
4174 return VisitStmt(S, asc: AddStmtChoice::AlwaysAdd);
4175}
4176
4177CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
4178 // "@try"/"@catch" is a control-flow statement. Thus we stop processing the
4179 // current block.
4180 CFGBlock *TrySuccessor = nullptr;
4181
4182 if (Block) {
4183 if (badCFG)
4184 return nullptr;
4185 TrySuccessor = Block;
4186 } else
4187 TrySuccessor = Succ;
4188
4189 // FIXME: Implement @finally support.
4190 if (Terminator->getFinallyStmt())
4191 return NYS();
4192
4193 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
4194
4195 // Create a new block that will contain the try statement.
4196 CFGBlock *NewTryTerminatedBlock = createBlock(add_successor: false);
4197 // Add the terminator in the try block.
4198 NewTryTerminatedBlock->setTerminator(Terminator);
4199
4200 bool HasCatchAll = false;
4201 for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
4202 // The code after the try is the implicit successor.
4203 Succ = TrySuccessor;
4204 if (CS->hasEllipsis()) {
4205 HasCatchAll = true;
4206 }
4207 Block = nullptr;
4208 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
4209 if (!CatchBlock)
4210 return nullptr;
4211 // Add this block to the list of successors for the block with the try
4212 // statement.
4213 addSuccessor(NewTryTerminatedBlock, CatchBlock);
4214 }
4215
4216 // FIXME: This needs updating when @finally support is added.
4217 if (!HasCatchAll) {
4218 if (PrevTryTerminatedBlock)
4219 addSuccessor(B: NewTryTerminatedBlock, S: PrevTryTerminatedBlock);
4220 else
4221 addSuccessor(B: NewTryTerminatedBlock, S: &cfg->getExit());
4222 }
4223
4224 // The code after the try is the implicit successor.
4225 Succ = TrySuccessor;
4226
4227 // Save the current "try" context.
4228 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
4229 cfg->addTryDispatchBlock(block: TryTerminatedBlock);
4230
4231 assert(Terminator->getTryBody() && "try must contain a non-NULL body");
4232 Block = nullptr;
4233 return addStmt(S: Terminator->getTryBody());
4234}
4235
4236CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
4237 AddStmtChoice asc) {
4238 findConstructionContextsForArguments(E: ME);
4239
4240 autoCreateBlock();
4241 appendObjCMessage(B: Block, ME);
4242
4243 return VisitChildren(ME);
4244}
4245
4246CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
4247 // If we were in the middle of a block we stop processing that block.
4248 if (badCFG)
4249 return nullptr;
4250
4251 // Create the new block.
4252 Block = createBlock(add_successor: false);
4253
4254 if (TryTerminatedBlock)
4255 // The current try statement is the only successor.
4256 addSuccessor(B: Block, S: TryTerminatedBlock);
4257 else
4258 // otherwise the Exit block is the only successor.
4259 addSuccessor(B: Block, S: &cfg->getExit());
4260
4261 // Add the statement to the block. This may create new blocks if S contains
4262 // control-flow (short-circuit operations).
4263 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
4264}
4265
4266CFGBlock *CFGBuilder::VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc) {
4267 if (asc.alwaysAdd(*this, S)) {
4268 autoCreateBlock();
4269 appendStmt(Block, S);
4270 }
4271
4272 // C++ [expr.typeid]p3:
4273 // When typeid is applied to an expression other than an glvalue of a
4274 // polymorphic class type [...] [the] expression is an unevaluated
4275 // operand. [...]
4276 // We add only potentially evaluated statements to the block to avoid
4277 // CFG generation for unevaluated operands.
4278 if (!S->isTypeDependent() && S->isPotentiallyEvaluated())
4279 return VisitChildren(S);
4280
4281 // Return block without CFG for unevaluated operands.
4282 return Block;
4283}
4284
4285CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
4286 CFGBlock *LoopSuccessor = nullptr;
4287
4288 addLoopExit(LoopStmt: D);
4289
4290 // "do...while" is a control-flow statement. Thus we stop processing the
4291 // current block.
4292 if (Block) {
4293 if (badCFG)
4294 return nullptr;
4295 LoopSuccessor = Block;
4296 } else
4297 LoopSuccessor = Succ;
4298
4299 // Because of short-circuit evaluation, the condition of the loop can span
4300 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
4301 // evaluate the condition.
4302 CFGBlock *ExitConditionBlock = createBlock(add_successor: false);
4303 CFGBlock *EntryConditionBlock = ExitConditionBlock;
4304
4305 // Set the terminator for the "exit" condition block.
4306 ExitConditionBlock->setTerminator(D);
4307
4308 // Now add the actual condition to the condition block. Because the condition
4309 // itself may contain control-flow, new blocks may be created.
4310 if (Stmt *C = D->getCond()) {
4311 Block = ExitConditionBlock;
4312 EntryConditionBlock = addStmt(S: C);
4313 if (Block) {
4314 if (badCFG)
4315 return nullptr;
4316 }
4317 }
4318
4319 // The condition block is the implicit successor for the loop body.
4320 Succ = EntryConditionBlock;
4321
4322 // See if this is a known constant.
4323 const TryResult &KnownVal = tryEvaluateBool(S: D->getCond());
4324
4325 // Process the loop body.
4326 CFGBlock *BodyBlock = nullptr;
4327 {
4328 assert(D->getBody());
4329
4330 // Save the current values for Block, Succ, and continue and break targets
4331 SaveAndRestore save_Block(Block), save_Succ(Succ);
4332 SaveAndRestore save_continue(ContinueJumpTarget),
4333 save_break(BreakJumpTarget);
4334
4335 // All continues within this loop should go to the condition block
4336 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
4337
4338 // All breaks should go to the code following the loop.
4339 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4340
4341 // NULL out Block to force lazy instantiation of blocks for the body.
4342 Block = nullptr;
4343
4344 // If body is not a compound statement create implicit scope
4345 // and add destructors.
4346 if (!isa<CompoundStmt>(Val: D->getBody()))
4347 addLocalScopeAndDtors(S: D->getBody());
4348
4349 // Create the body. The returned block is the entry to the loop body.
4350 BodyBlock = addStmt(S: D->getBody());
4351
4352 if (!BodyBlock)
4353 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
4354 else if (Block) {
4355 if (badCFG)
4356 return nullptr;
4357 }
4358
4359 // Add an intermediate block between the BodyBlock and the
4360 // ExitConditionBlock to represent the "loop back" transition. Create an
4361 // empty block to represent the transition block for looping back to the
4362 // head of the loop.
4363 // FIXME: Can we do this more efficiently without adding another block?
4364 Block = nullptr;
4365 Succ = BodyBlock;
4366 CFGBlock *LoopBackBlock = createBlock();
4367 LoopBackBlock->setLoopTarget(D);
4368
4369 if (!KnownVal.isFalse())
4370 // Add the loop body entry as a successor to the condition.
4371 addSuccessor(B: ExitConditionBlock, S: LoopBackBlock);
4372 else
4373 addSuccessor(B: ExitConditionBlock, S: nullptr);
4374 }
4375
4376 // Link up the condition block with the code that follows the loop.
4377 // (the false branch).
4378 addSuccessor(B: ExitConditionBlock, S: KnownVal.isTrue() ? nullptr : LoopSuccessor);
4379
4380 // There can be no more statements in the body block(s) since we loop back to
4381 // the body. NULL out Block to force lazy creation of another block.
4382 Block = nullptr;
4383
4384 // Return the loop body, which is the dominating block for the loop.
4385 Succ = BodyBlock;
4386 return BodyBlock;
4387}
4388
4389CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
4390 // "continue" is a control-flow statement. Thus we stop processing the
4391 // current block.
4392 if (badCFG)
4393 return nullptr;
4394
4395 // Now create a new block that ends with the continue statement.
4396 Block = createBlock(add_successor: false);
4397 Block->setTerminator(C);
4398
4399 // If there is no target for the continue, then we are looking at an
4400 // incomplete AST. This means the CFG cannot be constructed.
4401 if (ContinueJumpTarget.block) {
4402 addAutomaticObjHandling(B: ScopePos, E: ContinueJumpTarget.scopePosition, S: C);
4403 addSuccessor(B: Block, S: ContinueJumpTarget.block);
4404 } else
4405 badCFG = true;
4406
4407 return Block;
4408}
4409
4410CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
4411 AddStmtChoice asc) {
4412 if (asc.alwaysAdd(*this, E)) {
4413 autoCreateBlock();
4414 appendStmt(Block, E);
4415 }
4416
4417 // VLA types have expressions that must be evaluated.
4418 // Evaluation is done only for `sizeof`.
4419
4420 if (E->getKind() != UETT_SizeOf)
4421 return Block;
4422
4423 CFGBlock *lastBlock = Block;
4424
4425 if (E->isArgumentType()) {
4426 for (const VariableArrayType *VA =FindVA(t: E->getArgumentType().getTypePtr());
4427 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
4428 lastBlock = addStmt(VA->getSizeExpr());
4429 }
4430 return lastBlock;
4431}
4432
4433/// VisitStmtExpr - Utility method to handle (nested) statement
4434/// expressions (a GCC extension).
4435CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
4436 if (asc.alwaysAdd(*this, SE)) {
4437 autoCreateBlock();
4438 appendStmt(Block, SE);
4439 }
4440 return VisitCompoundStmt(C: SE->getSubStmt(), /*ExternallyDestructed=*/true);
4441}
4442
4443CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
4444 // "switch" is a control-flow statement. Thus we stop processing the current
4445 // block.
4446 CFGBlock *SwitchSuccessor = nullptr;
4447
4448 // Save local scope position because in case of condition variable ScopePos
4449 // won't be restored when traversing AST.
4450 SaveAndRestore save_scope_pos(ScopePos);
4451
4452 // Create local scope for C++17 switch init-stmt if one exists.
4453 if (Stmt *Init = Terminator->getInit())
4454 addLocalScopeForStmt(S: Init);
4455
4456 // Create local scope for possible condition variable.
4457 // Store scope position. Add implicit destructor.
4458 if (VarDecl *VD = Terminator->getConditionVariable())
4459 addLocalScopeForVarDecl(VD);
4460
4461 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
4462
4463 if (Block) {
4464 if (badCFG)
4465 return nullptr;
4466 SwitchSuccessor = Block;
4467 } else SwitchSuccessor = Succ;
4468
4469 // Save the current "switch" context.
4470 SaveAndRestore save_switch(SwitchTerminatedBlock),
4471 save_default(DefaultCaseBlock);
4472 SaveAndRestore save_break(BreakJumpTarget);
4473
4474 // Set the "default" case to be the block after the switch statement. If the
4475 // switch statement contains a "default:", this value will be overwritten with
4476 // the block for that code.
4477 DefaultCaseBlock = SwitchSuccessor;
4478
4479 // Create a new block that will contain the switch statement.
4480 SwitchTerminatedBlock = createBlock(add_successor: false);
4481
4482 // Now process the switch body. The code after the switch is the implicit
4483 // successor.
4484 Succ = SwitchSuccessor;
4485 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
4486
4487 // When visiting the body, the case statements should automatically get linked
4488 // up to the switch. We also don't keep a pointer to the body, since all
4489 // control-flow from the switch goes to case/default statements.
4490 assert(Terminator->getBody() && "switch must contain a non-NULL body");
4491 Block = nullptr;
4492
4493 // For pruning unreachable case statements, save the current state
4494 // for tracking the condition value.
4495 SaveAndRestore save_switchExclusivelyCovered(switchExclusivelyCovered, false);
4496
4497 // Determine if the switch condition can be explicitly evaluated.
4498 assert(Terminator->getCond() && "switch condition must be non-NULL");
4499 Expr::EvalResult result;
4500 bool b = tryEvaluate(S: Terminator->getCond(), outResult&: result);
4501 SaveAndRestore save_switchCond(switchCond, b ? &result : nullptr);
4502
4503 // If body is not a compound statement create implicit scope
4504 // and add destructors.
4505 if (!isa<CompoundStmt>(Val: Terminator->getBody()))
4506 addLocalScopeAndDtors(S: Terminator->getBody());
4507
4508 addStmt(S: Terminator->getBody());
4509 if (Block) {
4510 if (badCFG)
4511 return nullptr;
4512 }
4513
4514 // If we have no "default:" case, the default transition is to the code
4515 // following the switch body. Moreover, take into account if all the
4516 // cases of a switch are covered (e.g., switching on an enum value).
4517 //
4518 // Note: We add a successor to a switch that is considered covered yet has no
4519 // case statements if the enumeration has no enumerators.
4520 bool SwitchAlwaysHasSuccessor = false;
4521 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
4522 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
4523 Terminator->getSwitchCaseList();
4524 addSuccessor(B: SwitchTerminatedBlock, S: DefaultCaseBlock,
4525 IsReachable: !SwitchAlwaysHasSuccessor);
4526
4527 // Add the terminator and condition in the switch block.
4528 SwitchTerminatedBlock->setTerminator(Terminator);
4529 Block = SwitchTerminatedBlock;
4530 CFGBlock *LastBlock = addStmt(Terminator->getCond());
4531
4532 // If the SwitchStmt contains a condition variable, add both the
4533 // SwitchStmt and the condition variable initialization to the CFG.
4534 if (VarDecl *VD = Terminator->getConditionVariable()) {
4535 if (Expr *Init = VD->getInit()) {
4536 autoCreateBlock();
4537 appendStmt(B: Block, S: Terminator->getConditionVariableDeclStmt());
4538 LastBlock = addStmt(Init);
4539 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
4540 }
4541 }
4542
4543 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
4544 if (Stmt *Init = Terminator->getInit()) {
4545 autoCreateBlock();
4546 LastBlock = addStmt(S: Init);
4547 }
4548
4549 return LastBlock;
4550}
4551
4552static bool shouldAddCase(bool &switchExclusivelyCovered,
4553 const Expr::EvalResult *switchCond,
4554 const CaseStmt *CS,
4555 ASTContext &Ctx) {
4556 if (!switchCond)
4557 return true;
4558
4559 bool addCase = false;
4560
4561 if (!switchExclusivelyCovered) {
4562 if (switchCond->Val.isInt()) {
4563 // Evaluate the LHS of the case value.
4564 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
4565 const llvm::APSInt &condInt = switchCond->Val.getInt();
4566
4567 if (condInt == lhsInt) {
4568 addCase = true;
4569 switchExclusivelyCovered = true;
4570 }
4571 else if (condInt > lhsInt) {
4572 if (const Expr *RHS = CS->getRHS()) {
4573 // Evaluate the RHS of the case value.
4574 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
4575 if (V2 >= condInt) {
4576 addCase = true;
4577 switchExclusivelyCovered = true;
4578 }
4579 }
4580 }
4581 }
4582 else
4583 addCase = true;
4584 }
4585 return addCase;
4586}
4587
4588CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
4589 // CaseStmts are essentially labels, so they are the first statement in a
4590 // block.
4591 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
4592
4593 if (Stmt *Sub = CS->getSubStmt()) {
4594 // For deeply nested chains of CaseStmts, instead of doing a recursion
4595 // (which can blow out the stack), manually unroll and create blocks
4596 // along the way.
4597 while (isa<CaseStmt>(Val: Sub)) {
4598 CFGBlock *currentBlock = createBlock(add_successor: false);
4599 currentBlock->setLabel(CS);
4600
4601 if (TopBlock)
4602 addSuccessor(B: LastBlock, S: currentBlock);
4603 else
4604 TopBlock = currentBlock;
4605
4606 addSuccessor(B: SwitchTerminatedBlock,
4607 S: shouldAddCase(switchExclusivelyCovered, switchCond,
4608 CS, Ctx&: *Context)
4609 ? currentBlock : nullptr);
4610
4611 LastBlock = currentBlock;
4612 CS = cast<CaseStmt>(Val: Sub);
4613 Sub = CS->getSubStmt();
4614 }
4615
4616 addStmt(S: Sub);
4617 }
4618
4619 CFGBlock *CaseBlock = Block;
4620 if (!CaseBlock)
4621 CaseBlock = createBlock();
4622
4623 // Cases statements partition blocks, so this is the top of the basic block we
4624 // were processing (the "case XXX:" is the label).
4625 CaseBlock->setLabel(CS);
4626
4627 if (badCFG)
4628 return nullptr;
4629
4630 // Add this block to the list of successors for the block with the switch
4631 // statement.
4632 assert(SwitchTerminatedBlock);
4633 addSuccessor(B: SwitchTerminatedBlock, S: CaseBlock,
4634 IsReachable: shouldAddCase(switchExclusivelyCovered, switchCond,
4635 CS, Ctx&: *Context));
4636
4637 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4638 Block = nullptr;
4639
4640 if (TopBlock) {
4641 addSuccessor(B: LastBlock, S: CaseBlock);
4642 Succ = TopBlock;
4643 } else {
4644 // This block is now the implicit successor of other blocks.
4645 Succ = CaseBlock;
4646 }
4647
4648 return Succ;
4649}
4650
4651CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
4652 if (Terminator->getSubStmt())
4653 addStmt(S: Terminator->getSubStmt());
4654
4655 DefaultCaseBlock = Block;
4656
4657 if (!DefaultCaseBlock)
4658 DefaultCaseBlock = createBlock();
4659
4660 // Default statements partition blocks, so this is the top of the basic block
4661 // we were processing (the "default:" is the label).
4662 DefaultCaseBlock->setLabel(Terminator);
4663
4664 if (badCFG)
4665 return nullptr;
4666
4667 // Unlike case statements, we don't add the default block to the successors
4668 // for the switch statement immediately. This is done when we finish
4669 // processing the switch statement. This allows for the default case
4670 // (including a fall-through to the code after the switch statement) to always
4671 // be the last successor of a switch-terminated block.
4672
4673 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4674 Block = nullptr;
4675
4676 // This block is now the implicit successor of other blocks.
4677 Succ = DefaultCaseBlock;
4678
4679 return DefaultCaseBlock;
4680}
4681
4682CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
4683 // "try"/"catch" is a control-flow statement. Thus we stop processing the
4684 // current block.
4685 CFGBlock *TrySuccessor = nullptr;
4686
4687 if (Block) {
4688 if (badCFG)
4689 return nullptr;
4690 TrySuccessor = Block;
4691 } else
4692 TrySuccessor = Succ;
4693
4694 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
4695
4696 // Create a new block that will contain the try statement.
4697 CFGBlock *NewTryTerminatedBlock = createBlock(add_successor: false);
4698 // Add the terminator in the try block.
4699 NewTryTerminatedBlock->setTerminator(Terminator);
4700
4701 bool HasCatchAll = false;
4702 for (unsigned I = 0, E = Terminator->getNumHandlers(); I != E; ++I) {
4703 // The code after the try is the implicit successor.
4704 Succ = TrySuccessor;
4705 CXXCatchStmt *CS = Terminator->getHandler(i: I);
4706 if (CS->getExceptionDecl() == nullptr) {
4707 HasCatchAll = true;
4708 }
4709 Block = nullptr;
4710 CFGBlock *CatchBlock = VisitCXXCatchStmt(S: CS);
4711 if (!CatchBlock)
4712 return nullptr;
4713 // Add this block to the list of successors for the block with the try
4714 // statement.
4715 addSuccessor(B: NewTryTerminatedBlock, S: CatchBlock);
4716 }
4717 if (!HasCatchAll) {
4718 if (PrevTryTerminatedBlock)
4719 addSuccessor(B: NewTryTerminatedBlock, S: PrevTryTerminatedBlock);
4720 else
4721 addSuccessor(B: NewTryTerminatedBlock, S: &cfg->getExit());
4722 }
4723
4724 // The code after the try is the implicit successor.
4725 Succ = TrySuccessor;
4726
4727 // Save the current "try" context.
4728 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
4729 cfg->addTryDispatchBlock(block: TryTerminatedBlock);
4730
4731 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
4732 Block = nullptr;
4733 return addStmt(Terminator->getTryBlock());
4734}
4735
4736CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
4737 // CXXCatchStmt are treated like labels, so they are the first statement in a
4738 // block.
4739
4740 // Save local scope position because in case of exception variable ScopePos
4741 // won't be restored when traversing AST.
4742 SaveAndRestore save_scope_pos(ScopePos);
4743
4744 // Create local scope for possible exception variable.
4745 // Store scope position. Add implicit destructor.
4746 if (VarDecl *VD = CS->getExceptionDecl()) {
4747 LocalScope::const_iterator BeginScopePos = ScopePos;
4748 addLocalScopeForVarDecl(VD);
4749 addAutomaticObjHandling(B: ScopePos, E: BeginScopePos, S: CS);
4750 }
4751
4752 if (CS->getHandlerBlock())
4753 addStmt(S: CS->getHandlerBlock());
4754
4755 CFGBlock *CatchBlock = Block;
4756 if (!CatchBlock)
4757 CatchBlock = createBlock();
4758
4759 // CXXCatchStmt is more than just a label. They have semantic meaning
4760 // as well, as they implicitly "initialize" the catch variable. Add
4761 // it to the CFG as a CFGElement so that the control-flow of these
4762 // semantics gets captured.
4763 appendStmt(B: CatchBlock, S: CS);
4764
4765 // Also add the CXXCatchStmt as a label, to mirror handling of regular
4766 // labels.
4767 CatchBlock->setLabel(CS);
4768
4769 // Bail out if the CFG is bad.
4770 if (badCFG)
4771 return nullptr;
4772
4773 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4774 Block = nullptr;
4775
4776 return CatchBlock;
4777}
4778
4779CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4780 // C++0x for-range statements are specified as [stmt.ranged]:
4781 //
4782 // {
4783 // auto && __range = range-init;
4784 // for ( auto __begin = begin-expr,
4785 // __end = end-expr;
4786 // __begin != __end;
4787 // ++__begin ) {
4788 // for-range-declaration = *__begin;
4789 // statement
4790 // }
4791 // }
4792
4793 // Save local scope position before the addition of the implicit variables.
4794 SaveAndRestore save_scope_pos(ScopePos);
4795
4796 // Create local scopes and destructors for range, begin and end variables.
4797 if (Stmt *Range = S->getRangeStmt())
4798 addLocalScopeForStmt(S: Range);
4799 if (Stmt *Begin = S->getBeginStmt())
4800 addLocalScopeForStmt(S: Begin);
4801 if (Stmt *End = S->getEndStmt())
4802 addLocalScopeForStmt(S: End);
4803 addAutomaticObjHandling(B: ScopePos, E: save_scope_pos.get(), S);
4804
4805 LocalScope::const_iterator ContinueScopePos = ScopePos;
4806
4807 // "for" is a control-flow statement. Thus we stop processing the current
4808 // block.
4809 CFGBlock *LoopSuccessor = nullptr;
4810 if (Block) {
4811 if (badCFG)
4812 return nullptr;
4813 LoopSuccessor = Block;
4814 } else
4815 LoopSuccessor = Succ;
4816
4817 // Save the current value for the break targets.
4818 // All breaks should go to the code following the loop.
4819 SaveAndRestore save_break(BreakJumpTarget);
4820 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4821
4822 // The block for the __begin != __end expression.
4823 CFGBlock *ConditionBlock = createBlock(add_successor: false);
4824 ConditionBlock->setTerminator(S);
4825
4826 // Now add the actual condition to the condition block.
4827 if (Expr *C = S->getCond()) {
4828 Block = ConditionBlock;
4829 CFGBlock *BeginConditionBlock = addStmt(C);
4830 if (badCFG)
4831 return nullptr;
4832 assert(BeginConditionBlock == ConditionBlock &&
4833 "condition block in for-range was unexpectedly complex");
4834 (void)BeginConditionBlock;
4835 }
4836
4837 // The condition block is the implicit successor for the loop body as well as
4838 // any code above the loop.
4839 Succ = ConditionBlock;
4840
4841 // See if this is a known constant.
4842 TryResult KnownVal(true);
4843
4844 if (S->getCond())
4845 KnownVal = tryEvaluateBool(S: S->getCond());
4846
4847 // Now create the loop body.
4848 {
4849 assert(S->getBody());
4850
4851 // Save the current values for Block, Succ, and continue targets.
4852 SaveAndRestore save_Block(Block), save_Succ(Succ);
4853 SaveAndRestore save_continue(ContinueJumpTarget);
4854
4855 // Generate increment code in its own basic block. This is the target of
4856 // continue statements.
4857 Block = nullptr;
4858 Succ = addStmt(S->getInc());
4859 if (badCFG)
4860 return nullptr;
4861 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
4862
4863 // The starting block for the loop increment is the block that should
4864 // represent the 'loop target' for looping back to the start of the loop.
4865 ContinueJumpTarget.block->setLoopTarget(S);
4866
4867 // Finish up the increment block and prepare to start the loop body.
4868 assert(Block);
4869 if (badCFG)
4870 return nullptr;
4871 Block = nullptr;
4872
4873 // Add implicit scope and dtors for loop variable.
4874 addLocalScopeAndDtors(S: S->getLoopVarStmt());
4875
4876 // If body is not a compound statement create implicit scope
4877 // and add destructors.
4878 if (!isa<CompoundStmt>(Val: S->getBody()))
4879 addLocalScopeAndDtors(S: S->getBody());
4880
4881 // Populate a new block to contain the loop body and loop variable.
4882 addStmt(S: S->getBody());
4883
4884 if (badCFG)
4885 return nullptr;
4886 CFGBlock *LoopVarStmtBlock = addStmt(S: S->getLoopVarStmt());
4887 if (badCFG)
4888 return nullptr;
4889
4890 // This new body block is a successor to our condition block.
4891 addSuccessor(B: ConditionBlock,
4892 S: KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
4893 }
4894
4895 // Link up the condition block with the code that follows the loop (the
4896 // false branch).
4897 addSuccessor(B: ConditionBlock, S: KnownVal.isTrue() ? nullptr : LoopSuccessor);
4898
4899 // Add the initialization statements.
4900 Block = createBlock();
4901 addStmt(S: S->getBeginStmt());
4902 addStmt(S: S->getEndStmt());
4903 CFGBlock *Head = addStmt(S: S->getRangeStmt());
4904 if (S->getInit())
4905 Head = addStmt(S: S->getInit());
4906 return Head;
4907}
4908
4909CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
4910 AddStmtChoice asc, bool ExternallyDestructed) {
4911 if (BuildOpts.AddTemporaryDtors) {
4912 // If adding implicit destructors visit the full expression for adding
4913 // destructors of temporaries.
4914 TempDtorContext Context;
4915 VisitForTemporaryDtors(E: E->getSubExpr(), ExternallyDestructed, Context);
4916
4917 // Full expression has to be added as CFGStmt so it will be sequenced
4918 // before destructors of it's temporaries.
4919 asc = asc.withAlwaysAdd(alwaysAdd: true);
4920 }
4921 return Visit(S: E->getSubExpr(), asc);
4922}
4923
4924CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
4925 AddStmtChoice asc) {
4926 if (asc.alwaysAdd(*this, E)) {
4927 autoCreateBlock();
4928 appendStmt(Block, E);
4929
4930 findConstructionContexts(
4931 ConstructionContextLayer::create(C&: cfg->getBumpVectorContext(), Item: E),
4932 E->getSubExpr());
4933
4934 // We do not want to propagate the AlwaysAdd property.
4935 asc = asc.withAlwaysAdd(alwaysAdd: false);
4936 }
4937 return Visit(E->getSubExpr(), asc);
4938}
4939
4940CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
4941 AddStmtChoice asc) {
4942 // If the constructor takes objects as arguments by value, we need to properly
4943 // construct these objects. Construction contexts we find here aren't for the
4944 // constructor C, they're for its arguments only.
4945 findConstructionContextsForArguments(E: C);
4946 appendConstructor(CE: C);
4947
4948 return VisitChildren(C);
4949}
4950
4951CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
4952 AddStmtChoice asc) {
4953 autoCreateBlock();
4954 appendStmt(Block, NE);
4955
4956 findConstructionContexts(
4957 ConstructionContextLayer::create(C&: cfg->getBumpVectorContext(), Item: NE),
4958 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
4959
4960 if (NE->getInitializer())
4961 Block = Visit(NE->getInitializer());
4962
4963 if (BuildOpts.AddCXXNewAllocator)
4964 appendNewAllocator(B: Block, NE);
4965
4966 if (NE->isArray() && *NE->getArraySize())
4967 Block = Visit(*NE->getArraySize());
4968
4969 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
4970 E = NE->placement_arg_end(); I != E; ++I)
4971 Block = Visit(*I);
4972
4973 return Block;
4974}
4975
4976CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
4977 AddStmtChoice asc) {
4978 autoCreateBlock();
4979 appendStmt(Block, DE);
4980 QualType DTy = DE->getDestroyedType();
4981 if (!DTy.isNull()) {
4982 DTy = DTy.getNonReferenceType();
4983 CXXRecordDecl *RD = Context->getBaseElementType(QT: DTy)->getAsCXXRecordDecl();
4984 if (RD) {
4985 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
4986 appendDeleteDtor(B: Block, RD, DE);
4987 }
4988 }
4989
4990 return VisitChildren(DE);
4991}
4992
4993CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
4994 AddStmtChoice asc) {
4995 if (asc.alwaysAdd(*this, E)) {
4996 autoCreateBlock();
4997 appendStmt(Block, E);
4998 // We do not want to propagate the AlwaysAdd property.
4999 asc = asc.withAlwaysAdd(alwaysAdd: false);
5000 }
5001 return Visit(S: E->getSubExpr(), asc);
5002}
5003
5004CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E,
5005 AddStmtChoice asc) {
5006 // If the constructor takes objects as arguments by value, we need to properly
5007 // construct these objects. Construction contexts we find here aren't for the
5008 // constructor C, they're for its arguments only.
5009 findConstructionContextsForArguments(E);
5010 appendConstructor(E);
5011
5012 return VisitChildren(E);
5013}
5014
5015CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
5016 AddStmtChoice asc) {
5017 if (asc.alwaysAdd(*this, E)) {
5018 autoCreateBlock();
5019 appendStmt(Block, E);
5020 }
5021
5022 if (E->getCastKind() == CK_IntegralToBoolean)
5023 tryEvaluateBool(S: E->getSubExpr()->IgnoreParens());
5024
5025 return Visit(S: E->getSubExpr(), asc: AddStmtChoice());
5026}
5027
5028CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
5029 return Visit(S: E->getSubExpr(), asc: AddStmtChoice());
5030}
5031
5032CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
5033 // Lazily create the indirect-goto dispatch block if there isn't one already.
5034 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
5035
5036 if (!IBlock) {
5037 IBlock = createBlock(add_successor: false);
5038 cfg->setIndirectGotoBlock(IBlock);
5039 }
5040
5041 // IndirectGoto is a control-flow statement. Thus we stop processing the
5042 // current block and create a new one.
5043 if (badCFG)
5044 return nullptr;
5045
5046 Block = createBlock(add_successor: false);
5047 Block->setTerminator(I);
5048 addSuccessor(B: Block, S: IBlock);
5049 return addStmt(I->getTarget());
5050}
5051
5052CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
5053 TempDtorContext &Context) {
5054 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
5055
5056tryAgain:
5057 if (!E) {
5058 badCFG = true;
5059 return nullptr;
5060 }
5061 switch (E->getStmtClass()) {
5062 default:
5063 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed: false, Context);
5064
5065 case Stmt::InitListExprClass:
5066 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
5067
5068 case Stmt::BinaryOperatorClass:
5069 return VisitBinaryOperatorForTemporaryDtors(E: cast<BinaryOperator>(Val: E),
5070 ExternallyDestructed,
5071 Context);
5072
5073 case Stmt::CXXBindTemporaryExprClass:
5074 return VisitCXXBindTemporaryExprForTemporaryDtors(
5075 E: cast<CXXBindTemporaryExpr>(Val: E), ExternallyDestructed, Context);
5076
5077 case Stmt::BinaryConditionalOperatorClass:
5078 case Stmt::ConditionalOperatorClass:
5079 return VisitConditionalOperatorForTemporaryDtors(
5080 E: cast<AbstractConditionalOperator>(Val: E), ExternallyDestructed, Context);
5081
5082 case Stmt::ImplicitCastExprClass:
5083 // For implicit cast we want ExternallyDestructed to be passed further.
5084 E = cast<CastExpr>(Val: E)->getSubExpr();
5085 goto tryAgain;
5086
5087 case Stmt::CXXFunctionalCastExprClass:
5088 // For functional cast we want ExternallyDestructed to be passed further.
5089 E = cast<CXXFunctionalCastExpr>(Val: E)->getSubExpr();
5090 goto tryAgain;
5091
5092 case Stmt::ConstantExprClass:
5093 E = cast<ConstantExpr>(Val: E)->getSubExpr();
5094 goto tryAgain;
5095
5096 case Stmt::ParenExprClass:
5097 E = cast<ParenExpr>(Val: E)->getSubExpr();
5098 goto tryAgain;
5099
5100 case Stmt::MaterializeTemporaryExprClass: {
5101 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(Val: E);
5102 ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression);
5103 SmallVector<const Expr *, 2> CommaLHSs;
5104 SmallVector<SubobjectAdjustment, 2> Adjustments;
5105 // Find the expression whose lifetime needs to be extended.
5106 E = const_cast<Expr *>(
5107 cast<MaterializeTemporaryExpr>(Val: E)
5108 ->getSubExpr()
5109 ->skipRValueSubobjectAdjustments(CommaLHS&: CommaLHSs, Adjustments));
5110 // Visit the skipped comma operator left-hand sides for other temporaries.
5111 for (const Expr *CommaLHS : CommaLHSs) {
5112 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
5113 /*ExternallyDestructed=*/false, Context);
5114 }
5115 goto tryAgain;
5116 }
5117
5118 case Stmt::BlockExprClass:
5119 // Don't recurse into blocks; their subexpressions don't get evaluated
5120 // here.
5121 return Block;
5122
5123 case Stmt::LambdaExprClass: {
5124 // For lambda expressions, only recurse into the capture initializers,
5125 // and not the body.
5126 auto *LE = cast<LambdaExpr>(Val: E);
5127 CFGBlock *B = Block;
5128 for (Expr *Init : LE->capture_inits()) {
5129 if (Init) {
5130 if (CFGBlock *R = VisitForTemporaryDtors(
5131 Init, /*ExternallyDestructed=*/true, Context))
5132 B = R;
5133 }
5134 }
5135 return B;
5136 }
5137
5138 case Stmt::StmtExprClass:
5139 // Don't recurse into statement expressions; any cleanups inside them
5140 // will be wrapped in their own ExprWithCleanups.
5141 return Block;
5142
5143 case Stmt::CXXDefaultArgExprClass:
5144 E = cast<CXXDefaultArgExpr>(Val: E)->getExpr();
5145 goto tryAgain;
5146
5147 case Stmt::CXXDefaultInitExprClass:
5148 E = cast<CXXDefaultInitExpr>(Val: E)->getExpr();
5149 goto tryAgain;
5150 }
5151}
5152
5153CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
5154 bool ExternallyDestructed,
5155 TempDtorContext &Context) {
5156 if (isa<LambdaExpr>(Val: E)) {
5157 // Do not visit the children of lambdas; they have their own CFGs.
5158 return Block;
5159 }
5160
5161 // When visiting children for destructors we want to visit them in reverse
5162 // order that they will appear in the CFG. Because the CFG is built
5163 // bottom-up, this means we visit them in their natural order, which
5164 // reverses them in the CFG.
5165 CFGBlock *B = Block;
5166 for (Stmt *Child : E->children())
5167 if (Child)
5168 if (CFGBlock *R = VisitForTemporaryDtors(E: Child, ExternallyDestructed, Context))
5169 B = R;
5170
5171 return B;
5172}
5173
5174CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
5175 BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) {
5176 if (E->isCommaOp()) {
5177 // For the comma operator, the LHS expression is evaluated before the RHS
5178 // expression, so prepend temporary destructors for the LHS first.
5179 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
5180 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), ExternallyDestructed, Context);
5181 return RHSBlock ? RHSBlock : LHSBlock;
5182 }
5183
5184 if (E->isLogicalOp()) {
5185 VisitForTemporaryDtors(E->getLHS(), false, Context);
5186 TryResult RHSExecuted = tryEvaluateBool(S: E->getLHS());
5187 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
5188 RHSExecuted.negate();
5189
5190 // We do not know at CFG-construction time whether the right-hand-side was
5191 // executed, thus we add a branch node that depends on the temporary
5192 // constructor call.
5193 TempDtorContext RHSContext(
5194 bothKnownTrue(R1: Context.KnownExecuted, R2: RHSExecuted));
5195 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
5196 InsertTempDtorDecisionBlock(Context: RHSContext);
5197
5198 return Block;
5199 }
5200
5201 if (E->isAssignmentOp()) {
5202 // For assignment operators, the RHS expression is evaluated before the LHS
5203 // expression, so prepend temporary destructors for the RHS first.
5204 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
5205 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
5206 return LHSBlock ? LHSBlock : RHSBlock;
5207 }
5208
5209 // Any other operator is visited normally.
5210 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
5211}
5212
5213CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
5214 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) {
5215 // First add destructors for temporaries in subexpression.
5216 // Because VisitCXXBindTemporaryExpr calls setDestructed:
5217 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), true, Context);
5218 if (!ExternallyDestructed) {
5219 // If lifetime of temporary is not prolonged (by assigning to constant
5220 // reference) add destructor for it.
5221
5222 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
5223
5224 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
5225 // If the destructor is marked as a no-return destructor, we need to
5226 // create a new block for the destructor which does not have as a
5227 // successor anything built thus far. Control won't flow out of this
5228 // block.
5229 if (B) Succ = B;
5230 Block = createNoReturnBlock();
5231 } else if (Context.needsTempDtorBranch()) {
5232 // If we need to introduce a branch, we add a new block that we will hook
5233 // up to a decision block later.
5234 if (B) Succ = B;
5235 Block = createBlock();
5236 } else {
5237 autoCreateBlock();
5238 }
5239 if (Context.needsTempDtorBranch()) {
5240 Context.setDecisionPoint(S: Succ, E);
5241 }
5242 appendTemporaryDtor(B: Block, E);
5243
5244 B = Block;
5245 }
5246 return B;
5247}
5248
5249void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
5250 CFGBlock *FalseSucc) {
5251 if (!Context.TerminatorExpr) {
5252 // If no temporary was found, we do not need to insert a decision point.
5253 return;
5254 }
5255 assert(Context.TerminatorExpr);
5256 CFGBlock *Decision = createBlock(add_successor: false);
5257 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
5258 CFGTerminator::TemporaryDtorsBranch));
5259 addSuccessor(B: Decision, S: Block, IsReachable: !Context.KnownExecuted.isFalse());
5260 addSuccessor(B: Decision, S: FalseSucc ? FalseSucc : Context.Succ,
5261 IsReachable: !Context.KnownExecuted.isTrue());
5262 Block = Decision;
5263}
5264
5265CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
5266 AbstractConditionalOperator *E, bool ExternallyDestructed,
5267 TempDtorContext &Context) {
5268 VisitForTemporaryDtors(E->getCond(), false, Context);
5269 CFGBlock *ConditionBlock = Block;
5270 CFGBlock *ConditionSucc = Succ;
5271 TryResult ConditionVal = tryEvaluateBool(S: E->getCond());
5272 TryResult NegatedVal = ConditionVal;
5273 if (NegatedVal.isKnown()) NegatedVal.negate();
5274
5275 TempDtorContext TrueContext(
5276 bothKnownTrue(R1: Context.KnownExecuted, R2: ConditionVal));
5277 VisitForTemporaryDtors(E->getTrueExpr(), ExternallyDestructed, TrueContext);
5278 CFGBlock *TrueBlock = Block;
5279
5280 Block = ConditionBlock;
5281 Succ = ConditionSucc;
5282 TempDtorContext FalseContext(
5283 bothKnownTrue(R1: Context.KnownExecuted, R2: NegatedVal));
5284 VisitForTemporaryDtors(E->getFalseExpr(), ExternallyDestructed, FalseContext);
5285
5286 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
5287 InsertTempDtorDecisionBlock(Context: FalseContext, FalseSucc: TrueBlock);
5288 } else if (TrueContext.TerminatorExpr) {
5289 Block = TrueBlock;
5290 InsertTempDtorDecisionBlock(Context: TrueContext);
5291 } else {
5292 InsertTempDtorDecisionBlock(Context: FalseContext);
5293 }
5294 return Block;
5295}
5296
5297CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D,
5298 AddStmtChoice asc) {
5299 if (asc.alwaysAdd(*this, D)) {
5300 autoCreateBlock();
5301 appendStmt(Block, D);
5302 }
5303
5304 // Iterate over all used expression in clauses.
5305 CFGBlock *B = Block;
5306
5307 // Reverse the elements to process them in natural order. Iterators are not
5308 // bidirectional, so we need to create temp vector.
5309 SmallVector<Stmt *, 8> Used(
5310 OMPExecutableDirective::used_clauses_children(Clauses: D->clauses()));
5311 for (Stmt *S : llvm::reverse(C&: Used)) {
5312 assert(S && "Expected non-null used-in-clause child.");
5313 if (CFGBlock *R = Visit(S))
5314 B = R;
5315 }
5316 // Visit associated structured block if any.
5317 if (!D->isStandaloneDirective()) {
5318 Stmt *S = D->getRawStmt();
5319 if (!isa<CompoundStmt>(Val: S))
5320 addLocalScopeAndDtors(S);
5321 if (CFGBlock *R = addStmt(S))
5322 B = R;
5323 }
5324
5325 return B;
5326}
5327
5328/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
5329/// no successors or predecessors. If this is the first block created in the
5330/// CFG, it is automatically set to be the Entry and Exit of the CFG.
5331CFGBlock *CFG::createBlock() {
5332 bool first_block = begin() == end();
5333
5334 // Create the block.
5335 CFGBlock *Mem = new (getAllocator()) CFGBlock(NumBlockIDs++, BlkBVC, this);
5336 Blocks.push_back(Elt: Mem, C&: BlkBVC);
5337
5338 // If this is the first block, set it as the Entry and Exit.
5339 if (first_block)
5340 Entry = Exit = &back();
5341
5342 // Return the block.
5343 return &back();
5344}
5345
5346/// buildCFG - Constructs a CFG from an AST.
5347std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
5348 ASTContext *C, const BuildOptions &BO) {
5349 CFGBuilder Builder(C, BO);
5350 return Builder.buildCFG(D, Statement);
5351}
5352
5353bool CFG::isLinear() const {
5354 // Quick path: if we only have the ENTRY block, the EXIT block, and some code
5355 // in between, then we have no room for control flow.
5356 if (size() <= 3)
5357 return true;
5358
5359 // Traverse the CFG until we find a branch.
5360 // TODO: While this should still be very fast,
5361 // maybe we should cache the answer.
5362 llvm::SmallPtrSet<const CFGBlock *, 4> Visited;
5363 const CFGBlock *B = Entry;
5364 while (B != Exit) {
5365 auto IteratorAndFlag = Visited.insert(Ptr: B);
5366 if (!IteratorAndFlag.second) {
5367 // We looped back to a block that we've already visited. Not linear.
5368 return false;
5369 }
5370
5371 // Iterate over reachable successors.
5372 const CFGBlock *FirstReachableB = nullptr;
5373 for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
5374 if (!AB.isReachable())
5375 continue;
5376
5377 if (FirstReachableB == nullptr) {
5378 FirstReachableB = &*AB;
5379 } else {
5380 // We've encountered a branch. It's not a linear CFG.
5381 return false;
5382 }
5383 }
5384
5385 if (!FirstReachableB) {
5386 // We reached a dead end. EXIT is unreachable. This is linear enough.
5387 return true;
5388 }
5389
5390 // There's only one way to move forward. Proceed.
5391 B = FirstReachableB;
5392 }
5393
5394 // We reached EXIT and found no branches.
5395 return true;
5396}
5397
5398const CXXDestructorDecl *
5399CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
5400 switch (getKind()) {
5401 case CFGElement::Initializer:
5402 case CFGElement::NewAllocator:
5403 case CFGElement::LoopExit:
5404 case CFGElement::LifetimeEnds:
5405 case CFGElement::Statement:
5406 case CFGElement::Constructor:
5407 case CFGElement::CXXRecordTypedCall:
5408 case CFGElement::ScopeBegin:
5409 case CFGElement::ScopeEnd:
5410 case CFGElement::CleanupFunction:
5411 llvm_unreachable("getDestructorDecl should only be used with "
5412 "ImplicitDtors");
5413 case CFGElement::AutomaticObjectDtor: {
5414 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
5415 QualType ty = var->getType();
5416
5417 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
5418 //
5419 // Lifetime-extending constructs are handled here. This works for a single
5420 // temporary in an initializer expression.
5421 if (ty->isReferenceType()) {
5422 if (const Expr *Init = var->getInit()) {
5423 ty = getReferenceInitTemporaryType(Init);
5424 }
5425 }
5426
5427 while (const ArrayType *arrayType = astContext.getAsArrayType(T: ty)) {
5428 ty = arrayType->getElementType();
5429 }
5430
5431 // The situation when the type of the lifetime-extending reference
5432 // does not correspond to the type of the object is supposed
5433 // to be handled by now. In particular, 'ty' is now the unwrapped
5434 // record type.
5435 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
5436 assert(classDecl);
5437 return classDecl->getDestructor();
5438 }
5439 case CFGElement::DeleteDtor: {
5440 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
5441 QualType DTy = DE->getDestroyedType();
5442 DTy = DTy.getNonReferenceType();
5443 const CXXRecordDecl *classDecl =
5444 astContext.getBaseElementType(QT: DTy)->getAsCXXRecordDecl();
5445 return classDecl->getDestructor();
5446 }
5447 case CFGElement::TemporaryDtor: {
5448 const CXXBindTemporaryExpr *bindExpr =
5449 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
5450 const CXXTemporary *temp = bindExpr->getTemporary();
5451 return temp->getDestructor();
5452 }
5453 case CFGElement::MemberDtor: {
5454 const FieldDecl *field = castAs<CFGMemberDtor>().getFieldDecl();
5455 QualType ty = field->getType();
5456
5457 while (const ArrayType *arrayType = astContext.getAsArrayType(T: ty)) {
5458 ty = arrayType->getElementType();
5459 }
5460
5461 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
5462 assert(classDecl);
5463 return classDecl->getDestructor();
5464 }
5465 case CFGElement::BaseDtor:
5466 // Not yet supported.
5467 return nullptr;
5468 }
5469 llvm_unreachable("getKind() returned bogus value");
5470}
5471
5472//===----------------------------------------------------------------------===//
5473// CFGBlock operations.
5474//===----------------------------------------------------------------------===//
5475
5476CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
5477 : ReachableBlock(IsReachable ? B : nullptr),
5478 UnreachableBlock(!IsReachable ? B : nullptr,
5479 B && IsReachable ? AB_Normal : AB_Unreachable) {}
5480
5481CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
5482 : ReachableBlock(B),
5483 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
5484 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
5485
5486void CFGBlock::addSuccessor(AdjacentBlock Succ,
5487 BumpVectorContext &C) {
5488 if (CFGBlock *B = Succ.getReachableBlock())
5489 B->Preds.push_back(Elt: AdjacentBlock(this, Succ.isReachable()), C);
5490
5491 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
5492 UnreachableB->Preds.push_back(Elt: AdjacentBlock(this, false), C);
5493
5494 Succs.push_back(Elt: Succ, C);
5495}
5496
5497bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
5498 const CFGBlock *From, const CFGBlock *To) {
5499 if (F.IgnoreNullPredecessors && !From)
5500 return true;
5501
5502 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
5503 // If the 'To' has no label or is labeled but the label isn't a
5504 // CaseStmt then filter this edge.
5505 if (const SwitchStmt *S =
5506 dyn_cast_or_null<SwitchStmt>(Val: From->getTerminatorStmt())) {
5507 if (S->isAllEnumCasesCovered()) {
5508 const Stmt *L = To->getLabel();
5509 if (!L || !isa<CaseStmt>(Val: L))
5510 return true;
5511 }
5512 }
5513 }
5514
5515 return false;
5516}
5517
5518//===----------------------------------------------------------------------===//
5519// CFG pretty printing
5520//===----------------------------------------------------------------------===//
5521
5522namespace {
5523
5524class StmtPrinterHelper : public PrinterHelper {
5525 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
5526 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
5527
5528 StmtMapTy StmtMap;
5529 DeclMapTy DeclMap;
5530 signed currentBlock = 0;
5531 unsigned currStmt = 0;
5532 const LangOptions &LangOpts;
5533
5534public:
5535 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
5536 : LangOpts(LO) {
5537 if (!cfg)
5538 return;
5539 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
5540 unsigned j = 1;
5541 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
5542 BI != BEnd; ++BI, ++j ) {
5543 if (std::optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
5544 const Stmt *stmt= SE->getStmt();
5545 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
5546 StmtMap[stmt] = P;
5547
5548 switch (stmt->getStmtClass()) {
5549 case Stmt::DeclStmtClass:
5550 DeclMap[cast<DeclStmt>(Val: stmt)->getSingleDecl()] = P;
5551 break;
5552 case Stmt::IfStmtClass: {
5553 const VarDecl *var = cast<IfStmt>(Val: stmt)->getConditionVariable();
5554 if (var)
5555 DeclMap[var] = P;
5556 break;
5557 }
5558 case Stmt::ForStmtClass: {
5559 const VarDecl *var = cast<ForStmt>(Val: stmt)->getConditionVariable();
5560 if (var)
5561 DeclMap[var] = P;
5562 break;
5563 }
5564 case Stmt::WhileStmtClass: {
5565 const VarDecl *var =
5566 cast<WhileStmt>(Val: stmt)->getConditionVariable();
5567 if (var)
5568 DeclMap[var] = P;
5569 break;
5570 }
5571 case Stmt::SwitchStmtClass: {
5572 const VarDecl *var =
5573 cast<SwitchStmt>(Val: stmt)->getConditionVariable();
5574 if (var)
5575 DeclMap[var] = P;
5576 break;
5577 }
5578 case Stmt::CXXCatchStmtClass: {
5579 const VarDecl *var =
5580 cast<CXXCatchStmt>(Val: stmt)->getExceptionDecl();
5581 if (var)
5582 DeclMap[var] = P;
5583 break;
5584 }
5585 default:
5586 break;
5587 }
5588 }
5589 }
5590 }
5591 }
5592
5593 ~StmtPrinterHelper() override = default;
5594
5595 const LangOptions &getLangOpts() const { return LangOpts; }
5596 void setBlockID(signed i) { currentBlock = i; }
5597 void setStmtID(unsigned i) { currStmt = i; }
5598
5599 bool handledStmt(Stmt *S, raw_ostream &OS) override {
5600 StmtMapTy::iterator I = StmtMap.find(Val: S);
5601
5602 if (I == StmtMap.end())
5603 return false;
5604
5605 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5606 && I->second.second == currStmt) {
5607 return false;
5608 }
5609
5610 OS << "[B" << I->second.first << "." << I->second.second << "]";
5611 return true;
5612 }
5613
5614 bool handleDecl(const Decl *D, raw_ostream &OS) {
5615 DeclMapTy::iterator I = DeclMap.find(Val: D);
5616
5617 if (I == DeclMap.end())
5618 return false;
5619
5620 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5621 && I->second.second == currStmt) {
5622 return false;
5623 }
5624
5625 OS << "[B" << I->second.first << "." << I->second.second << "]";
5626 return true;
5627 }
5628};
5629
5630class CFGBlockTerminatorPrint
5631 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
5632 raw_ostream &OS;
5633 StmtPrinterHelper* Helper;
5634 PrintingPolicy Policy;
5635
5636public:
5637 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
5638 const PrintingPolicy &Policy)
5639 : OS(os), Helper(helper), Policy(Policy) {
5640 this->Policy.IncludeNewlines = false;
5641 }
5642
5643 void VisitIfStmt(IfStmt *I) {
5644 OS << "if ";
5645 if (Stmt *C = I->getCond())
5646 C->printPretty(OS, Helper, Policy);
5647 }
5648
5649 // Default case.
5650 void VisitStmt(Stmt *Terminator) {
5651 Terminator->printPretty(OS, Helper, Policy);
5652 }
5653
5654 void VisitDeclStmt(DeclStmt *DS) {
5655 VarDecl *VD = cast<VarDecl>(Val: DS->getSingleDecl());
5656 OS << "static init " << VD->getName();
5657 }
5658
5659 void VisitForStmt(ForStmt *F) {
5660 OS << "for (" ;
5661 if (F->getInit())
5662 OS << "...";
5663 OS << "; ";
5664 if (Stmt *C = F->getCond())
5665 C->printPretty(OS, Helper, Policy);
5666 OS << "; ";
5667 if (F->getInc())
5668 OS << "...";
5669 OS << ")";
5670 }
5671
5672 void VisitWhileStmt(WhileStmt *W) {
5673 OS << "while " ;
5674 if (Stmt *C = W->getCond())
5675 C->printPretty(OS, Helper, Policy);
5676 }
5677
5678 void VisitDoStmt(DoStmt *D) {
5679 OS << "do ... while ";
5680 if (Stmt *C = D->getCond())
5681 C->printPretty(OS, Helper, Policy);
5682 }
5683
5684 void VisitSwitchStmt(SwitchStmt *Terminator) {
5685 OS << "switch ";
5686 Terminator->getCond()->printPretty(OS, Helper, Policy);
5687 }
5688
5689 void VisitCXXTryStmt(CXXTryStmt *) { OS << "try ..."; }
5690
5691 void VisitObjCAtTryStmt(ObjCAtTryStmt *) { OS << "@try ..."; }
5692
5693 void VisitSEHTryStmt(SEHTryStmt *CS) { OS << "__try ..."; }
5694
5695 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
5696 if (Stmt *Cond = C->getCond())
5697 Cond->printPretty(OS, Helper, Policy);
5698 OS << " ? ... : ...";
5699 }
5700
5701 void VisitChooseExpr(ChooseExpr *C) {
5702 OS << "__builtin_choose_expr( ";
5703 if (Stmt *Cond = C->getCond())
5704 Cond->printPretty(OS, Helper, Policy);
5705 OS << " )";
5706 }
5707
5708 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
5709 OS << "goto *";
5710 if (Stmt *T = I->getTarget())
5711 T->printPretty(OS, Helper, Policy);
5712 }
5713
5714 void VisitBinaryOperator(BinaryOperator* B) {
5715 if (!B->isLogicalOp()) {
5716 VisitExpr(B);
5717 return;
5718 }
5719
5720 if (B->getLHS())
5721 B->getLHS()->printPretty(OS, Helper, Policy);
5722
5723 switch (B->getOpcode()) {
5724 case BO_LOr:
5725 OS << " || ...";
5726 return;
5727 case BO_LAnd:
5728 OS << " && ...";
5729 return;
5730 default:
5731 llvm_unreachable("Invalid logical operator.");
5732 }
5733 }
5734
5735 void VisitExpr(Expr *E) {
5736 E->printPretty(OS, Helper, Policy);
5737 }
5738
5739public:
5740 void print(CFGTerminator T) {
5741 switch (T.getKind()) {
5742 case CFGTerminator::StmtBranch:
5743 Visit(T.getStmt());
5744 break;
5745 case CFGTerminator::TemporaryDtorsBranch:
5746 OS << "(Temp Dtor) ";
5747 Visit(T.getStmt());
5748 break;
5749 case CFGTerminator::VirtualBaseBranch:
5750 OS << "(See if most derived ctor has already initialized vbases)";
5751 break;
5752 }
5753 }
5754};
5755
5756} // namespace
5757
5758static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
5759 const CXXCtorInitializer *I) {
5760 if (I->isBaseInitializer())
5761 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
5762 else if (I->isDelegatingInitializer())
5763 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
5764 else
5765 OS << I->getAnyMember()->getName();
5766 OS << "(";
5767 if (Expr *IE = I->getInit())
5768 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5769 OS << ")";
5770
5771 if (I->isBaseInitializer())
5772 OS << " (Base initializer)";
5773 else if (I->isDelegatingInitializer())
5774 OS << " (Delegating initializer)";
5775 else
5776 OS << " (Member initializer)";
5777}
5778
5779static void print_construction_context(raw_ostream &OS,
5780 StmtPrinterHelper &Helper,
5781 const ConstructionContext *CC) {
5782 SmallVector<const Stmt *, 3> Stmts;
5783 switch (CC->getKind()) {
5784 case ConstructionContext::SimpleConstructorInitializerKind: {
5785 OS << ", ";
5786 const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(Val: CC);
5787 print_initializer(OS, Helper, I: SICC->getCXXCtorInitializer());
5788 return;
5789 }
5790 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
5791 OS << ", ";
5792 const auto *CICC =
5793 cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(Val: CC);
5794 print_initializer(OS, Helper, I: CICC->getCXXCtorInitializer());
5795 Stmts.push_back(CICC->getCXXBindTemporaryExpr());
5796 break;
5797 }
5798 case ConstructionContext::SimpleVariableKind: {
5799 const auto *SDSCC = cast<SimpleVariableConstructionContext>(Val: CC);
5800 Stmts.push_back(Elt: SDSCC->getDeclStmt());
5801 break;
5802 }
5803 case ConstructionContext::CXX17ElidedCopyVariableKind: {
5804 const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(Val: CC);
5805 Stmts.push_back(Elt: CDSCC->getDeclStmt());
5806 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
5807 break;
5808 }
5809 case ConstructionContext::NewAllocatedObjectKind: {
5810 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(Val: CC);
5811 Stmts.push_back(NECC->getCXXNewExpr());
5812 break;
5813 }
5814 case ConstructionContext::SimpleReturnedValueKind: {
5815 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(Val: CC);
5816 Stmts.push_back(RSCC->getReturnStmt());
5817 break;
5818 }
5819 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
5820 const auto *RSCC =
5821 cast<CXX17ElidedCopyReturnedValueConstructionContext>(Val: CC);
5822 Stmts.push_back(RSCC->getReturnStmt());
5823 Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
5824 break;
5825 }
5826 case ConstructionContext::SimpleTemporaryObjectKind: {
5827 const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(Val: CC);
5828 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5829 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5830 break;
5831 }
5832 case ConstructionContext::ElidedTemporaryObjectKind: {
5833 const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(Val: CC);
5834 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5835 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5836 Stmts.push_back(TOCC->getConstructorAfterElision());
5837 break;
5838 }
5839 case ConstructionContext::LambdaCaptureKind: {
5840 const auto *LCC = cast<LambdaCaptureConstructionContext>(Val: CC);
5841 Helper.handledStmt(const_cast<LambdaExpr *>(LCC->getLambdaExpr()), OS);
5842 OS << "+" << LCC->getIndex();
5843 return;
5844 }
5845 case ConstructionContext::ArgumentKind: {
5846 const auto *ACC = cast<ArgumentConstructionContext>(Val: CC);
5847 if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
5848 OS << ", ";
5849 Helper.handledStmt(S: const_cast<Stmt *>(BTE), OS);
5850 }
5851 OS << ", ";
5852 Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
5853 OS << "+" << ACC->getIndex();
5854 return;
5855 }
5856 }
5857 for (auto I: Stmts)
5858 if (I) {
5859 OS << ", ";
5860 Helper.handledStmt(S: const_cast<Stmt *>(I), OS);
5861 }
5862}
5863
5864static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5865 const CFGElement &E, bool TerminateWithNewLine = true);
5866
5867void CFGElement::dumpToStream(llvm::raw_ostream &OS,
5868 bool TerminateWithNewLine) const {
5869 LangOptions LangOpts;
5870 StmtPrinterHelper Helper(nullptr, LangOpts);
5871 print_elem(OS, Helper, E: *this, TerminateWithNewLine);
5872}
5873
5874static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5875 const CFGElement &E, bool TerminateWithNewLine) {
5876 switch (E.getKind()) {
5877 case CFGElement::Kind::Statement:
5878 case CFGElement::Kind::CXXRecordTypedCall:
5879 case CFGElement::Kind::Constructor: {
5880 CFGStmt CS = E.castAs<CFGStmt>();
5881 const Stmt *S = CS.getStmt();
5882 assert(S != nullptr && "Expecting non-null Stmt");
5883
5884 // special printing for statement-expressions.
5885 if (const StmtExpr *SE = dyn_cast<StmtExpr>(Val: S)) {
5886 const CompoundStmt *Sub = SE->getSubStmt();
5887
5888 auto Children = Sub->children();
5889 if (Children.begin() != Children.end()) {
5890 OS << "({ ... ; ";
5891 Helper.handledStmt(S: *SE->getSubStmt()->body_rbegin(),OS);
5892 OS << " })";
5893 if (TerminateWithNewLine)
5894 OS << '\n';
5895 return;
5896 }
5897 }
5898 // special printing for comma expressions.
5899 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(Val: S)) {
5900 if (B->getOpcode() == BO_Comma) {
5901 OS << "... , ";
5902 Helper.handledStmt(B->getRHS(),OS);
5903 if (TerminateWithNewLine)
5904 OS << '\n';
5905 return;
5906 }
5907 }
5908 S->printPretty(OS, Helper: &Helper, Policy: PrintingPolicy(Helper.getLangOpts()));
5909
5910 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
5911 if (isa<CXXOperatorCallExpr>(Val: S))
5912 OS << " (OperatorCall)";
5913 OS << " (CXXRecordTypedCall";
5914 print_construction_context(OS, Helper, CC: VTC->getConstructionContext());
5915 OS << ")";
5916 } else if (isa<CXXOperatorCallExpr>(Val: S)) {
5917 OS << " (OperatorCall)";
5918 } else if (isa<CXXBindTemporaryExpr>(Val: S)) {
5919 OS << " (BindTemporary)";
5920 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Val: S)) {
5921 OS << " (CXXConstructExpr";
5922 if (std::optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
5923 print_construction_context(OS, Helper, CC: CE->getConstructionContext());
5924 }
5925 OS << ", " << CCE->getType() << ")";
5926 } else if (const CastExpr *CE = dyn_cast<CastExpr>(Val: S)) {
5927 OS << " (" << CE->getStmtClassName() << ", " << CE->getCastKindName()
5928 << ", " << CE->getType() << ")";
5929 }
5930
5931 // Expressions need a newline.
5932 if (isa<Expr>(Val: S) && TerminateWithNewLine)
5933 OS << '\n';
5934
5935 return;
5936 }
5937
5938 case CFGElement::Kind::Initializer:
5939 print_initializer(OS, Helper, I: E.castAs<CFGInitializer>().getInitializer());
5940 break;
5941
5942 case CFGElement::Kind::AutomaticObjectDtor: {
5943 CFGAutomaticObjDtor DE = E.castAs<CFGAutomaticObjDtor>();
5944 const VarDecl *VD = DE.getVarDecl();
5945 Helper.handleDecl(VD, OS);
5946
5947 QualType T = VD->getType();
5948 if (T->isReferenceType())
5949 T = getReferenceInitTemporaryType(Init: VD->getInit(), FoundMTE: nullptr);
5950
5951 OS << ".~";
5952 T.getUnqualifiedType().print(OS, Policy: PrintingPolicy(Helper.getLangOpts()));
5953 OS << "() (Implicit destructor)";
5954 break;
5955 }
5956
5957 case CFGElement::Kind::CleanupFunction:
5958 OS << "CleanupFunction ("
5959 << E.castAs<CFGCleanupFunction>().getFunctionDecl()->getName() << ")";
5960 break;
5961
5962 case CFGElement::Kind::LifetimeEnds:
5963 Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS);
5964 OS << " (Lifetime ends)";
5965 break;
5966
5967 case CFGElement::Kind::LoopExit:
5968 OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName()
5969 << " (LoopExit)";
5970 break;
5971
5972 case CFGElement::Kind::ScopeBegin:
5973 OS << "CFGScopeBegin(";
5974 if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl())
5975 OS << VD->getQualifiedNameAsString();
5976 OS << ")";
5977 break;
5978
5979 case CFGElement::Kind::ScopeEnd:
5980 OS << "CFGScopeEnd(";
5981 if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl())
5982 OS << VD->getQualifiedNameAsString();
5983 OS << ")";
5984 break;
5985
5986 case CFGElement::Kind::NewAllocator:
5987 OS << "CFGNewAllocator(";
5988 if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr())
5989 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5990 OS << ")";
5991 break;
5992
5993 case CFGElement::Kind::DeleteDtor: {
5994 CFGDeleteDtor DE = E.castAs<CFGDeleteDtor>();
5995 const CXXRecordDecl *RD = DE.getCXXRecordDecl();
5996 if (!RD)
5997 return;
5998 CXXDeleteExpr *DelExpr =
5999 const_cast<CXXDeleteExpr*>(DE.getDeleteExpr());
6000 Helper.handledStmt(S: cast<Stmt>(Val: DelExpr->getArgument()), OS);
6001 OS << "->~" << RD->getName().str() << "()";
6002 OS << " (Implicit destructor)";
6003 break;
6004 }
6005
6006 case CFGElement::Kind::BaseDtor: {
6007 const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier();
6008 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
6009 OS << " (Base object destructor)";
6010 break;
6011 }
6012
6013 case CFGElement::Kind::MemberDtor: {
6014 const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl();
6015 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
6016 OS << "this->" << FD->getName();
6017 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
6018 OS << " (Member object destructor)";
6019 break;
6020 }
6021
6022 case CFGElement::Kind::TemporaryDtor: {
6023 const CXXBindTemporaryExpr *BT =
6024 E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
6025 OS << "~";
6026 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
6027 OS << "() (Temporary object destructor)";
6028 break;
6029 }
6030 }
6031 if (TerminateWithNewLine)
6032 OS << '\n';
6033}
6034
6035static void print_block(raw_ostream &OS, const CFG* cfg,
6036 const CFGBlock &B,
6037 StmtPrinterHelper &Helper, bool print_edges,
6038 bool ShowColors) {
6039 Helper.setBlockID(B.getBlockID());
6040
6041 // Print the header.
6042 if (ShowColors)
6043 OS.changeColor(Color: raw_ostream::YELLOW, Bold: true);
6044
6045 OS << "\n [B" << B.getBlockID();
6046
6047 if (&B == &cfg->getEntry())
6048 OS << " (ENTRY)]\n";
6049 else if (&B == &cfg->getExit())
6050 OS << " (EXIT)]\n";
6051 else if (&B == cfg->getIndirectGotoBlock())
6052 OS << " (INDIRECT GOTO DISPATCH)]\n";
6053 else if (B.hasNoReturnElement())
6054 OS << " (NORETURN)]\n";
6055 else
6056 OS << "]\n";
6057
6058 if (ShowColors)
6059 OS.resetColor();
6060
6061 // Print the label of this block.
6062 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
6063 if (print_edges)
6064 OS << " ";
6065
6066 if (LabelStmt *L = dyn_cast<LabelStmt>(Val: Label))
6067 OS << L->getName();
6068 else if (CaseStmt *C = dyn_cast<CaseStmt>(Val: Label)) {
6069 OS << "case ";
6070 if (const Expr *LHS = C->getLHS())
6071 LHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
6072 if (const Expr *RHS = C->getRHS()) {
6073 OS << " ... ";
6074 RHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
6075 }
6076 } else if (isa<DefaultStmt>(Val: Label))
6077 OS << "default";
6078 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Val: Label)) {
6079 OS << "catch (";
6080 if (const VarDecl *ED = CS->getExceptionDecl())
6081 ED->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
6082 else
6083 OS << "...";
6084 OS << ")";
6085 } else if (ObjCAtCatchStmt *CS = dyn_cast<ObjCAtCatchStmt>(Val: Label)) {
6086 OS << "@catch (";
6087 if (const VarDecl *PD = CS->getCatchParamDecl())
6088 PD->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
6089 else
6090 OS << "...";
6091 OS << ")";
6092 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Val: Label)) {
6093 OS << "__except (";
6094 ES->getFilterExpr()->printPretty(OS, &Helper,
6095 PrintingPolicy(Helper.getLangOpts()), 0);
6096 OS << ")";
6097 } else
6098 llvm_unreachable("Invalid label statement in CFGBlock.");
6099
6100 OS << ":\n";
6101 }
6102
6103 // Iterate through the statements in the block and print them.
6104 unsigned j = 1;
6105
6106 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
6107 I != E ; ++I, ++j ) {
6108 // Print the statement # in the basic block and the statement itself.
6109 if (print_edges)
6110 OS << " ";
6111
6112 OS << llvm::format(Fmt: "%3d", Vals: j) << ": ";
6113
6114 Helper.setStmtID(j);
6115
6116 print_elem(OS, Helper, E: *I);
6117 }
6118
6119 // Print the terminator of this block.
6120 if (B.getTerminator().isValid()) {
6121 if (ShowColors)
6122 OS.changeColor(Color: raw_ostream::GREEN);
6123
6124 OS << " T: ";
6125
6126 Helper.setBlockID(-1);
6127
6128 PrintingPolicy PP(Helper.getLangOpts());
6129 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
6130 TPrinter.print(T: B.getTerminator());
6131 OS << '\n';
6132
6133 if (ShowColors)
6134 OS.resetColor();
6135 }
6136
6137 if (print_edges) {
6138 // Print the predecessors of this block.
6139 if (!B.pred_empty()) {
6140 const raw_ostream::Colors Color = raw_ostream::BLUE;
6141 if (ShowColors)
6142 OS.changeColor(Color);
6143 OS << " Preds " ;
6144 if (ShowColors)
6145 OS.resetColor();
6146 OS << '(' << B.pred_size() << "):";
6147 unsigned i = 0;
6148
6149 if (ShowColors)
6150 OS.changeColor(Color);
6151
6152 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
6153 I != E; ++I, ++i) {
6154 if (i % 10 == 8)
6155 OS << "\n ";
6156
6157 CFGBlock *B = *I;
6158 bool Reachable = true;
6159 if (!B) {
6160 Reachable = false;
6161 B = I->getPossiblyUnreachableBlock();
6162 }
6163
6164 OS << " B" << B->getBlockID();
6165 if (!Reachable)
6166 OS << "(Unreachable)";
6167 }
6168
6169 if (ShowColors)
6170 OS.resetColor();
6171
6172 OS << '\n';
6173 }
6174
6175 // Print the successors of this block.
6176 if (!B.succ_empty()) {
6177 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
6178 if (ShowColors)
6179 OS.changeColor(Color);
6180 OS << " Succs ";
6181 if (ShowColors)
6182 OS.resetColor();
6183 OS << '(' << B.succ_size() << "):";
6184 unsigned i = 0;
6185
6186 if (ShowColors)
6187 OS.changeColor(Color);
6188
6189 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
6190 I != E; ++I, ++i) {
6191 if (i % 10 == 8)
6192 OS << "\n ";
6193
6194 CFGBlock *B = *I;
6195
6196 bool Reachable = true;
6197 if (!B) {
6198 Reachable = false;
6199 B = I->getPossiblyUnreachableBlock();
6200 }
6201
6202 if (B) {
6203 OS << " B" << B->getBlockID();
6204 if (!Reachable)
6205 OS << "(Unreachable)";
6206 }
6207 else {
6208 OS << " NULL";
6209 }
6210 }
6211
6212 if (ShowColors)
6213 OS.resetColor();
6214 OS << '\n';
6215 }
6216 }
6217}
6218
6219/// dump - A simple pretty printer of a CFG that outputs to stderr.
6220void CFG::dump(const LangOptions &LO, bool ShowColors) const {
6221 print(OS&: llvm::errs(), LO, ShowColors);
6222}
6223
6224/// print - A simple pretty printer of a CFG that outputs to an ostream.
6225void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
6226 StmtPrinterHelper Helper(this, LO);
6227
6228 // Print the entry block.
6229 print_block(OS, cfg: this, B: getEntry(), Helper, print_edges: true, ShowColors);
6230
6231 // Iterate through the CFGBlocks and print them one by one.
6232 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
6233 // Skip the entry block, because we already printed it.
6234 if (&(**I) == &getEntry() || &(**I) == &getExit())
6235 continue;
6236
6237 print_block(OS, cfg: this, B: **I, Helper, print_edges: true, ShowColors);
6238 }
6239
6240 // Print the exit block.
6241 print_block(OS, cfg: this, B: getExit(), Helper, print_edges: true, ShowColors);
6242 OS << '\n';
6243 OS.flush();
6244}
6245
6246size_t CFGBlock::getIndexInCFG() const {
6247 return llvm::find(Range&: *getParent(), Val: this) - getParent()->begin();
6248}
6249
6250/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
6251void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
6252 bool ShowColors) const {
6253 print(OS&: llvm::errs(), cfg, LO, ShowColors);
6254}
6255
6256LLVM_DUMP_METHOD void CFGBlock::dump() const {
6257 dump(cfg: getParent(), LO: LangOptions(), ShowColors: false);
6258}
6259
6260/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
6261/// Generally this will only be called from CFG::print.
6262void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
6263 const LangOptions &LO, bool ShowColors) const {
6264 StmtPrinterHelper Helper(cfg, LO);
6265 print_block(OS, cfg, B: *this, Helper, print_edges: true, ShowColors);
6266 OS << '\n';
6267}
6268
6269/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
6270void CFGBlock::printTerminator(raw_ostream &OS,
6271 const LangOptions &LO) const {
6272 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
6273 TPrinter.print(T: getTerminator());
6274}
6275
6276/// printTerminatorJson - Pretty-prints the terminator in JSON format.
6277void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
6278 bool AddQuotes) const {
6279 std::string Buf;
6280 llvm::raw_string_ostream TempOut(Buf);
6281
6282 printTerminator(OS&: TempOut, LO);
6283
6284 Out << JsonFormat(RawSR: Buf, AddQuotes);
6285}
6286
6287// Returns true if by simply looking at the block, we can be sure that it
6288// results in a sink during analysis. This is useful to know when the analysis
6289// was interrupted, and we try to figure out if it would sink eventually.
6290// There may be many more reasons why a sink would appear during analysis
6291// (eg. checkers may generate sinks arbitrarily), but here we only consider
6292// sinks that would be obvious by looking at the CFG.
6293static bool isImmediateSinkBlock(const CFGBlock *Blk) {
6294 if (Blk->hasNoReturnElement())
6295 return true;
6296
6297 // FIXME: Throw-expressions are currently generating sinks during analysis:
6298 // they're not supported yet, and also often used for actually terminating
6299 // the program. So we should treat them as sinks in this analysis as well,
6300 // at least for now, but once we have better support for exceptions,
6301 // we'd need to carefully handle the case when the throw is being
6302 // immediately caught.
6303 if (llvm::any_of(Range: *Blk, P: [](const CFGElement &Elm) {
6304 if (std::optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
6305 if (isa<CXXThrowExpr>(Val: StmtElm->getStmt()))
6306 return true;
6307 return false;
6308 }))
6309 return true;
6310
6311 return false;
6312}
6313
6314bool CFGBlock::isInevitablySinking() const {
6315 const CFG &Cfg = *getParent();
6316
6317 const CFGBlock *StartBlk = this;
6318 if (isImmediateSinkBlock(Blk: StartBlk))
6319 return true;
6320
6321 llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
6322 llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
6323
6324 DFSWorkList.push_back(Elt: StartBlk);
6325 while (!DFSWorkList.empty()) {
6326 const CFGBlock *Blk = DFSWorkList.pop_back_val();
6327 Visited.insert(Ptr: Blk);
6328
6329 // If at least one path reaches the CFG exit, it means that control is
6330 // returned to the caller. For now, say that we are not sure what
6331 // happens next. If necessary, this can be improved to analyze
6332 // the parent StackFrameContext's call site in a similar manner.
6333 if (Blk == &Cfg.getExit())
6334 return false;
6335
6336 for (const auto &Succ : Blk->succs()) {
6337 if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
6338 if (!isImmediateSinkBlock(Blk: SuccBlk) && !Visited.count(Ptr: SuccBlk)) {
6339 // If the block has reachable child blocks that aren't no-return,
6340 // add them to the worklist.
6341 DFSWorkList.push_back(Elt: SuccBlk);
6342 }
6343 }
6344 }
6345 }
6346
6347 // Nothing reached the exit. It can only mean one thing: there's no return.
6348 return true;
6349}
6350
6351const Expr *CFGBlock::getLastCondition() const {
6352 // If the terminator is a temporary dtor or a virtual base, etc, we can't
6353 // retrieve a meaningful condition, bail out.
6354 if (Terminator.getKind() != CFGTerminator::StmtBranch)
6355 return nullptr;
6356
6357 // Also, if this method was called on a block that doesn't have 2 successors,
6358 // this block doesn't have retrievable condition.
6359 if (succ_size() < 2)
6360 return nullptr;
6361
6362 // FIXME: Is there a better condition expression we can return in this case?
6363 if (size() == 0)
6364 return nullptr;
6365
6366 auto StmtElem = rbegin()->getAs<CFGStmt>();
6367 if (!StmtElem)
6368 return nullptr;
6369
6370 const Stmt *Cond = StmtElem->getStmt();
6371 if (isa<ObjCForCollectionStmt>(Val: Cond) || isa<DeclStmt>(Val: Cond))
6372 return nullptr;
6373
6374 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
6375 // the cast<>.
6376 return cast<Expr>(Val: Cond)->IgnoreParens();
6377}
6378
6379Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
6380 Stmt *Terminator = getTerminatorStmt();
6381 if (!Terminator)
6382 return nullptr;
6383
6384 Expr *E = nullptr;
6385
6386 switch (Terminator->getStmtClass()) {
6387 default:
6388 break;
6389
6390 case Stmt::CXXForRangeStmtClass:
6391 E = cast<CXXForRangeStmt>(Val: Terminator)->getCond();
6392 break;
6393
6394 case Stmt::ForStmtClass:
6395 E = cast<ForStmt>(Val: Terminator)->getCond();
6396 break;
6397
6398 case Stmt::WhileStmtClass:
6399 E = cast<WhileStmt>(Val: Terminator)->getCond();
6400 break;
6401
6402 case Stmt::DoStmtClass:
6403 E = cast<DoStmt>(Val: Terminator)->getCond();
6404 break;
6405
6406 case Stmt::IfStmtClass:
6407 E = cast<IfStmt>(Val: Terminator)->getCond();
6408 break;
6409
6410 case Stmt::ChooseExprClass:
6411 E = cast<ChooseExpr>(Val: Terminator)->getCond();
6412 break;
6413
6414 case Stmt::IndirectGotoStmtClass:
6415 E = cast<IndirectGotoStmt>(Val: Terminator)->getTarget();
6416 break;
6417
6418 case Stmt::SwitchStmtClass:
6419 E = cast<SwitchStmt>(Val: Terminator)->getCond();
6420 break;
6421
6422 case Stmt::BinaryConditionalOperatorClass:
6423 E = cast<BinaryConditionalOperator>(Val: Terminator)->getCond();
6424 break;
6425
6426 case Stmt::ConditionalOperatorClass:
6427 E = cast<ConditionalOperator>(Val: Terminator)->getCond();
6428 break;
6429
6430 case Stmt::BinaryOperatorClass: // '&&' and '||'
6431 E = cast<BinaryOperator>(Val: Terminator)->getLHS();
6432 break;
6433
6434 case Stmt::ObjCForCollectionStmtClass:
6435 return Terminator;
6436 }
6437
6438 if (!StripParens)
6439 return E;
6440
6441 return E ? E->IgnoreParens() : nullptr;
6442}
6443
6444//===----------------------------------------------------------------------===//
6445// CFG Graphviz Visualization
6446//===----------------------------------------------------------------------===//
6447
6448static StmtPrinterHelper *GraphHelper;
6449
6450void CFG::viewCFG(const LangOptions &LO) const {
6451 StmtPrinterHelper H(this, LO);
6452 GraphHelper = &H;
6453 llvm::ViewGraph(G: this,Name: "CFG");
6454 GraphHelper = nullptr;
6455}
6456
6457namespace llvm {
6458
6459template<>
6460struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
6461 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
6462
6463 static std::string getNodeLabel(const CFGBlock *Node, const CFG *Graph) {
6464 std::string OutStr;
6465 llvm::raw_string_ostream Out(OutStr);
6466 print_block(OS&: Out,cfg: Graph, B: *Node, Helper&: *GraphHelper, print_edges: false, ShowColors: false);
6467
6468 if (OutStr[0] == '\n') OutStr.erase(position: OutStr.begin());
6469
6470 // Process string output to make it nicer...
6471 for (unsigned i = 0; i != OutStr.length(); ++i)
6472 if (OutStr[i] == '\n') { // Left justify
6473 OutStr[i] = '\\';
6474 OutStr.insert(p: OutStr.begin()+i+1, c: 'l');
6475 }
6476
6477 return OutStr;
6478 }
6479};
6480
6481} // namespace llvm
6482

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

source code of clang/lib/Analysis/CFG.cpp