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