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