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