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