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