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