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