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