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