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 (CFGBlock *R = Visit(CRS->getPromiseCall()))
3436 B = R;
3437
3438 if (Expr *RV = CRS->getOperand())
3439 if (RV->getType()->isVoidType() && !isa<InitListExpr>(RV))
3440 // A non-initlist void expression.
3441 if (CFGBlock *R = Visit(RV))
3442 B = R;
3443
3444 return B;
3445}
3446
3447CFGBlock *CFGBuilder::VisitCoroutineSuspendExpr(CoroutineSuspendExpr *E,
3448 AddStmtChoice asc) {
3449 // We're modelling the pre-coro-xform CFG. Thus just evalate the various
3450 // active components of the co_await or co_yield. Note we do not model the
3451 // edge from the builtin_suspend to the exit node.
3452 if (asc.alwaysAdd(*this, E)) {
3453 autoCreateBlock();
3454 appendStmt(Block, E);
3455 }
3456 CFGBlock *B = Block;
3457 if (auto *R = Visit(E->getResumeExpr()))
3458 B = R;
3459 if (auto *R = Visit(E->getSuspendExpr()))
3460 B = R;
3461 if (auto *R = Visit(E->getReadyExpr()))
3462 B = R;
3463 if (auto *R = Visit(E->getCommonExpr()))
3464 B = R;
3465 return B;
3466}
3467
3468CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
3469 // SEHExceptStmt are treated like labels, so they are the first statement in a
3470 // block.
3471
3472 // Save local scope position because in case of exception variable ScopePos
3473 // won't be restored when traversing AST.
3474 SaveAndRestore save_scope_pos(ScopePos);
3475
3476 addStmt(ES->getBlock());
3477 CFGBlock *SEHExceptBlock = Block;
3478 if (!SEHExceptBlock)
3479 SEHExceptBlock = createBlock();
3480
3481 appendStmt(SEHExceptBlock, ES);
3482
3483 // Also add the SEHExceptBlock as a label, like with regular labels.
3484 SEHExceptBlock->setLabel(ES);
3485
3486 // Bail out if the CFG is bad.
3487 if (badCFG)
3488 return nullptr;
3489
3490 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3491 Block = nullptr;
3492
3493 return SEHExceptBlock;
3494}
3495
3496CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
3497 return VisitCompoundStmt(FS->getBlock(), /*ExternallyDestructed=*/false);
3498}
3499
3500CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
3501 // "__leave" is a control-flow statement. Thus we stop processing the current
3502 // block.
3503 if (badCFG)
3504 return nullptr;
3505
3506 // Now create a new block that ends with the __leave statement.
3507 Block = createBlock(false);
3508 Block->setTerminator(LS);
3509
3510 // If there is no target for the __leave, then we are looking at an incomplete
3511 // AST. This means that the CFG cannot be constructed.
3512 if (SEHLeaveJumpTarget.block) {
3513 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
3514 addSuccessor(Block, SEHLeaveJumpTarget.block);
3515 } else
3516 badCFG = true;
3517
3518 return Block;
3519}
3520
3521CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
3522 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
3523 // processing the current block.
3524 CFGBlock *SEHTrySuccessor = nullptr;
3525
3526 if (Block) {
3527 if (badCFG)
3528 return nullptr;
3529 SEHTrySuccessor = Block;
3530 } else SEHTrySuccessor = Succ;
3531
3532 // FIXME: Implement __finally support.
3533 if (Terminator->getFinallyHandler())
3534 return NYS();
3535
3536 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
3537
3538 // Create a new block that will contain the __try statement.
3539 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3540
3541 // Add the terminator in the __try block.
3542 NewTryTerminatedBlock->setTerminator(Terminator);
3543
3544 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
3545 // The code after the try is the implicit successor if there's an __except.
3546 Succ = SEHTrySuccessor;
3547 Block = nullptr;
3548 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
3549 if (!ExceptBlock)
3550 return nullptr;
3551 // Add this block to the list of successors for the block with the try
3552 // statement.
3553 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
3554 }
3555 if (PrevSEHTryTerminatedBlock)
3556 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
3557 else
3558 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3559
3560 // The code after the try is the implicit successor.
3561 Succ = SEHTrySuccessor;
3562
3563 // Save the current "__try" context.
3564 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
3565 cfg->addTryDispatchBlock(TryTerminatedBlock);
3566
3567 // Save the current value for the __leave target.
3568 // All __leaves should go to the code following the __try
3569 // (FIXME: or if the __try has a __finally, to the __finally.)
3570 SaveAndRestore save_break(SEHLeaveJumpTarget);
3571 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
3572
3573 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
3574 Block = nullptr;
3575 return addStmt(Terminator->getTryBlock());
3576}
3577
3578CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
3579 // Get the block of the labeled statement. Add it to our map.
3580 addStmt(L->getSubStmt());
3581 CFGBlock *LabelBlock = Block;
3582
3583 if (!LabelBlock) // This can happen when the body is empty, i.e.
3584 LabelBlock = createBlock(); // scopes that only contains NullStmts.
3585
3586 assert(!LabelMap.contains(L->getDecl()) && "label already in map");
3587 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
3588
3589 // Labels partition blocks, so this is the end of the basic block we were
3590 // processing (L is the block's label). Because this is label (and we have
3591 // already processed the substatement) there is no extra control-flow to worry
3592 // about.
3593 LabelBlock->setLabel(L);
3594 if (badCFG)
3595 return nullptr;
3596
3597 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3598 Block = nullptr;
3599
3600 // This block is now the implicit successor of other blocks.
3601 Succ = LabelBlock;
3602
3603 return LabelBlock;
3604}
3605
3606CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
3607 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3608 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
3609 if (Expr *CopyExpr = CI.getCopyExpr()) {
3610 CFGBlock *Tmp = Visit(CopyExpr);
3611 if (Tmp)
3612 LastBlock = Tmp;
3613 }
3614 }
3615 return LastBlock;
3616}
3617
3618CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
3619 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3620
3621 // Visit the capture initializers in reverse order so they appear in
3622 // left-to-right (natural) order in the CFG.
3623 unsigned Idx = E->capture_size();
3624 for (Expr *Init : reverse(E->capture_inits())) {
3625 --Idx;
3626 if (Init) {
3627 // If the initializer is an ArrayInitLoopExpr, we want to extract the
3628 // initializer, that's used for each element.
3630 dyn_cast<ArrayInitLoopExpr>(Init));
3631
3632 findConstructionContexts(ConstructionContextLayer::create(
3633 cfg->getBumpVectorContext(), {E, Idx}),
3634 AILEInit ? AILEInit : Init);
3635
3636 CFGBlock *Tmp = Visit(Init);
3637 if (Tmp)
3638 LastBlock = Tmp;
3639 }
3640 }
3641 return LastBlock;
3642}
3643
3644CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
3645 // Goto is a control-flow statement. Thus we stop processing the current
3646 // block and create a new one.
3647
3648 Block = createBlock(false);
3649 Block->setTerminator(G);
3650
3651 // If we already know the mapping to the label block add the successor now.
3652 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
3653
3654 if (I == LabelMap.end())
3655 // We will need to backpatch this block later.
3656 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3657 else {
3658 JumpTarget JT = I->second;
3659 addSuccessor(Block, JT.block);
3660 addScopeChangesHandling(ScopePos, JT.scopePosition, G);
3661 }
3662
3663 return Block;
3664}
3665
3666CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
3667 // Goto is a control-flow statement. Thus we stop processing the current
3668 // block and create a new one.
3669
3670 if (!G->isAsmGoto())
3671 return VisitStmt(G, asc);
3672
3673 if (Block) {
3674 Succ = Block;
3675 if (badCFG)
3676 return nullptr;
3677 }
3678 Block = createBlock();
3679 Block->setTerminator(G);
3680 // We will backpatch this block later for all the labels.
3681 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3682 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
3683 // used to avoid adding "Succ" again.
3684 BackpatchBlocks.push_back(JumpSource(Succ, ScopePos));
3685 return VisitChildren(G);
3686}
3687
3688CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
3689 CFGBlock *LoopSuccessor = nullptr;
3690
3691 // Save local scope position because in case of condition variable ScopePos
3692 // won't be restored when traversing AST.
3693 SaveAndRestore save_scope_pos(ScopePos);
3694
3695 // Create local scope for init statement and possible condition variable.
3696 // Add destructor for init statement and condition variable.
3697 // Store scope position for continue statement.
3698 if (Stmt *Init = F->getInit())
3699 addLocalScopeForStmt(Init);
3700 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3701
3702 if (VarDecl *VD = F->getConditionVariable())
3703 addLocalScopeForVarDecl(VD);
3704 LocalScope::const_iterator ContinueScopePos = ScopePos;
3705
3706 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
3707
3708 addLoopExit(F);
3709
3710 // "for" is a control-flow statement. Thus we stop processing the current
3711 // block.
3712 if (Block) {
3713 if (badCFG)
3714 return nullptr;
3715 LoopSuccessor = Block;
3716 } else
3717 LoopSuccessor = Succ;
3718
3719 // Save the current value for the break targets.
3720 // All breaks should go to the code following the loop.
3721 SaveAndRestore save_break(BreakJumpTarget);
3722 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3723
3724 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3725
3726 // Now create the loop body.
3727 {
3728 assert(F->getBody());
3729
3730 // Save the current values for Block, Succ, continue and break targets.
3731 SaveAndRestore save_Block(Block), save_Succ(Succ);
3732 SaveAndRestore save_continue(ContinueJumpTarget);
3733
3734 // Create an empty block to represent the transition block for looping back
3735 // to the head of the loop. If we have increment code, it will
3736 // go in this block as well.
3737 Block = Succ = TransitionBlock = createBlock(false);
3738 TransitionBlock->setLoopTarget(F);
3739
3740
3741 // Loop iteration (after increment) should end with destructor of Condition
3742 // variable (if any).
3743 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
3744
3745 if (Stmt *I = F->getInc()) {
3746 // Generate increment code in its own basic block. This is the target of
3747 // continue statements.
3748 Succ = addStmt(I);
3749 }
3750
3751 // Finish up the increment (or empty) block if it hasn't been already.
3752 if (Block) {
3753 assert(Block == Succ);
3754 if (badCFG)
3755 return nullptr;
3756 Block = nullptr;
3757 }
3758
3759 // The starting block for the loop increment is the block that should
3760 // represent the 'loop target' for looping back to the start of the loop.
3761 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3762 ContinueJumpTarget.block->setLoopTarget(F);
3763
3764
3765 // If body is not a compound statement create implicit scope
3766 // and add destructors.
3767 if (!isa<CompoundStmt>(F->getBody()))
3768 addLocalScopeAndDtors(F->getBody());
3769
3770 // Now populate the body block, and in the process create new blocks as we
3771 // walk the body of the loop.
3772 BodyBlock = addStmt(F->getBody());
3773
3774 if (!BodyBlock) {
3775 // In the case of "for (...;...;...);" we can have a null BodyBlock.
3776 // Use the continue jump target as the proxy for the body.
3777 BodyBlock = ContinueJumpTarget.block;
3778 }
3779 else if (badCFG)
3780 return nullptr;
3781 }
3782
3783 // Because of short-circuit evaluation, the condition of the loop can span
3784 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3785 // evaluate the condition.
3786 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3787
3788 do {
3789 Expr *C = F->getCond();
3790 SaveAndRestore save_scope_pos(ScopePos);
3791
3792 // Specially handle logical operators, which have a slightly
3793 // more optimal CFG representation.
3794 if (BinaryOperator *Cond =
3795 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
3796 if (Cond->isLogicalOp()) {
3797 std::tie(EntryConditionBlock, ExitConditionBlock) =
3798 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
3799 break;
3800 }
3801
3802 // The default case when not handling logical operators.
3803 EntryConditionBlock = ExitConditionBlock = createBlock(false);
3804 ExitConditionBlock->setTerminator(F);
3805
3806 // See if this is a known constant.
3807 TryResult KnownVal(true);
3808
3809 if (C) {
3810 // Now add the actual condition to the condition block.
3811 // Because the condition itself may contain control-flow, new blocks may
3812 // be created. Thus we update "Succ" after adding the condition.
3813 Block = ExitConditionBlock;
3814 EntryConditionBlock = addStmt(C);
3815
3816 // If this block contains a condition variable, add both the condition
3817 // variable and initializer to the CFG.
3818 if (VarDecl *VD = F->getConditionVariable()) {
3819 if (Expr *Init = VD->getInit()) {
3820 autoCreateBlock();
3821 const DeclStmt *DS = F->getConditionVariableDeclStmt();
3822 assert(DS->isSingleDecl());
3823 findConstructionContexts(
3824 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
3825 Init);
3826 appendStmt(Block, DS);
3827 EntryConditionBlock = addStmt(Init);
3828 assert(Block == EntryConditionBlock);
3829 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
3830 }
3831 }
3832
3833 if (Block && badCFG)
3834 return nullptr;
3835
3836 KnownVal = tryEvaluateBool(C);
3837 }
3838
3839 // Add the loop body entry as a successor to the condition.
3840 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
3841 // Link up the condition block with the code that follows the loop. (the
3842 // false branch).
3843 addSuccessor(ExitConditionBlock,
3844 KnownVal.isTrue() ? nullptr : LoopSuccessor);
3845 } while (false);
3846
3847 // Link up the loop-back block to the entry condition block.
3848 addSuccessor(TransitionBlock, EntryConditionBlock);
3849
3850 // The condition block is the implicit successor for any code above the loop.
3851 Succ = EntryConditionBlock;
3852
3853 // If the loop contains initialization, create a new block for those
3854 // statements. This block can also contain statements that precede the loop.
3855 if (Stmt *I = F->getInit()) {
3856 SaveAndRestore save_scope_pos(ScopePos);
3857 ScopePos = LoopBeginScopePos;
3858 Block = createBlock();
3859 return addStmt(I);
3860 }
3861
3862 // There is no loop initialization. We are thus basically a while loop.
3863 // NULL out Block to force lazy block construction.
3864 Block = nullptr;
3865 Succ = EntryConditionBlock;
3866 return EntryConditionBlock;
3867}
3868
3869CFGBlock *
3870CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
3871 AddStmtChoice asc) {
3872 findConstructionContexts(
3873 ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
3874 MTE->getSubExpr());
3875
3876 return VisitStmt(MTE, asc);
3877}
3878
3879CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
3880 if (asc.alwaysAdd(*this, M)) {
3881 autoCreateBlock();
3882 appendStmt(Block, M);
3883 }
3884 return Visit(M->getBase());
3885}
3886
3887CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
3888 // Objective-C fast enumeration 'for' statements:
3889 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3890 //
3891 // for ( Type newVariable in collection_expression ) { statements }
3892 //
3893 // becomes:
3894 //
3895 // prologue:
3896 // 1. collection_expression
3897 // T. jump to loop_entry
3898 // loop_entry:
3899 // 1. side-effects of element expression
3900 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3901 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3902 // TB:
3903 // statements
3904 // T. jump to loop_entry
3905 // FB:
3906 // what comes after
3907 //
3908 // and
3909 //
3910 // Type existingItem;
3911 // for ( existingItem in expression ) { statements }
3912 //
3913 // becomes:
3914 //
3915 // the same with newVariable replaced with existingItem; the binding works
3916 // the same except that for one ObjCForCollectionStmt::getElement() returns
3917 // a DeclStmt and the other returns a DeclRefExpr.
3918
3919 CFGBlock *LoopSuccessor = nullptr;
3920
3921 if (Block) {
3922 if (badCFG)
3923 return nullptr;
3924 LoopSuccessor = Block;
3925 Block = nullptr;
3926 } else
3927 LoopSuccessor = Succ;
3928
3929 // Build the condition blocks.
3930 CFGBlock *ExitConditionBlock = createBlock(false);
3931
3932 // Set the terminator for the "exit" condition block.
3933 ExitConditionBlock->setTerminator(S);
3934
3935 // The last statement in the block should be the ObjCForCollectionStmt, which
3936 // performs the actual binding to 'element' and determines if there are any
3937 // more items in the collection.
3938 appendStmt(ExitConditionBlock, S);
3939 Block = ExitConditionBlock;
3940
3941 // Walk the 'element' expression to see if there are any side-effects. We
3942 // generate new blocks as necessary. We DON'T add the statement by default to
3943 // the CFG unless it contains control-flow.
3944 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3945 AddStmtChoice::NotAlwaysAdd);
3946 if (Block) {
3947 if (badCFG)
3948 return nullptr;
3949 Block = nullptr;
3950 }
3951
3952 // The condition block is the implicit successor for the loop body as well as
3953 // any code above the loop.
3954 Succ = EntryConditionBlock;
3955
3956 // Now create the true branch.
3957 {
3958 // Save the current values for Succ, continue and break targets.
3959 SaveAndRestore save_Block(Block), save_Succ(Succ);
3960 SaveAndRestore save_continue(ContinueJumpTarget),
3961 save_break(BreakJumpTarget);
3962
3963 // Add an intermediate block between the BodyBlock and the
3964 // EntryConditionBlock to represent the "loop back" transition, for looping
3965 // back to the head of the loop.
3966 CFGBlock *LoopBackBlock = nullptr;
3967 Succ = LoopBackBlock = createBlock();
3968 LoopBackBlock->setLoopTarget(S);
3969
3970 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3971 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
3972
3973 CFGBlock *BodyBlock = addStmt(S->getBody());
3974
3975 if (!BodyBlock)
3976 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
3977 else if (Block) {
3978 if (badCFG)
3979 return nullptr;
3980 }
3981
3982 // This new body block is a successor to our "exit" condition block.
3983 addSuccessor(ExitConditionBlock, BodyBlock);
3984 }
3985
3986 // Link up the condition block with the code that follows the loop.
3987 // (the false branch).
3988 addSuccessor(ExitConditionBlock, LoopSuccessor);
3989
3990 // Now create a prologue block to contain the collection expression.
3991 Block = createBlock();
3992 return addStmt(S->getCollection());
3993}
3994
3995CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3996 // Inline the body.
3997 return addStmt(S->getSubStmt());
3998 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3999}
4000
4001CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
4002 // FIXME: Add locking 'primitives' to CFG for @synchronized.
4003
4004 // Inline the body.
4005 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
4006
4007 // The sync body starts its own basic block. This makes it a little easier
4008 // for diagnostic clients.
4009 if (SyncBlock) {
4010 if (badCFG)
4011 return nullptr;
4012
4013 Block = nullptr;
4014 Succ = SyncBlock;
4015 }
4016
4017 // Add the @synchronized to the CFG.
4018 autoCreateBlock();
4019 appendStmt(Block, S);
4020
4021 // Inline the sync expression.
4022 return addStmt(S->getSynchExpr());
4023}
4024
4025CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
4026 autoCreateBlock();
4027
4028 // Add the PseudoObject as the last thing.
4029 appendStmt(Block, E);
4030
4031 CFGBlock *lastBlock = Block;
4032
4033 // Before that, evaluate all of the semantics in order. In
4034 // CFG-land, that means appending them in reverse order.
4035 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
4036 Expr *Semantic = E->getSemanticExpr(--i);
4037
4038 // If the semantic is an opaque value, we're being asked to bind
4039 // it to its source expression.
4040 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
4041 Semantic = OVE->getSourceExpr();
4042
4043 if (CFGBlock *B = Visit(Semantic))
4044 lastBlock = B;
4045 }
4046
4047 return lastBlock;
4048}
4049
4050CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
4051 CFGBlock *LoopSuccessor = nullptr;
4052
4053 // Save local scope position because in case of condition variable ScopePos
4054 // won't be restored when traversing AST.
4055 SaveAndRestore save_scope_pos(ScopePos);
4056
4057 // Create local scope for possible condition variable.
4058 // Store scope position for continue statement.
4059 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
4060 if (VarDecl *VD = W->getConditionVariable()) {
4061 addLocalScopeForVarDecl(VD);
4062 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
4063 }
4064 addLoopExit(W);
4065
4066 // "while" is a control-flow statement. Thus we stop processing the current
4067 // block.
4068 if (Block) {
4069 if (badCFG)
4070 return nullptr;
4071 LoopSuccessor = Block;
4072 Block = nullptr;
4073 } else {
4074 LoopSuccessor = Succ;
4075 }
4076
4077 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
4078
4079 // Process the loop body.
4080 {
4081 assert(W->getBody());
4082
4083 // Save the current values for Block, Succ, continue and break targets.
4084 SaveAndRestore save_Block(Block), save_Succ(Succ);
4085 SaveAndRestore save_continue(ContinueJumpTarget),
4086 save_break(BreakJumpTarget);
4087
4088 // Create an empty block to represent the transition block for looping back
4089 // to the head of the loop.
4090 Succ = TransitionBlock = createBlock(false);
4091 TransitionBlock->setLoopTarget(W);
4092 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
4093
4094 // All breaks should go to the code following the loop.
4095 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4096
4097 // Loop body should end with destructor of Condition variable (if any).
4098 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
4099
4100 // If body is not a compound statement create implicit scope
4101 // and add destructors.
4102 if (!isa<CompoundStmt>(W->getBody()))
4103 addLocalScopeAndDtors(W->getBody());
4104
4105 // Create the body. The returned block is the entry to the loop body.
4106 BodyBlock = addStmt(W->getBody());
4107
4108 if (!BodyBlock)
4109 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
4110 else if (Block && badCFG)
4111 return nullptr;
4112 }
4113
4114 // Because of short-circuit evaluation, the condition of the loop can span
4115 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
4116 // evaluate the condition.
4117 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
4118
4119 do {
4120 Expr *C = W->getCond();
4121
4122 // Specially handle logical operators, which have a slightly
4123 // more optimal CFG representation.
4124 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
4125 if (Cond->isLogicalOp()) {
4126 std::tie(EntryConditionBlock, ExitConditionBlock) =
4127 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
4128 break;
4129 }
4130
4131 // The default case when not handling logical operators.
4132 ExitConditionBlock = createBlock(false);
4133 ExitConditionBlock->setTerminator(W);
4134
4135 // Now add the actual condition to the condition block.
4136 // Because the condition itself may contain control-flow, new blocks may
4137 // be created. Thus we update "Succ" after adding the condition.
4138 Block = ExitConditionBlock;
4139 Block = EntryConditionBlock = addStmt(C);
4140
4141 // If this block contains a condition variable, add both the condition
4142 // variable and initializer to the CFG.
4143 if (VarDecl *VD = W->getConditionVariable()) {
4144 if (Expr *Init = VD->getInit()) {
4145 autoCreateBlock();
4146 const DeclStmt *DS = W->getConditionVariableDeclStmt();
4147 assert(DS->isSingleDecl());
4148 findConstructionContexts(
4149 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
4150 const_cast<DeclStmt *>(DS)),
4151 Init);
4152 appendStmt(Block, DS);
4153 EntryConditionBlock = addStmt(Init);
4154 assert(Block == EntryConditionBlock);
4155 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
4156 }
4157 }
4158
4159 if (Block && badCFG)
4160 return nullptr;
4161
4162 // See if this is a known constant.
4163 const TryResult& KnownVal = tryEvaluateBool(C);
4164
4165 // Add the loop body entry as a successor to the condition.
4166 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
4167 // Link up the condition block with the code that follows the loop. (the
4168 // false branch).
4169 addSuccessor(ExitConditionBlock,
4170 KnownVal.isTrue() ? nullptr : LoopSuccessor);
4171 } while(false);
4172
4173 // Link up the loop-back block to the entry condition block.
4174 addSuccessor(TransitionBlock, EntryConditionBlock);
4175
4176 // There can be no more statements in the condition block since we loop back
4177 // to this block. NULL out Block to force lazy creation of another block.
4178 Block = nullptr;
4179
4180 // Return the condition block, which is the dominating block for the loop.
4181 Succ = EntryConditionBlock;
4182 return EntryConditionBlock;
4183}
4184
4185CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
4186 AddStmtChoice asc) {
4187 if (asc.alwaysAdd(*this, A)) {
4188 autoCreateBlock();
4189 appendStmt(Block, A);
4190 }
4191
4192 CFGBlock *B = Block;
4193
4194 if (CFGBlock *R = Visit(A->getSubExpr()))
4195 B = R;
4196
4197 OpaqueValueExpr *OVE = A->getCommonExpr();
4198 if (CFGBlock *R = Visit(OVE->getSourceExpr()))
4199 B = R;
4200
4201 return B;
4202}
4203
4204CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
4205 // ObjCAtCatchStmt are treated like labels, so they are the first statement
4206 // in a block.
4207
4208 // Save local scope position because in case of exception variable ScopePos
4209 // won't be restored when traversing AST.
4210 SaveAndRestore save_scope_pos(ScopePos);
4211
4212 if (CS->getCatchBody())
4213 addStmt(CS->getCatchBody());
4214
4215 CFGBlock *CatchBlock = Block;
4216 if (!CatchBlock)
4217 CatchBlock = createBlock();
4218
4219 appendStmt(CatchBlock, CS);
4220
4221 // Also add the ObjCAtCatchStmt as a label, like with regular labels.
4222 CatchBlock->setLabel(CS);
4223
4224 // Bail out if the CFG is bad.
4225 if (badCFG)
4226 return nullptr;
4227
4228 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4229 Block = nullptr;
4230
4231 return CatchBlock;
4232}
4233
4234CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
4235 // If we were in the middle of a block we stop processing that block.
4236 if (badCFG)
4237 return nullptr;
4238
4239 // Create the new block.
4240 Block = createBlock(false);
4241
4242 if (TryTerminatedBlock)
4243 // The current try statement is the only successor.
4244 addSuccessor(Block, TryTerminatedBlock);
4245 else
4246 // otherwise the Exit block is the only successor.
4247 addSuccessor(Block, &cfg->getExit());
4248
4249 // Add the statement to the block. This may create new blocks if S contains
4250 // control-flow (short-circuit operations).
4251 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
4252}
4253
4254CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
4255 // "@try"/"@catch" is a control-flow statement. Thus we stop processing the
4256 // current block.
4257 CFGBlock *TrySuccessor = nullptr;
4258
4259 if (Block) {
4260 if (badCFG)
4261 return nullptr;
4262 TrySuccessor = Block;
4263 } else
4264 TrySuccessor = Succ;
4265
4266 // FIXME: Implement @finally support.
4267 if (Terminator->getFinallyStmt())
4268 return NYS();
4269
4270 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
4271
4272 // Create a new block that will contain the try statement.
4273 CFGBlock *NewTryTerminatedBlock = createBlock(false);
4274 // Add the terminator in the try block.
4275 NewTryTerminatedBlock->setTerminator(Terminator);
4276
4277 bool HasCatchAll = false;
4278 for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
4279 // The code after the try is the implicit successor.
4280 Succ = TrySuccessor;
4281 if (CS->hasEllipsis()) {
4282 HasCatchAll = true;
4283 }
4284 Block = nullptr;
4285 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
4286 if (!CatchBlock)
4287 return nullptr;
4288 // Add this block to the list of successors for the block with the try
4289 // statement.
4290 addSuccessor(NewTryTerminatedBlock, CatchBlock);
4291 }
4292
4293 // FIXME: This needs updating when @finally support is added.
4294 if (!HasCatchAll) {
4295 if (PrevTryTerminatedBlock)
4296 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
4297 else
4298 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
4299 }
4300
4301 // The code after the try is the implicit successor.
4302 Succ = TrySuccessor;
4303
4304 // Save the current "try" context.
4305 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
4306 cfg->addTryDispatchBlock(TryTerminatedBlock);
4307
4308 assert(Terminator->getTryBody() && "try must contain a non-NULL body");
4309 Block = nullptr;
4310 return addStmt(Terminator->getTryBody());
4311}
4312
4313CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
4314 AddStmtChoice asc) {
4315 findConstructionContextsForArguments(ME);
4316
4317 autoCreateBlock();
4318 appendObjCMessage(Block, ME);
4319
4320 return VisitChildren(ME);
4321}
4322
4323CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
4324 // If we were in the middle of a block we stop processing that block.
4325 if (badCFG)
4326 return nullptr;
4327
4328 // Create the new block.
4329 Block = createBlock(false);
4330
4331 if (TryTerminatedBlock)
4332 // The current try statement is the only successor.
4333 addSuccessor(Block, TryTerminatedBlock);
4334 else
4335 // otherwise the Exit block is the only successor.
4336 addSuccessor(Block, &cfg->getExit());
4337
4338 // Add the statement to the block. This may create new blocks if S contains
4339 // control-flow (short-circuit operations).
4340 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
4341}
4342
4343CFGBlock *CFGBuilder::VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc) {
4344 if (asc.alwaysAdd(*this, S)) {
4345 autoCreateBlock();
4346 appendStmt(Block, S);
4347 }
4348
4349 // C++ [expr.typeid]p3:
4350 // When typeid is applied to an expression other than an glvalue of a
4351 // polymorphic class type [...] [the] expression is an unevaluated
4352 // operand. [...]
4353 // We add only potentially evaluated statements to the block to avoid
4354 // CFG generation for unevaluated operands.
4355 if (!S->isTypeDependent() && S->isPotentiallyEvaluated())
4356 return VisitChildren(S);
4357
4358 // Return block without CFG for unevaluated operands.
4359 return Block;
4360}
4361
4362CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
4363 CFGBlock *LoopSuccessor = nullptr;
4364
4365 addLoopExit(D);
4366
4367 // "do...while" is a control-flow statement. Thus we stop processing the
4368 // current block.
4369 if (Block) {
4370 if (badCFG)
4371 return nullptr;
4372 LoopSuccessor = Block;
4373 } else
4374 LoopSuccessor = Succ;
4375
4376 // Because of short-circuit evaluation, the condition of the loop can span
4377 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
4378 // evaluate the condition.
4379 CFGBlock *ExitConditionBlock = createBlock(false);
4380 CFGBlock *EntryConditionBlock = ExitConditionBlock;
4381
4382 // Set the terminator for the "exit" condition block.
4383 ExitConditionBlock->setTerminator(D);
4384
4385 // Now add the actual condition to the condition block. Because the condition
4386 // itself may contain control-flow, new blocks may be created.
4387 if (Stmt *C = D->getCond()) {
4388 Block = ExitConditionBlock;
4389 EntryConditionBlock = addStmt(C);
4390 if (Block) {
4391 if (badCFG)
4392 return nullptr;
4393 }
4394 }
4395
4396 // The condition block is the implicit successor for the loop body.
4397 Succ = EntryConditionBlock;
4398
4399 // See if this is a known constant.
4400 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
4401
4402 // Process the loop body.
4403 CFGBlock *BodyBlock = nullptr;
4404 {
4405 assert(D->getBody());
4406
4407 // Save the current values for Block, Succ, and continue and break targets
4408 SaveAndRestore save_Block(Block), save_Succ(Succ);
4409 SaveAndRestore save_continue(ContinueJumpTarget),
4410 save_break(BreakJumpTarget);
4411
4412 // All continues within this loop should go to the condition block
4413 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
4414
4415 // All breaks should go to the code following the loop.
4416 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4417
4418 // NULL out Block to force lazy instantiation of blocks for the body.
4419 Block = nullptr;
4420
4421 // If body is not a compound statement create implicit scope
4422 // and add destructors.
4423 if (!isa<CompoundStmt>(D->getBody()))
4424 addLocalScopeAndDtors(D->getBody());
4425
4426 // Create the body. The returned block is the entry to the loop body.
4427 BodyBlock = addStmt(D->getBody());
4428
4429 if (!BodyBlock)
4430 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
4431 else if (Block) {
4432 if (badCFG)
4433 return nullptr;
4434 }
4435
4436 // Add an intermediate block between the BodyBlock and the
4437 // ExitConditionBlock to represent the "loop back" transition. Create an
4438 // empty block to represent the transition block for looping back to the
4439 // head of the loop.
4440 // FIXME: Can we do this more efficiently without adding another block?
4441 Block = nullptr;
4442 Succ = BodyBlock;
4443 CFGBlock *LoopBackBlock = createBlock();
4444 LoopBackBlock->setLoopTarget(D);
4445
4446 if (!KnownVal.isFalse())
4447 // Add the loop body entry as a successor to the condition.
4448 addSuccessor(ExitConditionBlock, LoopBackBlock);
4449 else
4450 addSuccessor(ExitConditionBlock, nullptr);
4451 }
4452
4453 // Link up the condition block with the code that follows the loop.
4454 // (the false branch).
4455 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
4456
4457 // There can be no more statements in the body block(s) since we loop back to
4458 // the body. NULL out Block to force lazy creation of another block.
4459 Block = nullptr;
4460
4461 // Return the loop body, which is the dominating block for the loop.
4462 Succ = BodyBlock;
4463 return BodyBlock;
4464}
4465
4466CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
4467 // "continue" is a control-flow statement. Thus we stop processing the
4468 // current block.
4469 if (badCFG)
4470 return nullptr;
4471
4472 // Now create a new block that ends with the continue statement.
4473 Block = createBlock(false);
4474 Block->setTerminator(C);
4475
4476 // If there is no target for the continue, then we are looking at an
4477 // incomplete AST. This means the CFG cannot be constructed.
4478 if (ContinueJumpTarget.block) {
4479 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
4480 addSuccessor(Block, ContinueJumpTarget.block);
4481 } else
4482 badCFG = true;
4483
4484 return Block;
4485}
4486
4487CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
4488 AddStmtChoice asc) {
4489 if (asc.alwaysAdd(*this, E)) {
4490 autoCreateBlock();
4491 appendStmt(Block, E);
4492 }
4493
4494 // VLA types have expressions that must be evaluated.
4495 // Evaluation is done only for `sizeof`.
4496
4497 if (E->getKind() != UETT_SizeOf)
4498 return Block;
4499
4500 CFGBlock *lastBlock = Block;
4501
4502 if (E->isArgumentType()) {
4503 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
4504 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
4505 lastBlock = addStmt(VA->getSizeExpr());
4506 }
4507 return lastBlock;
4508}
4509
4510/// VisitStmtExpr - Utility method to handle (nested) statement
4511/// expressions (a GCC extension).
4512CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
4513 if (asc.alwaysAdd(*this, SE)) {
4514 autoCreateBlock();
4515 appendStmt(Block, SE);
4516 }
4517 return VisitCompoundStmt(SE->getSubStmt(), /*ExternallyDestructed=*/true);
4518}
4519
4520CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
4521 // "switch" is a control-flow statement. Thus we stop processing the current
4522 // block.
4523 CFGBlock *SwitchSuccessor = nullptr;
4524
4525 // Save local scope position because in case of condition variable ScopePos
4526 // won't be restored when traversing AST.
4527 SaveAndRestore save_scope_pos(ScopePos);
4528
4529 // Create local scope for C++17 switch init-stmt if one exists.
4530 if (Stmt *Init = Terminator->getInit())
4531 addLocalScopeForStmt(Init);
4532
4533 // Create local scope for possible condition variable.
4534 // Store scope position. Add implicit destructor.
4535 if (VarDecl *VD = Terminator->getConditionVariable())
4536 addLocalScopeForVarDecl(VD);
4537
4538 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
4539
4540 if (Block) {
4541 if (badCFG)
4542 return nullptr;
4543 SwitchSuccessor = Block;
4544 } else SwitchSuccessor = Succ;
4545
4546 // Save the current "switch" context.
4547 SaveAndRestore save_switch(SwitchTerminatedBlock),
4548 save_default(DefaultCaseBlock);
4549 SaveAndRestore save_break(BreakJumpTarget);
4550
4551 // Set the "default" case to be the block after the switch statement. If the
4552 // switch statement contains a "default:", this value will be overwritten with
4553 // the block for that code.
4554 DefaultCaseBlock = SwitchSuccessor;
4555
4556 // Create a new block that will contain the switch statement.
4557 SwitchTerminatedBlock = createBlock(false);
4558
4559 // Now process the switch body. The code after the switch is the implicit
4560 // successor.
4561 Succ = SwitchSuccessor;
4562 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
4563
4564 // When visiting the body, the case statements should automatically get linked
4565 // up to the switch. We also don't keep a pointer to the body, since all
4566 // control-flow from the switch goes to case/default statements.
4567 assert(Terminator->getBody() && "switch must contain a non-NULL body");
4568 Block = nullptr;
4569
4570 // For pruning unreachable case statements, save the current state
4571 // for tracking the condition value.
4572 SaveAndRestore save_switchExclusivelyCovered(switchExclusivelyCovered, false);
4573
4574 // Determine if the switch condition can be explicitly evaluated.
4575 assert(Terminator->getCond() && "switch condition must be non-NULL");
4576 Expr::EvalResult result;
4577 bool b = tryEvaluate(Terminator->getCond(), result);
4578 SaveAndRestore save_switchCond(switchCond, b ? &result : nullptr);
4579
4580 // If body is not a compound statement create implicit scope
4581 // and add destructors.
4582 if (!isa<CompoundStmt>(Terminator->getBody()))
4583 addLocalScopeAndDtors(Terminator->getBody());
4584
4585 addStmt(Terminator->getBody());
4586 if (Block) {
4587 if (badCFG)
4588 return nullptr;
4589 }
4590
4591 // If we have no "default:" case, the default transition is to the code
4592 // following the switch body. Moreover, take into account if all the
4593 // cases of a switch are covered (e.g., switching on an enum value).
4594 //
4595 // Note: We add a successor to a switch that is considered covered yet has no
4596 // case statements if the enumeration has no enumerators.
4597 // We also consider this successor reachable if
4598 // BuildOpts.SwitchReqDefaultCoveredEnum is true.
4599 bool SwitchAlwaysHasSuccessor = false;
4600 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
4601 SwitchAlwaysHasSuccessor |=
4603 Terminator->isAllEnumCasesCovered() && Terminator->getSwitchCaseList();
4604 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
4605 !SwitchAlwaysHasSuccessor);
4606
4607 // Add the terminator and condition in the switch block.
4608 SwitchTerminatedBlock->setTerminator(Terminator);
4609 Block = SwitchTerminatedBlock;
4610 CFGBlock *LastBlock = addStmt(Terminator->getCond());
4611
4612 // If the SwitchStmt contains a condition variable, add both the
4613 // SwitchStmt and the condition variable initialization to the CFG.
4614 if (VarDecl *VD = Terminator->getConditionVariable()) {
4615 if (Expr *Init = VD->getInit()) {
4616 autoCreateBlock();
4617 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
4618 LastBlock = addStmt(Init);
4619 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
4620 }
4621 }
4622
4623 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
4624 if (Stmt *Init = Terminator->getInit()) {
4625 autoCreateBlock();
4626 LastBlock = addStmt(Init);
4627 }
4628
4629 return LastBlock;
4630}
4631
4632static bool shouldAddCase(bool &switchExclusivelyCovered,
4633 const Expr::EvalResult *switchCond,
4634 const CaseStmt *CS,
4635 ASTContext &Ctx) {
4636 if (!switchCond)
4637 return true;
4638
4639 bool addCase = false;
4640
4641 if (!switchExclusivelyCovered) {
4642 if (switchCond->Val.isInt()) {
4643 // Evaluate the LHS of the case value.
4644 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
4645 const llvm::APSInt &condInt = switchCond->Val.getInt();
4646
4647 if (condInt == lhsInt) {
4648 addCase = true;
4649 switchExclusivelyCovered = true;
4650 }
4651 else if (condInt > lhsInt) {
4652 if (const Expr *RHS = CS->getRHS()) {
4653 // Evaluate the RHS of the case value.
4654 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
4655 if (V2 >= condInt) {
4656 addCase = true;
4657 switchExclusivelyCovered = true;
4658 }
4659 }
4660 }
4661 }
4662 else
4663 addCase = true;
4664 }
4665 return addCase;
4666}
4667
4668CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
4669 // CaseStmts are essentially labels, so they are the first statement in a
4670 // block.
4671 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
4672
4673 if (Stmt *Sub = CS->getSubStmt()) {
4674 // For deeply nested chains of CaseStmts, instead of doing a recursion
4675 // (which can blow out the stack), manually unroll and create blocks
4676 // along the way.
4677 while (isa<CaseStmt>(Sub)) {
4678 CFGBlock *currentBlock = createBlock(false);
4679 currentBlock->setLabel(CS);
4680
4681 if (TopBlock)
4682 addSuccessor(LastBlock, currentBlock);
4683 else
4684 TopBlock = currentBlock;
4685
4686 addSuccessor(SwitchTerminatedBlock,
4687 shouldAddCase(switchExclusivelyCovered, switchCond,
4688 CS, *Context)
4689 ? currentBlock : nullptr);
4690
4691 LastBlock = currentBlock;
4692 CS = cast<CaseStmt>(Sub);
4693 Sub = CS->getSubStmt();
4694 }
4695
4696 addStmt(Sub);
4697 }
4698
4699 CFGBlock *CaseBlock = Block;
4700 if (!CaseBlock)
4701 CaseBlock = createBlock();
4702
4703 // Cases statements partition blocks, so this is the top of the basic block we
4704 // were processing (the "case XXX:" is the label).
4705 CaseBlock->setLabel(CS);
4706
4707 if (badCFG)
4708 return nullptr;
4709
4710 // Add this block to the list of successors for the block with the switch
4711 // statement.
4712 assert(SwitchTerminatedBlock);
4713 addSuccessor(SwitchTerminatedBlock, CaseBlock,
4714 shouldAddCase(switchExclusivelyCovered, switchCond,
4715 CS, *Context));
4716
4717 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4718 Block = nullptr;
4719
4720 if (TopBlock) {
4721 addSuccessor(LastBlock, CaseBlock);
4722 Succ = TopBlock;
4723 } else {
4724 // This block is now the implicit successor of other blocks.
4725 Succ = CaseBlock;
4726 }
4727
4728 return Succ;
4729}
4730
4731CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
4732 if (Terminator->getSubStmt())
4733 addStmt(Terminator->getSubStmt());
4734
4735 DefaultCaseBlock = Block;
4736
4737 if (!DefaultCaseBlock)
4738 DefaultCaseBlock = createBlock();
4739
4740 // Default statements partition blocks, so this is the top of the basic block
4741 // we were processing (the "default:" is the label).
4742 DefaultCaseBlock->setLabel(Terminator);
4743
4744 if (badCFG)
4745 return nullptr;
4746
4747 // Unlike case statements, we don't add the default block to the successors
4748 // for the switch statement immediately. This is done when we finish
4749 // processing the switch statement. This allows for the default case
4750 // (including a fall-through to the code after the switch statement) to always
4751 // be the last successor of a switch-terminated block.
4752
4753 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4754 Block = nullptr;
4755
4756 // This block is now the implicit successor of other blocks.
4757 Succ = DefaultCaseBlock;
4758
4759 return DefaultCaseBlock;
4760}
4761
4762CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
4763 // "try"/"catch" is a control-flow statement. Thus we stop processing the
4764 // current block.
4765 CFGBlock *TrySuccessor = nullptr;
4766
4767 if (Block) {
4768 if (badCFG)
4769 return nullptr;
4770 TrySuccessor = Block;
4771 } else
4772 TrySuccessor = Succ;
4773
4774 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
4775
4776 // Create a new block that will contain the try statement.
4777 CFGBlock *NewTryTerminatedBlock = createBlock(false);
4778 // Add the terminator in the try block.
4779 NewTryTerminatedBlock->setTerminator(Terminator);
4780
4781 bool HasCatchAll = false;
4782 for (unsigned I = 0, E = Terminator->getNumHandlers(); I != E; ++I) {
4783 // The code after the try is the implicit successor.
4784 Succ = TrySuccessor;
4785 CXXCatchStmt *CS = Terminator->getHandler(I);
4786 if (CS->getExceptionDecl() == nullptr) {
4787 HasCatchAll = true;
4788 }
4789 Block = nullptr;
4790 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
4791 if (!CatchBlock)
4792 return nullptr;
4793 // Add this block to the list of successors for the block with the try
4794 // statement.
4795 addSuccessor(NewTryTerminatedBlock, CatchBlock);
4796 }
4797 if (!HasCatchAll) {
4798 if (PrevTryTerminatedBlock)
4799 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
4800 else
4801 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
4802 }
4803
4804 // The code after the try is the implicit successor.
4805 Succ = TrySuccessor;
4806
4807 // Save the current "try" context.
4808 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
4809 cfg->addTryDispatchBlock(TryTerminatedBlock);
4810
4811 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
4812 Block = nullptr;
4813 return addStmt(Terminator->getTryBlock());
4814}
4815
4816CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
4817 // CXXCatchStmt are treated like labels, so they are the first statement in a
4818 // block.
4819
4820 // Save local scope position because in case of exception variable ScopePos
4821 // won't be restored when traversing AST.
4822 SaveAndRestore save_scope_pos(ScopePos);
4823
4824 // Create local scope for possible exception variable.
4825 // Store scope position. Add implicit destructor.
4826 if (VarDecl *VD = CS->getExceptionDecl()) {
4827 LocalScope::const_iterator BeginScopePos = ScopePos;
4828 addLocalScopeForVarDecl(VD);
4829 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
4830 }
4831
4832 if (CS->getHandlerBlock())
4833 addStmt(CS->getHandlerBlock());
4834
4835 CFGBlock *CatchBlock = Block;
4836 if (!CatchBlock)
4837 CatchBlock = createBlock();
4838
4839 // CXXCatchStmt is more than just a label. They have semantic meaning
4840 // as well, as they implicitly "initialize" the catch variable. Add
4841 // it to the CFG as a CFGElement so that the control-flow of these
4842 // semantics gets captured.
4843 appendStmt(CatchBlock, CS);
4844
4845 // Also add the CXXCatchStmt as a label, to mirror handling of regular
4846 // labels.
4847 CatchBlock->setLabel(CS);
4848
4849 // Bail out if the CFG is bad.
4850 if (badCFG)
4851 return nullptr;
4852
4853 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4854 Block = nullptr;
4855
4856 return CatchBlock;
4857}
4858
4859CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4860 // C++0x for-range statements are specified as [stmt.ranged]:
4861 //
4862 // {
4863 // auto && __range = range-init;
4864 // for ( auto __begin = begin-expr,
4865 // __end = end-expr;
4866 // __begin != __end;
4867 // ++__begin ) {
4868 // for-range-declaration = *__begin;
4869 // statement
4870 // }
4871 // }
4872
4873 // Save local scope position before the addition of the implicit variables.
4874 SaveAndRestore save_scope_pos(ScopePos);
4875
4876 // Create local scopes and destructors for init, range, begin and end
4877 // variables.
4878 if (Stmt *Init = S->getInit())
4879 addLocalScopeForStmt(Init);
4880 if (Stmt *Range = S->getRangeStmt())
4881 addLocalScopeForStmt(Range);
4882 if (Stmt *Begin = S->getBeginStmt())
4883 addLocalScopeForStmt(Begin);
4884 if (Stmt *End = S->getEndStmt())
4885 addLocalScopeForStmt(End);
4886 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
4887
4888 LocalScope::const_iterator ContinueScopePos = ScopePos;
4889
4890 // "for" is a control-flow statement. Thus we stop processing the current
4891 // block.
4892 CFGBlock *LoopSuccessor = nullptr;
4893 if (Block) {
4894 if (badCFG)
4895 return nullptr;
4896 LoopSuccessor = Block;
4897 } else
4898 LoopSuccessor = Succ;
4899
4900 // Save the current value for the break targets.
4901 // All breaks should go to the code following the loop.
4902 SaveAndRestore save_break(BreakJumpTarget);
4903 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4904
4905 // The block for the __begin != __end expression.
4906 CFGBlock *ConditionBlock = createBlock(false);
4907 ConditionBlock->setTerminator(S);
4908
4909 // Now add the actual condition to the condition block.
4910 if (Expr *C = S->getCond()) {
4911 Block = ConditionBlock;
4912 CFGBlock *BeginConditionBlock = addStmt(C);
4913 if (badCFG)
4914 return nullptr;
4915 assert(BeginConditionBlock == ConditionBlock &&
4916 "condition block in for-range was unexpectedly complex");
4917 (void)BeginConditionBlock;
4918 }
4919
4920 // The condition block is the implicit successor for the loop body as well as
4921 // any code above the loop.
4922 Succ = ConditionBlock;
4923
4924 // See if this is a known constant.
4925 TryResult KnownVal(true);
4926
4927 if (S->getCond())
4928 KnownVal = tryEvaluateBool(S->getCond());
4929
4930 // Now create the loop body.
4931 {
4932 assert(S->getBody());
4933
4934 // Save the current values for Block, Succ, and continue targets.
4935 SaveAndRestore save_Block(Block), save_Succ(Succ);
4936 SaveAndRestore save_continue(ContinueJumpTarget);
4937
4938 // Generate increment code in its own basic block. This is the target of
4939 // continue statements.
4940 Block = nullptr;
4941 Succ = addStmt(S->getInc());
4942 if (badCFG)
4943 return nullptr;
4944 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
4945
4946 // The starting block for the loop increment is the block that should
4947 // represent the 'loop target' for looping back to the start of the loop.
4948 ContinueJumpTarget.block->setLoopTarget(S);
4949
4950 // Finish up the increment block and prepare to start the loop body.
4951 assert(Block);
4952 if (badCFG)
4953 return nullptr;
4954 Block = nullptr;
4955
4956 // Add implicit scope and dtors for loop variable.
4957 addLocalScopeAndDtors(S->getLoopVarStmt());
4958
4959 // If body is not a compound statement create implicit scope
4960 // and add destructors.
4961 if (!isa<CompoundStmt>(S->getBody()))
4962 addLocalScopeAndDtors(S->getBody());
4963
4964 // Populate a new block to contain the loop body and loop variable.
4965 addStmt(S->getBody());
4966
4967 if (badCFG)
4968 return nullptr;
4969 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
4970 if (badCFG)
4971 return nullptr;
4972
4973 // This new body block is a successor to our condition block.
4974 addSuccessor(ConditionBlock,
4975 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
4976 }
4977
4978 // Link up the condition block with the code that follows the loop (the
4979 // false branch).
4980 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
4981
4982 // Add the initialization statements.
4983 Block = createBlock();
4984 addStmt(S->getBeginStmt());
4985 addStmt(S->getEndStmt());
4986 CFGBlock *Head = addStmt(S->getRangeStmt());
4987 if (S->getInit())
4988 Head = addStmt(S->getInit());
4989 return Head;
4990}
4991
4992CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
4993 AddStmtChoice asc,
4994 bool ExternallyDestructed) {
4995 if (BuildOpts.AddTemporaryDtors || BuildOpts.AddLifetime) {
4996 // If adding implicit destructors visit the full expression for adding
4997 // destructors of temporaries.
4998 TempDtorContext Context;
4999 Expr *FullExpr = E->getSubExpr();
5000 VisitForTemporaries(FullExpr, ExternallyDestructed, Context);
5001
5002 addFullExprCleanupMarker(Context, E);
5003
5004 // Full expression has to be added as CFGStmt so it will be sequenced
5005 // before destructors of it's temporaries.
5006 asc = asc.withAlwaysAdd(true);
5007 }
5008 return Visit(E->getSubExpr(), asc);
5009}
5010
5011CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
5012 AddStmtChoice asc) {
5013 if (asc.alwaysAdd(*this, E)) {
5014 autoCreateBlock();
5015 appendStmt(Block, E);
5016
5017 findConstructionContexts(
5018 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
5019 E->getSubExpr());
5020
5021 // We do not want to propagate the AlwaysAdd property.
5022 asc = asc.withAlwaysAdd(false);
5023 }
5024 return Visit(E->getSubExpr(), asc);
5025}
5026
5027CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
5028 AddStmtChoice asc) {
5029 // If the constructor takes objects as arguments by value, we need to properly
5030 // construct these objects. Construction contexts we find here aren't for the
5031 // constructor C, they're for its arguments only.
5032 findConstructionContextsForArguments(C);
5033 appendConstructor(C);
5034
5035 return VisitChildren(C);
5036}
5037
5038CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
5039 AddStmtChoice asc) {
5040 autoCreateBlock();
5041 appendStmt(Block, NE);
5042
5043 findConstructionContexts(
5044 ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
5045 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
5046
5047 if (NE->getInitializer())
5048 Block = Visit(NE->getInitializer());
5049
5050 if (BuildOpts.AddCXXNewAllocator)
5051 appendNewAllocator(Block, NE);
5052
5053 if (NE->isArray() && *NE->getArraySize())
5054 Block = Visit(*NE->getArraySize());
5055
5056 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
5057 E = NE->placement_arg_end(); I != E; ++I)
5058 Block = Visit(*I);
5059
5060 return Block;
5061}
5062
5063CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
5064 AddStmtChoice asc) {
5065 autoCreateBlock();
5066 appendStmt(Block, DE);
5067 QualType DTy = DE->getDestroyedType();
5068 if (!DTy.isNull()) {
5069 DTy = DTy.getNonReferenceType();
5070 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
5071 if (RD) {
5072 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
5073 appendDeleteDtor(Block, RD, DE);
5074 }
5075 }
5076
5077 return VisitChildren(DE);
5078}
5079
5080CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
5081 AddStmtChoice asc) {
5082 if (asc.alwaysAdd(*this, E)) {
5083 autoCreateBlock();
5084 appendStmt(Block, E);
5085 // We do not want to propagate the AlwaysAdd property.
5086 asc = asc.withAlwaysAdd(false);
5087 }
5088 return Visit(E->getSubExpr(), asc);
5089}
5090
5091CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E,
5092 AddStmtChoice asc) {
5093 // If the constructor takes objects as arguments by value, we need to properly
5094 // construct these objects. Construction contexts we find here aren't for the
5095 // constructor C, they're for its arguments only.
5096 findConstructionContextsForArguments(E);
5097 appendConstructor(E);
5098
5099 return VisitChildren(E);
5100}
5101
5102CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
5103 AddStmtChoice asc) {
5104 if (asc.alwaysAdd(*this, E)) {
5105 autoCreateBlock();
5106 appendStmt(Block, E);
5107 }
5108
5109 if (E->getCastKind() == CK_IntegralToBoolean)
5110 tryEvaluateBool(E->getSubExpr()->IgnoreParens());
5111
5112 return Visit(E->getSubExpr(), AddStmtChoice());
5113}
5114
5115CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
5116 return Visit(E->getSubExpr(), AddStmtChoice());
5117}
5118
5119CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
5120 // Lazily create the indirect-goto dispatch block if there isn't one already.
5121 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
5122
5123 if (!IBlock) {
5124 IBlock = createBlock(false);
5125 cfg->setIndirectGotoBlock(IBlock);
5126 }
5127
5128 // IndirectGoto is a control-flow statement. Thus we stop processing the
5129 // current block and create a new one.
5130 if (badCFG)
5131 return nullptr;
5132
5133 Block = createBlock(false);
5134 Block->setTerminator(I);
5135 addSuccessor(Block, IBlock);
5136 return addStmt(I->getTarget());
5137}
5138
5139CFGBlock *CFGBuilder::VisitForTemporaries(Stmt *E, bool ExternallyDestructed,
5140 TempDtorContext &Context) {
5141
5142tryAgain:
5143 if (!E) {
5144 badCFG = true;
5145 return nullptr;
5146 }
5147 switch (E->getStmtClass()) {
5148 default:
5149 return VisitChildrenForTemporaries(E, false, Context);
5150
5151 case Stmt::InitListExprClass:
5152 return VisitChildrenForTemporaries(E, ExternallyDestructed, Context);
5153
5154 case Stmt::BinaryOperatorClass:
5155 case Stmt::CompoundAssignOperatorClass:
5156 return VisitBinaryOperatorForTemporaries(cast<BinaryOperator>(E),
5157 ExternallyDestructed, Context);
5158
5159 case Stmt::CXXOperatorCallExprClass:
5160 return VisitCXXOperatorCallExprForTemporaryDtors(
5161 cast<CXXOperatorCallExpr>(E), Context);
5162
5163 case Stmt::CXXBindTemporaryExprClass:
5164 return VisitCXXBindTemporaryExprForTemporaryDtors(
5165 cast<CXXBindTemporaryExpr>(E), ExternallyDestructed, Context);
5166
5167 case Stmt::BinaryConditionalOperatorClass:
5168 case Stmt::ConditionalOperatorClass:
5169 return VisitConditionalOperatorForTemporaries(
5170 cast<AbstractConditionalOperator>(E), ExternallyDestructed, Context);
5171
5172 case Stmt::ImplicitCastExprClass:
5173 // For implicit cast we want ExternallyDestructed to be passed further.
5174 E = cast<CastExpr>(E)->getSubExpr();
5175 goto tryAgain;
5176
5177 case Stmt::CXXFunctionalCastExprClass:
5178 // For functional cast we want ExternallyDestructed to be passed further.
5179 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
5180 goto tryAgain;
5181
5182 case Stmt::ConstantExprClass:
5183 E = cast<ConstantExpr>(E)->getSubExpr();
5184 goto tryAgain;
5185
5186 case Stmt::ParenExprClass:
5187 E = cast<ParenExpr>(E)->getSubExpr();
5188 goto tryAgain;
5189
5190 case Stmt::MaterializeTemporaryExprClass: {
5191 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
5192 ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression);
5193 if (BuildOpts.AddLifetime && !ExternallyDestructed)
5194 Context.track(MTE);
5195 SmallVector<const Expr *, 2> CommaLHSs;
5196 SmallVector<SubobjectAdjustment, 2> Adjustments;
5197 // Find the expression whose lifetime needs to be extended.
5198 E = const_cast<Expr *>(
5200 ->getSubExpr()
5201 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5202 // Visit the skipped comma operator left-hand sides for other temporaries.
5203 for (const Expr *CommaLHS : CommaLHSs) {
5204 VisitForTemporaries(const_cast<Expr *>(CommaLHS),
5205 /*ExternallyDestructed=*/false, Context);
5206 }
5207 goto tryAgain;
5208 }
5209
5210 case Stmt::BlockExprClass:
5211 // Don't recurse into blocks; their subexpressions don't get evaluated
5212 // here.
5213 return Block;
5214
5215 case Stmt::LambdaExprClass: {
5216 // For lambda expressions, only recurse into the capture initializers,
5217 // and not the body.
5218 auto *LE = cast<LambdaExpr>(E);
5219 CFGBlock *B = Block;
5220 for (Expr *Init : LE->capture_inits()) {
5221 if (Init) {
5222 if (CFGBlock *R = VisitForTemporaries(
5223 Init, /*ExternallyDestructed=*/true, Context))
5224 B = R;
5225 }
5226 }
5227 return B;
5228 }
5229
5230 case Stmt::StmtExprClass:
5231 // Don't recurse into statement expressions; any cleanups inside them
5232 // will be wrapped in their own ExprWithCleanups.
5233 return Block;
5234
5235 case Stmt::CXXDefaultArgExprClass:
5236 E = cast<CXXDefaultArgExpr>(E)->getExpr();
5237 goto tryAgain;
5238
5239 case Stmt::CXXDefaultInitExprClass:
5240 E = cast<CXXDefaultInitExpr>(E)->getExpr();
5241 goto tryAgain;
5242 }
5243}
5244
5245CFGBlock *CFGBuilder::VisitChildrenForTemporaries(Stmt *E,
5246 bool ExternallyDestructed,
5247 TempDtorContext &Context) {
5248 if (isa<LambdaExpr>(E)) {
5249 // Do not visit the children of lambdas; they have their own CFGs.
5250 return Block;
5251 }
5252
5253 // When visiting children for destructors or lifetime markers we want to visit
5254 // them in reverse order that they will appear in the CFG. Because the CFG is
5255 // built bottom-up, this means we visit them in their natural order, which
5256 // reverses them in the CFG.
5257 CFGBlock *B = Block;
5258 for (Stmt *Child : E->children())
5259 if (Child)
5260 if (CFGBlock *R =
5261 VisitForTemporaries(Child, ExternallyDestructed, Context))
5262 B = R;
5263
5264 return B;
5265}
5266
5267CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaries(
5268 BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) {
5269 if (E->isCommaOp()) {
5270 // For the comma operator, the LHS expression is evaluated before the RHS
5271 // expression, so prepend temporary destructors for the LHS first.
5272 CFGBlock *LHSBlock = VisitForTemporaries(E->getLHS(), false, Context);
5273 CFGBlock *RHSBlock =
5274 VisitForTemporaries(E->getRHS(), ExternallyDestructed, Context);
5275 return RHSBlock ? RHSBlock : LHSBlock;
5276 }
5277
5278 if (E->isLogicalOp()) {
5279 VisitForTemporaries(E->getLHS(), false, Context);
5280 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
5281 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
5282 RHSExecuted.negate();
5283
5284 // We do not know at CFG-construction time whether the right-hand-side was
5285 // executed, thus we add a branch node that depends on the temporary
5286 // constructor call.
5287 TempDtorContext RHSContext(
5288 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
5289 VisitForTemporaries(E->getRHS(), false, RHSContext);
5290 InsertTempDecisionBlock(RHSContext);
5291
5292 if (BuildOpts.AddLifetime)
5293 Context.CollectedMTEs.append(RHSContext.CollectedMTEs);
5294
5295 return Block;
5296 }
5297
5298 if (E->isAssignmentOp()) {
5299 // For assignment operators, the RHS expression is evaluated before the LHS
5300 // expression, so prepend temporary destructors for the RHS first.
5301 CFGBlock *RHSBlock = VisitForTemporaries(E->getRHS(), false, Context);
5302 CFGBlock *LHSBlock = VisitForTemporaries(E->getLHS(), false, Context);
5303 return LHSBlock ? LHSBlock : RHSBlock;
5304 }
5305
5306 // Any other operator is visited normally.
5307 return VisitChildrenForTemporaries(E, ExternallyDestructed, Context);
5308}
5309
5310CFGBlock *CFGBuilder::VisitCXXOperatorCallExprForTemporaryDtors(
5311 CXXOperatorCallExpr *E, TempDtorContext &Context) {
5312 if (E->isAssignmentOp()) {
5313 // For assignment operators, the RHS expression is evaluated before the LHS
5314 // expression, so prepend temporary destructors for the RHS first.
5315 CFGBlock *RHSBlock = VisitForTemporaries(E->getArg(1), false, Context);
5316 CFGBlock *LHSBlock = VisitForTemporaries(E->getArg(0), false, Context);
5317 return LHSBlock ? LHSBlock : RHSBlock;
5318 }
5319 return VisitChildrenForTemporaries(E, false, Context);
5320}
5321
5322CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
5323 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) {
5324 // First add destructors for temporaries in subexpression.
5325 // Because VisitCXXBindTemporaryExpr calls setDestructed:
5326 CFGBlock *B = VisitForTemporaries(E->getSubExpr(), true, Context);
5327 if (!ExternallyDestructed && BuildOpts.AddImplicitDtors &&
5328 BuildOpts.AddTemporaryDtors) {
5329 // If lifetime of temporary is not prolonged (by assigning to constant
5330 // reference) add destructor for it.
5331
5332 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
5333
5334 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
5335 // If the destructor is marked as a no-return destructor, we need to
5336 // create a new block for the destructor which does not have as a
5337 // successor anything built thus far. Control won't flow out of this
5338 // block.
5339 if (B) Succ = B;
5340 Block = createNoReturnBlock();
5341 } else if (Context.needsTempDtorBranch()) {
5342 // If we need to introduce a branch, we add a new block that we will hook
5343 // up to a decision block later.
5344 if (B) Succ = B;
5345 Block = createBlock();
5346 } else {
5347 autoCreateBlock();
5348 }
5349 if (Context.needsTempDtorBranch()) {
5350 Context.setDecisionPoint(Succ, E);
5351 }
5352 appendTemporaryDtor(Block, E);
5353 B = Block;
5354 }
5355 return B;
5356}
5357
5358void CFGBuilder::InsertTempDecisionBlock(const TempDtorContext &Context,
5359 CFGBlock *FalseSucc) {
5360 if (!Context.TerminatorExpr) {
5361 // If no temporary was found, we do not need to insert a decision point.
5362 return;
5363 }
5364 assert(Context.TerminatorExpr);
5365 CFGBlock *Decision = createBlock(false);
5366 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
5368 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
5369 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
5370 !Context.KnownExecuted.isTrue());
5371 Block = Decision;
5372}
5373
5374CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaries(
5375 AbstractConditionalOperator *E, bool ExternallyDestructed,
5376 TempDtorContext &Context) {
5377 VisitForTemporaries(E->getCond(), false, Context);
5378 CFGBlock *ConditionBlock = Block;
5379 CFGBlock *ConditionSucc = Succ;
5380 TryResult ConditionVal = tryEvaluateBool(E->getCond());
5381 TryResult NegatedVal = ConditionVal;
5382 if (NegatedVal.isKnown()) NegatedVal.negate();
5383
5384 TempDtorContext TrueContext(
5385 bothKnownTrue(Context.KnownExecuted, ConditionVal));
5386 VisitForTemporaries(E->getTrueExpr(), ExternallyDestructed, TrueContext);
5387 CFGBlock *TrueBlock = Block;
5388
5389 Block = ConditionBlock;
5390 Succ = ConditionSucc;
5391 TempDtorContext FalseContext(
5392 bothKnownTrue(Context.KnownExecuted, NegatedVal));
5393 VisitForTemporaries(E->getFalseExpr(), ExternallyDestructed, FalseContext);
5394
5395 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
5396 InsertTempDecisionBlock(FalseContext, TrueBlock);
5397 } else if (TrueContext.TerminatorExpr) {
5398 Block = TrueBlock;
5399 InsertTempDecisionBlock(TrueContext);
5400 } else {
5401 InsertTempDecisionBlock(FalseContext);
5402 }
5403 if (BuildOpts.AddLifetime) {
5404 Context.CollectedMTEs.append(TrueContext.CollectedMTEs);
5405 Context.CollectedMTEs.append(FalseContext.CollectedMTEs);
5406 }
5407
5408 return Block;
5409}
5410
5411CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D,
5412 AddStmtChoice asc) {
5413 if (asc.alwaysAdd(*this, D)) {
5414 autoCreateBlock();
5415 appendStmt(Block, D);
5416 }
5417
5418 // Iterate over all used expression in clauses.
5419 CFGBlock *B = Block;
5420
5421 // Reverse the elements to process them in natural order. Iterators are not
5422 // bidirectional, so we need to create temp vector.
5423 SmallVector<Stmt *, 8> Used(
5424 OMPExecutableDirective::used_clauses_children(D->clauses()));
5425 for (Stmt *S : llvm::reverse(Used)) {
5426 assert(S && "Expected non-null used-in-clause child.");
5427 if (CFGBlock *R = Visit(S))
5428 B = R;
5429 }
5430 // Visit associated structured block if any.
5431 if (!D->isStandaloneDirective()) {
5432 Stmt *S = D->getRawStmt();
5433 if (!isa<CompoundStmt>(S))
5434 addLocalScopeAndDtors(S);
5435 if (CFGBlock *R = addStmt(S))
5436 B = R;
5437 }
5438
5439 return B;
5440}
5441
5442/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
5443/// no successors or predecessors. If this is the first block created in the
5444/// CFG, it is automatically set to be the Entry and Exit of the CFG.
5446 bool first_block = begin() == end();
5447
5448 // Create the block.
5449 CFGBlock *Mem = new (getAllocator()) CFGBlock(NumBlockIDs++, BlkBVC, this);
5450 Blocks.push_back(Mem, BlkBVC);
5451
5452 // If this is the first block, set it as the Entry and Exit.
5453 if (first_block)
5454 Entry = Exit = &back();
5455
5456 // Return the block.
5457 return &back();
5458}
5459
5460/// buildCFG - Constructs a CFG from an AST.
5461std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
5462 ASTContext *C, const BuildOptions &BO) {
5463 llvm::TimeTraceScope TimeProfile("BuildCFG");
5464 CFGBuilder Builder(C, BO);
5465 return Builder.buildCFG(D, Statement);
5466}
5467
5468bool CFG::isLinear() const {
5469 // Quick path: if we only have the ENTRY block, the EXIT block, and some code
5470 // in between, then we have no room for control flow.
5471 if (size() <= 3)
5472 return true;
5473
5474 // Traverse the CFG until we find a branch.
5475 // TODO: While this should still be very fast,
5476 // maybe we should cache the answer.
5478 const CFGBlock *B = Entry;
5479 while (B != Exit) {
5480 auto IteratorAndFlag = Visited.insert(B);
5481 if (!IteratorAndFlag.second) {
5482 // We looped back to a block that we've already visited. Not linear.
5483 return false;
5484 }
5485
5486 // Iterate over reachable successors.
5487 const CFGBlock *FirstReachableB = nullptr;
5488 for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
5489 if (!AB.isReachable())
5490 continue;
5491
5492 if (FirstReachableB == nullptr) {
5493 FirstReachableB = &*AB;
5494 } else {
5495 // We've encountered a branch. It's not a linear CFG.
5496 return false;
5497 }
5498 }
5499
5500 if (!FirstReachableB) {
5501 // We reached a dead end. EXIT is unreachable. This is linear enough.
5502 return true;
5503 }
5504
5505 // There's only one way to move forward. Proceed.
5506 B = FirstReachableB;
5507 }
5508
5509 // We reached EXIT and found no branches.
5510 return true;
5511}
5512
5513const CXXDestructorDecl *
5515 switch (getKind()) {
5527 llvm_unreachable("getDestructorDecl should only be used with "
5528 "ImplicitDtors");
5530 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
5531 QualType ty = var->getType();
5532
5533 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
5534 //
5535 // Lifetime-extending constructs are handled here. This works for a single
5536 // temporary in an initializer expression.
5537 if (ty->isReferenceType()) {
5538 if (const Expr *Init = var->getInit()) {
5540 }
5541 }
5542
5543 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
5544 ty = arrayType->getElementType();
5545 }
5546
5547 // The situation when the type of the lifetime-extending reference
5548 // does not correspond to the type of the object is supposed
5549 // to be handled by now. In particular, 'ty' is now the unwrapped
5550 // record type.
5551 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
5552 assert(classDecl);
5553 return classDecl->getDestructor();
5554 }
5556 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
5557 QualType DTy = DE->getDestroyedType();
5558 DTy = DTy.getNonReferenceType();
5559 const CXXRecordDecl *classDecl =
5560 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
5561 return classDecl->getDestructor();
5562 }
5564 const CXXBindTemporaryExpr *bindExpr =
5565 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
5566 const CXXTemporary *temp = bindExpr->getTemporary();
5567 return temp->getDestructor();
5568 }
5570 const FieldDecl *field = castAs<CFGMemberDtor>().getFieldDecl();
5571 QualType ty = field->getType();
5572
5573 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
5574 ty = arrayType->getElementType();
5575 }
5576
5577 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
5578 assert(classDecl);
5579 return classDecl->getDestructor();
5580 }
5582 // Not yet supported.
5583 return nullptr;
5584 }
5585 llvm_unreachable("getKind() returned bogus value");
5586}
5587
5588//===----------------------------------------------------------------------===//
5589// CFGBlock operations.
5590//===----------------------------------------------------------------------===//
5591
5593 : ReachableBlock(IsReachable ? B : nullptr),
5594 UnreachableBlock(!IsReachable ? B : nullptr,
5595 B && IsReachable ? AB_Normal : AB_Unreachable) {}
5596
5598 : ReachableBlock(B),
5599 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
5600 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
5601
5604 if (CFGBlock *B = Succ.getReachableBlock())
5605 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
5606
5607 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
5608 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
5609
5610 Succs.push_back(Succ, C);
5611}
5612
5614 const CFGBlock *From, const CFGBlock *To) {
5615 if (F.IgnoreNullPredecessors && !From)
5616 return true;
5617
5618 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
5619 // If the 'To' has no label or is labeled but the label isn't a
5620 // CaseStmt then filter this edge.
5621 if (const SwitchStmt *S =
5622 dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) {
5623 if (S->isAllEnumCasesCovered()) {
5624 const Stmt *L = To->getLabel();
5625 if (!L || !isa<CaseStmt>(L))
5626 return true;
5627 }
5628 }
5629 }
5630
5631 return false;
5632}
5633
5634//===----------------------------------------------------------------------===//
5635// CFG pretty printing
5636//===----------------------------------------------------------------------===//
5637
5638namespace {
5639
5640class StmtPrinterHelper : public PrinterHelper {
5641 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
5642 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
5643
5644 StmtMapTy StmtMap;
5645 DeclMapTy DeclMap;
5646 signed currentBlock = 0;
5647 unsigned currStmt = 0;
5648 const LangOptions &LangOpts;
5649
5650public:
5651 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
5652 : LangOpts(LO) {
5653 if (!cfg)
5654 return;
5655 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
5656 unsigned j = 1;
5657 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
5658 BI != BEnd; ++BI, ++j ) {
5659 if (std::optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
5660 const Stmt *stmt= SE->getStmt();
5661 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
5662 StmtMap[stmt] = P;
5663
5664 switch (stmt->getStmtClass()) {
5665 case Stmt::DeclStmtClass:
5666 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
5667 break;
5668 case Stmt::IfStmtClass: {
5669 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
5670 if (var)
5671 DeclMap[var] = P;
5672 break;
5673 }
5674 case Stmt::ForStmtClass: {
5675 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
5676 if (var)
5677 DeclMap[var] = P;
5678 break;
5679 }
5680 case Stmt::WhileStmtClass: {
5681 const VarDecl *var =
5682 cast<WhileStmt>(stmt)->getConditionVariable();
5683 if (var)
5684 DeclMap[var] = P;
5685 break;
5686 }
5687 case Stmt::SwitchStmtClass: {
5688 const VarDecl *var =
5689 cast<SwitchStmt>(stmt)->getConditionVariable();
5690 if (var)
5691 DeclMap[var] = P;
5692 break;
5693 }
5694 case Stmt::CXXCatchStmtClass: {
5695 const VarDecl *var =
5696 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
5697 if (var)
5698 DeclMap[var] = P;
5699 break;
5700 }
5701 default:
5702 break;
5703 }
5704 }
5705 }
5706 }
5707 }
5708
5709 ~StmtPrinterHelper() override = default;
5710
5711 const LangOptions &getLangOpts() const { return LangOpts; }
5712 void setBlockID(signed i) { currentBlock = i; }
5713 void setStmtID(unsigned i) { currStmt = i; }
5714
5715 bool handledStmt(Stmt *S, raw_ostream &OS) override {
5716 StmtMapTy::iterator I = StmtMap.find(S);
5717
5718 if (I == StmtMap.end())
5719 return false;
5720
5721 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5722 && I->second.second == currStmt) {
5723 return false;
5724 }
5725
5726 OS << "[B" << I->second.first << "." << I->second.second << "]";
5727 return true;
5728 }
5729
5730 bool handleDecl(const Decl *D, raw_ostream &OS) {
5731 DeclMapTy::iterator I = DeclMap.find(D);
5732
5733 if (I == DeclMap.end()) {
5734 // ParmVarDecls are not declared in the CFG itself, so they do not appear
5735 // in DeclMap.
5736 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(D)) {
5737 OS << "[Parm: " << PVD->getNameAsString() << "]";
5738 return true;
5739 }
5740 return false;
5741 }
5742
5743 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5744 && I->second.second == currStmt) {
5745 return false;
5746 }
5747
5748 OS << "[B" << I->second.first << "." << I->second.second << "]";
5749 return true;
5750 }
5751};
5752
5753class CFGBlockTerminatorPrint
5754 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
5755 raw_ostream &OS;
5756 StmtPrinterHelper* Helper;
5757 PrintingPolicy Policy;
5758
5759public:
5760 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
5761 const PrintingPolicy &Policy)
5762 : OS(os), Helper(helper), Policy(Policy) {
5763 this->Policy.IncludeNewlines = false;
5764 }
5765
5766 void VisitIfStmt(IfStmt *I) {
5767 OS << "if ";
5768 if (Stmt *C = I->getCond())
5769 C->printPretty(OS, Helper, Policy);
5770 }
5771
5772 // Default case.
5773 void VisitStmt(Stmt *Terminator) {
5774 Terminator->printPretty(OS, Helper, Policy);
5775 }
5776
5777 void VisitDeclStmt(DeclStmt *DS) {
5778 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
5779 OS << "static init " << VD->getName();
5780 }
5781
5782 void VisitForStmt(ForStmt *F) {
5783 OS << "for (" ;
5784 if (F->getInit())
5785 OS << "...";
5786 OS << "; ";
5787 if (Stmt *C = F->getCond())
5788 C->printPretty(OS, Helper, Policy);
5789 OS << "; ";
5790 if (F->getInc())
5791 OS << "...";
5792 OS << ")";
5793 }
5794
5795 void VisitWhileStmt(WhileStmt *W) {
5796 OS << "while " ;
5797 if (Stmt *C = W->getCond())
5798 C->printPretty(OS, Helper, Policy);
5799 }
5800
5801 void VisitDoStmt(DoStmt *D) {
5802 OS << "do ... while ";
5803 if (Stmt *C = D->getCond())
5804 C->printPretty(OS, Helper, Policy);
5805 }
5806
5807 void VisitSwitchStmt(SwitchStmt *Terminator) {
5808 OS << "switch ";
5809 Terminator->getCond()->printPretty(OS, Helper, Policy);
5810 }
5811
5812 void VisitCXXTryStmt(CXXTryStmt *) { OS << "try ..."; }
5813
5814 void VisitObjCAtTryStmt(ObjCAtTryStmt *) { OS << "@try ..."; }
5815
5816 void VisitSEHTryStmt(SEHTryStmt *CS) { OS << "__try ..."; }
5817
5818 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
5819 if (Stmt *Cond = C->getCond())
5820 Cond->printPretty(OS, Helper, Policy);
5821 OS << " ? ... : ...";
5822 }
5823
5824 void VisitChooseExpr(ChooseExpr *C) {
5825 OS << "__builtin_choose_expr( ";
5826 if (Stmt *Cond = C->getCond())
5827 Cond->printPretty(OS, Helper, Policy);
5828 OS << " )";
5829 }
5830
5831 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
5832 OS << "goto *";
5833 if (Stmt *T = I->getTarget())
5834 T->printPretty(OS, Helper, Policy);
5835 }
5836
5837 void VisitBinaryOperator(BinaryOperator* B) {
5838 if (!B->isLogicalOp()) {
5839 VisitExpr(B);
5840 return;
5841 }
5842
5843 if (B->getLHS())
5844 B->getLHS()->printPretty(OS, Helper, Policy);
5845
5846 switch (B->getOpcode()) {
5847 case BO_LOr:
5848 OS << " || ...";
5849 return;
5850 case BO_LAnd:
5851 OS << " && ...";
5852 return;
5853 default:
5854 llvm_unreachable("Invalid logical operator.");
5855 }
5856 }
5857
5858 void VisitExpr(Expr *E) {
5859 E->printPretty(OS, Helper, Policy);
5860 }
5861
5862public:
5863 void print(CFGTerminator T) {
5864 switch (T.getKind()) {
5866 Visit(T.getStmt());
5867 break;
5869 OS << "(Temp Dtor) ";
5870 Visit(T.getStmt());
5871 break;
5873 OS << "(See if most derived ctor has already initialized vbases)";
5874 break;
5875 }
5876 }
5877};
5878
5879} // namespace
5880
5881static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
5882 const CXXCtorInitializer *I) {
5883 if (I->isBaseInitializer())
5884 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
5885 else if (I->isDelegatingInitializer())
5887 else
5888 OS << I->getAnyMember()->getName();
5889 OS << "(";
5890 if (Expr *IE = I->getInit())
5891 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5892 OS << ")";
5893
5894 if (I->isBaseInitializer())
5895 OS << " (Base initializer)";
5896 else if (I->isDelegatingInitializer())
5897 OS << " (Delegating initializer)";
5898 else
5899 OS << " (Member initializer)";
5900}
5901
5902static void print_construction_context(raw_ostream &OS,
5903 StmtPrinterHelper &Helper,
5904 const ConstructionContext *CC) {
5906 switch (CC->getKind()) {
5908 OS << ", ";
5910 print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
5911 return;
5912 }
5914 OS << ", ";
5915 const auto *CICC =
5917 print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
5918 Stmts.push_back(CICC->getCXXBindTemporaryExpr());
5919 break;
5920 }
5922 const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
5923 Stmts.push_back(SDSCC->getDeclStmt());
5924 break;
5925 }
5928 Stmts.push_back(CDSCC->getDeclStmt());
5929 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
5930 break;
5931 }
5933 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
5934 Stmts.push_back(NECC->getCXXNewExpr());
5935 break;
5936 }
5938 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
5939 Stmts.push_back(RSCC->getReturnStmt());
5940 break;
5941 }
5943 const auto *RSCC =
5945 Stmts.push_back(RSCC->getReturnStmt());
5946 Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
5947 break;
5948 }
5951 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5952 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5953 break;
5954 }
5957 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5958 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5959 Stmts.push_back(TOCC->getConstructorAfterElision());
5960 break;
5961 }
5963 const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
5964 Helper.handledStmt(const_cast<LambdaExpr *>(LCC->getLambdaExpr()), OS);
5965 OS << "+" << LCC->getIndex();
5966 return;
5967 }
5969 const auto *ACC = cast<ArgumentConstructionContext>(CC);
5970 if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
5971 OS << ", ";
5972 Helper.handledStmt(const_cast<Stmt *>(BTE), OS);
5973 }
5974 OS << ", ";
5975 Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
5976 OS << "+" << ACC->getIndex();
5977 return;
5978 }
5979 }
5980 for (auto I: Stmts)
5981 if (I) {
5982 OS << ", ";
5983 Helper.handledStmt(const_cast<Stmt *>(I), OS);
5984 }
5985}
5986
5987static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5988 const CFGElement &E, bool TerminateWithNewLine = true);
5989
5990void CFGElement::dumpToStream(llvm::raw_ostream &OS,
5991 bool TerminateWithNewLine) const {
5992 LangOptions LangOpts;
5993 StmtPrinterHelper Helper(nullptr, LangOpts);
5994 print_elem(OS, Helper, *this, TerminateWithNewLine);
5995}
5996
5997static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5998 const CFGElement &E, bool TerminateWithNewLine) {
5999 switch (E.getKind()) {
6003 CFGStmt CS = E.castAs<CFGStmt>();
6004 const Stmt *S = CS.getStmt();
6005 assert(S != nullptr && "Expecting non-null Stmt");
6006
6007 // special printing for statement-expressions.
6008 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
6009 const CompoundStmt *Sub = SE->getSubStmt();
6010
6011 auto Children = Sub->children();
6012 if (Children.begin() != Children.end()) {
6013 OS << "({ ... ; ";
6014 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
6015 OS << " })";
6016 if (TerminateWithNewLine)
6017 OS << '\n';
6018 return;
6019 }
6020 }
6021 // special printing for comma expressions.
6022 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
6023 if (B->getOpcode() == BO_Comma) {
6024 OS << "... , ";
6025 Helper.handledStmt(B->getRHS(),OS);
6026 if (TerminateWithNewLine)
6027 OS << '\n';
6028 return;
6029 }
6030 }
6031 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
6032
6033 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
6035 OS << " (OperatorCall)";
6036 OS << " (CXXRecordTypedCall";
6037 print_construction_context(OS, Helper, VTC->getConstructionContext());
6038 OS << ")";
6039 } else if (isa<CXXOperatorCallExpr>(S)) {
6040 OS << " (OperatorCall)";
6041 } else if (isa<CXXBindTemporaryExpr>(S)) {
6042 OS << " (BindTemporary)";
6043 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
6044 OS << " (CXXConstructExpr";
6045 if (std::optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
6046 print_construction_context(OS, Helper, CE->getConstructionContext());
6047 }
6048 OS << ", " << CCE->getType() << ")";
6049 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
6050 OS << " (" << CE->getStmtClassName() << ", " << CE->getCastKindName()
6051 << ", " << CE->getType() << ")";
6052 }
6053
6054 // Expressions need a newline.
6055 if (isa<Expr>(S) && TerminateWithNewLine)
6056 OS << '\n';
6057
6058 return;
6059 }
6060
6063 break;
6064
6067 const VarDecl *VD = DE.getVarDecl();
6068 Helper.handleDecl(VD, OS);
6069
6070 QualType T = VD->getType();
6071 if (T->isReferenceType())
6072 T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
6073
6074 OS << ".~";
6075 T.getUnqualifiedType().print(OS, PrintingPolicy(Helper.getLangOpts()));
6076 OS << "() (Implicit destructor)";
6077 break;
6078 }
6079
6081 OS << "CleanupFunction ("
6082 << E.castAs<CFGCleanupFunction>().getFunctionDecl()->getName() << ")";
6083 break;
6084
6086 Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS);
6087 OS << " (Lifetime ends)";
6088 break;
6089
6091 auto MTEs = E.castAs<CFGFullExprCleanup>().getExpiringMTEs();
6092 size_t MTECount = MTEs.size();
6093 OS << "(FullExprCleanup collected " << MTECount
6094 << (MTECount > 1 ? " MTEs: " : " MTE: ");
6095 bool FirstMTE = true;
6096 for (const MaterializeTemporaryExpr *MTE : MTEs) {
6097 if (!FirstMTE)
6098 OS << ", ";
6099 if (!Helper.handledStmt(MTE->getSubExpr(), OS)) {
6100 PrintingPolicy Policy{Helper.getLangOpts()};
6101 Policy.IncludeNewlines = false;
6102 // Pretty print the sub-expresion as a fallback
6103 MTE->printPretty(OS, &Helper, Policy);
6104 }
6105 FirstMTE = false;
6106 }
6107 OS << ")";
6108 break;
6109 }
6110
6112 OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName()
6113 << " (LoopExit)";
6114 break;
6115
6117 OS << "CFGScopeBegin(";
6118 if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl())
6119 OS << VD->getQualifiedNameAsString();
6120 OS << ")";
6121 break;
6122
6124 OS << "CFGScopeEnd(";
6125 if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl())
6126 OS << VD->getQualifiedNameAsString();
6127 OS << ")";
6128 break;
6129
6131 OS << "CFGNewAllocator(";
6132 if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr())
6133 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
6134 OS << ")";
6135 break;
6136
6139 const CXXRecordDecl *RD = DE.getCXXRecordDecl();
6140 if (!RD)
6141 return;
6142 CXXDeleteExpr *DelExpr =
6143 const_cast<CXXDeleteExpr*>(DE.getDeleteExpr());
6144 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
6145 OS << "->~" << RD->getName().str() << "()";
6146 OS << " (Implicit destructor)";
6147 break;
6148 }
6149
6151 const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier();
6152 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
6153 OS << " (Base object destructor)";
6154 break;
6155 }
6156
6158 const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl();
6159 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
6160 OS << "this->" << FD->getName();
6161 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
6162 OS << " (Member object destructor)";
6163 break;
6164 }
6165
6167 const CXXBindTemporaryExpr *BT =
6168 E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
6169 OS << "~";
6170 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
6171 OS << "() (Temporary object destructor)";
6172 break;
6173 }
6174 }
6175 if (TerminateWithNewLine)
6176 OS << '\n';
6177}
6178
6179static void print_block(raw_ostream &OS, const CFG* cfg,
6180 const CFGBlock &B,
6181 StmtPrinterHelper &Helper, bool print_edges,
6182 bool ShowColors) {
6183 Helper.setBlockID(B.getBlockID());
6184
6185 // Print the header.
6186 if (ShowColors)
6187 OS.changeColor(raw_ostream::YELLOW, true);
6188
6189 OS << "\n [B" << B.getBlockID();
6190
6191 if (&B == &cfg->getEntry())
6192 OS << " (ENTRY)]\n";
6193 else if (&B == &cfg->getExit())
6194 OS << " (EXIT)]\n";
6195 else if (&B == cfg->getIndirectGotoBlock())
6196 OS << " (INDIRECT GOTO DISPATCH)]\n";
6197 else if (B.hasNoReturnElement())
6198 OS << " (NORETURN)]\n";
6199 else
6200 OS << "]\n";
6201
6202 if (ShowColors)
6203 OS.resetColor();
6204
6205 // Print the label of this block.
6206 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
6207 if (print_edges)
6208 OS << " ";
6209
6210 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
6211 OS << L->getName();
6212 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
6213 OS << "case ";
6214 if (const Expr *LHS = C->getLHS())
6215 LHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
6216 if (const Expr *RHS = C->getRHS()) {
6217 OS << " ... ";
6218 RHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
6219 }
6220 } else if (isa<DefaultStmt>(Label))
6221 OS << "default";
6222 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
6223 OS << "catch (";
6224 if (const VarDecl *ED = CS->getExceptionDecl())
6225 ED->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
6226 else
6227 OS << "...";
6228 OS << ")";
6229 } else if (ObjCAtCatchStmt *CS = dyn_cast<ObjCAtCatchStmt>(Label)) {
6230 OS << "@catch (";
6231 if (const VarDecl *PD = CS->getCatchParamDecl())
6232 PD->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
6233 else
6234 OS << "...";
6235 OS << ")";
6236 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
6237 OS << "__except (";
6238 ES->getFilterExpr()->printPretty(OS, &Helper,
6239 PrintingPolicy(Helper.getLangOpts()), 0);
6240 OS << ")";
6241 } else
6242 llvm_unreachable("Invalid label statement in CFGBlock.");
6243
6244 OS << ":\n";
6245 }
6246
6247 // Iterate through the statements in the block and print them.
6248 unsigned j = 1;
6249
6250 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
6251 I != E ; ++I, ++j ) {
6252 // Print the statement # in the basic block and the statement itself.
6253 if (print_edges)
6254 OS << " ";
6255
6256 OS << llvm::format("%3d", j) << ": ";
6257
6258 Helper.setStmtID(j);
6259
6260 print_elem(OS, Helper, *I);
6261 }
6262
6263 // Print the terminator of this block.
6264 if (B.getTerminator().isValid()) {
6265 if (ShowColors)
6266 OS.changeColor(raw_ostream::GREEN);
6267
6268 OS << " T: ";
6269
6270 Helper.setBlockID(-1);
6271
6272 PrintingPolicy PP(Helper.getLangOpts());
6273 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
6274 TPrinter.print(B.getTerminator());
6275 OS << '\n';
6276
6277 if (ShowColors)
6278 OS.resetColor();
6279 }
6280
6281 if (print_edges) {
6282 // Print the predecessors of this block.
6283 if (!B.pred_empty()) {
6284 const raw_ostream::Colors Color = raw_ostream::BLUE;
6285 if (ShowColors)
6286 OS.changeColor(Color);
6287 OS << " Preds " ;
6288 if (ShowColors)
6289 OS.resetColor();
6290 OS << '(' << B.pred_size() << "):";
6291 unsigned i = 0;
6292
6293 if (ShowColors)
6294 OS.changeColor(Color);
6295
6297 I != E; ++I, ++i) {
6298 if (i % 10 == 8)
6299 OS << "\n ";
6300
6301 CFGBlock *B = *I;
6302 bool Reachable = true;
6303 if (!B) {
6304 Reachable = false;
6305 B = I->getPossiblyUnreachableBlock();
6306 }
6307
6308 OS << " B" << B->getBlockID();
6309 if (!Reachable)
6310 OS << "(Unreachable)";
6311 }
6312
6313 if (ShowColors)
6314 OS.resetColor();
6315
6316 OS << '\n';
6317 }
6318
6319 // Print the successors of this block.
6320 if (!B.succ_empty()) {
6321 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
6322 if (ShowColors)
6323 OS.changeColor(Color);
6324 OS << " Succs ";
6325 if (ShowColors)
6326 OS.resetColor();
6327 OS << '(' << B.succ_size() << "):";
6328 unsigned i = 0;
6329
6330 if (ShowColors)
6331 OS.changeColor(Color);
6332
6334 I != E; ++I, ++i) {
6335 if (i % 10 == 8)
6336 OS << "\n ";
6337
6338 CFGBlock *B = *I;
6339
6340 bool Reachable = true;
6341 if (!B) {
6342 Reachable = false;
6343 B = I->getPossiblyUnreachableBlock();
6344 }
6345
6346 if (B) {
6347 OS << " B" << B->getBlockID();
6348 if (!Reachable)
6349 OS << "(Unreachable)";
6350 }
6351 else {
6352 OS << " NULL";
6353 }
6354 }
6355
6356 if (ShowColors)
6357 OS.resetColor();
6358 OS << '\n';
6359 }
6360 }
6361}
6362
6363/// dump - A simple pretty printer of a CFG that outputs to stderr.
6364void CFG::dump(const LangOptions &LO, bool ShowColors) const {
6365 print(llvm::errs(), LO, ShowColors);
6366}
6367
6368/// print - A simple pretty printer of a CFG that outputs to an ostream.
6369void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
6370 StmtPrinterHelper Helper(this, LO);
6371
6372 // Print the entry block.
6373 print_block(OS, this, getEntry(), Helper, true, ShowColors);
6374
6375 // Iterate through the CFGBlocks and print them one by one.
6376 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
6377 // Skip the entry block, because we already printed it.
6378 if (&(**I) == &getEntry() || &(**I) == &getExit())
6379 continue;
6380
6381 print_block(OS, this, **I, Helper, true, ShowColors);
6382 }
6383
6384 // Print the exit block.
6385 print_block(OS, this, getExit(), Helper, true, ShowColors);
6386 OS << '\n';
6387 OS.flush();
6388}
6389
6391 return llvm::find(*getParent(), this) - getParent()->begin();
6392}
6393
6394/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
6395void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
6396 bool ShowColors) const {
6397 print(llvm::errs(), cfg, LO, ShowColors);
6398}
6399
6400LLVM_DUMP_METHOD void CFGBlock::dump() const {
6401 dump(getParent(), LangOptions(), false);
6402}
6403
6404/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
6405/// Generally this will only be called from CFG::print.
6406void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
6407 const LangOptions &LO, bool ShowColors) const {
6408 StmtPrinterHelper Helper(cfg, LO);
6409 print_block(OS, cfg, *this, Helper, true, ShowColors);
6410 OS << '\n';
6411}
6412
6413/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
6414void CFGBlock::printTerminator(raw_ostream &OS,
6415 const LangOptions &LO) const {
6416 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
6417 TPrinter.print(getTerminator());
6418}
6419
6420/// printTerminatorJson - Pretty-prints the terminator in JSON format.
6421void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
6422 bool AddQuotes) const {
6423 std::string Buf;
6424 llvm::raw_string_ostream TempOut(Buf);
6425
6426 printTerminator(TempOut, LO);
6427
6428 Out << JsonFormat(Buf, AddQuotes);
6429}
6430
6431// Returns true if by simply looking at the block, we can be sure that it
6432// results in a sink during analysis. This is useful to know when the analysis
6433// was interrupted, and we try to figure out if it would sink eventually.
6434// There may be many more reasons why a sink would appear during analysis
6435// (eg. checkers may generate sinks arbitrarily), but here we only consider
6436// sinks that would be obvious by looking at the CFG.
6437static bool isImmediateSinkBlock(const CFGBlock *Blk) {
6438 if (Blk->hasNoReturnElement())
6439 return true;
6440
6441 // FIXME: Throw-expressions are currently generating sinks during analysis:
6442 // they're not supported yet, and also often used for actually terminating
6443 // the program. So we should treat them as sinks in this analysis as well,
6444 // at least for now, but once we have better support for exceptions,
6445 // we'd need to carefully handle the case when the throw is being
6446 // immediately caught.
6447 if (llvm::any_of(*Blk, [](const CFGElement &Elm) {
6448 if (std::optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
6449 if (isa<CXXThrowExpr>(StmtElm->getStmt()))
6450 return true;
6451 return false;
6452 }))
6453 return true;
6454
6455 return false;
6456}
6457
6459 const CFG &Cfg = *getParent();
6460
6461 const CFGBlock *StartBlk = this;
6462 if (isImmediateSinkBlock(StartBlk))
6463 return true;
6464
6467
6468 DFSWorkList.push_back(StartBlk);
6469 while (!DFSWorkList.empty()) {
6470 const CFGBlock *Blk = DFSWorkList.pop_back_val();
6471 Visited.insert(Blk);
6472
6473 // If at least one path reaches the CFG exit, it means that control is
6474 // returned to the caller. For now, say that we are not sure what
6475 // happens next. If necessary, this can be improved to analyze
6476 // the parent StackFrame's call site in a similar manner.
6477 if (Blk == &Cfg.getExit())
6478 return false;
6479
6480 for (const auto &Succ : Blk->succs()) {
6481 if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
6482 if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
6483 // If the block has reachable child blocks that aren't no-return,
6484 // add them to the worklist.
6485 DFSWorkList.push_back(SuccBlk);
6486 }
6487 }
6488 }
6489 }
6490
6491 // Nothing reached the exit. It can only mean one thing: there's no return.
6492 return true;
6493}
6494
6496 // If the terminator is a temporary dtor or a virtual base, etc, we can't
6497 // retrieve a meaningful condition, bail out.
6498 if (Terminator.getKind() != CFGTerminator::StmtBranch)
6499 return nullptr;
6500
6501 // Also, if this method was called on a block that doesn't have 2 successors,
6502 // this block doesn't have retrievable condition.
6503 if (succ_size() < 2)
6504 return nullptr;
6505
6506 // FIXME: Is there a better condition expression we can return in this case?
6507 if (size() == 0)
6508 return nullptr;
6509
6510 auto StmtElem = rbegin()->getAs<CFGStmt>();
6511 if (!StmtElem)
6512 return nullptr;
6513
6514 const Stmt *Cond = StmtElem->getStmt();
6516 return nullptr;
6517
6518 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
6519 // the cast<>.
6520 return cast<Expr>(Cond)->IgnoreParens();
6521}
6522
6523const Stmt *CFGBlock::getTerminatorCondition(bool StripParens) const {
6525 if (!Terminator)
6526 return nullptr;
6527
6528 const Expr *E = nullptr;
6529
6530 switch (Terminator->getStmtClass()) {
6531 default:
6532 break;
6533
6534 case Stmt::CXXForRangeStmtClass:
6535 E = cast<CXXForRangeStmt>(Terminator)->getCond();
6536 break;
6537
6538 case Stmt::ForStmtClass:
6539 E = cast<ForStmt>(Terminator)->getCond();
6540 break;
6541
6542 case Stmt::WhileStmtClass:
6543 E = cast<WhileStmt>(Terminator)->getCond();
6544 break;
6545
6546 case Stmt::DoStmtClass:
6547 E = cast<DoStmt>(Terminator)->getCond();
6548 break;
6549
6550 case Stmt::IfStmtClass:
6551 E = cast<IfStmt>(Terminator)->getCond();
6552 break;
6553
6554 case Stmt::ChooseExprClass:
6555 E = cast<ChooseExpr>(Terminator)->getCond();
6556 break;
6557
6558 case Stmt::IndirectGotoStmtClass:
6559 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
6560 break;
6561
6562 case Stmt::SwitchStmtClass:
6563 E = cast<SwitchStmt>(Terminator)->getCond();
6564 break;
6565
6566 case Stmt::BinaryConditionalOperatorClass:
6568 break;
6569
6570 case Stmt::ConditionalOperatorClass:
6571 E = cast<ConditionalOperator>(Terminator)->getCond();
6572 break;
6573
6574 case Stmt::BinaryOperatorClass: // '&&' and '||'
6575 E = cast<BinaryOperator>(Terminator)->getLHS();
6576 break;
6577
6578 case Stmt::ObjCForCollectionStmtClass:
6579 return Terminator;
6580 }
6581
6582 if (!StripParens)
6583 return E;
6584
6585 return E ? E->IgnoreParens() : nullptr;
6586}
6587
6588//===----------------------------------------------------------------------===//
6589// CFG Graphviz Visualization
6590//===----------------------------------------------------------------------===//
6591
6592static StmtPrinterHelper *GraphHelper;
6593
6594void CFG::viewCFG(const LangOptions &LO) const {
6595 StmtPrinterHelper H(this, LO);
6596 GraphHelper = &H;
6597 llvm::ViewGraph(this,"CFG");
6598 GraphHelper = nullptr;
6599}
6600
6601namespace llvm {
6602
6603template<>
6605 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
6606
6607 static std::string getNodeLabel(const CFGBlock *Node, const CFG *Graph) {
6608 std::string OutStr;
6609 llvm::raw_string_ostream Out(OutStr);
6610 print_block(Out,Graph, *Node, *GraphHelper, false, false);
6611
6612 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
6613
6614 // Process string output to make it nicer...
6615 for (unsigned i = 0; i != OutStr.length(); ++i)
6616 if (OutStr[i] == '\n') { // Left justify
6617 OutStr[i] = '\\';
6618 OutStr.insert(OutStr.begin()+i+1, 'l');
6619 }
6620
6621 return OutStr;
6622 }
6623};
6624
6625} // namespace llvm
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static StmtPrinterHelper * GraphHelper
Definition CFG.cpp:6592
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:5997
static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper, const CXXCtorInitializer *I)
Definition CFG.cpp:5881
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:6179
static bool isImmediateSinkBlock(const CFGBlock *Blk)
Definition CFG.cpp:6437
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:5902
static bool shouldAddCase(bool &switchExclusivelyCovered, const Expr::EvalResult *switchCond, const CaseStmt *CS, ASTContext &Ctx)
Definition CFG.cpp:4632
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:965
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:4537
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4543
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4549
LabelDecl * getLabel() const
Definition Expr.h:4579
Represents a loop initializing the elements of an array.
Definition Expr.h:5980
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5995
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6000
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3821
Represents an attribute applied to a statement.
Definition Stmt.h:2212
Stmt * getSubStmt()
Definition Stmt.h:2248
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2244
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition Expr.h:4497
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition Expr.h:4494
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4177
Expr * getLHS() const
Definition Expr.h:4094
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4138
static bool isCommaOp(Opcode Opc)
Definition Expr.h:4147
Expr * getRHS() const
Definition Expr.h:4096
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4180
Opcode getOpcode() const
Definition Expr.h:4089
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4141
ArrayRef< Capture > captures() const
Definition Decl.h:4843
const BlockDecl * getBlockDecl() const
Definition Expr.h:6696
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:5592
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:6414
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:6458
pred_iterator pred_end()
Definition CFG.h:1020
size_t getIndexInCFG() const
Definition CFG.cpp:6390
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:5613
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:6406
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:6421
succ_range succs()
Definition CFG.h:1047
void dump() const
Definition CFG.cpp:6400
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:6523
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:6495
void addSuccessor(AdjacentBlock Succ, BumpVectorContext &C)
Adds a (potentially unreachable) successor block to the current block.
Definition CFG.cpp:5602
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:5990
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:5514
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:6369
iterator end()
Definition CFG.h:1358
bool isLinear() const
Returns true if the CFG has no branches.
Definition CFG.cpp:5468
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:5461
llvm::BumpPtrAllocator & getAllocator()
Definition CFG.h:1491
CFGBlock * createBlock()
Create a new block in the CFG.
Definition CFG.cpp:5445
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:6364
void viewCFG(const LangOptions &LO) const
Definition CFG.cpp:6594
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:1496
CXXTemporary * getTemporary()
Definition ExprCXX.h:1514
const Expr * getSubExpr() const
Definition ExprCXX.h:1518
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:1551
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1614
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
bool isDelegatingInitializer() const
Determine whether this initializer is creating a delegating constructor.
Definition DeclCXX.h:2498
Expr * getInit() const
Get the initializer.
Definition DeclCXX.h:2600
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition DeclCXX.h:2532
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition DeclCXX.h:2470
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:2544
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2629
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition ExprCXX.cpp:343
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
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:2284
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2358
ExprIterator arg_iterator
Definition ExprCXX.h:2572
static bool isAssignmentOp(OverloadedOperatorKind Opc)
Definition ExprCXX.h:119
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:1377
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:1557
Represents a C++ temporary.
Definition ExprCXX.h:1462
const CXXDestructorDecl * getDestructor() const
Definition ExprCXX.h:1473
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:134
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1598
CaseStmt - Represent a case statement.
Definition Stmt.h:1929
Stmt * getSubStmt()
Definition Stmt.h:2042
Expr * getLHS()
Definition Stmt.h:2012
Expr * getRHS()
Definition Stmt.h:2024
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
CastKind getCastKind() const
Definition Expr.h:3726
Expr * getSubExpr()
Definition Expr.h:3732
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1749
reverse_body_iterator body_rbegin()
Definition Stmt.h:1844
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:5310
Expr * getResumeExpr() const
Definition ExprCXX.h:5318
Expr * getSuspendExpr() const
Definition ExprCXX.h:5314
Expr * getCommonExpr() const
Definition ExprCXX.h:5303
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:1699
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition Stmt.h:1653
decl_iterator decl_begin()
Definition Stmt.h:1694
decl_range decls()
Definition Stmt.h:1688
const Decl * getSingleDecl() const
Definition Stmt.h:1655
reverse_decl_iterator decl_rend()
Definition Stmt.h:1705
reverse_decl_iterator decl_rbegin()
Definition Stmt.h:1701
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:2090
Stmt * getBody()
Definition Stmt.h:2866
Expr * getCond()
Definition Stmt.h:2859
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3660
This represents one expression.
Definition Expr.h:112
bool isGLValue() const
Definition Expr.h:287
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3057
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3101
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
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:3699
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:4332
QualType getType() const
Definition Expr.h:144
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:138
Represents a member of a struct/union/class.
Definition Decl.h:3204
Stmt * getInit()
Definition Stmt.h:2912
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2941
Expr * getInc()
Definition Stmt.h:2940
Expr * getCond()
Definition Stmt.h:2939
DeclStmt * getConditionVariableDeclStmt()
If this ForStmt has a condition variable, return the faux DeclStmt associated with the creation of th...
Definition Stmt.h:2927
const Expr * getSubExpr() const
Definition Expr.h:1068
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5406
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4602
bool isAsmGoto() const
Definition Stmt.h:3601
LabelDecl * getLabel() const
Definition Stmt.h:2991
Stmt * getThen()
Definition Stmt.h:2357
Stmt * getInit()
Definition Stmt.h:2418
Expr * getCond()
Definition Stmt.h:2345
Stmt * getElse()
Definition Stmt.h:2366
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition Stmt.h:2401
bool isConsteval() const
Definition Stmt.h:2448
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
unsigned getNumInits() const
Definition Expr.h:5347
Expr ** getInits()
Retrieve the set of initializers.
Definition Expr.h:5360
LabelStmt - Represents a label, which has a substatement.
Definition Stmt.h:2155
LabelDecl * getDecl() const
Definition Stmt.h:2173
Stmt * getSubStmt()
Definition Stmt.h:2177
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:1971
unsigned capture_size() const
Determine the number of captures in this lambda.
Definition ExprCXX.h:2052
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2086
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:4919
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4944
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4936
Expr * getBase() const
Definition Expr.h:3447
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1683
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:1234
unsigned getNumSemanticExprs() const
Definition Expr.h:6873
Expr * getSemanticExpr(unsigned index)
Definition Expr.h:6895
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:8489
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:8674
field_range fields() const
Definition Decl.h:4572
CompoundStmt * getBlock() const
Definition Stmt.h:3802
Expr * getFilterExpr() const
Definition Stmt.h:3798
CompoundStmt * getBlock() const
Definition Stmt.h:3839
CompoundStmt * getTryBlock() const
Definition Stmt.h:3883
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:4601
CompoundStmt * getSubStmt()
Definition Expr.h:4618
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:1502
const char * getStmtClassName() const
Definition Stmt.cpp:86
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2518
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:2678
Expr * getCond()
Definition Stmt.h:2581
Stmt * getBody()
Definition Stmt.h:2593
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2598
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2649
DeclStmt * getConditionVariableDeclStmt()
If this SwitchStmt has a condition variable, return the faux DeclStmt associated with the creation of...
Definition Stmt.h:2632
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3862
bool isUnion() const
Definition Decl.h:3972
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8471
The base class of the type hierarchy.
Definition TypeBase.h:1876
bool isBlockPointerType() const
Definition TypeBase.h:8746
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:8793
bool isReferenceType() const
Definition TypeBase.h:8750
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:9272
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2865
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:2336
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
QualType getArgumentType() const
Definition Expr.h:2674
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2663
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:932
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1214
const Expr * getInit() const
Definition Decl.h:1391
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1190
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4065
Expr * getCond()
Definition Stmt.h:2758
DeclStmt * getConditionVariableDeclStmt()
If this WhileStmt has a condition variable, return the faux DeclStmt associated with the creation of ...
Definition Stmt.h:2794
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2770
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:436
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1511
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1525
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2820
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8624
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',...
Expr * Cond
};
@ Default
Set to the current date and time.
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:341
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:563
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:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
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:6605
static std::string getNodeLabel(const CFGBlock *Node, const CFG *Graph)
Definition CFG.cpp:6607