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