blob: 80f5a46ceab4745dc4153dbcde8ccc80c93a6e1b [file] [log] [blame]
Eugene Zelenko38c70522017-12-07 21:55:09 +00001//===- CFG.cpp - Classes for representing and building CFGs ---------------===//
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00006//
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
Ted Kremenek6796fbd2009-07-16 18:13:04 +000014#include "clang/Analysis/CFG.h"
Benjamin Kramer1ea8e092012-07-04 17:04:04 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclBase.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/DeclCXX.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000020#include "clang/AST/DeclGroup.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/OperationKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000024#include "clang/AST/PrettyPrinter.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000025#include "clang/AST/Stmt.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "clang/AST/StmtVisitor.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000029#include "clang/AST/Type.h"
Artem Dergachev40684812018-02-27 20:03:35 +000030#include "clang/Analysis/ConstructionContext.h"
Csaba Dabisdea605e2019-05-29 18:29:31 +000031#include "clang/Analysis/Support/BumpVector.h"
Jordan Rose5374c072013-08-19 16:27:28 +000032#include "clang/Basic/Builtins.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000033#include "clang/Basic/ExceptionSpecificationType.h"
Csaba Dabisdea605e2019-05-29 18:29:31 +000034#include "clang/Basic/JsonSupport.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000035#include "clang/Basic/LLVM.h"
36#include "clang/Basic/LangOptions.h"
37#include "clang/Basic/SourceLocation.h"
38#include "clang/Basic/Specifiers.h"
39#include "llvm/ADT/APInt.h"
40#include "llvm/ADT/APSInt.h"
41#include "llvm/ADT/ArrayRef.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000042#include "llvm/ADT/DenseMap.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000043#include "llvm/ADT/Optional.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/SetVector.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000046#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000047#include "llvm/ADT/SmallVector.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000048#include "llvm/Support/Allocator.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000049#include "llvm/Support/Casting.h"
50#include "llvm/Support/Compiler.h"
51#include "llvm/Support/DOTGraphTraits.h"
52#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000053#include "llvm/Support/Format.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000054#include "llvm/Support/GraphWriter.h"
55#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000056#include "llvm/Support/raw_ostream.h"
57#include <cassert>
58#include <memory>
59#include <string>
60#include <tuple>
61#include <utility>
62#include <vector>
Ted Kremeneke5ccf9a2008-01-11 00:40:29 +000063
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +000064using namespace clang;
65
Ted Kremenek5ef32db2011-08-12 23:37:29 +000066static SourceLocation GetEndLoc(Decl *D) {
67 if (VarDecl *VD = dyn_cast<VarDecl>(D))
68 if (Expr *Ex = VD->getInit())
Ted Kremenek8889bb32008-08-06 23:20:50 +000069 return Ex->getSourceRange().getEnd();
Mike Stump31feda52009-07-17 01:31:16 +000070 return D->getLocation();
Ted Kremenek8889bb32008-08-06 23:20:50 +000071}
Ted Kremenekdc03bd02010-08-02 23:46:59 +000072
George Burgess IVced56e62015-10-01 18:47:52 +000073/// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
74/// or EnumConstantDecl from the given Expr. If it fails, returns nullptr.
Eugene Zelenko38c70522017-12-07 21:55:09 +000075static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
George Burgess IVced56e62015-10-01 18:47:52 +000076 E = E->IgnoreParens();
77 if (isa<IntegerLiteral>(E))
78 return E;
79 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
80 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
81 return nullptr;
82}
83
84/// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is
85/// an integer literal or an enum constant.
86///
87/// If this fails, at least one of the returned DeclRefExpr or Expr will be
88/// null.
89static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *>
90tryNormalizeBinaryOperator(const BinaryOperator *B) {
91 BinaryOperatorKind Op = B->getOpcode();
92
93 const Expr *MaybeDecl = B->getLHS();
94 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
95 // Expr looked like `0 == Foo` instead of `Foo == 0`
96 if (Constant == nullptr) {
97 // Flip the operator
98 if (Op == BO_GT)
99 Op = BO_LT;
100 else if (Op == BO_GE)
101 Op = BO_LE;
102 else if (Op == BO_LT)
103 Op = BO_GT;
104 else if (Op == BO_LE)
105 Op = BO_GE;
106
107 MaybeDecl = B->getRHS();
108 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
109 }
110
111 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts());
112 return std::make_tuple(D, Op, Constant);
113}
114
115/// For an expression `x == Foo && x == Bar`, this determines whether the
116/// `Foo` and `Bar` are either of the same enumeration type, or both integer
117/// literals.
118///
119/// It's an error to pass this arguments that are not either IntegerLiterals
120/// or DeclRefExprs (that have decls of type EnumConstantDecl)
121static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
122 // User intent isn't clear if they're mixing int literals with enum
123 // constants.
124 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2))
125 return false;
126
127 // Integer literal comparisons, regardless of literal type, are acceptable.
128 if (isa<IntegerLiteral>(E1))
129 return true;
130
131 // IntegerLiterals are handled above and only EnumConstantDecls are expected
132 // beyond this point
133 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
134 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
135 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
136
137 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
138 const DeclContext *DC1 = Decl1->getDeclContext();
139 const DeclContext *DC2 = Decl2->getDeclContext();
140
141 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
142 return DC1 == DC2;
143}
144
Eugene Zelenko38c70522017-12-07 21:55:09 +0000145namespace {
146
Ted Kremenek7c58d352011-03-10 01:14:11 +0000147class CFGBuilder;
Fangrui Song6907ce22018-07-30 19:24:48 +0000148
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000149/// The CFG builder uses a recursive algorithm to build the CFG. When
150/// we process an expression, sometimes we know that we must add the
151/// subexpressions as block-level expressions. For example:
152///
153/// exp1 || exp2
154///
155/// When processing the '||' expression, we know that exp1 and exp2
156/// need to be added as block-level expressions, even though they
157/// might not normally need to be. AddStmtChoice records this
158/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
159/// the builder has an option not to add a subexpression as a
160/// block-level expression.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000161class AddStmtChoice {
162public:
Ted Kremenek8219b822010-12-16 07:46:53 +0000163 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000164
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000165 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000166
Ted Kremenek7c58d352011-03-10 01:14:11 +0000167 bool alwaysAdd(CFGBuilder &builder,
168 const Stmt *stmt) const;
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000169
170 /// Return a copy of this object, except with the 'always-add' bit
171 /// set as specified.
172 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
Ted Kremenek7c58d352011-03-10 01:14:11 +0000173 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000174 }
175
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000176private:
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000177 Kind kind;
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000178};
Mike Stump31feda52009-07-17 01:31:16 +0000179
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000180/// LocalScope - Node in tree of local scopes created for C++ implicit
181/// destructor calls generation. It contains list of automatic variables
182/// declared in the scope and link to position in previous scope this scope
183/// began in.
184///
185/// The process of creating local scopes is as follows:
186/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
187/// - Before processing statements in scope (e.g. CompoundStmt) create
188/// LocalScope object using CFGBuilder::ScopePos as link to previous scope
189/// and set CFGBuilder::ScopePos to the end of new scope,
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000190/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000191/// at this VarDecl,
192/// - For every normal (without jump) end of scope add to CFGBlock destructors
193/// for objects in the current scope,
194/// - For every jump add to CFGBlock destructors for objects
195/// between CFGBuilder::ScopePos and local scope position saved for jump
196/// target. Thanks to C++ restrictions on goto jumps we can be sure that
197/// jump target position will be on the path to root from CFGBuilder::ScopePos
198/// (adding any variable that doesn't need constructor to be called to
199/// LocalScope can break this assumption),
200///
201class LocalScope {
202public:
Eugene Zelenko38c70522017-12-07 21:55:09 +0000203 friend class const_iterator;
204
205 using AutomaticVarsTy = BumpVector<VarDecl *>;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000206
207 /// const_iterator - Iterates local scope backwards and jumps to previous
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000208 /// scope on reaching the beginning of currently iterated scope.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000209 class const_iterator {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000210 const LocalScope* Scope = nullptr;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000211
212 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
213 /// Invalid iterator (with null Scope) has VarIter equal to 0.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000214 unsigned VarIter = 0;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000215
216 public:
217 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
218 /// Incrementing invalid iterator is allowed and will result in invalid
219 /// iterator.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000220 const_iterator() = default;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000221
222 /// Create valid iterator. In case when S.Prev is an invalid iterator and
223 /// I is equal to 0, this will create invalid iterator.
224 const_iterator(const LocalScope& S, unsigned I)
225 : Scope(&S), VarIter(I) {
226 // Iterator to "end" of scope is not allowed. Handle it by going up
227 // in scopes tree possibly up to invalid iterator in the root.
228 if (VarIter == 0 && Scope)
229 *this = Scope->Prev;
230 }
231
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000232 VarDecl *const* operator->() const {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000233 assert(Scope && "Dereferencing invalid iterator is not allowed");
234 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000235 return &Scope->Vars[VarIter - 1];
236 }
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000237
238 const VarDecl *getFirstVarInScope() const {
239 assert(Scope && "Dereferencing invalid iterator is not allowed");
240 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
241 return Scope->Vars[0];
242 }
243
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000244 VarDecl *operator*() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000245 return *this->operator->();
246 }
247
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000248 const_iterator &operator++() {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000249 if (!Scope)
250 return *this;
251
Eugene Zelenko38c70522017-12-07 21:55:09 +0000252 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000253 --VarIter;
254 if (VarIter == 0)
255 *this = Scope->Prev;
256 return *this;
257 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000258 const_iterator operator++(int) {
259 const_iterator P = *this;
260 ++*this;
261 return P;
262 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000263
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000264 bool operator==(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000265 return Scope == rhs.Scope && VarIter == rhs.VarIter;
266 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000267 bool operator!=(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000268 return !(*this == rhs);
269 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000270
Aaron Ballman67347662015-02-15 22:00:28 +0000271 explicit operator bool() const {
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000272 return *this != const_iterator();
273 }
274
275 int distance(const_iterator L);
Matthias Gehre351c2182017-07-12 07:04:19 +0000276 const_iterator shared_parent(const_iterator L);
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000277 bool pointsToFirstDeclaredVar() { return VarIter == 1; }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000278 };
279
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000280private:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000281 BumpVectorContext ctx;
Fangrui Song6907ce22018-07-30 19:24:48 +0000282
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000283 /// Automatic variables in order of declaration.
284 AutomaticVarsTy Vars;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000285
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000286 /// Iterator to variable in previous scope that was declared just before
287 /// begin of this scope.
288 const_iterator Prev;
289
290public:
291 /// Constructs empty scope linked to previous scope in specified place.
David Blaikiec1334cc2015-08-13 22:12:21 +0000292 LocalScope(BumpVectorContext ctx, const_iterator P)
293 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000294
295 /// Begin of scope in direction of CFG building (backwards).
296 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000297
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000298 void addVar(VarDecl *VD) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000299 Vars.push_back(VD, ctx);
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000300 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000301};
302
Eugene Zelenko38c70522017-12-07 21:55:09 +0000303} // namespace
304
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000305/// distance - Calculates distance from this to L. L must be reachable from this
306/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
307/// number of scopes between this and L.
308int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
309 int D = 0;
310 const_iterator F = *this;
311 while (F.Scope != L.Scope) {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000312 assert(F != const_iterator() &&
313 "L iterator is not reachable from F iterator.");
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000314 D += F.VarIter;
315 F = F.Scope->Prev;
316 }
317 D += F.VarIter - L.VarIter;
318 return D;
319}
320
Matthias Gehre351c2182017-07-12 07:04:19 +0000321/// Calculates the closest parent of this iterator
322/// that is in a scope reachable through the parents of L.
323/// I.e. when using 'goto' from this to L, the lifetime of all variables
324/// between this and shared_parent(L) end.
325LocalScope::const_iterator
326LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
327 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
328 while (true) {
329 ScopesOfL.insert(L.Scope);
330 if (L == const_iterator())
331 break;
332 L = L.Scope->Prev;
333 }
334
335 const_iterator F = *this;
336 while (true) {
337 if (ScopesOfL.count(F.Scope))
338 return F;
339 assert(F != const_iterator() &&
340 "L iterator is not reachable from F iterator.");
341 F = F.Scope->Prev;
342 }
343}
344
Eugene Zelenko38c70522017-12-07 21:55:09 +0000345namespace {
346
Jonathan Roelofs99bdd982015-05-19 18:51:56 +0000347/// Structure for specifying position in CFG during its build process. It
348/// consists of CFGBlock that specifies position in CFG and
349/// LocalScope::const_iterator that specifies position in LocalScope graph.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000350struct BlockScopePosPair {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000351 CFGBlock *block = nullptr;
352 LocalScope::const_iterator scopePosition;
353
354 BlockScopePosPair() = default;
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000355 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000356 : block(b), scopePosition(scopePos) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000357};
358
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000359/// TryResult - a class representing a variant over the values
360/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
361/// and is used by the CFGBuilder to decide if a branch condition
362/// can be decided up front during CFG construction.
363class TryResult {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000364 int X = -1;
365
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000366public:
Eugene Zelenko38c70522017-12-07 21:55:09 +0000367 TryResult() = default;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000368 TryResult(bool b) : X(b ? 1 : 0) {}
Fangrui Song6907ce22018-07-30 19:24:48 +0000369
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000370 bool isTrue() const { return X == 1; }
371 bool isFalse() const { return X == 0; }
372 bool isKnown() const { return X >= 0; }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000373
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000374 void negate() {
375 assert(isKnown());
376 X ^= 0x1;
377 }
378};
379
Eugene Zelenko38c70522017-12-07 21:55:09 +0000380} // namespace
381
382static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
Manuel Klimekdeb02622014-08-08 07:37:13 +0000383 if (!R1.isKnown() || !R2.isKnown())
384 return TryResult();
385 return TryResult(R1.isTrue() && R2.isTrue());
386}
387
Eugene Zelenko38c70522017-12-07 21:55:09 +0000388namespace {
389
Ted Kremenek8ae67872013-02-05 22:00:19 +0000390class reverse_children {
391 llvm::SmallVector<Stmt *, 12> childrenBuf;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000392 ArrayRef<Stmt *> children;
393
Ted Kremenek8ae67872013-02-05 22:00:19 +0000394public:
395 reverse_children(Stmt *S);
396
Eugene Zelenko38c70522017-12-07 21:55:09 +0000397 using iterator = ArrayRef<Stmt *>::reverse_iterator;
398
Ted Kremenek8ae67872013-02-05 22:00:19 +0000399 iterator begin() const { return children.rbegin(); }
400 iterator end() const { return children.rend(); }
401};
402
Eugene Zelenko38c70522017-12-07 21:55:09 +0000403} // namespace
Ted Kremenek8ae67872013-02-05 22:00:19 +0000404
405reverse_children::reverse_children(Stmt *S) {
406 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
407 children = CE->getRawSubExprs();
408 return;
409 }
410 switch (S->getStmtClass()) {
Ted Kremenek7d86b9c2013-02-05 22:03:14 +0000411 // Note: Fill in this switch with more cases we want to optimize.
Ted Kremenek8ae67872013-02-05 22:00:19 +0000412 case Stmt::InitListExprClass: {
413 InitListExpr *IE = cast<InitListExpr>(S);
414 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
415 IE->getNumInits());
416 return;
417 }
418 default:
419 break;
420 }
421
422 // Default case for all other statements.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000423 for (Stmt *SubStmt : S->children())
424 childrenBuf.push_back(SubStmt);
Ted Kremenek8ae67872013-02-05 22:00:19 +0000425
426 // This needs to be done *after* childrenBuf has been populated.
427 children = childrenBuf;
428}
429
Eugene Zelenko38c70522017-12-07 21:55:09 +0000430namespace {
431
Ted Kremenekbe9b33b2008-08-04 22:51:42 +0000432/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000433/// The builder is stateful: an instance of the builder should be used to only
434/// construct a single CFG.
435///
436/// Example usage:
437///
438/// CFGBuilder builder;
Jonathan Roelofsab046c52015-07-27 16:05:36 +0000439/// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000440///
Mike Stump31feda52009-07-17 01:31:16 +0000441/// CFG construction is done via a recursive walk of an AST. We actually parse
442/// the AST in reverse order so that the successor of a basic block is
443/// constructed prior to its predecessor. This allows us to nicely capture
444/// implicit fall-throughs without extra basic blocks.
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000445class CFGBuilder {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000446 using JumpTarget = BlockScopePosPair;
447 using JumpSource = BlockScopePosPair;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000448
Mike Stump0d76d072009-07-20 23:24:15 +0000449 ASTContext *Context;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000450 std::unique_ptr<CFG> cfg;
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000451
Eugene Zelenko38c70522017-12-07 21:55:09 +0000452 // Current block.
453 CFGBlock *Block = nullptr;
454
455 // Block after the current block.
456 CFGBlock *Succ = nullptr;
457
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000458 JumpTarget ContinueJumpTarget;
459 JumpTarget BreakJumpTarget;
Nico Weber699670e2017-08-23 15:33:16 +0000460 JumpTarget SEHLeaveJumpTarget;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000461 CFGBlock *SwitchTerminatedBlock = nullptr;
462 CFGBlock *DefaultCaseBlock = nullptr;
Nico Weber699670e2017-08-23 15:33:16 +0000463
464 // This can point either to a try or a __try block. The frontend forbids
465 // mixing both kinds in one function, so having one for both is enough.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000466 CFGBlock *TryTerminatedBlock = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000467
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000468 // Current position in local scope.
469 LocalScope::const_iterator ScopePos;
470
471 // LabelMap records the mapping from Label expressions to their jump targets.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000472 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
Ted Kremenek8a632182007-08-21 23:26:17 +0000473 LabelMapTy LabelMap;
Mike Stump31feda52009-07-17 01:31:16 +0000474
475 // A list of blocks that end with a "goto" that must be backpatched to their
476 // resolved targets upon completion of CFG construction.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000477 using BackpatchBlocksTy = std::vector<JumpSource>;
Ted Kremenek8a632182007-08-21 23:26:17 +0000478 BackpatchBlocksTy BackpatchBlocks;
Mike Stump31feda52009-07-17 01:31:16 +0000479
Ted Kremenekeda180e22007-08-28 19:26:49 +0000480 // A list of labels whose address has been taken (for indirect gotos).
Eugene Zelenko38c70522017-12-07 21:55:09 +0000481 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
Ted Kremenekeda180e22007-08-28 19:26:49 +0000482 LabelSetTy AddressTakenLabels;
Mike Stump31feda52009-07-17 01:31:16 +0000483
Artem Dergachev41ffb302018-02-08 22:58:15 +0000484 // Information about the currently visited C++ object construction site.
485 // This is set in the construction trigger and read when the constructor
Artem Dergachev1527dec2018-03-12 23:12:40 +0000486 // or a function that returns an object by value is being visited.
487 llvm::DenseMap<Expr *, const ConstructionContextLayer *>
Artem Dergachev5e2f6ba2018-02-23 22:49:25 +0000488 ConstructionContextMap;
Artem Dergachev41ffb302018-02-08 22:58:15 +0000489
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000490 using DeclsWithEndedScopeSetTy = llvm::SmallSetVector<VarDecl *, 16>;
491 DeclsWithEndedScopeSetTy DeclsWithEndedScope;
492
Eugene Zelenko38c70522017-12-07 21:55:09 +0000493 bool badCFG = false;
Ted Kremenekf9d82902011-03-10 01:14:05 +0000494 const CFG::BuildOptions &BuildOpts;
Fangrui Song6907ce22018-07-30 19:24:48 +0000495
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000496 // State to track for building switch statements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000497 bool switchExclusivelyCovered = false;
498 Expr::EvalResult *switchCond = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000499
Eugene Zelenko38c70522017-12-07 21:55:09 +0000500 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
501 const Stmt *lastLookup = nullptr;
Zhongxing Xud38fb842010-09-16 03:28:18 +0000502
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000503 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
504 // during construction of branches for chained logical operators.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000505 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000506 CachedBoolEvalsTy CachedBoolEvals;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000507
Mike Stump31feda52009-07-17 01:31:16 +0000508public:
Ted Kremenekf9d82902011-03-10 01:14:05 +0000509 explicit CFGBuilder(ASTContext *astContext,
Nico Weber699670e2017-08-23 15:33:16 +0000510 const CFG::BuildOptions &buildOpts)
511 : Context(astContext), cfg(new CFG()), // crew a new CFG
Artem Dergachev5e2f6ba2018-02-23 22:49:25 +0000512 ConstructionContextMap(), BuildOpts(buildOpts) {}
513
Mike Stump31feda52009-07-17 01:31:16 +0000514
Ted Kremenek9aae5132007-08-23 21:42:29 +0000515 // buildCFG - Used by external clients to construct the CFG.
David Blaikiee90195c2014-08-29 18:53:26 +0000516 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
Mike Stump31feda52009-07-17 01:31:16 +0000517
Ted Kremeneka099c592011-03-10 03:50:34 +0000518 bool alwaysAdd(const Stmt *stmt);
Fangrui Song6907ce22018-07-30 19:24:48 +0000519
Ted Kremenek93668002009-07-17 22:18:43 +0000520private:
521 // Visitors to walk an AST and construct the CFG.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000522 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
523 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000524 CFGBlock *VisitBreakStmt(BreakStmt *B);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000525 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000526 CFGBlock *VisitCaseStmt(CaseStmt *C);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000527 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000528 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
John McCallc07a0c72011-02-17 10:25:35 +0000529 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
530 AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000531 CFGBlock *VisitContinueStmt(ContinueStmt *C);
Ted Kremenek6f400242012-07-14 05:04:01 +0000532 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
533 AddStmtChoice asc);
534 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
535 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
Jordan Rosec9176072014-01-13 17:59:19 +0000536 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
Jordan Rosed2f40792013-09-03 17:00:57 +0000537 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000538 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
539 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
540 AddStmtChoice asc);
541 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
542 AddStmtChoice asc);
543 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
544 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000545 CFGBlock *VisitDeclStmt(DeclStmt *DS);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000546 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
Ted Kremenek21822592009-07-17 18:20:32 +0000547 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
548 CFGBlock *VisitDoStmt(DoStmt *D);
Ted Kremenek6f400242012-07-14 05:04:01 +0000549 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000550 CFGBlock *VisitForStmt(ForStmt *F);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000551 CFGBlock *VisitGotoStmt(GotoStmt *G);
Jennifer Yub8fee672019-06-03 15:57:25 +0000552 CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000553 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000554 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Bill Wendling8003edc2018-11-09 00:41:36 +0000555 CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000556 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
557 CFGBlock *VisitLabelStmt(LabelStmt *L);
Devin Coughlinb6029b72015-11-25 22:35:37 +0000558 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000559 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000560 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000561 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
562 Stmt *Term,
563 CFGBlock *TrueBlock,
564 CFGBlock *FalseBlock);
Artem Dergachevf43ac4c2018-02-24 02:00:30 +0000565 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
566 AddStmtChoice asc);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000567 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000568 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
569 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
570 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
571 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000572 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000573 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000574 CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
John McCallfe96e0b2011-11-06 09:01:30 +0000575 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Brian Gesiaka87ecf62018-11-03 22:35:17 +0000576 CFGBlock *VisitReturnStmt(Stmt *S);
Nico Weber699670e2017-08-23 15:33:16 +0000577 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
578 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
579 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
580 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000581 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000582 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000583 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
584 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000585 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000586 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000587
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000588 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
589 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000590 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000591 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000592
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000593 void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
594 const Stmt *S) {
595 if (ScopePos && (VD == ScopePos.getFirstVarInScope()))
596 appendScopeBegin(B, VD, S);
597 }
598
Manuel Klimekb5616c92014-08-07 10:42:17 +0000599 /// When creating the CFG for temporary destructors, we want to mirror the
600 /// branch structure of the corresponding constructor calls.
601 /// Thus, while visiting a statement for temporary destructors, we keep a
602 /// context to keep track of the following information:
603 /// - whether a subexpression is executed unconditionally
604 /// - if a subexpression is executed conditionally, the first
605 /// CXXBindTemporaryExpr we encounter in that subexpression (which
606 /// corresponds to the last temporary destructor we have to call for this
607 /// subexpression) and the CFG block at that point (which will become the
608 /// successor block when inserting the decision point).
609 ///
610 /// That way, we can build the branch structure for temporary destructors as
611 /// follows:
612 /// 1. If a subexpression is executed unconditionally, we add the temporary
613 /// destructor calls to the current block.
614 /// 2. If a subexpression is executed conditionally, when we encounter a
615 /// CXXBindTemporaryExpr:
616 /// a) If it is the first temporary destructor call in the subexpression,
617 /// we remember the CXXBindTemporaryExpr and the current block in the
618 /// TempDtorContext; we start a new block, and insert the temporary
619 /// destructor call.
620 /// b) Otherwise, add the temporary destructor call to the current block.
621 /// 3. When we finished visiting a conditionally executed subexpression,
622 /// and we found at least one temporary constructor during the visitation
623 /// (2.a has executed), we insert a decision block that uses the
624 /// CXXBindTemporaryExpr as terminator, and branches to the current block
625 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
626 /// branches to the stored successor.
627 struct TempDtorContext {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000628 TempDtorContext() = default;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000629 TempDtorContext(TryResult KnownExecuted)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000630 : IsConditional(true), KnownExecuted(KnownExecuted) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000631
632 /// Returns whether we need to start a new branch for a temporary destructor
Eric Christopher2c4555a2015-06-19 01:52:53 +0000633 /// call. This is the case when the temporary destructor is
Manuel Klimekb5616c92014-08-07 10:42:17 +0000634 /// conditionally executed, and it is the first one we encounter while
635 /// visiting a subexpression - other temporary destructors at the same level
636 /// will be added to the same block and are executed under the same
637 /// condition.
638 bool needsTempDtorBranch() const {
639 return IsConditional && !TerminatorExpr;
640 }
641
642 /// Remember the successor S of a temporary destructor decision branch for
643 /// the corresponding CXXBindTemporaryExpr E.
644 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
645 Succ = S;
646 TerminatorExpr = E;
647 }
648
Eugene Zelenko38c70522017-12-07 21:55:09 +0000649 const bool IsConditional = false;
650 const TryResult KnownExecuted = true;
651 CFGBlock *Succ = nullptr;
652 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000653 };
654
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000655 // Visitors to walk an AST and generate destructors of temporaries in
656 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000657 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
658 TempDtorContext &Context);
659 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
660 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
661 TempDtorContext &Context);
662 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
663 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
664 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
665 AbstractConditionalOperator *E, bool BindToTemporary,
666 TempDtorContext &Context);
667 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
668 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000669
Ted Kremenek6065ef62008-04-28 18:00:46 +0000670 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000671 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000672 badCFG = true;
673 return Block;
674 }
Mike Stump31feda52009-07-17 01:31:16 +0000675
Artem Dergachev40684812018-02-27 20:03:35 +0000676 // Remember to apply the construction context based on the current \p Layer
677 // when constructing the CFG element for \p CE.
678 void consumeConstructionContext(const ConstructionContextLayer *Layer,
Artem Dergachev1527dec2018-03-12 23:12:40 +0000679 Expr *E);
Artem Dergachevc1b07bd2018-02-23 23:38:41 +0000680
Artem Dergachev40684812018-02-27 20:03:35 +0000681 // Scan \p Child statement to find constructors in it, while keeping in mind
682 // that its parent statement is providing a partial construction context
683 // described by \p Layer. If a constructor is found, it would be assigned
684 // the context based on the layer. If an additional construction context layer
685 // is found, the function recurses into that.
686 void findConstructionContexts(const ConstructionContextLayer *Layer,
Artem Dergachev783a4572018-02-23 22:20:39 +0000687 Stmt *Child);
Artem Dergachev40684812018-02-27 20:03:35 +0000688
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000689 // Scan all arguments of a call expression for a construction context.
690 // These sorts of call expressions don't have a common superclass,
691 // hence strict duck-typing.
692 template <typename CallLikeExpr,
693 typename = typename std::enable_if<
694 std::is_same<CallLikeExpr, CallExpr>::value ||
695 std::is_same<CallLikeExpr, CXXConstructExpr>::value ||
696 std::is_same<CallLikeExpr, ObjCMessageExpr>::value>>
697 void findConstructionContextsForArguments(CallLikeExpr *E) {
Artem Dergacheva657a322018-07-31 20:45:53 +0000698 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
699 Expr *Arg = E->getArg(i);
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000700 if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
701 findConstructionContexts(
Artem Dergachev1f8cb3a2018-07-31 21:12:42 +0000702 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
703 ConstructionContextItem(E, i)),
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000704 Arg);
Artem Dergacheva657a322018-07-31 20:45:53 +0000705 }
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000706 }
707
Artem Dergachev41ffb302018-02-08 22:58:15 +0000708 // Unset the construction context after consuming it. This is done immediately
Artem Dergachev1527dec2018-03-12 23:12:40 +0000709 // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so
710 // there's no need to do this manually in every Visit... function.
711 void cleanupConstructionContext(Expr *E);
Artem Dergachev41ffb302018-02-08 22:58:15 +0000712
Ted Kremenek93668002009-07-17 22:18:43 +0000713 void autoCreateBlock() { if (!Block) Block = createBlock(); }
714 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000715 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000716
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000717 CFGBlock *addStmt(Stmt *S) {
718 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000719 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000720
Alexis Hunt1d792652011-01-08 20:30:50 +0000721 CFGBlock *addInitializer(CXXCtorInitializer *I);
Peter Szecsi999a25f2017-08-19 11:19:16 +0000722 void addLoopExit(const Stmt *LoopStmt);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000723 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000724 LocalScope::const_iterator E, Stmt *S);
Matthias Gehre351c2182017-07-12 07:04:19 +0000725 void addLifetimeEnds(LocalScope::const_iterator B,
726 LocalScope::const_iterator E, Stmt *S);
727 void addAutomaticObjHandling(LocalScope::const_iterator B,
728 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000729 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000730 void addScopesEnd(LocalScope::const_iterator B, LocalScope::const_iterator E,
731 Stmt *S);
732
733 void getDeclsWithEndedScope(LocalScope::const_iterator B,
734 LocalScope::const_iterator E, Stmt *S);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000735
Marcin Swiderski5e415732010-09-30 23:05:00 +0000736 // Local scopes creation.
737 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
738
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000739 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000740 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
741 LocalScope* Scope = nullptr);
742 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000743
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000744 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000745
Artem Dergacheve1f30622018-07-31 19:46:14 +0000746 const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
747 if (!BuildOpts.AddRichCXXConstructors)
748 return nullptr;
749
750 const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E);
751 if (!Layer)
752 return nullptr;
753
754 cleanupConstructionContext(E);
755 return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(),
756 Layer);
757 }
758
Marcin Swiderski5e415732010-09-30 23:05:00 +0000759 // Interface to CFGBlock - adding CFGElements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000760
Ted Kremenek37881932011-04-04 23:29:12 +0000761 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000762 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000763 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000764
Jordy Rose17347372011-06-10 08:49:37 +0000765 // All block-level expressions should have already been IgnoreParens()ed.
766 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000767 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000768 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000769
Artem Dergachev41ffb302018-02-08 22:58:15 +0000770 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
Artem Dergacheve1f30622018-07-31 19:46:14 +0000771 if (const ConstructionContext *CC =
772 retrieveAndCleanupConstructionContext(CE)) {
773 B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
774 return;
Artem Dergachev41ffb302018-02-08 22:58:15 +0000775 }
776
777 // No valid construction context found. Fall back to statement.
778 B->appendStmt(CE, cfg->getBumpVectorContext());
779 }
780
Artem Dergachev1527dec2018-03-12 23:12:40 +0000781 void appendCall(CFGBlock *B, CallExpr *CE) {
Richard Trieuf4a0e9a2018-03-15 00:09:26 +0000782 if (alwaysAdd(CE) && cachedEntry)
783 cachedEntry->second = B;
784
Artem Dergacheve1f30622018-07-31 19:46:14 +0000785 if (const ConstructionContext *CC =
786 retrieveAndCleanupConstructionContext(CE)) {
787 B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
788 return;
Artem Dergachev1527dec2018-03-12 23:12:40 +0000789 }
790
791 // No valid construction context found. Fall back to statement.
792 B->appendStmt(CE, cfg->getBumpVectorContext());
793 }
794
Alexis Hunt1d792652011-01-08 20:30:50 +0000795 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000796 B->appendInitializer(I, cfg->getBumpVectorContext());
797 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000798
Jordan Rosec9176072014-01-13 17:59:19 +0000799 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
800 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
801 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000802
Marcin Swiderski20b88732010-10-05 05:37:00 +0000803 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
804 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
805 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000806
Marcin Swiderski20b88732010-10-05 05:37:00 +0000807 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
808 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
809 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000810
Artem Dergacheve1f30622018-07-31 19:46:14 +0000811 void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
812 if (alwaysAdd(ME) && cachedEntry)
813 cachedEntry->second = B;
814
815 if (const ConstructionContext *CC =
816 retrieveAndCleanupConstructionContext(ME)) {
817 B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
818 return;
819 }
820
821 B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
822 cfg->getBumpVectorContext());
823 }
824
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000825 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
826 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
827 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000828
Chandler Carruthad747252011-09-13 06:09:01 +0000829 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
830 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
831 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000832
Matthias Gehre351c2182017-07-12 07:04:19 +0000833 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
834 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
835 }
836
Peter Szecsi999a25f2017-08-19 11:19:16 +0000837 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
838 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
839 }
840
Jordan Rosed2f40792013-09-03 17:00:57 +0000841 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
842 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
843 }
844
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000845 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000846 LocalScope::const_iterator B, LocalScope::const_iterator E);
847
Matthias Gehre351c2182017-07-12 07:04:19 +0000848 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
849 LocalScope::const_iterator B,
850 LocalScope::const_iterator E);
851
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000852 const VarDecl *
853 prependAutomaticObjScopeEndWithTerminator(CFGBlock *Blk,
854 LocalScope::const_iterator B,
855 LocalScope::const_iterator E);
856
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000857 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
858 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
859 cfg->getBumpVectorContext());
860 }
861
862 /// Add a reachable successor to a block, with the alternate variant that is
863 /// unreachable.
864 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
865 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
866 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000867 }
Mike Stump11289f42009-09-09 15:08:12 +0000868
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000869 void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
870 if (BuildOpts.AddScopes)
871 B->appendScopeBegin(VD, S, cfg->getBumpVectorContext());
872 }
873
874 void prependScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
875 if (BuildOpts.AddScopes)
876 B->prependScopeBegin(VD, S, cfg->getBumpVectorContext());
877 }
878
879 void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
880 if (BuildOpts.AddScopes)
881 B->appendScopeEnd(VD, S, cfg->getBumpVectorContext());
882 }
883
884 void prependScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
885 if (BuildOpts.AddScopes)
886 B->prependScopeEnd(VD, S, cfg->getBumpVectorContext());
887 }
888
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000889 /// Find a relational comparison with an expression evaluating to a
Richard Trieuf935b562014-04-05 05:17:01 +0000890 /// boolean and a constant other than 0 and 1.
891 /// e.g. if ((x < y) == 10)
892 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
893 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
894 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
895
896 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
897 const Expr *BoolExpr = RHSExpr;
898 bool IntFirst = true;
899 if (!IntLiteral) {
900 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
901 BoolExpr = LHSExpr;
902 IntFirst = false;
903 }
904
905 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
906 return TryResult();
907
908 llvm::APInt IntValue = IntLiteral->getValue();
909 if ((IntValue == 1) || (IntValue == 0))
910 return TryResult();
911
912 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
913 !IntValue.isNegative();
914
915 BinaryOperatorKind Bok = B->getOpcode();
916 if (Bok == BO_GT || Bok == BO_GE) {
917 // Always true for 10 > bool and bool > -1
918 // Always false for -1 > bool and bool > 10
919 return TryResult(IntFirst == IntLarger);
920 } else {
921 // Always true for -1 < bool and bool < 10
922 // Always false for 10 < bool and bool < -1
923 return TryResult(IntFirst != IntLarger);
924 }
925 }
926
Jordan Rose7afd71e2014-05-20 17:31:11 +0000927 /// Find an incorrect equality comparison. Either with an expression
928 /// evaluating to a boolean and a constant other than 0 and 1.
929 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
930 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000931 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
932 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
933 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
934
935 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
936 const Expr *BoolExpr = RHSExpr;
937
938 if (!IntLiteral) {
939 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
940 BoolExpr = LHSExpr;
941 }
942
Jordan Rose7afd71e2014-05-20 17:31:11 +0000943 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000944 return TryResult();
945
Jordan Rose7afd71e2014-05-20 17:31:11 +0000946 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
947 if (BitOp && (BitOp->getOpcode() == BO_And ||
948 BitOp->getOpcode() == BO_Or)) {
949 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
950 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
951
952 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
953
954 if (!IntLiteral2)
955 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
956
957 if (!IntLiteral2)
958 return TryResult();
959
960 llvm::APInt L1 = IntLiteral->getValue();
961 llvm::APInt L2 = IntLiteral2->getValue();
962 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
963 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
964 if (BuildOpts.Observer)
965 BuildOpts.Observer->compareBitwiseEquality(B,
966 B->getOpcode() != BO_EQ);
967 TryResult(B->getOpcode() != BO_EQ);
968 }
969 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
970 llvm::APInt IntValue = IntLiteral->getValue();
971 if ((IntValue == 1) || (IntValue == 0)) {
972 return TryResult();
973 }
974 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000975 }
976
Jordan Rose7afd71e2014-05-20 17:31:11 +0000977 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000978 }
979
980 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
981 const llvm::APSInt &Value1,
982 const llvm::APSInt &Value2) {
983 assert(Value1.isSigned() == Value2.isSigned());
984 switch (Relation) {
985 default:
986 return TryResult();
987 case BO_EQ:
988 return TryResult(Value1 == Value2);
989 case BO_NE:
990 return TryResult(Value1 != Value2);
991 case BO_LT:
992 return TryResult(Value1 < Value2);
993 case BO_LE:
994 return TryResult(Value1 <= Value2);
995 case BO_GT:
996 return TryResult(Value1 > Value2);
997 case BO_GE:
998 return TryResult(Value1 >= Value2);
999 }
1000 }
1001
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001002 /// Find a pair of comparison expressions with or without parentheses
Richard Trieuf935b562014-04-05 05:17:01 +00001003 /// with a shared variable and constants and a logical operator between them
1004 /// that always evaluates to either true or false.
1005 /// e.g. if (x != 3 || x != 4)
1006 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
1007 assert(B->isLogicalOp());
1008 const BinaryOperator *LHS =
1009 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
1010 const BinaryOperator *RHS =
1011 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
1012 if (!LHS || !RHS)
Eugene Zelenko38c70522017-12-07 21:55:09 +00001013 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001014
1015 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001016 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001017
George Burgess IVced56e62015-10-01 18:47:52 +00001018 const DeclRefExpr *Decl1;
1019 const Expr *Expr1;
1020 BinaryOperatorKind BO1;
1021 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001022
George Burgess IVced56e62015-10-01 18:47:52 +00001023 if (!Decl1 || !Expr1)
Eugene Zelenko38c70522017-12-07 21:55:09 +00001024 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001025
George Burgess IVced56e62015-10-01 18:47:52 +00001026 const DeclRefExpr *Decl2;
1027 const Expr *Expr2;
1028 BinaryOperatorKind BO2;
1029 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001030
George Burgess IVced56e62015-10-01 18:47:52 +00001031 if (!Decl2 || !Expr2)
Eugene Zelenko38c70522017-12-07 21:55:09 +00001032 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001033
1034 // Check that it is the same variable on both sides.
1035 if (Decl1->getDecl() != Decl2->getDecl())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001036 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001037
George Burgess IVced56e62015-10-01 18:47:52 +00001038 // Make sure the user's intent is clear (e.g. they're comparing against two
1039 // int literals, or two things from the same enum)
1040 if (!areExprTypesCompatible(Expr1, Expr2))
Eugene Zelenko38c70522017-12-07 21:55:09 +00001041 return {};
George Burgess IVced56e62015-10-01 18:47:52 +00001042
Fangrui Song407659a2018-11-30 23:41:18 +00001043 Expr::EvalResult L1Result, L2Result;
1044 if (!Expr1->EvaluateAsInt(L1Result, *Context) ||
1045 !Expr2->EvaluateAsInt(L2Result, *Context))
Fangrui Songf5d33352018-11-30 21:26:09 +00001046 return {};
Hans Wennborg48ee4ad2018-11-28 14:04:12 +00001047
Fangrui Song407659a2018-11-30 23:41:18 +00001048 llvm::APSInt L1 = L1Result.Val.getInt();
1049 llvm::APSInt L2 = L2Result.Val.getInt();
1050
Richard Trieuf935b562014-04-05 05:17:01 +00001051 // Can't compare signed with unsigned or with different bit width.
1052 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001053 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001054
1055 // Values that will be used to determine if result of logical
1056 // operator is always true/false
1057 const llvm::APSInt Values[] = {
1058 // Value less than both Value1 and Value2
1059 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
1060 // L1
1061 L1,
1062 // Value between Value1 and Value2
1063 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
1064 L1.isUnsigned()),
1065 // L2
1066 L2,
1067 // Value greater than both Value1 and Value2
1068 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
1069 };
1070
1071 // Check whether expression is always true/false by evaluating the following
1072 // * variable x is less than the smallest literal.
1073 // * variable x is equal to the smallest literal.
1074 // * Variable x is between smallest and largest literal.
1075 // * Variable x is equal to the largest literal.
1076 // * Variable x is greater than largest literal.
1077 bool AlwaysTrue = true, AlwaysFalse = true;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00001078 for (const llvm::APSInt &Value : Values) {
Richard Trieuf935b562014-04-05 05:17:01 +00001079 TryResult Res1, Res2;
1080 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
1081 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
1082
1083 if (!Res1.isKnown() || !Res2.isKnown())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001084 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001085
1086 if (B->getOpcode() == BO_LAnd) {
1087 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
1088 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
1089 } else {
1090 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
1091 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
1092 }
1093 }
1094
1095 if (AlwaysTrue || AlwaysFalse) {
1096 if (BuildOpts.Observer)
1097 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
1098 return TryResult(AlwaysTrue);
1099 }
Eugene Zelenko38c70522017-12-07 21:55:09 +00001100 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001101 }
1102
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00001103 /// Try and evaluate an expression to an integer constant.
1104 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
1105 if (!BuildOpts.PruneTriviallyFalseEdges)
1106 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001107 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +00001108 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +00001109 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00001110 }
Mike Stump11289f42009-09-09 15:08:12 +00001111
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001112 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +00001113 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001114 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +00001115 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001116 S->isTypeDependent() || S->isValueDependent())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001117 return {};
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001118
1119 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1120 if (Bop->isLogicalOp()) {
1121 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +00001122 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1123 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001124 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +00001125
1126 // Retrieve result at first, or the map might be updated.
1127 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1128 CachedBoolEvals[S] = Result; // update or insert
1129 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001130 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001131 else {
1132 switch (Bop->getOpcode()) {
1133 default: break;
1134 // For 'x & 0' and 'x * 0', we can determine that
1135 // the value is always false.
1136 case BO_Mul:
1137 case BO_And: {
1138 // If either operand is zero, we know the value
1139 // must be false.
Fangrui Song407659a2018-11-30 23:41:18 +00001140 Expr::EvalResult LHSResult;
1141 if (Bop->getLHS()->EvaluateAsInt(LHSResult, *Context)) {
1142 llvm::APSInt IntVal = LHSResult.Val.getInt();
David Blaikie7a3cbb22015-03-09 02:02:07 +00001143 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001144 return TryResult(false);
1145 }
1146 }
Fangrui Song407659a2018-11-30 23:41:18 +00001147 Expr::EvalResult RHSResult;
1148 if (Bop->getRHS()->EvaluateAsInt(RHSResult, *Context)) {
1149 llvm::APSInt IntVal = RHSResult.Val.getInt();
David Blaikie7a3cbb22015-03-09 02:02:07 +00001150 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001151 return TryResult(false);
1152 }
1153 }
1154 }
1155 break;
1156 }
1157 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001158 }
1159
1160 return evaluateAsBooleanConditionNoCache(S);
1161 }
1162
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001163 /// Evaluate as boolean \param E without using the cache.
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001164 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1165 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1166 if (Bop->isLogicalOp()) {
1167 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1168 if (LHS.isKnown()) {
1169 // We were able to evaluate the LHS, see if we can get away with not
1170 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1171 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1172 return LHS.isTrue();
1173
1174 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1175 if (RHS.isKnown()) {
1176 if (Bop->getOpcode() == BO_LOr)
1177 return LHS.isTrue() || RHS.isTrue();
1178 else
1179 return LHS.isTrue() && RHS.isTrue();
1180 }
1181 } else {
1182 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1183 if (RHS.isKnown()) {
1184 // We can't evaluate the LHS; however, sometimes the result
1185 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1186 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1187 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +00001188 } else {
1189 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1190 if (BopRes.isKnown())
1191 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001192 }
1193 }
1194
Eugene Zelenko38c70522017-12-07 21:55:09 +00001195 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001196 } else if (Bop->isEqualityOp()) {
1197 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1198 if (BopRes.isKnown())
1199 return BopRes.isTrue();
1200 } else if (Bop->isRelationalOp()) {
1201 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1202 if (BopRes.isKnown())
1203 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001204 }
1205 }
1206
1207 bool Result;
1208 if (E->EvaluateAsBooleanCondition(Result, *Context))
1209 return Result;
1210
Eugene Zelenko38c70522017-12-07 21:55:09 +00001211 return {};
Mike Stump773582d2009-07-23 23:25:26 +00001212 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001213
1214 bool hasTrivialDestructor(VarDecl *VD);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00001215};
Mike Stump31feda52009-07-17 01:31:16 +00001216
Eugene Zelenko38c70522017-12-07 21:55:09 +00001217} // namespace
1218
Ted Kremeneka099c592011-03-10 03:50:34 +00001219inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1220 const Stmt *stmt) const {
1221 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1222}
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001223
Ted Kremeneka099c592011-03-10 03:50:34 +00001224bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +00001225 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
Fangrui Song6907ce22018-07-30 19:24:48 +00001226
Ted Kremeneka099c592011-03-10 03:50:34 +00001227 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +00001228 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001229
Fangrui Song6907ce22018-07-30 19:24:48 +00001230 if (lastLookup == stmt) {
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001231 if (cachedEntry) {
1232 assert(cachedEntry->first == stmt);
1233 return true;
1234 }
Ted Kremenek8b46c002011-07-19 14:18:43 +00001235 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001236 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001237
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001238 lastLookup = stmt;
1239
1240 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +00001241 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1242
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001243 if (!fb) {
1244 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +00001245 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +00001246 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001247 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001248
1249 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001250 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +00001251 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +00001252 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001253 }
1254
Ted Kremeneka099c592011-03-10 03:50:34 +00001255 cachedEntry = &*itr;
1256 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +00001257}
Fangrui Song6907ce22018-07-30 19:24:48 +00001258
Douglas Gregor4619e432008-12-05 23:32:09 +00001259// FIXME: Add support for dependent-sized array types in C++?
1260// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +00001261static const VariableArrayType *FindVA(const Type *t) {
1262 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1263 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001264 if (vat->getSizeExpr())
1265 return vat;
Mike Stump31feda52009-07-17 01:31:16 +00001266
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001267 t = vt->getElementType().getTypePtr();
1268 }
Mike Stump31feda52009-07-17 01:31:16 +00001269
Craig Topper25542942014-05-20 04:30:07 +00001270 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001271}
Mike Stump31feda52009-07-17 01:31:16 +00001272
Artem Dergachev40684812018-02-27 20:03:35 +00001273void CFGBuilder::consumeConstructionContext(
Artem Dergachev1527dec2018-03-12 23:12:40 +00001274 const ConstructionContextLayer *Layer, Expr *E) {
Artem Dergacheve1f30622018-07-31 19:46:14 +00001275 assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
1276 isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
Artem Dergachev40684812018-02-27 20:03:35 +00001277 if (const ConstructionContextLayer *PreviouslyStoredLayer =
Artem Dergachev1527dec2018-03-12 23:12:40 +00001278 ConstructionContextMap.lookup(E)) {
George Burgess IVa47e1b72018-03-06 07:45:11 +00001279 (void)PreviouslyStoredLayer;
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001280 // We might have visited this child when we were finding construction
1281 // contexts within its parents.
Artem Dergachev40684812018-02-27 20:03:35 +00001282 assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001283 "Already within a different construction context!");
1284 } else {
Artem Dergachev1527dec2018-03-12 23:12:40 +00001285 ConstructionContextMap[E] = Layer;
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001286 }
1287}
1288
Artem Dergachev783a4572018-02-23 22:20:39 +00001289void CFGBuilder::findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00001290 const ConstructionContextLayer *Layer, Stmt *Child) {
Artem Dergachev41ffb302018-02-08 22:58:15 +00001291 if (!BuildOpts.AddRichCXXConstructors)
1292 return;
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001293
Artem Dergachev41ffb302018-02-08 22:58:15 +00001294 if (!Child)
1295 return;
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001296
Artem Dergachev1f8cb3a2018-07-31 21:12:42 +00001297 auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) {
1298 return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item,
1299 Layer);
Artem Dergachevff267df2018-06-28 00:04:54 +00001300 };
1301
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001302 switch(Child->getStmtClass()) {
1303 case Stmt::CXXConstructExprClass:
1304 case Stmt::CXXTemporaryObjectExprClass: {
Artem Dergachevff267df2018-06-28 00:04:54 +00001305 // Support pre-C++17 copy elision AST.
1306 auto *CE = cast<CXXConstructExpr>(Child);
1307 if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
Artem Dergachevff267df2018-06-28 00:04:54 +00001308 findConstructionContexts(withExtraLayer(CE), CE->getArg(0));
1309 }
1310
1311 consumeConstructionContext(Layer, CE);
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001312 break;
1313 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00001314 // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
1315 // FIXME: An isa<> would look much better but this whole switch is a
1316 // workaround for an internal compiler error in MSVC 2015 (see r326021).
1317 case Stmt::CallExprClass:
1318 case Stmt::CXXMemberCallExprClass:
1319 case Stmt::CXXOperatorCallExprClass:
Artem Dergacheve1f30622018-07-31 19:46:14 +00001320 case Stmt::UserDefinedLiteralClass:
1321 case Stmt::ObjCMessageExprClass: {
1322 auto *E = cast<Expr>(Child);
1323 if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
1324 consumeConstructionContext(Layer, E);
Artem Dergachev1527dec2018-03-12 23:12:40 +00001325 break;
1326 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001327 case Stmt::ExprWithCleanupsClass: {
1328 auto *Cleanups = cast<ExprWithCleanups>(Child);
Artem Dergachev40684812018-02-27 20:03:35 +00001329 findConstructionContexts(Layer, Cleanups->getSubExpr());
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001330 break;
1331 }
1332 case Stmt::CXXFunctionalCastExprClass: {
1333 auto *Cast = cast<CXXFunctionalCastExpr>(Child);
Artem Dergachev40684812018-02-27 20:03:35 +00001334 findConstructionContexts(Layer, Cast->getSubExpr());
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001335 break;
1336 }
1337 case Stmt::ImplicitCastExprClass: {
1338 auto *Cast = cast<ImplicitCastExpr>(Child);
Artem Dergachev317291e2018-03-22 21:37:39 +00001339 // Should we support other implicit cast kinds?
Artem Dergachev13f96642018-03-09 01:39:59 +00001340 switch (Cast->getCastKind()) {
1341 case CK_NoOp:
1342 case CK_ConstructorConversion:
Artem Dergachev66030522018-03-01 01:09:24 +00001343 findConstructionContexts(Layer, Cast->getSubExpr());
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00001344 break;
Artem Dergachev13f96642018-03-09 01:39:59 +00001345 default:
1346 break;
1347 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001348 break;
1349 }
1350 case Stmt::CXXBindTemporaryExprClass: {
1351 auto *BTE = cast<CXXBindTemporaryExpr>(Child);
Artem Dergachevff267df2018-06-28 00:04:54 +00001352 findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
1353 break;
1354 }
1355 case Stmt::MaterializeTemporaryExprClass: {
1356 // Normally we don't want to search in MaterializeTemporaryExpr because
1357 // it indicates the beginning of a temporary object construction context,
1358 // so it shouldn't be found in the middle. However, if it is the beginning
1359 // of an elidable copy or move construction context, we need to include it.
Artem Dergachev1f8cb3a2018-07-31 21:12:42 +00001360 if (Layer->getItem().getKind() ==
1361 ConstructionContextItem::ElidableConstructorKind) {
1362 auto *MTE = cast<MaterializeTemporaryExpr>(Child);
1363 findConstructionContexts(withExtraLayer(MTE), MTE->GetTemporaryExpr());
Artem Dergachevff267df2018-06-28 00:04:54 +00001364 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001365 break;
1366 }
1367 case Stmt::ConditionalOperatorClass: {
1368 auto *CO = cast<ConditionalOperator>(Child);
Artem Dergachev1f8cb3a2018-07-31 21:12:42 +00001369 if (Layer->getItem().getKind() !=
1370 ConstructionContextItem::MaterializationKind) {
Artem Dergachev9d3a7d82018-03-30 19:21:18 +00001371 // If the object returned by the conditional operator is not going to be a
1372 // temporary object that needs to be immediately materialized, then
1373 // it must be C++17 with its mandatory copy elision. Do not yet promise
1374 // to support this case.
1375 assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
1376 Context->getLangOpts().CPlusPlus17);
1377 break;
1378 }
Artem Dergachev40684812018-02-27 20:03:35 +00001379 findConstructionContexts(Layer, CO->getLHS());
1380 findConstructionContexts(Layer, CO->getRHS());
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001381 break;
1382 }
Artem Dergachevaa403152019-03-21 00:15:07 +00001383 case Stmt::InitListExprClass: {
1384 auto *ILE = cast<InitListExpr>(Child);
1385 if (ILE->isTransparent()) {
1386 findConstructionContexts(Layer, ILE->getInit(0));
1387 break;
1388 }
1389 // TODO: Handle other cases. For now, fail to find construction contexts.
1390 break;
1391 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001392 default:
1393 break;
Artem Dergachev41ffb302018-02-08 22:58:15 +00001394 }
1395}
1396
Artem Dergachev1527dec2018-03-12 23:12:40 +00001397void CFGBuilder::cleanupConstructionContext(Expr *E) {
Artem Dergachev783a4572018-02-23 22:20:39 +00001398 assert(BuildOpts.AddRichCXXConstructors &&
1399 "We should not be managing construction contexts!");
Artem Dergachev1527dec2018-03-12 23:12:40 +00001400 assert(ConstructionContextMap.count(E) &&
Artem Dergachev41ffb302018-02-08 22:58:15 +00001401 "Cannot exit construction context without the context!");
Artem Dergachev1527dec2018-03-12 23:12:40 +00001402 ConstructionContextMap.erase(E);
Artem Dergachev41ffb302018-02-08 22:58:15 +00001403}
1404
1405
Mike Stump31feda52009-07-17 01:31:16 +00001406/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1407/// arbitrary statement. Examples include a single expression or a function
1408/// body (compound statement). The ownership of the returned CFG is
1409/// transferred to the caller. If CFG construction fails, this method returns
1410/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +00001411std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +00001412 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +00001413 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +00001414 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001415
Mike Stump31feda52009-07-17 01:31:16 +00001416 // Create an empty block that will serve as the exit block for the CFG. Since
1417 // this is the first block added to the CFG, it will be implicitly registered
1418 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +00001419 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +00001420 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +00001421 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +00001422
Matthias Gehre351c2182017-07-12 07:04:19 +00001423 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1424 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1425
Marcin Swiderski20b88732010-10-05 05:37:00 +00001426 if (BuildOpts.AddImplicitDtors)
1427 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1428 addImplicitDtorsForDestructor(DD);
1429
Ted Kremenek9aae5132007-08-23 21:42:29 +00001430 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001431 CFGBlock *B = addStmt(Statement);
1432
1433 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001434 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001435
Artem Dergachev192a7472019-05-24 23:37:08 +00001436 // For C++ constructor add initializers to CFG. Constructors of virtual bases
1437 // are ignored unless the object is of the most derived class.
1438 // class VBase { VBase() = default; VBase(int) {} };
1439 // class A : virtual public VBase { A() : VBase(0) {} };
1440 // class B : public A {};
1441 // B b; // Constructor calls in order: VBase(), A(), B().
1442 // // VBase(0) is ignored because A isn't the most derived class.
1443 // This may result in the virtual base(s) being already initialized at this
1444 // point, in which case we should jump right onto non-virtual bases and
1445 // fields. To handle this, make a CFG branch. We only need to add one such
1446 // branch per constructor, since the Standard states that all virtual bases
1447 // shall be initialized before non-virtual bases and direct data members.
1448 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
1449 CFGBlock *VBaseSucc = nullptr;
Pete Cooper57d3f142015-07-30 17:22:52 +00001450 for (auto *I : llvm::reverse(CD->inits())) {
Artem Dergachev192a7472019-05-24 23:37:08 +00001451 if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
1452 I->isBaseInitializer() && I->isBaseVirtual()) {
1453 // We've reached the first virtual base init while iterating in reverse
1454 // order. Make a new block for virtual base initializers so that we
1455 // could skip them.
1456 VBaseSucc = Succ = B ? B : &cfg->getExit();
1457 Block = createBlock();
1458 }
Pete Cooper57d3f142015-07-30 17:22:52 +00001459 B = addInitializer(I);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001460 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001461 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001462 }
Artem Dergachev192a7472019-05-24 23:37:08 +00001463 if (VBaseSucc) {
1464 // Make a branch block for potentially skipping virtual base initializers.
1465 Succ = VBaseSucc;
1466 B = createBlock();
1467 B->setTerminator(
1468 CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch));
1469 addSuccessor(B, Block, true);
1470 }
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001471 }
1472
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001473 if (B)
1474 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001475
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001476 // Backpatch the gotos whose label -> block mappings we didn't know when we
1477 // encountered them.
1478 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1479 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001480
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001481 CFGBlock *B = I->block;
Jennifer Yub8fee672019-06-03 15:57:25 +00001482 if (auto *G = dyn_cast<GotoStmt>(B->getTerminator())) {
1483 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
1484 // If there is no target for the goto, then we are looking at an
1485 // incomplete AST. Handle this by not registering a successor.
1486 if (LI == LabelMap.end())
1487 continue;
1488 JumpTarget JT = LI->second;
1489 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1490 JT.scopePosition);
1491 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1492 JT.scopePosition);
1493 const VarDecl *VD = prependAutomaticObjScopeEndWithTerminator(
1494 B, I->scopePosition, JT.scopePosition);
1495 appendScopeBegin(JT.block, VD, G);
1496 addSuccessor(B, JT.block);
1497 };
1498 if (auto *G = dyn_cast<GCCAsmStmt>(B->getTerminator())) {
1499 CFGBlock *Successor = (I+1)->block;
1500 for (auto *L : G->labels()) {
1501 LabelMapTy::iterator LI = LabelMap.find(L->getLabel());
1502 // If there is no target for the goto, then we are looking at an
1503 // incomplete AST. Handle this by not registering a successor.
1504 if (LI == LabelMap.end())
1505 continue;
1506 JumpTarget JT = LI->second;
1507 // Successor has been added, so skip it.
1508 if (JT.block == Successor)
1509 continue;
1510 addSuccessor(B, JT.block);
1511 }
1512 I++;
1513 }
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001514 }
1515
1516 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001517 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001518 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1519 E = AddressTakenLabels.end(); I != E; ++I ) {
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001520 // Lookup the target block.
1521 LabelMapTy::iterator LI = LabelMap.find(*I);
1522
1523 // If there is no target block that contains label, then we are looking
1524 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001525 if (LI == LabelMap.end()) continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001526
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001527 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001528 }
Mike Stump31feda52009-07-17 01:31:16 +00001529
Mike Stump31feda52009-07-17 01:31:16 +00001530 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001531 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001532
Artem Dergachev783a4572018-02-23 22:20:39 +00001533 if (BuildOpts.AddRichCXXConstructors)
1534 assert(ConstructionContextMap.empty() &&
1535 "Not all construction contexts were cleaned up!");
1536
David Blaikiee90195c2014-08-29 18:53:26 +00001537 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001538}
Mike Stump31feda52009-07-17 01:31:16 +00001539
Ted Kremenek9aae5132007-08-23 21:42:29 +00001540/// createBlock - Used to lazily create blocks that are connected
1541/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001542CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1543 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001544 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001545 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001546 return B;
1547}
Mike Stump31feda52009-07-17 01:31:16 +00001548
Chandler Carrutha70991b2011-09-13 09:13:49 +00001549/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1550/// CFG. It is *not* connected to the current (global) successor, and instead
1551/// directly tied to the exit block in order to be reachable.
1552CFGBlock *CFGBuilder::createNoReturnBlock() {
1553 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001554 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001555 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001556 return B;
1557}
1558
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001559/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001560CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001561 if (!BuildOpts.AddInitializers)
1562 return Block;
1563
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001564 bool HasTemporaries = false;
1565
1566 // Destructors of temporaries in initialization expression should be called
1567 // after initialization finishes.
1568 Expr *Init = I->getInit();
1569 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001570 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001571
Jordan Rose6d671cc2012-09-05 22:55:23 +00001572 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001573 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001574 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001575 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1576 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001577 }
1578 }
1579
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001580 autoCreateBlock();
1581 appendInitializer(Block, I);
1582
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001583 if (Init) {
Artem Dergachev783a4572018-02-23 22:20:39 +00001584 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00001585 ConstructionContextLayer::create(cfg->getBumpVectorContext(), I),
Artem Dergachev783a4572018-02-23 22:20:39 +00001586 Init);
Artem Dergachev5a281bb2018-02-10 02:18:04 +00001587
Ted Kremenek8219b822010-12-16 07:46:53 +00001588 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001589 // For expression with temporaries go directly to subexpression to omit
1590 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001591 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1592 }
Enrico Pertosofaed8012015-06-03 10:12:40 +00001593 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1594 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1595 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1596 // may cause the same Expr to appear more than once in the CFG. Doing it
1597 // here is safe because there's only one initializer per field.
1598 autoCreateBlock();
1599 appendStmt(Block, Default);
1600 if (Stmt *Child = Default->getExpr())
1601 if (CFGBlock *R = Visit(Child))
1602 Block = R;
1603 return Block;
1604 }
1605 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001606 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001607 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001608
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001609 return Block;
1610}
1611
Fangrui Song6907ce22018-07-30 19:24:48 +00001612/// Retrieve the type of the temporary object whose lifetime was
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001613/// extended by a local reference with the given initializer.
Artem Dergacheva25809f2018-06-04 18:56:25 +00001614static QualType getReferenceInitTemporaryType(const Expr *Init,
Richard Smithb8c0f552016-12-09 18:49:13 +00001615 bool *FoundMTE = nullptr) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001616 while (true) {
1617 // Skip parentheses.
1618 Init = Init->IgnoreParens();
Artem Dergacheva25809f2018-06-04 18:56:25 +00001619
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001620 // Skip through cleanups.
1621 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1622 Init = EWC->getSubExpr();
1623 continue;
1624 }
Artem Dergacheva25809f2018-06-04 18:56:25 +00001625
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001626 // Skip through the temporary-materialization expression.
1627 if (const MaterializeTemporaryExpr *MTE
1628 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1629 Init = MTE->GetTemporaryExpr();
Richard Smithb8c0f552016-12-09 18:49:13 +00001630 if (FoundMTE)
1631 *FoundMTE = true;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001632 continue;
1633 }
Artem Dergacheva25809f2018-06-04 18:56:25 +00001634
1635 // Skip sub-object accesses into rvalues.
1636 SmallVector<const Expr *, 2> CommaLHSs;
1637 SmallVector<SubobjectAdjustment, 2> Adjustments;
1638 const Expr *SkippedInit =
1639 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1640 if (SkippedInit != Init) {
1641 Init = SkippedInit;
1642 continue;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001643 }
Artem Dergacheva25809f2018-06-04 18:56:25 +00001644
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001645 break;
1646 }
1647
1648 return Init->getType();
1649}
Matthias Gehre351c2182017-07-12 07:04:19 +00001650
Peter Szecsi999a25f2017-08-19 11:19:16 +00001651// TODO: Support adding LoopExit element to the CFG in case where the loop is
1652// ended by ReturnStmt, GotoStmt or ThrowExpr.
1653void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1654 if(!BuildOpts.AddLoopExit)
1655 return;
1656 autoCreateBlock();
1657 appendLoopExit(Block, LoopStmt);
1658}
1659
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001660void CFGBuilder::getDeclsWithEndedScope(LocalScope::const_iterator B,
1661 LocalScope::const_iterator E, Stmt *S) {
1662 if (!BuildOpts.AddScopes)
1663 return;
1664
1665 if (B == E)
1666 return;
1667
1668 // To go from B to E, one first goes up the scopes from B to P
1669 // then sideways in one scope from P to P' and then down
1670 // the scopes from P' to E.
1671 // The lifetime of all objects between B and P end.
1672 LocalScope::const_iterator P = B.shared_parent(E);
1673 int Dist = B.distance(P);
1674 if (Dist <= 0)
1675 return;
1676
1677 for (LocalScope::const_iterator I = B; I != P; ++I)
1678 if (I.pointsToFirstDeclaredVar())
1679 DeclsWithEndedScope.insert(*I);
1680}
1681
Matthias Gehre351c2182017-07-12 07:04:19 +00001682void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1683 LocalScope::const_iterator E,
1684 Stmt *S) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001685 getDeclsWithEndedScope(B, E, S);
1686 if (BuildOpts.AddScopes)
1687 addScopesEnd(B, E, S);
Matthias Gehre351c2182017-07-12 07:04:19 +00001688 if (BuildOpts.AddImplicitDtors)
1689 addAutomaticObjDtors(B, E, S);
1690 if (BuildOpts.AddLifetime)
1691 addLifetimeEnds(B, E, S);
1692}
1693
1694/// Add to current block automatic objects that leave the scope.
1695void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1696 LocalScope::const_iterator E, Stmt *S) {
1697 if (!BuildOpts.AddLifetime)
1698 return;
1699
1700 if (B == E)
1701 return;
1702
1703 // To go from B to E, one first goes up the scopes from B to P
1704 // then sideways in one scope from P to P' and then down
1705 // the scopes from P' to E.
1706 // The lifetime of all objects between B and P end.
1707 LocalScope::const_iterator P = B.shared_parent(E);
1708 int dist = B.distance(P);
1709 if (dist <= 0)
1710 return;
1711
1712 // We need to perform the scope leaving in reverse order
1713 SmallVector<VarDecl *, 10> DeclsTrivial;
1714 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1715 DeclsTrivial.reserve(dist);
1716 DeclsNonTrivial.reserve(dist);
1717
1718 for (LocalScope::const_iterator I = B; I != P; ++I)
1719 if (hasTrivialDestructor(*I))
1720 DeclsTrivial.push_back(*I);
1721 else
1722 DeclsNonTrivial.push_back(*I);
1723
1724 autoCreateBlock();
1725 // object with trivial destructor end their lifetime last (when storage
1726 // duration ends)
1727 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1728 E = DeclsTrivial.rend();
1729 I != E; ++I)
1730 appendLifetimeEnds(Block, *I, S);
1731
1732 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1733 I = DeclsNonTrivial.rbegin(),
1734 E = DeclsNonTrivial.rend();
1735 I != E; ++I)
1736 appendLifetimeEnds(Block, *I, S);
1737}
1738
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001739/// Add to current block markers for ending scopes.
1740void CFGBuilder::addScopesEnd(LocalScope::const_iterator B,
1741 LocalScope::const_iterator E, Stmt *S) {
1742 // If implicit destructors are enabled, we'll add scope ends in
1743 // addAutomaticObjDtors.
1744 if (BuildOpts.AddImplicitDtors)
1745 return;
1746
1747 autoCreateBlock();
1748
1749 for (auto I = DeclsWithEndedScope.rbegin(), E = DeclsWithEndedScope.rend();
1750 I != E; ++I)
1751 appendScopeEnd(Block, *I, S);
1752
1753 return;
1754}
1755
Marcin Swiderski5e415732010-09-30 23:05:00 +00001756/// addAutomaticObjDtors - Add to current block automatic objects destructors
1757/// for objects in range of local scope positions. Use S as trigger statement
1758/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001759void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001760 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001761 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001762 return;
1763
Marcin Swiderski5e415732010-09-30 23:05:00 +00001764 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001765 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001766
Chandler Carruthad747252011-09-13 06:09:01 +00001767 // We need to append the destructors in reverse order, but any one of them
1768 // may be a no-return destructor which changes the CFG. As a result, buffer
1769 // this sequence up and replay them in reverse order when appending onto the
1770 // CFGBlock(s).
1771 SmallVector<VarDecl*, 10> Decls;
1772 Decls.reserve(B.distance(E));
1773 for (LocalScope::const_iterator I = B; I != E; ++I)
1774 Decls.push_back(*I);
1775
1776 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1777 E = Decls.rend();
1778 I != E; ++I) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001779 if (hasTrivialDestructor(*I)) {
1780 // If AddScopes is enabled and *I is a first variable in a scope, add a
1781 // ScopeEnd marker in a Block.
1782 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I)) {
1783 autoCreateBlock();
1784 appendScopeEnd(Block, *I, S);
1785 }
1786 continue;
1787 }
Chandler Carruthad747252011-09-13 06:09:01 +00001788 // If this destructor is marked as a no-return destructor, we need to
1789 // create a new block for the destructor which does not have as a successor
1790 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001791 QualType Ty = (*I)->getType();
1792 if (Ty->isReferenceType()) {
Artem Dergacheva25809f2018-06-04 18:56:25 +00001793 Ty = getReferenceInitTemporaryType((*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001794 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001795 Ty = Context->getBaseElementType(Ty);
1796
Richard Trieu95a192a2015-05-28 00:14:02 +00001797 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001798 Block = createNoReturnBlock();
1799 else
Chandler Carruthad747252011-09-13 06:09:01 +00001800 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001801
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001802 // Add ScopeEnd just after automatic obj destructor.
1803 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I))
1804 appendScopeEnd(Block, *I, S);
Chandler Carruthad747252011-09-13 06:09:01 +00001805 appendAutomaticObjDtor(Block, *I, S);
1806 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001807}
1808
Marcin Swiderski20b88732010-10-05 05:37:00 +00001809/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1810/// base and member objects in destructor.
1811void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
Eugene Zelenko38c70522017-12-07 21:55:09 +00001812 assert(BuildOpts.AddImplicitDtors &&
1813 "Can be called only when dtors should be added");
Marcin Swiderski20b88732010-10-05 05:37:00 +00001814 const CXXRecordDecl *RD = DD->getParent();
1815
1816 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001817 for (const auto &VI : RD->vbases()) {
Artem Dergachev192a7472019-05-24 23:37:08 +00001818 // TODO: Add a VirtualBaseBranch to see if the most derived class
1819 // (which is different from the current class) is responsible for
1820 // destroying them.
Aaron Ballman445a9392014-03-13 16:15:17 +00001821 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001822 if (!CD->hasTrivialDestructor()) {
1823 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001824 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001825 }
1826 }
1827
1828 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001829 for (const auto &BI : RD->bases()) {
1830 if (!BI.isVirtual()) {
1831 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001832 if (!CD->hasTrivialDestructor()) {
1833 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001834 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001835 }
1836 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001837 }
1838
1839 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001840 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001841 // Check for constant size array. Set type to array element type.
1842 QualType QT = FI->getType();
1843 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1844 if (AT->getSize() == 0)
1845 continue;
1846 QT = AT->getElementType();
1847 }
1848
1849 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001850 if (!CD->hasTrivialDestructor()) {
1851 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001852 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001853 }
1854 }
1855}
1856
Marcin Swiderski5e415732010-09-30 23:05:00 +00001857/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1858/// way return valid LocalScope object.
1859LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
David Blaikiec1334cc2015-08-13 22:12:21 +00001860 if (Scope)
1861 return Scope;
1862 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1863 return new (alloc.Allocate<LocalScope>())
1864 LocalScope(BumpVectorContext(alloc), ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001865}
1866
1867/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Fangrui Song6907ce22018-07-30 19:24:48 +00001868/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001869void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001870 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1871 !BuildOpts.AddScopes)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001872 return;
1873
Craig Topper25542942014-05-20 04:30:07 +00001874 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001875
1876 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001877 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001878 for (auto *BI : CS->body()) {
1879 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001880 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001881 Scope = addLocalScopeForDeclStmt(DS, Scope);
1882 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001883 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001884 }
1885
1886 // For any other statement scope will be implicit and as such will be
1887 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001888 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001889 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001890}
1891
1892/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1893/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001894LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001895 LocalScope* Scope) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001896 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1897 !BuildOpts.AddScopes)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001898 return Scope;
1899
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001900 for (auto *DI : DS->decls())
1901 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001902 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001903 return Scope;
1904}
1905
Matthias Gehre351c2182017-07-12 07:04:19 +00001906bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1907 // Check for const references bound to temporary. Set type to pointee.
1908 QualType QT = VD->getType();
Artem Dergacheva25809f2018-06-04 18:56:25 +00001909 if (QT->isReferenceType()) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001910 // Attempt to determine whether this declaration lifetime-extends a
1911 // temporary.
1912 //
1913 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1914 // temporaries, and a single declaration can extend multiple temporaries.
1915 // We should look at the storage duration on each nested
1916 // MaterializeTemporaryExpr instead.
1917
1918 const Expr *Init = VD->getInit();
Artem Dergacheva25809f2018-06-04 18:56:25 +00001919 if (!Init) {
1920 // Probably an exception catch-by-reference variable.
1921 // FIXME: It doesn't really mean that the object has a trivial destructor.
1922 // Also are there other cases?
Matthias Gehre351c2182017-07-12 07:04:19 +00001923 return true;
Artem Dergacheva25809f2018-06-04 18:56:25 +00001924 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001925
Artem Dergacheva25809f2018-06-04 18:56:25 +00001926 // Lifetime-extending a temporary?
Matthias Gehre351c2182017-07-12 07:04:19 +00001927 bool FoundMTE = false;
Artem Dergacheva25809f2018-06-04 18:56:25 +00001928 QT = getReferenceInitTemporaryType(Init, &FoundMTE);
Matthias Gehre351c2182017-07-12 07:04:19 +00001929 if (!FoundMTE)
1930 return true;
1931 }
1932
1933 // Check for constant size array. Set type to array element type.
1934 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1935 if (AT->getSize() == 0)
1936 return true;
1937 QT = AT->getElementType();
1938 }
1939
1940 // Check if type is a C++ class with non-trivial destructor.
1941 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1942 return !CD->hasDefinition() || CD->hasTrivialDestructor();
1943 return true;
1944}
1945
Marcin Swiderski5e415732010-09-30 23:05:00 +00001946/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1947/// create add scope for automatic objects and temporary objects bound to
1948/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001949LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001950 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001951 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1952 "AddImplicitDtors and AddLifetime cannot be used at the same time");
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001953 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1954 !BuildOpts.AddScopes)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001955 return Scope;
1956
1957 // Check if variable is local.
1958 switch (VD->getStorageClass()) {
1959 case SC_None:
1960 case SC_Auto:
1961 case SC_Register:
1962 break;
1963 default: return Scope;
1964 }
1965
Matthias Gehre351c2182017-07-12 07:04:19 +00001966 if (BuildOpts.AddImplicitDtors) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001967 if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001968 // Add the variable to scope
1969 Scope = createOrReuseLocalScope(Scope);
1970 Scope->addVar(VD);
1971 ScopePos = Scope->begin();
1972 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001973 return Scope;
1974 }
1975
1976 assert(BuildOpts.AddLifetime);
1977 // Add the variable to scope
1978 Scope = createOrReuseLocalScope(Scope);
1979 Scope->addVar(VD);
1980 ScopePos = Scope->begin();
Marcin Swiderski5e415732010-09-30 23:05:00 +00001981 return Scope;
1982}
1983
1984/// addLocalScopeAndDtors - For given statement add local scope for it and
1985/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001986void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001987 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001988 addLocalScopeForStmt(S);
Matthias Gehre351c2182017-07-12 07:04:19 +00001989 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001990}
1991
Marcin Swiderski321a7072010-09-30 22:54:37 +00001992/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1993/// variables with automatic storage duration to CFGBlock's elements vector.
1994/// Elements will be prepended to physical beginning of the vector which
1995/// happens to be logical end. Use blocks terminator as statement that specifies
1996/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001997/// FIXME: This mechanism for adding automatic destructors doesn't handle
1998/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001999void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00002000 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Matthias Gehre351c2182017-07-12 07:04:19 +00002001 if (!BuildOpts.AddImplicitDtors)
2002 return;
Chandler Carruthad747252011-09-13 06:09:01 +00002003 BumpVectorContext &C = cfg->getBumpVectorContext();
2004 CFGBlock::iterator InsertPos
2005 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
2006 for (LocalScope::const_iterator I = B; I != E; ++I)
2007 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
Artem Dergachev4e530322019-05-24 01:34:22 +00002008 Blk->getTerminatorStmt());
Marcin Swiderski321a7072010-09-30 22:54:37 +00002009}
2010
Matthias Gehre351c2182017-07-12 07:04:19 +00002011/// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
2012/// variables with automatic storage duration to CFGBlock's elements vector.
2013/// Elements will be prepended to physical beginning of the vector which
2014/// happens to be logical end. Use blocks terminator as statement that specifies
2015/// where lifetime ends.
2016void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
2017 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
2018 if (!BuildOpts.AddLifetime)
2019 return;
2020 BumpVectorContext &C = cfg->getBumpVectorContext();
2021 CFGBlock::iterator InsertPos =
2022 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
Artem Dergachev4e530322019-05-24 01:34:22 +00002023 for (LocalScope::const_iterator I = B; I != E; ++I) {
2024 InsertPos =
2025 Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminatorStmt());
2026 }
Matthias Gehre351c2182017-07-12 07:04:19 +00002027}
Eugene Zelenko38c70522017-12-07 21:55:09 +00002028
Maxim Ostapenkodebca452018-03-12 12:26:15 +00002029/// prependAutomaticObjScopeEndWithTerminator - Prepend scope end CFGElements for
2030/// variables with automatic storage duration to CFGBlock's elements vector.
2031/// Elements will be prepended to physical beginning of the vector which
2032/// happens to be logical end. Use blocks terminator as statement that specifies
2033/// where scope ends.
2034const VarDecl *
2035CFGBuilder::prependAutomaticObjScopeEndWithTerminator(
2036 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
2037 if (!BuildOpts.AddScopes)
2038 return nullptr;
2039 BumpVectorContext &C = cfg->getBumpVectorContext();
2040 CFGBlock::iterator InsertPos =
2041 Blk->beginScopeEndInsert(Blk->end(), 1, C);
2042 LocalScope::const_iterator PlaceToInsert = B;
2043 for (LocalScope::const_iterator I = B; I != E; ++I)
2044 PlaceToInsert = I;
Artem Dergachev4e530322019-05-24 01:34:22 +00002045 Blk->insertScopeEnd(InsertPos, *PlaceToInsert, Blk->getTerminatorStmt());
Maxim Ostapenkodebca452018-03-12 12:26:15 +00002046 return *PlaceToInsert;
2047}
2048
Ted Kremenek93668002009-07-17 22:18:43 +00002049/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00002050/// blocks for ternary operators, &&, and ||. We also process "," and
2051/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002052CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00002053 if (!S) {
2054 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00002055 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00002056 }
Jordy Rose17347372011-06-10 08:49:37 +00002057
2058 if (Expr *E = dyn_cast<Expr>(S))
2059 S = E->IgnoreParens();
2060
Ted Kremenek93668002009-07-17 22:18:43 +00002061 switch (S->getStmtClass()) {
2062 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002063 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00002064
2065 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002066 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002067
John McCallc07a0c72011-02-17 10:25:35 +00002068 case Stmt::BinaryConditionalOperatorClass:
2069 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
2070
Ted Kremenek93668002009-07-17 22:18:43 +00002071 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002072 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002073
Ted Kremenek93668002009-07-17 22:18:43 +00002074 case Stmt::BlockExprClass:
Devin Coughlinb6029b72015-11-25 22:35:37 +00002075 return VisitBlockExpr(cast<BlockExpr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00002076
Ted Kremenek93668002009-07-17 22:18:43 +00002077 case Stmt::BreakStmtClass:
2078 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002079
Ted Kremenek93668002009-07-17 22:18:43 +00002080 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00002081 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00002082 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002083 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002084 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002085
Ted Kremenek93668002009-07-17 22:18:43 +00002086 case Stmt::CaseStmtClass:
2087 return VisitCaseStmt(cast<CaseStmt>(S));
2088
2089 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002090 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002091
Ted Kremenek93668002009-07-17 22:18:43 +00002092 case Stmt::CompoundStmtClass:
2093 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002094
Ted Kremenek93668002009-07-17 22:18:43 +00002095 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002096 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002097
Ted Kremenek93668002009-07-17 22:18:43 +00002098 case Stmt::ContinueStmtClass:
2099 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002100
Ted Kremenekb27378c2010-01-19 20:40:33 +00002101 case Stmt::CXXCatchStmtClass:
2102 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
2103
John McCall5d413782010-12-06 08:20:24 +00002104 case Stmt::ExprWithCleanupsClass:
2105 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00002106
Jordan Rosee5d53932012-08-23 18:10:53 +00002107 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00002108 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00002109 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
2110 // called function's declaration, not by the caller. If we simply add
2111 // this expression to the CFG, we could end up with the same Expr
2112 // appearing multiple times.
2113 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00002114 //
2115 // It's likewise possible for multiple CXXDefaultInitExprs for the same
2116 // expression to be used in the same function (through aggregate
2117 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00002118 return VisitStmt(S, asc);
2119
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00002120 case Stmt::CXXBindTemporaryExprClass:
2121 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
2122
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00002123 case Stmt::CXXConstructExprClass:
2124 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
2125
Jordan Rosec9176072014-01-13 17:59:19 +00002126 case Stmt::CXXNewExprClass:
2127 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
2128
Jordan Rosed2f40792013-09-03 17:00:57 +00002129 case Stmt::CXXDeleteExprClass:
2130 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
2131
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00002132 case Stmt::CXXFunctionalCastExprClass:
2133 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
2134
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00002135 case Stmt::CXXTemporaryObjectExprClass:
2136 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
2137
Ted Kremenekb27378c2010-01-19 20:40:33 +00002138 case Stmt::CXXThrowExprClass:
2139 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002140
Ted Kremenekb27378c2010-01-19 20:40:33 +00002141 case Stmt::CXXTryStmtClass:
2142 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002143
Richard Smith02e85f32011-04-14 22:09:26 +00002144 case Stmt::CXXForRangeStmtClass:
2145 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
2146
Ted Kremenek93668002009-07-17 22:18:43 +00002147 case Stmt::DeclStmtClass:
2148 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002149
Ted Kremenek93668002009-07-17 22:18:43 +00002150 case Stmt::DefaultStmtClass:
2151 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002152
Ted Kremenek93668002009-07-17 22:18:43 +00002153 case Stmt::DoStmtClass:
2154 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002155
Ted Kremenek93668002009-07-17 22:18:43 +00002156 case Stmt::ForStmtClass:
2157 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002158
Ted Kremenek93668002009-07-17 22:18:43 +00002159 case Stmt::GotoStmtClass:
2160 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002161
Jennifer Yub8fee672019-06-03 15:57:25 +00002162 case Stmt::GCCAsmStmtClass:
2163 return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc);
2164
Ted Kremenek93668002009-07-17 22:18:43 +00002165 case Stmt::IfStmtClass:
2166 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002167
Ted Kremenek8219b822010-12-16 07:46:53 +00002168 case Stmt::ImplicitCastExprClass:
2169 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00002170
Bill Wendling8003edc2018-11-09 00:41:36 +00002171 case Stmt::ConstantExprClass:
2172 return VisitConstantExpr(cast<ConstantExpr>(S), asc);
2173
Ted Kremenek93668002009-07-17 22:18:43 +00002174 case Stmt::IndirectGotoStmtClass:
2175 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002176
Ted Kremenek93668002009-07-17 22:18:43 +00002177 case Stmt::LabelStmtClass:
2178 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002179
Ted Kremenekda76a942012-04-12 20:34:52 +00002180 case Stmt::LambdaExprClass:
2181 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
2182
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00002183 case Stmt::MaterializeTemporaryExprClass:
2184 return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
2185 asc);
2186
Ted Kremenek5868ec62010-04-11 17:02:10 +00002187 case Stmt::MemberExprClass:
2188 return VisitMemberExpr(cast<MemberExpr>(S), asc);
2189
Ted Kremenek04268232011-11-05 00:10:15 +00002190 case Stmt::NullStmtClass:
2191 return Block;
2192
Ted Kremenek93668002009-07-17 22:18:43 +00002193 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00002194 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
2195
Ted Kremenek5022f1d2012-03-06 23:40:47 +00002196 case Stmt::ObjCAutoreleasePoolStmtClass:
2197 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
2198
Ted Kremenek93668002009-07-17 22:18:43 +00002199 case Stmt::ObjCAtSynchronizedStmtClass:
2200 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002201
Ted Kremenek93668002009-07-17 22:18:43 +00002202 case Stmt::ObjCAtThrowStmtClass:
2203 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002204
Ted Kremenek93668002009-07-17 22:18:43 +00002205 case Stmt::ObjCAtTryStmtClass:
2206 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002207
Ted Kremenek93668002009-07-17 22:18:43 +00002208 case Stmt::ObjCForCollectionStmtClass:
2209 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002210
Artem Dergachevbd880fe2018-07-31 19:39:37 +00002211 case Stmt::ObjCMessageExprClass:
2212 return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc);
2213
Ted Kremenek04268232011-11-05 00:10:15 +00002214 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00002215 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00002216
John McCallfe96e0b2011-11-06 09:01:30 +00002217 case Stmt::PseudoObjectExprClass:
2218 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
2219
Ted Kremenek93668002009-07-17 22:18:43 +00002220 case Stmt::ReturnStmtClass:
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002221 case Stmt::CoreturnStmtClass:
2222 return VisitReturnStmt(S);
Mike Stump11289f42009-09-09 15:08:12 +00002223
Nico Weber699670e2017-08-23 15:33:16 +00002224 case Stmt::SEHExceptStmtClass:
2225 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
2226
2227 case Stmt::SEHFinallyStmtClass:
2228 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
2229
2230 case Stmt::SEHLeaveStmtClass:
2231 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
2232
2233 case Stmt::SEHTryStmtClass:
2234 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
2235
Peter Collingbournee190dee2011-03-11 19:24:49 +00002236 case Stmt::UnaryExprOrTypeTraitExprClass:
2237 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
2238 asc);
Mike Stump11289f42009-09-09 15:08:12 +00002239
Ted Kremenek93668002009-07-17 22:18:43 +00002240 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002241 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002242
Ted Kremenek93668002009-07-17 22:18:43 +00002243 case Stmt::SwitchStmtClass:
2244 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002245
Zhanyong Wan6dace612010-11-22 08:45:56 +00002246 case Stmt::UnaryOperatorClass:
2247 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
2248
Ted Kremenek93668002009-07-17 22:18:43 +00002249 case Stmt::WhileStmtClass:
2250 return VisitWhileStmt(cast<WhileStmt>(S));
2251 }
2252}
Mike Stump11289f42009-09-09 15:08:12 +00002253
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002254CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002255 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00002256 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002257 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00002258 }
Mike Stump11289f42009-09-09 15:08:12 +00002259
Ted Kremenek93668002009-07-17 22:18:43 +00002260 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00002261}
Mike Stump31feda52009-07-17 01:31:16 +00002262
Ted Kremenek93668002009-07-17 22:18:43 +00002263/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00002264CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
2265 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00002266
Ted Kremenek8ae67872013-02-05 22:00:19 +00002267 // Visit the children in their reverse order so that they appear in
2268 // left-to-right (natural) order in the CFG.
2269 reverse_children RChildren(S);
2270 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
2271 I != E; ++I) {
2272 if (Stmt *Child = *I)
2273 if (CFGBlock *R = Visit(Child))
2274 B = R;
2275 }
2276 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00002277}
Mike Stump11289f42009-09-09 15:08:12 +00002278
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002279CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
2280 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00002281 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00002282
Ted Kremenek7c58d352011-03-10 01:14:11 +00002283 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00002284 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002285 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00002286 }
Ted Kremenek81e14852007-08-27 19:46:09 +00002287
Ted Kremenek9aae5132007-08-23 21:42:29 +00002288 return Block;
2289}
Mike Stump11289f42009-09-09 15:08:12 +00002290
Zhanyong Wan6dace612010-11-22 08:45:56 +00002291CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00002292 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002293 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00002294 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002295 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00002296 }
2297
Ted Kremenek8219b822010-12-16 07:46:53 +00002298 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00002299}
2300
Ted Kremeneka16436f2012-07-14 05:04:06 +00002301CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
2302 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2303 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00002304
Ted Kremeneka16436f2012-07-14 05:04:06 +00002305 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002306 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00002307
Craig Topper25542942014-05-20 04:30:07 +00002308 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
2309 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002310}
2311
2312std::pair<CFGBlock*, CFGBlock*>
2313CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
2314 Stmt *Term,
2315 CFGBlock *TrueBlock,
2316 CFGBlock *FalseBlock) {
Ted Kremenekb50e7162012-07-14 05:04:10 +00002317 // Introspect the RHS. If it is a nested logical operation, we recursively
2318 // build the CFG using this function. Otherwise, resort to default
2319 // CFG construction behavior.
2320 Expr *RHS = B->getRHS()->IgnoreParens();
2321 CFGBlock *RHSBlock, *ExitBlock;
2322
2323 do {
2324 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
2325 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002326 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002327 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
2328 break;
2329 }
2330
2331 // The RHS is not a nested logical operation. Don't push the terminator
2332 // down further, but instead visit RHS and construct the respective
2333 // pieces of the CFG, and link up the RHSBlock with the terminator
2334 // we have been provided.
2335 ExitBlock = RHSBlock = createBlock(false);
2336
Richard Trieu6a6af522017-01-04 00:46:30 +00002337 // Even though KnownVal is only used in the else branch of the next
2338 // conditional, tryEvaluateBool performs additional checking on the
2339 // Expr, so it should be called unconditionally.
2340 TryResult KnownVal = tryEvaluateBool(RHS);
2341 if (!KnownVal.isKnown())
2342 KnownVal = tryEvaluateBool(B);
2343
Ted Kremenekb50e7162012-07-14 05:04:10 +00002344 if (!Term) {
2345 assert(TrueBlock == FalseBlock);
2346 addSuccessor(RHSBlock, TrueBlock);
2347 }
2348 else {
2349 RHSBlock->setTerminator(Term);
Ted Kremenek782f0032014-03-07 02:25:53 +00002350 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
2351 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00002352 }
2353
2354 Block = RHSBlock;
2355 RHSBlock = addStmt(RHS);
2356 }
2357 while (false);
2358
2359 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002360 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002361
2362 // Generate the blocks for evaluating the LHS.
2363 Expr *LHS = B->getLHS()->IgnoreParens();
2364
2365 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
2366 if (B_LHS->isLogicalOp()) {
2367 if (B->getOpcode() == BO_LOr)
2368 FalseBlock = RHSBlock;
2369 else
2370 TrueBlock = RHSBlock;
2371
2372 // For the LHS, treat 'B' as the terminator that we want to sink
2373 // into the nested branch. The RHS always gets the top-most
2374 // terminator.
2375 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
2376 }
2377
2378 // Create the block evaluating the LHS.
2379 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00002380 CFGBlock *LHSBlock = createBlock(false);
2381 LHSBlock->setTerminator(B);
2382
Ted Kremeneka16436f2012-07-14 05:04:06 +00002383 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002384 CFGBlock *EntryLHSBlock = addStmt(LHS);
2385
2386 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002387 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002388
2389 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002390 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002391
2392 // Now link the LHSBlock with RHSBlock.
2393 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00002394 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2395 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002396 } else {
2397 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00002398 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2399 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002400 }
2401
Ted Kremenekb50e7162012-07-14 05:04:10 +00002402 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002403}
2404
2405CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2406 AddStmtChoice asc) {
2407 // && or ||
2408 if (B->isLogicalOp())
2409 return VisitLogicalOperator(B);
2410
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002411 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00002412 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002413 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00002414 addStmt(B->getRHS());
2415 return addStmt(B->getLHS());
2416 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002417
2418 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002419 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002420 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002421 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002422 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002423 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00002424 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002425 }
Mike Stump11289f42009-09-09 15:08:12 +00002426
Ted Kremenek7c58d352011-03-10 01:14:11 +00002427 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00002428 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002429 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00002430 }
2431
Zhongxing Xud95ccd52010-10-27 03:23:10 +00002432 CFGBlock *RBlock = Visit(B->getRHS());
2433 CFGBlock *LBlock = Visit(B->getLHS());
2434 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2435 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2436 // return RBlock. Otherwise we'll incorrectly return NULL.
2437 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00002438}
2439
Ted Kremeneke2499842012-04-12 20:03:44 +00002440CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002441 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00002442 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002443 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00002444 }
2445 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002446}
2447
Ted Kremenek93668002009-07-17 22:18:43 +00002448CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2449 // "break" is a control-flow statement. Thus we stop processing the current
2450 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002451 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002452 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002453
Ted Kremenek93668002009-07-17 22:18:43 +00002454 // Now create a new block that ends with the break statement.
2455 Block = createBlock(false);
2456 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00002457
Ted Kremenek93668002009-07-17 22:18:43 +00002458 // If there is no target for the break, then we are looking at an incomplete
2459 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002460 if (BreakJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00002461 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002462 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002463 } else
Ted Kremenek93668002009-07-17 22:18:43 +00002464 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00002465
Ted Kremenek9aae5132007-08-23 21:42:29 +00002466 return Block;
2467}
Mike Stump11289f42009-09-09 15:08:12 +00002468
Sebastian Redl31ad7542011-03-13 17:09:40 +00002469static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00002470 QualType Ty = E->getType();
2471 if (Ty->isFunctionPointerType())
2472 Ty = Ty->getAs<PointerType>()->getPointeeType();
2473 else if (Ty->isBlockPointerType())
2474 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002475
Mike Stump04c68512010-01-21 15:20:48 +00002476 const FunctionType *FT = Ty->getAs<FunctionType>();
2477 if (FT) {
2478 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00002479 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smitheaf11ad2018-05-03 03:58:32 +00002480 Proto->isNothrow())
Mike Stump04c68512010-01-21 15:20:48 +00002481 return false;
2482 }
2483 return true;
2484}
2485
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002486CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00002487 // Compute the callee type.
2488 QualType calleeType = C->getCallee()->getType();
2489 if (calleeType == Context->BoundMemberTy) {
2490 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2491
2492 // We should only get a null bound type if processing a dependent
2493 // CFG. Recover by assuming nothing.
2494 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00002495 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002496
John McCallc67067f2011-05-11 07:19:11 +00002497 // If this is a call to a no-return function, this stops the block here.
2498 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2499
Mike Stump04c68512010-01-21 15:20:48 +00002500 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00002501
2502 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002503 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00002504 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00002505 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00002506 }
2507
Jordan Rose5374c072013-08-19 16:27:28 +00002508 // If this is a call to a builtin function, it might not actually evaluate
2509 // its arguments. Don't add them to the CFG if this is the case.
2510 bool OmitArguments = false;
2511
Mike Stump92244b02010-01-19 22:00:14 +00002512 if (FunctionDecl *FD = C->getDirectCallee()) {
Artem Dergachev594b5412018-08-29 21:50:52 +00002513 // TODO: Support construction contexts for variadic function arguments.
2514 // These are a bit problematic and not very useful because passing
2515 // C++ objects as C-style variadic arguments doesn't work in general
2516 // (see [expr.call]).
2517 if (!FD->isVariadic())
2518 findConstructionContextsForArguments(C);
2519
Nico Weber758fbac2018-02-13 21:31:47 +00002520 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
Mike Stump8c5d7992009-07-25 21:26:53 +00002521 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00002522 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00002523 AddEHEdge = false;
Erik Pilkington9c3b5882019-01-30 20:34:53 +00002524 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size ||
2525 FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size)
Jordan Rose5374c072013-08-19 16:27:28 +00002526 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00002527 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002528
Sebastian Redl31ad7542011-03-13 17:09:40 +00002529 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00002530 AddEHEdge = false;
2531
Jordan Rose5374c072013-08-19 16:27:28 +00002532 if (OmitArguments) {
2533 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2534 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2535 autoCreateBlock();
2536 appendStmt(Block, C);
2537 return Visit(C->getCallee());
2538 }
2539
2540 if (!NoReturn && !AddEHEdge) {
Artem Dergachev1527dec2018-03-12 23:12:40 +00002541 autoCreateBlock();
2542 appendCall(Block, C);
2543
2544 return VisitChildren(C);
Jordan Rose5374c072013-08-19 16:27:28 +00002545 }
Mike Stump11289f42009-09-09 15:08:12 +00002546
Mike Stump92244b02010-01-19 22:00:14 +00002547 if (Block) {
2548 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002549 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002550 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00002551 }
Mike Stump11289f42009-09-09 15:08:12 +00002552
Chandler Carrutha70991b2011-09-13 09:13:49 +00002553 if (NoReturn)
2554 Block = createNoReturnBlock();
2555 else
2556 Block = createBlock();
2557
Artem Dergachev1527dec2018-03-12 23:12:40 +00002558 appendCall(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00002559
Mike Stump04c68512010-01-21 15:20:48 +00002560 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00002561 // Add exceptional edges.
2562 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002563 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00002564 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002565 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00002566 }
Mike Stump11289f42009-09-09 15:08:12 +00002567
Mike Stump8c5d7992009-07-25 21:26:53 +00002568 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00002569}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002570
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002571CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2572 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002573 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002574 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002575 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002576 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002577
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002578 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00002579 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002580 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002581 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002582 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002583 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002584
Ted Kremenek21822592009-07-17 18:20:32 +00002585 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002586 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002587 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002588 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002589 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002590
Ted Kremenek21822592009-07-17 18:20:32 +00002591 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00002592 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002593 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00002594 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2595 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00002596 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00002597 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00002598}
Mike Stump11289f42009-09-09 15:08:12 +00002599
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002600CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Matthias Gehre09a134e2015-11-14 00:36:50 +00002601 LocalScope::const_iterator scopeBeginPos = ScopePos;
Matthias Gehre351c2182017-07-12 07:04:19 +00002602 addLocalScopeForStmt(C);
2603
Matthias Gehre09a134e2015-11-14 00:36:50 +00002604 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
Richard Smitha547eb22016-07-14 00:11:03 +00002605 // If the body ends with a ReturnStmt, the dtors will be added in
2606 // VisitReturnStmt.
Matthias Gehre351c2182017-07-12 07:04:19 +00002607 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
Matthias Gehre09a134e2015-11-14 00:36:50 +00002608 }
2609
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002610 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002611
2612 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2613 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00002614 // If we hit a segment of code just containing ';' (NullStmts), we can
2615 // get a null block back. In such cases, just use the LastBlock
2616 if (CFGBlock *newBlock = addStmt(*I))
2617 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002618
Ted Kremenekce499c22009-08-27 23:16:26 +00002619 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002620 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002621 }
Mike Stump92244b02010-01-19 22:00:14 +00002622
Ted Kremenek93668002009-07-17 22:18:43 +00002623 return LastBlock;
2624}
Mike Stump11289f42009-09-09 15:08:12 +00002625
John McCallc07a0c72011-02-17 10:25:35 +00002626CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002627 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00002628 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00002629 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00002630
Ted Kremenek51d40b02009-07-17 18:15:54 +00002631 // Create the confluence block that will "merge" the results of the ternary
2632 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002633 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002634 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002635 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002636 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002637
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002638 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002639
Ted Kremenek51d40b02009-07-17 18:15:54 +00002640 // Create a block for the LHS expression if there is an LHS expression. A
2641 // GCC extension allows LHS to be NULL, causing the condition to be the
2642 // value that is returned instead.
2643 // e.g: x ?: y is shorthand for: x ? x : y;
2644 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002645 Block = nullptr;
2646 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00002647 const Expr *trueExpr = C->getTrueExpr();
2648 if (trueExpr != opaqueValue) {
2649 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002650 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002651 return nullptr;
2652 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00002653 }
Ted Kremenekd8138012011-02-24 03:09:15 +00002654 else
2655 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002656
Ted Kremenek51d40b02009-07-17 18:15:54 +00002657 // Create the block for the RHS expression.
2658 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002659 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002660 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002661 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002662
Richard Smithf676e452012-07-24 21:02:14 +00002663 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2664 if (BinaryOperator *Cond =
2665 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2666 if (Cond->isLogicalOp())
2667 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2668
Ted Kremenek51d40b02009-07-17 18:15:54 +00002669 // Create the block that will contain the condition.
2670 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00002671
Mike Stump773582d2009-07-23 23:25:26 +00002672 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002673 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00002674 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2675 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00002676 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00002677 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00002678
Ted Kremenekd8138012011-02-24 03:09:15 +00002679 if (opaqueValue) {
2680 // Run the condition expression if it's not trivially expressed in
2681 // terms of the opaque value (or if there is no opaque value).
2682 if (condExpr != opaqueValue)
2683 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00002684
Ted Kremenekd8138012011-02-24 03:09:15 +00002685 // Before that, run the common subexpression if there was one.
2686 // At least one of this or the above will be run.
2687 return addStmt(BCO->getCommon());
2688 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002689
Ted Kremenekd8138012011-02-24 03:09:15 +00002690 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00002691}
2692
Ted Kremenek93668002009-07-17 22:18:43 +00002693CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00002694 // Check if the Decl is for an __label__. If so, elide it from the
2695 // CFG entirely.
2696 if (isa<LabelDecl>(*DS->decl_begin()))
2697 return Block;
Fangrui Song6907ce22018-07-30 19:24:48 +00002698
Ted Kremenek3a601142011-05-24 20:41:31 +00002699 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002700 if (DS->isSingleDecl())
2701 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00002702
Craig Topper25542942014-05-20 04:30:07 +00002703 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002704
Jordan Rose8c6c8a92012-07-20 18:50:48 +00002705 // Build an individual DeclStmt for each decl.
2706 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2707 E = DS->decl_rend();
2708 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002709
Ted Kremenek93668002009-07-17 22:18:43 +00002710 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2711 // automatically freed with the CFG.
2712 DeclGroupRef DG(*I);
2713 Decl *D = *I;
George Karpenkovc1ac8082018-10-02 21:19:01 +00002714 DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00002715 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00002716
Ted Kremenek93668002009-07-17 22:18:43 +00002717 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002718 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002719 }
Mike Stump11289f42009-09-09 15:08:12 +00002720
2721 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002722}
Mike Stump11289f42009-09-09 15:08:12 +00002723
Ted Kremenek93668002009-07-17 22:18:43 +00002724/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002725/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002726CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002727 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002728 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002729
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002730 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002731 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2732 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002733 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002734 }
Mike Stump11289f42009-09-09 15:08:12 +00002735
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002736 bool HasTemporaries = false;
2737
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002738 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002739 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002740
2741 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2742 // For static variables, we need to create a branch to track
2743 // whether or not they are initialized.
2744 if (Block) {
2745 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002746 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002747 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002748 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002749 }
2750 blockAfterStaticInit = Succ;
2751 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002752
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002753 // Destructors of temporaries in initialization expression should be called
2754 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002755 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002756 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002757 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002758
Jordan Rose6d671cc2012-09-05 22:55:23 +00002759 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002760 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002761 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002762 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2763 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002764 }
2765 }
2766
2767 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002768 appendStmt(Block, DS);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002769
Artem Dergachev783a4572018-02-23 22:20:39 +00002770 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00002771 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
Artem Dergachev783a4572018-02-23 22:20:39 +00002772 Init);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002773
Ted Kremenek213d0532012-03-22 05:57:43 +00002774 // Keep track of the last non-null block, as 'Block' can be nulled out
2775 // if the initializer expression is something like a 'while' in a
2776 // statement-expression.
2777 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002778
Ted Kremenek93668002009-07-17 22:18:43 +00002779 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002780 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002781 // For expression with temporaries go directly to subexpression to omit
2782 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002783 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2784 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2785 LastBlock = newBlock;
2786 }
2787 else {
2788 if (CFGBlock *newBlock = Visit(Init))
2789 LastBlock = newBlock;
2790 }
Ted Kremenek93668002009-07-17 22:18:43 +00002791 }
Mike Stump11289f42009-09-09 15:08:12 +00002792
Ted Kremenek93668002009-07-17 22:18:43 +00002793 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002794 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002795 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002796 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2797 LastBlock = newBlock;
2798 }
Mike Stump11289f42009-09-09 15:08:12 +00002799
Maxim Ostapenkodebca452018-03-12 12:26:15 +00002800 maybeAddScopeBeginForVarDecl(Block, VD, DS);
2801
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002802 // Remove variable from local scope.
2803 if (ScopePos && VD == *ScopePos)
2804 ++ScopePos;
2805
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002806 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002807 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002808 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002809 Block = createBlock(false);
2810 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002811 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002812 addSuccessor(Block, B);
2813 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002814 }
2815
2816 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002817}
2818
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002819CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002820 // We may see an if statement in the middle of a basic block, or it may be the
2821 // first statement we are processing. In either case, we create a new basic
2822 // block. First, we create the blocks for the then...else statements, and
2823 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002824 // middle of a block, we stop processing that block. That block is then the
2825 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002826
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002827 // Save local scope position because in case of condition variable ScopePos
2828 // won't be restored when traversing AST.
2829 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2830
Richard Smitha547eb22016-07-14 00:11:03 +00002831 // Create local scope for C++17 if init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00002832 if (Stmt *Init = I->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00002833 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00002834
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002835 // Create local scope for possible condition variable.
2836 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00002837 if (VarDecl *VD = I->getConditionVariable())
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002838 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00002839
Matthias Gehre351c2182017-07-12 07:04:19 +00002840 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002841
Chris Lattner57540c52011-04-15 05:22:18 +00002842 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002843 // block.
2844 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002845 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002846 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002847 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002848 }
Mike Stump31feda52009-07-17 01:31:16 +00002849
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002850 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002851 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002852
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002853 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002854 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002855
Ted Kremenek9aae5132007-08-23 21:42:29 +00002856 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002857 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002858 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002859
2860 // If branch is not a compound statement create implicit scope
2861 // and add destructors.
2862 if (!isa<CompoundStmt>(Else))
2863 addLocalScopeAndDtors(Else);
2864
Ted Kremenek93668002009-07-17 22:18:43 +00002865 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002866
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002867 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2868 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002869 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002870 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002871 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002872 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002873 }
Mike Stump31feda52009-07-17 01:31:16 +00002874
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002875 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002876 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002877 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002878 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002879 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002880 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002881 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002882
2883 // If branch is not a compound statement create implicit scope
2884 // and add destructors.
2885 if (!isa<CompoundStmt>(Then))
2886 addLocalScopeAndDtors(Then);
2887
Ted Kremenek93668002009-07-17 22:18:43 +00002888 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002889
Ted Kremenek1b379512009-04-01 03:52:47 +00002890 if (!ThenBlock) {
2891 // We can reach here if the "then" body has all NullStmts.
2892 // Create an empty block so we can distinguish between true and false
2893 // branches in path-sensitive analyses.
2894 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002895 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002896 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002897 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002898 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002899 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002900 }
2901
Ted Kremenekb50e7162012-07-14 05:04:10 +00002902 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2903 // having these handle the actual control-flow jump. Note that
2904 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2905 // we resort to the old control-flow behavior. This special handling
2906 // removes infeasible paths from the control-flow graph by having the
2907 // control-flow transfer of '&&' or '||' go directly into the then/else
2908 // blocks directly.
Richard Smith509bbd12017-01-13 22:16:41 +00002909 BinaryOperator *Cond =
2910 I->getConditionVariable()
2911 ? nullptr
2912 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
2913 CFGBlock *LastBlock;
2914 if (Cond && Cond->isLogicalOp())
2915 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2916 else {
2917 // Now create a new block containing the if statement.
2918 Block = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002919
Richard Smith509bbd12017-01-13 22:16:41 +00002920 // Set the terminator of the new block to the If statement.
2921 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002922
Richard Smith509bbd12017-01-13 22:16:41 +00002923 // See if this is a known constant.
2924 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002925
Richard Smith509bbd12017-01-13 22:16:41 +00002926 // Add the successors. If we know that specific branches are
2927 // unreachable, inform addSuccessor() of that knowledge.
2928 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2929 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump773582d2009-07-23 23:25:26 +00002930
Richard Smith509bbd12017-01-13 22:16:41 +00002931 // Add the condition as the last statement in the new block. This may
2932 // create new blocks as the condition may contain control-flow. Any newly
2933 // created blocks will be pointed to be "Block".
2934 LastBlock = addStmt(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002935
Richard Smith509bbd12017-01-13 22:16:41 +00002936 // If the IfStmt contains a condition variable, add it and its
2937 // initializer to the CFG.
2938 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2939 autoCreateBlock();
2940 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2941 }
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002942 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002943
Richard Smitha547eb22016-07-14 00:11:03 +00002944 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2945 if (Stmt *Init = I->getInit()) {
2946 autoCreateBlock();
2947 LastBlock = addStmt(Init);
2948 }
2949
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002950 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002951}
Mike Stump31feda52009-07-17 01:31:16 +00002952
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002953CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002954 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002955 //
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002956 // NOTE: If a "return" or "co_return" appears in the middle of a block, this
2957 // means that the code afterwards is DEAD (unreachable). We still keep
2958 // a basic block for that code; a simple "mark-and-sweep" from the entry
2959 // block will be able to report such dead blocks.
2960 assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S));
Ted Kremenek9aae5132007-08-23 21:42:29 +00002961
2962 // Create the new block.
2963 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002964
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002965 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), S);
Pavel Labath921e7652013-09-06 08:12:48 +00002966
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002967 if (auto *R = dyn_cast<ReturnStmt>(S))
2968 findConstructionContexts(
2969 ConstructionContextLayer::create(cfg->getBumpVectorContext(), R),
2970 R->getRetValue());
Artem Dergachev9ac2e112018-02-12 22:36:36 +00002971
Pavel Labath921e7652013-09-06 08:12:48 +00002972 // If the one of the destructors does not return, we already have the Exit
2973 // block as a successor.
2974 if (!Block->hasNoReturnElement())
2975 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002976
2977 // Add the return statement to the block. This may create new blocks if R
2978 // contains control-flow (short-circuit operations).
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002979 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002980}
2981
Nico Weber699670e2017-08-23 15:33:16 +00002982CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
2983 // SEHExceptStmt are treated like labels, so they are the first statement in a
2984 // block.
2985
2986 // Save local scope position because in case of exception variable ScopePos
2987 // won't be restored when traversing AST.
2988 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2989
2990 addStmt(ES->getBlock());
2991 CFGBlock *SEHExceptBlock = Block;
2992 if (!SEHExceptBlock)
2993 SEHExceptBlock = createBlock();
2994
2995 appendStmt(SEHExceptBlock, ES);
2996
2997 // Also add the SEHExceptBlock as a label, like with regular labels.
2998 SEHExceptBlock->setLabel(ES);
2999
3000 // Bail out if the CFG is bad.
3001 if (badCFG)
3002 return nullptr;
3003
3004 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3005 Block = nullptr;
3006
3007 return SEHExceptBlock;
3008}
3009
3010CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
3011 return VisitCompoundStmt(FS->getBlock());
3012}
3013
3014CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
3015 // "__leave" is a control-flow statement. Thus we stop processing the current
3016 // block.
3017 if (badCFG)
3018 return nullptr;
3019
3020 // Now create a new block that ends with the __leave statement.
3021 Block = createBlock(false);
3022 Block->setTerminator(LS);
3023
3024 // If there is no target for the __leave, then we are looking at an incomplete
3025 // AST. This means that the CFG cannot be constructed.
3026 if (SEHLeaveJumpTarget.block) {
3027 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
3028 addSuccessor(Block, SEHLeaveJumpTarget.block);
3029 } else
3030 badCFG = true;
3031
3032 return Block;
3033}
3034
3035CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
3036 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
3037 // processing the current block.
3038 CFGBlock *SEHTrySuccessor = nullptr;
3039
3040 if (Block) {
3041 if (badCFG)
3042 return nullptr;
3043 SEHTrySuccessor = Block;
3044 } else SEHTrySuccessor = Succ;
3045
3046 // FIXME: Implement __finally support.
3047 if (Terminator->getFinallyHandler())
3048 return NYS();
3049
3050 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
3051
3052 // Create a new block that will contain the __try statement.
3053 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3054
3055 // Add the terminator in the __try block.
3056 NewTryTerminatedBlock->setTerminator(Terminator);
3057
3058 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
3059 // The code after the try is the implicit successor if there's an __except.
3060 Succ = SEHTrySuccessor;
3061 Block = nullptr;
3062 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
3063 if (!ExceptBlock)
3064 return nullptr;
3065 // Add this block to the list of successors for the block with the try
3066 // statement.
3067 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
3068 }
3069 if (PrevSEHTryTerminatedBlock)
3070 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
3071 else
3072 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3073
3074 // The code after the try is the implicit successor.
3075 Succ = SEHTrySuccessor;
3076
3077 // Save the current "__try" context.
3078 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
3079 NewTryTerminatedBlock);
3080 cfg->addTryDispatchBlock(TryTerminatedBlock);
3081
3082 // Save the current value for the __leave target.
3083 // All __leaves should go to the code following the __try
3084 // (FIXME: or if the __try has a __finally, to the __finally.)
3085 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
3086 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
3087
3088 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
3089 Block = nullptr;
3090 return addStmt(Terminator->getTryBlock());
3091}
3092
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003093CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003094 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00003095 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003096 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003097
Ted Kremenek93668002009-07-17 22:18:43 +00003098 if (!LabelBlock) // This can happen when the body is empty, i.e.
3099 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00003100
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003101 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
3102 "label already in map");
3103 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003104
3105 // Labels partition blocks, so this is the end of the basic block we were
3106 // processing (L is the block's label). Because this is label (and we have
3107 // already processed the substatement) there is no extra control-flow to worry
3108 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00003109 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003110 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003111 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003112
3113 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00003114 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003115
Ted Kremenek9aae5132007-08-23 21:42:29 +00003116 // This block is now the implicit successor of other blocks.
3117 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003118
Ted Kremenek9aae5132007-08-23 21:42:29 +00003119 return LabelBlock;
3120}
3121
Devin Coughlinb6029b72015-11-25 22:35:37 +00003122CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
3123 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3124 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
3125 if (Expr *CopyExpr = CI.getCopyExpr()) {
3126 CFGBlock *Tmp = Visit(CopyExpr);
3127 if (Tmp)
3128 LastBlock = Tmp;
3129 }
3130 }
3131 return LastBlock;
3132}
3133
Ted Kremenekda76a942012-04-12 20:34:52 +00003134CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
3135 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3136 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
3137 et = E->capture_init_end(); it != et; ++it) {
3138 if (Expr *Init = *it) {
3139 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00003140 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00003141 LastBlock = Tmp;
3142 }
3143 }
3144 return LastBlock;
3145}
Fangrui Song6907ce22018-07-30 19:24:48 +00003146
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003147CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00003148 // Goto is a control-flow statement. Thus we stop processing the current
3149 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00003150
Ted Kremenek9aae5132007-08-23 21:42:29 +00003151 Block = createBlock(false);
3152 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00003153
3154 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003155 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00003156
Ted Kremenek9aae5132007-08-23 21:42:29 +00003157 if (I == LabelMap.end())
3158 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003159 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3160 else {
3161 JumpTarget JT = I->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00003162 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003163 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003164 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00003165
Mike Stump31feda52009-07-17 01:31:16 +00003166 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003167}
3168
Jennifer Yub8fee672019-06-03 15:57:25 +00003169CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
3170 // Goto is a control-flow statement. Thus we stop processing the current
3171 // block and create a new one.
3172
3173 if (!G->isAsmGoto())
3174 return VisitStmt(G, asc);
3175
3176 if (Block) {
3177 Succ = Block;
3178 if (badCFG)
3179 return nullptr;
3180 }
3181 Block = createBlock();
3182 Block->setTerminator(G);
3183 // We will backpatch this block later for all the labels.
3184 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3185 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
3186 // used to avoid adding "Succ" again.
3187 BackpatchBlocks.push_back(JumpSource(Succ, ScopePos));
3188 return Block;
3189}
3190
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003191CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00003192 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003193
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003194 // Save local scope position because in case of condition variable ScopePos
3195 // won't be restored when traversing AST.
3196 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3197
3198 // Create local scope for init statement and possible condition variable.
3199 // Add destructor for init statement and condition variable.
3200 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003201 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003202 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003203 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3204
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003205 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003206 addLocalScopeForVarDecl(VD);
3207 LocalScope::const_iterator ContinueScopePos = ScopePos;
3208
Matthias Gehre351c2182017-07-12 07:04:19 +00003209 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003210
Peter Szecsi999a25f2017-08-19 11:19:16 +00003211 addLoopExit(F);
3212
Mike Stump014b3ea2009-07-21 01:12:51 +00003213 // "for" is a control-flow statement. Thus we stop processing the current
3214 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003215 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003216 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003217 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003218 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003219 } else
3220 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003221
Ted Kremenek304a9532010-05-21 20:30:15 +00003222 // Save the current value for the break targets.
3223 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003224 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003225 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00003226
Craig Topper25542942014-05-20 04:30:07 +00003227 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00003228
Ted Kremenek9aae5132007-08-23 21:42:29 +00003229 // Now create the loop body.
3230 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003231 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003232
Ted Kremenekb50e7162012-07-14 05:04:10 +00003233 // Save the current values for Block, Succ, continue and break targets.
3234 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3235 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003236
Ted Kremenekb50e7162012-07-14 05:04:10 +00003237 // Create an empty block to represent the transition block for looping back
3238 // to the head of the loop. If we have increment code, it will
3239 // go in this block as well.
3240 Block = Succ = TransitionBlock = createBlock(false);
3241 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00003242
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003243 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00003244 // Generate increment code in its own basic block. This is the target of
3245 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00003246 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00003247 }
Mike Stump31feda52009-07-17 01:31:16 +00003248
Ted Kremenek902393b2009-04-28 00:51:56 +00003249 // Finish up the increment (or empty) block if it hasn't been already.
3250 if (Block) {
3251 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003252 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003253 return nullptr;
3254 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00003255 }
Mike Stump31feda52009-07-17 01:31:16 +00003256
Ted Kremenekb50e7162012-07-14 05:04:10 +00003257 // The starting block for the loop increment is the block that should
3258 // represent the 'loop target' for looping back to the start of the loop.
3259 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3260 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00003261
Ted Kremenekb50e7162012-07-14 05:04:10 +00003262 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00003263 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00003264
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003265 // If body is not a compound statement create implicit scope
3266 // and add destructors.
3267 if (!isa<CompoundStmt>(F->getBody()))
3268 addLocalScopeAndDtors(F->getBody());
3269
Mike Stump31feda52009-07-17 01:31:16 +00003270 // Now populate the body block, and in the process create new blocks as we
3271 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003272 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00003273
Ted Kremenekb50e7162012-07-14 05:04:10 +00003274 if (!BodyBlock) {
3275 // In the case of "for (...;...;...);" we can have a null BodyBlock.
3276 // Use the continue jump target as the proxy for the body.
3277 BodyBlock = ContinueJumpTarget.block;
3278 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003279 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003280 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003281 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003282
Ted Kremenekb50e7162012-07-14 05:04:10 +00003283 // Because of short-circuit evaluation, the condition of the loop can span
3284 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3285 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00003286 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003287
Ted Kremenekb50e7162012-07-14 05:04:10 +00003288 do {
3289 Expr *C = F->getCond();
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003290 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003291
3292 // Specially handle logical operators, which have a slightly
3293 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00003294 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00003295 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00003296 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003297 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00003298 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
3299 break;
3300 }
3301
3302 // The default case when not handling logical operators.
3303 EntryConditionBlock = ExitConditionBlock = createBlock(false);
3304 ExitConditionBlock->setTerminator(F);
3305
3306 // See if this is a known constant.
3307 TryResult KnownVal(true);
3308
3309 if (C) {
3310 // Now add the actual condition to the condition block.
3311 // Because the condition itself may contain control-flow, new blocks may
3312 // be created. Thus we update "Succ" after adding the condition.
3313 Block = ExitConditionBlock;
3314 EntryConditionBlock = addStmt(C);
3315
3316 // If this block contains a condition variable, add both the condition
3317 // variable and initializer to the CFG.
3318 if (VarDecl *VD = F->getConditionVariable()) {
3319 if (Expr *Init = VD->getInit()) {
3320 autoCreateBlock();
Artem Dergachevab9b78b2018-04-19 23:30:15 +00003321 const DeclStmt *DS = F->getConditionVariableDeclStmt();
3322 assert(DS->isSingleDecl());
3323 findConstructionContexts(
Artem Dergachev1f8cb3a2018-07-31 21:12:42 +00003324 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
Artem Dergachevab9b78b2018-04-19 23:30:15 +00003325 Init);
3326 appendStmt(Block, DS);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003327 EntryConditionBlock = addStmt(Init);
3328 assert(Block == EntryConditionBlock);
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003329 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003330 }
3331 }
3332
3333 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003334 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003335
3336 KnownVal = tryEvaluateBool(C);
3337 }
3338
3339 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00003340 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003341 // Link up the condition block with the code that follows the loop. (the
3342 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003343 addSuccessor(ExitConditionBlock,
3344 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003345 } while (false);
3346
3347 // Link up the loop-back block to the entry condition block.
3348 addSuccessor(TransitionBlock, EntryConditionBlock);
Fangrui Song6907ce22018-07-30 19:24:48 +00003349
Ted Kremenekb50e7162012-07-14 05:04:10 +00003350 // The condition block is the implicit successor for any code above the loop.
3351 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003352
Ted Kremenek9aae5132007-08-23 21:42:29 +00003353 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00003354 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003355 if (Stmt *I = F->getInit()) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003356 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3357 ScopePos = LoopBeginScopePos;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003358 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00003359 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003360 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003361
3362 // There is no loop initialization. We are thus basically a while loop.
3363 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00003364 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003365 Succ = EntryConditionBlock;
3366 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003367}
3368
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00003369CFGBlock *
3370CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
3371 AddStmtChoice asc) {
3372 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00003373 ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00003374 MTE->getTemporary());
3375
3376 return VisitStmt(MTE, asc);
3377}
3378
Ted Kremenek5868ec62010-04-11 17:02:10 +00003379CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003380 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00003381 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003382 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00003383 }
Ted Kremenek8219b822010-12-16 07:46:53 +00003384 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00003385}
3386
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003387CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00003388 // Objective-C fast enumeration 'for' statements:
3389 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3390 //
3391 // for ( Type newVariable in collection_expression ) { statements }
3392 //
3393 // becomes:
3394 //
3395 // prologue:
3396 // 1. collection_expression
3397 // T. jump to loop_entry
3398 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003399 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00003400 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3401 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3402 // TB:
3403 // statements
3404 // T. jump to loop_entry
3405 // FB:
3406 // what comes after
3407 //
3408 // and
3409 //
3410 // Type existingItem;
3411 // for ( existingItem in expression ) { statements }
3412 //
3413 // becomes:
3414 //
Mike Stump31feda52009-07-17 01:31:16 +00003415 // the same with newVariable replaced with existingItem; the binding works
3416 // the same except that for one ObjCForCollectionStmt::getElement() returns
3417 // a DeclStmt and the other returns a DeclRefExpr.
Mike Stump31feda52009-07-17 01:31:16 +00003418
Craig Topper25542942014-05-20 04:30:07 +00003419 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003420
Ted Kremenek9d56e642008-11-11 17:10:00 +00003421 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003422 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003423 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00003424 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003425 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00003426 } else
3427 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003428
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003429 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003430 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003431
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003432 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003433 ExitConditionBlock->setTerminator(S);
3434
3435 // The last statement in the block should be the ObjCForCollectionStmt, which
3436 // performs the actual binding to 'element' and determines if there are any
3437 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00003438 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003439 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003440
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003441 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00003442 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00003443 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00003444 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3445 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00003446 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003447 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003448 return nullptr;
3449 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003450 }
Mike Stump31feda52009-07-17 01:31:16 +00003451
3452 // The condition block is the implicit successor for the loop body as well as
3453 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003454 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003455
Ted Kremenek9d56e642008-11-11 17:10:00 +00003456 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00003457 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003458 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00003459 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003460 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00003461 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003462
Anna Zaks56b49752013-06-22 00:23:20 +00003463 // Add an intermediate block between the BodyBlock and the
3464 // EntryConditionBlock to represent the "loop back" transition, for looping
3465 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00003466 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00003467 Succ = LoopBackBlock = createBlock();
3468 LoopBackBlock->setLoopTarget(S);
Fangrui Song6907ce22018-07-30 19:24:48 +00003469
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003470 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00003471 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003472
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003473 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003474
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003475 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00003476 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00003477 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003478 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003479 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003480 }
Mike Stump31feda52009-07-17 01:31:16 +00003481
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003482 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003483 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003484 }
Mike Stump31feda52009-07-17 01:31:16 +00003485
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003486 // Link up the condition block with the code that follows the loop.
3487 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003488 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003489
Ted Kremenek9d56e642008-11-11 17:10:00 +00003490 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003491 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00003492 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00003493}
3494
Ted Kremenek5022f1d2012-03-06 23:40:47 +00003495CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3496 // Inline the body.
3497 return addStmt(S->getSubStmt());
3498 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3499}
3500
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003501CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00003502 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00003503
Ted Kremenek49805452009-05-02 01:49:13 +00003504 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00003505 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00003506
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003507 // The sync body starts its own basic block. This makes it a little easier
3508 // for diagnostic clients.
3509 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003510 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003511 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003512
Craig Topper25542942014-05-20 04:30:07 +00003513 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00003514 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003515 }
Mike Stump31feda52009-07-17 01:31:16 +00003516
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003517 // Add the @synchronized to the CFG.
3518 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003519 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003520
Ted Kremenek49805452009-05-02 01:49:13 +00003521 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00003522 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00003523}
Mike Stump31feda52009-07-17 01:31:16 +00003524
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003525CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003526 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00003527 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00003528}
Ted Kremenek9d56e642008-11-11 17:10:00 +00003529
John McCallfe96e0b2011-11-06 09:01:30 +00003530CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3531 autoCreateBlock();
3532
3533 // Add the PseudoObject as the last thing.
3534 appendStmt(Block, E);
3535
Fangrui Song6907ce22018-07-30 19:24:48 +00003536 CFGBlock *lastBlock = Block;
John McCallfe96e0b2011-11-06 09:01:30 +00003537
3538 // Before that, evaluate all of the semantics in order. In
3539 // CFG-land, that means appending them in reverse order.
3540 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3541 Expr *Semantic = E->getSemanticExpr(--i);
3542
3543 // If the semantic is an opaque value, we're being asked to bind
3544 // it to its source expression.
3545 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3546 Semantic = OVE->getSourceExpr();
3547
3548 if (CFGBlock *B = Visit(Semantic))
3549 lastBlock = B;
3550 }
3551
3552 return lastBlock;
3553}
3554
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003555CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00003556 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003557
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003558 // Save local scope position because in case of condition variable ScopePos
3559 // won't be restored when traversing AST.
3560 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3561
3562 // Create local scope for possible condition variable.
3563 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003564 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003565 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003566 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003567 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003568 }
Peter Szecsi999a25f2017-08-19 11:19:16 +00003569 addLoopExit(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003570
Mike Stump014b3ea2009-07-21 01:12:51 +00003571 // "while" is a control-flow statement. Thus we stop processing the current
3572 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003573 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003574 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003575 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003576 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003577 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003578 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00003579 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00003580 }
Mike Stump31feda52009-07-17 01:31:16 +00003581
Craig Topper25542942014-05-20 04:30:07 +00003582 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00003583
Ted Kremenek9aae5132007-08-23 21:42:29 +00003584 // Process the loop body.
3585 {
Ted Kremenek49936f72009-04-28 03:09:44 +00003586 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00003587
Ted Kremenekb50e7162012-07-14 05:04:10 +00003588 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003589 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3590 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00003591 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00003592
Mike Stump31feda52009-07-17 01:31:16 +00003593 // Create an empty block to represent the transition block for looping back
3594 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003595 Succ = TransitionBlock = createBlock(false);
3596 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003597 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003598
Ted Kremenek9aae5132007-08-23 21:42:29 +00003599 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003600 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003601
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003602 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00003603 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003604
3605 // If body is not a compound statement create implicit scope
3606 // and add destructors.
3607 if (!isa<CompoundStmt>(W->getBody()))
3608 addLocalScopeAndDtors(W->getBody());
3609
Ted Kremenek9aae5132007-08-23 21:42:29 +00003610 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003611 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003612
Ted Kremeneke9610502007-08-30 18:39:40 +00003613 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003614 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00003615 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003616 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003617 }
3618
3619 // Because of short-circuit evaluation, the condition of the loop can span
3620 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3621 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00003622 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003623
3624 do {
3625 Expr *C = W->getCond();
3626
3627 // Specially handle logical operators, which have a slightly
3628 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00003629 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00003630 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003631 std::tie(EntryConditionBlock, ExitConditionBlock) =
3632 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003633 break;
3634 }
3635
3636 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00003637 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003638 ExitConditionBlock->setTerminator(W);
3639
3640 // Now add the actual condition to the condition block.
3641 // Because the condition itself may contain control-flow, new blocks may
3642 // be created. Thus we update "Succ" after adding the condition.
3643 Block = ExitConditionBlock;
3644 Block = EntryConditionBlock = addStmt(C);
3645
3646 // If this block contains a condition variable, add both the condition
3647 // variable and initializer to the CFG.
3648 if (VarDecl *VD = W->getConditionVariable()) {
3649 if (Expr *Init = VD->getInit()) {
3650 autoCreateBlock();
Artem Dergachevab9b78b2018-04-19 23:30:15 +00003651 const DeclStmt *DS = W->getConditionVariableDeclStmt();
3652 assert(DS->isSingleDecl());
3653 findConstructionContexts(
3654 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
3655 const_cast<DeclStmt *>(DS)),
3656 Init);
3657 appendStmt(Block, DS);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003658 EntryConditionBlock = addStmt(Init);
3659 assert(Block == EntryConditionBlock);
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003660 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003661 }
Ted Kremenek55957a82009-05-02 00:13:27 +00003662 }
Mike Stump31feda52009-07-17 01:31:16 +00003663
Ted Kremenekb50e7162012-07-14 05:04:10 +00003664 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003665 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003666
3667 // See if this is a known constant.
3668 const TryResult& KnownVal = tryEvaluateBool(C);
3669
Ted Kremenek30754282009-07-24 04:47:11 +00003670 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00003671 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003672 // Link up the condition block with the code that follows the loop. (the
3673 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003674 addSuccessor(ExitConditionBlock,
3675 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003676 } while(false);
3677
3678 // Link up the loop-back block to the entry condition block.
3679 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00003680
3681 // There can be no more statements in the condition block since we loop back
3682 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003683 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003684
Ted Kremenek1ce53c42009-12-24 01:34:10 +00003685 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003686 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00003687 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003688}
Mike Stump11289f42009-09-09 15:08:12 +00003689
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003690CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003691 // FIXME: For now we pretend that @catch and the code it contains does not
3692 // exit.
3693 return Block;
3694}
Mike Stump31feda52009-07-17 01:31:16 +00003695
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003696CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00003697 // FIXME: This isn't complete. We basically treat @throw like a return
3698 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00003699
Ted Kremenek0868eea2009-09-24 18:45:41 +00003700 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003701 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003702 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003703
Ted Kremenek93041ba2008-12-09 20:20:09 +00003704 // Create the new block.
3705 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003706
Ted Kremenek93041ba2008-12-09 20:20:09 +00003707 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003708 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00003709
3710 // Add the statement to the block. This may create new blocks if S contains
3711 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003712 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00003713}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003714
Artem Dergachevbd880fe2018-07-31 19:39:37 +00003715CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
3716 AddStmtChoice asc) {
3717 findConstructionContextsForArguments(ME);
3718
3719 autoCreateBlock();
Artem Dergacheve1f30622018-07-31 19:46:14 +00003720 appendObjCMessage(Block, ME);
Artem Dergachevbd880fe2018-07-31 19:39:37 +00003721
3722 return VisitChildren(ME);
3723}
3724
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003725CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00003726 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003727 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003728 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003729
3730 // Create the new block.
3731 Block = createBlock(false);
3732
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003733 if (TryTerminatedBlock)
3734 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003735 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003736 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003737 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003738 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003739
3740 // Add the statement to the block. This may create new blocks if S contains
3741 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003742 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003743}
3744
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003745CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00003746 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003747
Peter Szecsi999a25f2017-08-19 11:19:16 +00003748 addLoopExit(D);
3749
Mike Stump8d50b6a2009-07-21 01:27:50 +00003750 // "do...while" is a control-flow statement. Thus we stop processing the
3751 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003752 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003753 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003754 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003755 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003756 } else
3757 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003758
3759 // Because of short-circuit evaluation, the condition of the loop can span
3760 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3761 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003762 CFGBlock *ExitConditionBlock = createBlock(false);
3763 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003764
Ted Kremenek81e14852007-08-27 19:46:09 +00003765 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003766 ExitConditionBlock->setTerminator(D);
3767
3768 // Now add the actual condition to the condition block. Because the condition
3769 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003770 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00003771 Block = ExitConditionBlock;
3772 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00003773 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003774 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003775 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003776 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003777 }
Mike Stump31feda52009-07-17 01:31:16 +00003778
Ted Kremeneka1523a32008-02-27 07:20:00 +00003779 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00003780 Succ = EntryConditionBlock;
3781
Mike Stump773582d2009-07-23 23:25:26 +00003782 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003783 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00003784
Ted Kremenek9aae5132007-08-23 21:42:29 +00003785 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00003786 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003787 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003788 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003789
Ted Kremenek9aae5132007-08-23 21:42:29 +00003790 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003791 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3792 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3793 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003794
Ted Kremenek9aae5132007-08-23 21:42:29 +00003795 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003796 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003797
Ted Kremenek9aae5132007-08-23 21:42:29 +00003798 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003799 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003800
Ted Kremenek9aae5132007-08-23 21:42:29 +00003801 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00003802 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003803
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003804 // If body is not a compound statement create implicit scope
3805 // and add destructors.
3806 if (!isa<CompoundStmt>(D->getBody()))
3807 addLocalScopeAndDtors(D->getBody());
3808
Ted Kremenek9aae5132007-08-23 21:42:29 +00003809 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00003810 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003811
Ted Kremeneke9610502007-08-30 18:39:40 +00003812 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00003813 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00003814 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003815 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003816 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003817 }
Mike Stump31feda52009-07-17 01:31:16 +00003818
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003819 // Add an intermediate block between the BodyBlock and the
3820 // ExitConditionBlock to represent the "loop back" transition. Create an
3821 // empty block to represent the transition block for looping back to the
3822 // head of the loop.
3823 // FIXME: Can we do this more efficiently without adding another block?
3824 Block = nullptr;
3825 Succ = BodyBlock;
3826 CFGBlock *LoopBackBlock = createBlock();
3827 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00003828
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003829 if (!KnownVal.isFalse())
Ted Kremenek110974d2010-08-17 20:59:56 +00003830 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003831 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00003832 else
Craig Topper25542942014-05-20 04:30:07 +00003833 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003834 }
Mike Stump31feda52009-07-17 01:31:16 +00003835
Ted Kremenek30754282009-07-24 04:47:11 +00003836 // Link up the condition block with the code that follows the loop.
3837 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00003838 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003839
3840 // There can be no more statements in the body block(s) since we loop back to
3841 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003842 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003843
Ted Kremenek9aae5132007-08-23 21:42:29 +00003844 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003845 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003846 return BodyBlock;
3847}
3848
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003849CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003850 // "continue" is a control-flow statement. Thus we stop processing the
3851 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003852 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003853 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003854
Ted Kremenek9aae5132007-08-23 21:42:29 +00003855 // Now create a new block that ends with the continue statement.
3856 Block = createBlock(false);
3857 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00003858
Ted Kremenek9aae5132007-08-23 21:42:29 +00003859 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00003860 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003861 if (ContinueJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00003862 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003863 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003864 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00003865 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00003866
Ted Kremenek9aae5132007-08-23 21:42:29 +00003867 return Block;
3868}
Mike Stump11289f42009-09-09 15:08:12 +00003869
Peter Collingbournee190dee2011-03-11 19:24:49 +00003870CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3871 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003872 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003873 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003874 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00003875 }
Mike Stump11289f42009-09-09 15:08:12 +00003876
Ted Kremenek93668002009-07-17 22:18:43 +00003877 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003878 CFGBlock *lastBlock = Block;
Fangrui Song6907ce22018-07-30 19:24:48 +00003879
Ted Kremenek93668002009-07-17 22:18:43 +00003880 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003881 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00003882 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003883 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00003884 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003885 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003886}
Mike Stump11289f42009-09-09 15:08:12 +00003887
Ted Kremenek93668002009-07-17 22:18:43 +00003888/// VisitStmtExpr - Utility method to handle (nested) statement
3889/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003890CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003891 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003892 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003893 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00003894 }
Ted Kremenek93668002009-07-17 22:18:43 +00003895 return VisitCompoundStmt(SE->getSubStmt());
3896}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003897
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003898CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00003899 // "switch" is a control-flow statement. Thus we stop processing the current
3900 // block.
Craig Topper25542942014-05-20 04:30:07 +00003901 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003902
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003903 // Save local scope position because in case of condition variable ScopePos
3904 // won't be restored when traversing AST.
3905 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3906
Richard Smitha547eb22016-07-14 00:11:03 +00003907 // Create local scope for C++17 switch init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00003908 if (Stmt *Init = Terminator->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00003909 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00003910
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003911 // Create local scope for possible condition variable.
3912 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00003913 if (VarDecl *VD = Terminator->getConditionVariable())
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003914 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00003915
Matthias Gehre351c2182017-07-12 07:04:19 +00003916 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003917
Ted Kremenek9aae5132007-08-23 21:42:29 +00003918 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003919 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003920 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003921 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003922 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003923
3924 // Save the current "switch" context.
3925 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003926 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003927 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003928
Mike Stump31feda52009-07-17 01:31:16 +00003929 // Set the "default" case to be the block after the switch statement. If the
3930 // switch statement contains a "default:", this value will be overwritten with
3931 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003932 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003933
Ted Kremenek9aae5132007-08-23 21:42:29 +00003934 // Create a new block that will contain the switch statement.
3935 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003936
Ted Kremenek9aae5132007-08-23 21:42:29 +00003937 // Now process the switch body. The code after the switch is the implicit
3938 // successor.
3939 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003940 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003941
3942 // When visiting the body, the case statements should automatically get linked
3943 // up to the switch. We also don't keep a pointer to the body, since all
3944 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003945 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003946 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003947
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003948 // For pruning unreachable case statements, save the current state
3949 // for tracking the condition value.
3950 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3951 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003952
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003953 // Determine if the switch condition can be explicitly evaluated.
3954 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003955 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003956 bool b = tryEvaluate(Terminator->getCond(), result);
3957 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003958 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003959
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003960 // If body is not a compound statement create implicit scope
3961 // and add destructors.
3962 if (!isa<CompoundStmt>(Terminator->getBody()))
3963 addLocalScopeAndDtors(Terminator->getBody());
3964
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003965 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003966 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003967 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003968 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003969 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003970
Mike Stump31feda52009-07-17 01:31:16 +00003971 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003972 // following the switch body. Moreover, take into account if all the
3973 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003974 //
3975 // Note: We add a successor to a switch that is considered covered yet has no
3976 // case statements if the enumeration has no enumerators.
3977 bool SwitchAlwaysHasSuccessor = false;
3978 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3979 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3980 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003981 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3982 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003983
Ted Kremenek81e14852007-08-27 19:46:09 +00003984 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003985 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003986 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003987 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003988
Richard Smitha547eb22016-07-14 00:11:03 +00003989 // If the SwitchStmt contains a condition variable, add both the
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003990 // SwitchStmt and the condition variable initialization to the CFG.
3991 if (VarDecl *VD = Terminator->getConditionVariable()) {
3992 if (Expr *Init = VD->getInit()) {
3993 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003994 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003995 LastBlock = addStmt(Init);
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003996 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003997 }
3998 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003999
Richard Smitha547eb22016-07-14 00:11:03 +00004000 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
4001 if (Stmt *Init = Terminator->getInit()) {
4002 autoCreateBlock();
4003 LastBlock = addStmt(Init);
4004 }
4005
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004006 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00004007}
Fangrui Song6907ce22018-07-30 19:24:48 +00004008
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004009static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00004010 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004011 const CaseStmt *CS,
4012 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00004013 if (!switchCond)
4014 return true;
4015
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004016 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00004017
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004018 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00004019 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004020 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00004021 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00004022 const llvm::APSInt &condInt = switchCond->Val.getInt();
Fangrui Song6907ce22018-07-30 19:24:48 +00004023
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004024 if (condInt == lhsInt) {
4025 addCase = true;
4026 switchExclusivelyCovered = true;
4027 }
Devin Coughlineb538ab2015-09-22 20:31:19 +00004028 else if (condInt > lhsInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004029 if (const Expr *RHS = CS->getRHS()) {
4030 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00004031 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
Devin Coughlineb538ab2015-09-22 20:31:19 +00004032 if (V2 >= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004033 addCase = true;
4034 switchExclusivelyCovered = true;
4035 }
4036 }
4037 }
4038 }
4039 else
4040 addCase = true;
4041 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004042 return addCase;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004043}
Ted Kremenek9aae5132007-08-23 21:42:29 +00004044
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004045CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00004046 // CaseStmts are essentially labels, so they are the first statement in a
4047 // block.
Craig Topper25542942014-05-20 04:30:07 +00004048 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00004049
Ted Kremenek60fa6572010-08-04 23:54:30 +00004050 if (Stmt *Sub = CS->getSubStmt()) {
4051 // For deeply nested chains of CaseStmts, instead of doing a recursion
4052 // (which can blow out the stack), manually unroll and create blocks
4053 // along the way.
4054 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004055 CFGBlock *currentBlock = createBlock(false);
4056 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00004057
Ted Kremenek60fa6572010-08-04 23:54:30 +00004058 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004059 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00004060 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004061 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00004062
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004063 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00004064 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004065 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00004066 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00004067
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004068 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00004069 CS = cast<CaseStmt>(Sub);
4070 Sub = CS->getSubStmt();
4071 }
4072
4073 addStmt(Sub);
4074 }
Mike Stump11289f42009-09-09 15:08:12 +00004075
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004076 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00004077 if (!CaseBlock)
4078 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004079
4080 // Cases statements partition blocks, so this is the top of the basic block we
4081 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00004082 CaseBlock->setLabel(CS);
4083
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004084 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004085 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004086
4087 // Add this block to the list of successors for the block with the switch
4088 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00004089 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004090 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00004091 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004092 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00004093
Ted Kremenek9aae5132007-08-23 21:42:29 +00004094 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00004095 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004096
Ted Kremenek60fa6572010-08-04 23:54:30 +00004097 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004098 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00004099 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004100 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00004101 // This block is now the implicit successor of other blocks.
4102 Succ = CaseBlock;
4103 }
Mike Stump31feda52009-07-17 01:31:16 +00004104
Ted Kremenek60fa6572010-08-04 23:54:30 +00004105 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00004106}
Mike Stump31feda52009-07-17 01:31:16 +00004107
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004108CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00004109 if (Terminator->getSubStmt())
4110 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00004111
Ted Kremenek654c78f2008-02-13 22:05:39 +00004112 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00004113
4114 if (!DefaultCaseBlock)
4115 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004116
4117 // Default statements partition blocks, so this is the top of the basic block
4118 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004119 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00004120
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004121 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004122 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00004123
Mike Stump31feda52009-07-17 01:31:16 +00004124 // Unlike case statements, we don't add the default block to the successors
4125 // for the switch statement immediately. This is done when we finish
4126 // processing the switch statement. This allows for the default case
4127 // (including a fall-through to the code after the switch statement) to always
4128 // be the last successor of a switch-terminated block.
4129
Ted Kremenek654c78f2008-02-13 22:05:39 +00004130 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00004131 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004132
Ted Kremenek654c78f2008-02-13 22:05:39 +00004133 // This block is now the implicit successor of other blocks.
4134 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00004135
4136 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00004137}
Ted Kremenek9aae5132007-08-23 21:42:29 +00004138
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004139CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
4140 // "try"/"catch" is a control-flow statement. Thus we stop processing the
4141 // current block.
Craig Topper25542942014-05-20 04:30:07 +00004142 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004143
4144 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004145 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004146 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004147 TrySuccessor = Block;
4148 } else TrySuccessor = Succ;
4149
Mike Stump0bdba6c2010-01-20 01:15:34 +00004150 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004151
4152 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00004153 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004154 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00004155 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004156
Mike Stump0bdba6c2010-01-20 01:15:34 +00004157 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004158 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
4159 // The code after the try is the implicit successor.
4160 Succ = TrySuccessor;
4161 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00004162 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00004163 HasCatchAll = true;
4164 }
Craig Topper25542942014-05-20 04:30:07 +00004165 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004166 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00004167 if (!CatchBlock)
4168 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004169 // Add this block to the list of successors for the block with the try
4170 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004171 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004172 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00004173 if (!HasCatchAll) {
4174 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004175 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00004176 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004177 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00004178 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004179
4180 // The code after the try is the implicit successor.
4181 Succ = TrySuccessor;
4182
Mike Stump845384a2010-01-20 01:30:58 +00004183 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00004184 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
4185 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00004186
Ted Kremenek1362b8b2010-01-19 20:46:35 +00004187 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00004188 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004189 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004190}
4191
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004192CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004193 // CXXCatchStmt are treated like labels, so they are the first statement in a
4194 // block.
4195
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00004196 // Save local scope position because in case of exception variable ScopePos
4197 // won't be restored when traversing AST.
4198 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4199
4200 // Create local scope for possible exception variable.
4201 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004202 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00004203 LocalScope::const_iterator BeginScopePos = ScopePos;
4204 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00004205 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00004206 }
4207
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004208 if (CS->getHandlerBlock())
4209 addStmt(CS->getHandlerBlock());
4210
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004211 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004212 if (!CatchBlock)
4213 CatchBlock = createBlock();
Fangrui Song6907ce22018-07-30 19:24:48 +00004214
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00004215 // CXXCatchStmt is more than just a label. They have semantic meaning
4216 // as well, as they implicitly "initialize" the catch variable. Add
4217 // it to the CFG as a CFGElement so that the control-flow of these
4218 // semantics gets captured.
4219 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004220
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00004221 // Also add the CXXCatchStmt as a label, to mirror handling of regular
4222 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004223 CatchBlock->setLabel(CS);
4224
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00004225 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004226 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004227 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004228
4229 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00004230 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004231
4232 return CatchBlock;
4233}
4234
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004235CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00004236 // C++0x for-range statements are specified as [stmt.ranged]:
4237 //
4238 // {
4239 // auto && __range = range-init;
4240 // for ( auto __begin = begin-expr,
4241 // __end = end-expr;
4242 // __begin != __end;
4243 // ++__begin ) {
4244 // for-range-declaration = *__begin;
4245 // statement
4246 // }
4247 // }
4248
4249 // Save local scope position before the addition of the implicit variables.
4250 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4251
4252 // Create local scopes and destructors for range, begin and end variables.
4253 if (Stmt *Range = S->getRangeStmt())
4254 addLocalScopeForStmt(Range);
Richard Smith01694c32016-03-20 10:33:40 +00004255 if (Stmt *Begin = S->getBeginStmt())
4256 addLocalScopeForStmt(Begin);
4257 if (Stmt *End = S->getEndStmt())
4258 addLocalScopeForStmt(End);
Matthias Gehre351c2182017-07-12 07:04:19 +00004259 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
Richard Smith02e85f32011-04-14 22:09:26 +00004260
4261 LocalScope::const_iterator ContinueScopePos = ScopePos;
4262
4263 // "for" is a control-flow statement. Thus we stop processing the current
4264 // block.
Craig Topper25542942014-05-20 04:30:07 +00004265 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004266 if (Block) {
4267 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004268 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004269 LoopSuccessor = Block;
4270 } else
4271 LoopSuccessor = Succ;
4272
4273 // Save the current value for the break targets.
4274 // All breaks should go to the code following the loop.
4275 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
4276 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4277
4278 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004279 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00004280 ConditionBlock->setTerminator(S);
4281
4282 // Now add the actual condition to the condition block.
4283 if (Expr *C = S->getCond()) {
4284 Block = ConditionBlock;
4285 CFGBlock *BeginConditionBlock = addStmt(C);
4286 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004287 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004288 assert(BeginConditionBlock == ConditionBlock &&
4289 "condition block in for-range was unexpectedly complex");
4290 (void)BeginConditionBlock;
4291 }
4292
4293 // The condition block is the implicit successor for the loop body as well as
4294 // any code above the loop.
4295 Succ = ConditionBlock;
4296
4297 // See if this is a known constant.
4298 TryResult KnownVal(true);
4299
4300 if (S->getCond())
4301 KnownVal = tryEvaluateBool(S->getCond());
4302
4303 // Now create the loop body.
4304 {
4305 assert(S->getBody());
4306
4307 // Save the current values for Block, Succ, and continue targets.
4308 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
4309 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
4310
4311 // Generate increment code in its own basic block. This is the target of
4312 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00004313 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004314 Succ = addStmt(S->getInc());
Alexander Kornienkoff2046a2016-07-08 10:50:51 +00004315 if (badCFG)
4316 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004317 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
4318
4319 // The starting block for the loop increment is the block that should
4320 // represent the 'loop target' for looping back to the start of the loop.
4321 ContinueJumpTarget.block->setLoopTarget(S);
4322
4323 // Finish up the increment block and prepare to start the loop body.
4324 assert(Block);
4325 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004326 return nullptr;
4327 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004328
4329 // Add implicit scope and dtors for loop variable.
4330 addLocalScopeAndDtors(S->getLoopVarStmt());
4331
4332 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004333 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00004334 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004335 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004336 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00004337 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004338 return nullptr;
4339
Richard Smith02e85f32011-04-14 22:09:26 +00004340 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00004341 addSuccessor(ConditionBlock,
4342 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00004343 }
4344
4345 // Link up the condition block with the code that follows the loop (the
4346 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00004347 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00004348
4349 // Add the initialization statements.
4350 Block = createBlock();
Richard Smith01694c32016-03-20 10:33:40 +00004351 addStmt(S->getBeginStmt());
4352 addStmt(S->getEndStmt());
Richard Smith8baa5002018-09-28 18:44:09 +00004353 CFGBlock *Head = addStmt(S->getRangeStmt());
4354 if (S->getInit())
4355 Head = addStmt(S->getInit());
4356 return Head;
Richard Smith02e85f32011-04-14 22:09:26 +00004357}
4358
John McCall5d413782010-12-06 08:20:24 +00004359CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004360 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00004361 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004362 // If adding implicit destructors visit the full expression for adding
4363 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00004364 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00004365 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004366
4367 // Full expression has to be added as CFGStmt so it will be sequenced
4368 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004369 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004370 }
4371 return Visit(E->getSubExpr(), asc);
4372}
4373
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004374CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
4375 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004376 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004377 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004378 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004379
Artem Dergachev783a4572018-02-23 22:20:39 +00004380 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00004381 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
Artem Dergachev783a4572018-02-23 22:20:39 +00004382 E->getSubExpr());
Artem Dergachev1f68d9d2018-02-15 03:13:36 +00004383
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004384 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004385 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004386 }
4387 return Visit(E->getSubExpr(), asc);
4388}
4389
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004390CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
4391 AddStmtChoice asc) {
Artem Dergachevbd880fe2018-07-31 19:39:37 +00004392 // If the constructor takes objects as arguments by value, we need to properly
4393 // construct these objects. Construction contexts we find here aren't for the
4394 // constructor C, they're for its arguments only.
4395 findConstructionContextsForArguments(C);
4396
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004397 autoCreateBlock();
Artem Dergachev41ffb302018-02-08 22:58:15 +00004398 appendConstructor(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004399
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004400 return VisitChildren(C);
4401}
4402
Jordan Rosec9176072014-01-13 17:59:19 +00004403CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
4404 AddStmtChoice asc) {
Jordan Rosec9176072014-01-13 17:59:19 +00004405 autoCreateBlock();
4406 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00004407
Artem Dergachev783a4572018-02-23 22:20:39 +00004408 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00004409 ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
Artem Dergachev783a4572018-02-23 22:20:39 +00004410 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
Artem Dergachev41ffb302018-02-08 22:58:15 +00004411
Jordan Rosec9176072014-01-13 17:59:19 +00004412 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00004413 Block = Visit(NE->getInitializer());
Artem Dergachev41ffb302018-02-08 22:58:15 +00004414
Jordan Rosec9176072014-01-13 17:59:19 +00004415 if (BuildOpts.AddCXXNewAllocator)
4416 appendNewAllocator(Block, NE);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004417
Richard Smithb9fb1212019-05-06 03:47:15 +00004418 if (NE->isArray() && *NE->getArraySize())
4419 Block = Visit(*NE->getArraySize());
Artem Dergachev41ffb302018-02-08 22:58:15 +00004420
Jordan Rosec9176072014-01-13 17:59:19 +00004421 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
4422 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00004423 Block = Visit(*I);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004424
Jordan Rosec9176072014-01-13 17:59:19 +00004425 return Block;
4426}
Jordan Rosed2f40792013-09-03 17:00:57 +00004427
4428CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
4429 AddStmtChoice asc) {
4430 autoCreateBlock();
4431 appendStmt(Block, DE);
4432 QualType DTy = DE->getDestroyedType();
Martin Bohmef44cde82016-12-05 11:33:19 +00004433 if (!DTy.isNull()) {
4434 DTy = DTy.getNonReferenceType();
4435 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
4436 if (RD) {
4437 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
4438 appendDeleteDtor(Block, RD, DE);
4439 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004440 }
4441
4442 return VisitChildren(DE);
4443}
4444
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004445CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
4446 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004447 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004448 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004449 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004450 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004451 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004452 }
4453 return Visit(E->getSubExpr(), asc);
4454}
4455
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004456CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
4457 AddStmtChoice asc) {
Artem Dergachevc531d542018-08-14 21:10:46 +00004458 // If the constructor takes objects as arguments by value, we need to properly
4459 // construct these objects. Construction contexts we find here aren't for the
4460 // constructor C, they're for its arguments only.
4461 findConstructionContextsForArguments(C);
4462
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004463 autoCreateBlock();
Artem Dergachev1f68d9d2018-02-15 03:13:36 +00004464 appendConstructor(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004465 return VisitChildren(C);
4466}
4467
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004468CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
4469 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004470 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004471 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004472 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004473 }
Ted Kremenek8219b822010-12-16 07:46:53 +00004474 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004475}
4476
Bill Wendling8003edc2018-11-09 00:41:36 +00004477CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
4478 return Visit(E->getSubExpr(), AddStmtChoice());
4479}
4480
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004481CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00004482 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004483 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004484
Ted Kremenekeda180e22007-08-28 19:26:49 +00004485 if (!IBlock) {
4486 IBlock = createBlock(false);
4487 cfg->setIndirectGotoBlock(IBlock);
4488 }
Mike Stump31feda52009-07-17 01:31:16 +00004489
Ted Kremenekeda180e22007-08-28 19:26:49 +00004490 // IndirectGoto is a control-flow statement. Thus we stop processing the
4491 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004492 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004493 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00004494
Ted Kremenekeda180e22007-08-28 19:26:49 +00004495 Block = createBlock(false);
4496 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004497 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00004498 return addStmt(I->getTarget());
4499}
4500
Manuel Klimekb5616c92014-08-07 10:42:17 +00004501CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
4502 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00004503 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4504
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004505tryAgain:
4506 if (!E) {
4507 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00004508 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004509 }
4510 switch (E->getStmtClass()) {
4511 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004512 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004513
4514 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004515 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4516 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004517
4518 case Stmt::CXXBindTemporaryExprClass:
4519 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004520 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004521
John McCallc07a0c72011-02-17 10:25:35 +00004522 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004523 case Stmt::ConditionalOperatorClass:
4524 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004525 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004526
4527 case Stmt::ImplicitCastExprClass:
4528 // For implicit cast we want BindToTemporary to be passed further.
4529 E = cast<CastExpr>(E)->getSubExpr();
4530 goto tryAgain;
4531
Manuel Klimekb0042c42014-07-30 08:34:42 +00004532 case Stmt::CXXFunctionalCastExprClass:
4533 // For functional cast we want BindToTemporary to be passed further.
4534 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4535 goto tryAgain;
4536
Bill Wendling8003edc2018-11-09 00:41:36 +00004537 case Stmt::ConstantExprClass:
4538 E = cast<ConstantExpr>(E)->getSubExpr();
4539 goto tryAgain;
4540
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004541 case Stmt::ParenExprClass:
4542 E = cast<ParenExpr>(E)->getSubExpr();
4543 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00004544
Manuel Klimekb0042c42014-07-30 08:34:42 +00004545 case Stmt::MaterializeTemporaryExprClass: {
4546 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4547 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
4548 SmallVector<const Expr *, 2> CommaLHSs;
4549 SmallVector<SubobjectAdjustment, 2> Adjustments;
4550 // Find the expression whose lifetime needs to be extended.
4551 E = const_cast<Expr *>(
4552 cast<MaterializeTemporaryExpr>(E)
4553 ->GetTemporaryExpr()
4554 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4555 // Visit the skipped comma operator left-hand sides for other temporaries.
4556 for (const Expr *CommaLHS : CommaLHSs) {
4557 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00004558 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00004559 }
Douglas Gregorfe314812011-06-21 17:03:29 +00004560 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00004561 }
Richard Smith4137af22014-07-27 05:12:49 +00004562
4563 case Stmt::BlockExprClass:
4564 // Don't recurse into blocks; their subexpressions don't get evaluated
4565 // here.
4566 return Block;
4567
4568 case Stmt::LambdaExprClass: {
4569 // For lambda expressions, only recurse into the capture initializers,
4570 // and not the body.
4571 auto *LE = cast<LambdaExpr>(E);
4572 CFGBlock *B = Block;
4573 for (Expr *Init : LE->capture_inits()) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00004574 if (Init) {
4575 if (CFGBlock *R = VisitForTemporaryDtors(
4576 Init, /*BindToTemporary=*/false, Context))
4577 B = R;
4578 }
Richard Smith4137af22014-07-27 05:12:49 +00004579 }
4580 return B;
4581 }
4582
4583 case Stmt::CXXDefaultArgExprClass:
4584 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4585 goto tryAgain;
4586
4587 case Stmt::CXXDefaultInitExprClass:
4588 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4589 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004590 }
4591}
4592
Manuel Klimekb5616c92014-08-07 10:42:17 +00004593CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
4594 TempDtorContext &Context) {
4595 if (isa<LambdaExpr>(E)) {
4596 // Do not visit the children of lambdas; they have their own CFGs.
4597 return Block;
4598 }
4599
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004600 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00004601 // order that they will appear in the CFG. Because the CFG is built
4602 // bottom-up, this means we visit them in their natural order, which
4603 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004604 CFGBlock *B = Block;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004605 for (Stmt *Child : E->children())
4606 if (Child)
Manuel Klimekb5616c92014-08-07 10:42:17 +00004607 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00004608 B = R;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004609
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004610 return B;
4611}
4612
Manuel Klimekb5616c92014-08-07 10:42:17 +00004613CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
4614 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004615 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004616 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00004617 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
4618 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
4619 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00004620
Manuel Klimekedf925b92014-08-07 18:44:19 +00004621 // We do not know at CFG-construction time whether the right-hand-side was
4622 // executed, thus we add a branch node that depends on the temporary
4623 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00004624 TempDtorContext RHSContext(
4625 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00004626 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00004627 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00004628
Manuel Klimekb5616c92014-08-07 10:42:17 +00004629 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004630 }
4631
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004632 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004633 // For assignment operator (=) LHS expression is visited
4634 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004635 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4636 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004637 return LHSBlock ? LHSBlock : RHSBlock;
4638 }
4639
4640 // For any other binary operator RHS expression is visited before
4641 // LHS expression (order of children). For destructors visit them in reverse
4642 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004643 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4644 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004645 return RHSBlock ? RHSBlock : LHSBlock;
4646}
4647
4648CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004649 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004650 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004651 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00004652 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004653 // If lifetime of temporary is not prolonged (by assigning to constant
4654 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00004655
Chandler Carruthad747252011-09-13 06:09:01 +00004656 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004657
Richard Trieu95a192a2015-05-28 00:14:02 +00004658 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004659 // If the destructor is marked as a no-return destructor, we need to
4660 // create a new block for the destructor which does not have as a
4661 // successor anything built thus far. Control won't flow out of this
4662 // block.
4663 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00004664 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004665 } else if (Context.needsTempDtorBranch()) {
4666 // If we need to introduce a branch, we add a new block that we will hook
4667 // up to a decision block later.
4668 if (B) Succ = B;
4669 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004670 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00004671 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004672 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00004673 if (Context.needsTempDtorBranch()) {
4674 Context.setDecisionPoint(Succ, E);
4675 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004676 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004677
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004678 B = Block;
4679 }
4680 return B;
4681}
4682
Manuel Klimekb5616c92014-08-07 10:42:17 +00004683void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
4684 CFGBlock *FalseSucc) {
4685 if (!Context.TerminatorExpr) {
4686 // If no temporary was found, we do not need to insert a decision point.
4687 return;
4688 }
4689 assert(Context.TerminatorExpr);
4690 CFGBlock *Decision = createBlock(false);
Artem Dergachev4e530322019-05-24 01:34:22 +00004691 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
4692 CFGTerminator::TemporaryDtorsBranch));
Manuel Klimekdeb02622014-08-08 07:37:13 +00004693 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004694 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00004695 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00004696 Block = Decision;
4697}
4698
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004699CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004700 AbstractConditionalOperator *E, bool BindToTemporary,
4701 TempDtorContext &Context) {
4702 VisitForTemporaryDtors(E->getCond(), false, Context);
4703 CFGBlock *ConditionBlock = Block;
4704 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00004705 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004706 TryResult NegatedVal = ConditionVal;
4707 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00004708
Manuel Klimekdeb02622014-08-08 07:37:13 +00004709 TempDtorContext TrueContext(
4710 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004711 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004712 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004713
Manuel Klimekb5616c92014-08-07 10:42:17 +00004714 Block = ConditionBlock;
4715 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004716 TempDtorContext FalseContext(
4717 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004718 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004719
Manuel Klimekb5616c92014-08-07 10:42:17 +00004720 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004721 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004722 } else if (TrueContext.TerminatorExpr) {
4723 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004724 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004725 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004726 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004727 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004728 return Block;
4729}
4730
Mike Stump31feda52009-07-17 01:31:16 +00004731/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
4732/// no successors or predecessors. If this is the first block created in the
4733/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004734CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00004735 bool first_block = begin() == end();
4736
4737 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004738 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00004739 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004740 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00004741
4742 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004743 if (first_block)
4744 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00004745
4746 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004747 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004748}
4749
David Blaikiee90195c2014-08-29 18:53:26 +00004750/// buildCFG - Constructs a CFG from an AST.
4751std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4752 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00004753 CFGBuilder Builder(C, BO);
4754 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00004755}
4756
Artem Dergachevab7747b2019-04-30 03:01:02 +00004757bool CFG::isLinear() const {
4758 // Quick path: if we only have the ENTRY block, the EXIT block, and some code
4759 // in between, then we have no room for control flow.
4760 if (size() <= 3)
4761 return true;
4762
4763 // Traverse the CFG until we find a branch.
4764 // TODO: While this should still be very fast,
4765 // maybe we should cache the answer.
4766 llvm::SmallPtrSet<const CFGBlock *, 4> Visited;
4767 const CFGBlock *B = Entry;
4768 while (B != Exit) {
4769 auto IteratorAndFlag = Visited.insert(B);
4770 if (!IteratorAndFlag.second) {
4771 // We looped back to a block that we've already visited. Not linear.
4772 return false;
4773 }
4774
4775 // Iterate over reachable successors.
4776 const CFGBlock *FirstReachableB = nullptr;
4777 for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
4778 if (!AB.isReachable())
4779 continue;
4780
4781 if (FirstReachableB == nullptr) {
4782 FirstReachableB = &*AB;
4783 } else {
4784 // We've encountered a branch. It's not a linear CFG.
4785 return false;
4786 }
4787 }
4788
4789 if (!FirstReachableB) {
4790 // We reached a dead end. EXIT is unreachable. This is linear enough.
4791 return true;
4792 }
4793
4794 // There's only one way to move forward. Proceed.
4795 B = FirstReachableB;
4796 }
4797
4798 // We reached EXIT and found no branches.
4799 return true;
4800}
4801
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004802const CXXDestructorDecl *
4803CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004804 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004805 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00004806 case CFGElement::NewAllocator:
Peter Szecsi999a25f2017-08-19 11:19:16 +00004807 case CFGElement::LoopExit:
Matthias Gehre351c2182017-07-12 07:04:19 +00004808 case CFGElement::LifetimeEnds:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004809 case CFGElement::Statement:
4810 case CFGElement::Constructor:
Artem Dergachev1527dec2018-03-12 23:12:40 +00004811 case CFGElement::CXXRecordTypedCall:
Maxim Ostapenkodebca452018-03-12 12:26:15 +00004812 case CFGElement::ScopeBegin:
4813 case CFGElement::ScopeEnd:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004814 llvm_unreachable("getDestructorDecl should only be used with "
4815 "ImplicitDtors");
4816 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00004817 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004818 QualType ty = var->getType();
Devin Coughlin6eb1ca72016-08-02 21:07:23 +00004819
4820 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4821 //
4822 // Lifetime-extending constructs are handled here. This works for a single
4823 // temporary in an initializer expression.
4824 if (ty->isReferenceType()) {
4825 if (const Expr *Init = var->getInit()) {
Artem Dergacheva25809f2018-06-04 18:56:25 +00004826 ty = getReferenceInitTemporaryType(Init);
Devin Coughlin6eb1ca72016-08-02 21:07:23 +00004827 }
4828 }
4829
Ted Kremeneke7d78882012-03-19 23:48:41 +00004830 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004831 ty = arrayType->getElementType();
4832 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004833 const RecordType *recordType = ty->getAs<RecordType>();
4834 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00004835 cast<CXXRecordDecl>(recordType->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004836 return classDecl->getDestructor();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004837 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004838 case CFGElement::DeleteDtor: {
4839 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
4840 QualType DTy = DE->getDestroyedType();
4841 DTy = DTy.getNonReferenceType();
4842 const CXXRecordDecl *classDecl =
4843 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
4844 return classDecl->getDestructor();
4845 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004846 case CFGElement::TemporaryDtor: {
4847 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00004848 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004849 const CXXTemporary *temp = bindExpr->getTemporary();
4850 return temp->getDestructor();
4851 }
4852 case CFGElement::BaseDtor:
4853 case CFGElement::MemberDtor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004854 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00004855 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004856 }
Ted Kremenek1676a042011-03-03 01:01:03 +00004857 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004858}
4859
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004860bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00004861 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
4862 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004863 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004864}
4865
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00004866//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004867// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00004868//===----------------------------------------------------------------------===//
4869
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004870CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004871 : ReachableBlock(IsReachable ? B : nullptr),
4872 UnreachableBlock(!IsReachable ? B : nullptr,
4873 B && IsReachable ? AB_Normal : AB_Unreachable) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004874
4875CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004876 : ReachableBlock(B),
4877 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
4878 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004879
4880void CFGBlock::addSuccessor(AdjacentBlock Succ,
4881 BumpVectorContext &C) {
4882 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004883 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004884
4885 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004886 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004887
4888 Succs.push_back(Succ, C);
4889}
4890
Ted Kremenekb0371852010-09-09 00:06:04 +00004891bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00004892 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004893 if (F.IgnoreNullPredecessors && !From)
4894 return true;
4895
4896 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004897 // If the 'To' has no label or is labeled but the label isn't a
4898 // CaseStmt then filter this edge.
4899 if (const SwitchStmt *S =
Artem Dergachev4e530322019-05-24 01:34:22 +00004900 dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004901 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00004902 const Stmt *L = To->getLabel();
4903 if (!L || !isa<CaseStmt>(L))
4904 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00004905 }
4906 }
4907 }
4908
4909 return false;
4910}
4911
4912//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004913// CFG pretty printing
4914//===----------------------------------------------------------------------===//
4915
Ted Kremenek7e776b12007-08-22 18:22:34 +00004916namespace {
4917
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004918class StmtPrinterHelper : public PrinterHelper {
Eugene Zelenko38c70522017-12-07 21:55:09 +00004919 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
4920 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
4921
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004922 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004923 DeclMapTy DeclMap;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004924 signed currentBlock = 0;
4925 unsigned currStmt = 0;
Chris Lattnerc61089a2009-06-30 01:26:17 +00004926 const LangOptions &LangOpts;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004927
Eugene Zelenko38c70522017-12-07 21:55:09 +00004928public:
Chris Lattnerc61089a2009-06-30 01:26:17 +00004929 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004930 : LangOpts(LO) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004931 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4932 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004933 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Fangrui Song6907ce22018-07-30 19:24:48 +00004934 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00004935 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4936 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004937 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00004938 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004939
Ted Kremenek96a7a592011-03-01 03:15:10 +00004940 switch (stmt->getStmtClass()) {
4941 case Stmt::DeclStmtClass:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004942 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4943 break;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004944 case Stmt::IfStmtClass: {
4945 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4946 if (var)
4947 DeclMap[var] = P;
4948 break;
4949 }
4950 case Stmt::ForStmtClass: {
4951 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4952 if (var)
4953 DeclMap[var] = P;
4954 break;
4955 }
4956 case Stmt::WhileStmtClass: {
4957 const VarDecl *var =
4958 cast<WhileStmt>(stmt)->getConditionVariable();
4959 if (var)
4960 DeclMap[var] = P;
4961 break;
4962 }
4963 case Stmt::SwitchStmtClass: {
4964 const VarDecl *var =
4965 cast<SwitchStmt>(stmt)->getConditionVariable();
4966 if (var)
4967 DeclMap[var] = P;
4968 break;
4969 }
4970 case Stmt::CXXCatchStmtClass: {
4971 const VarDecl *var =
4972 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4973 if (var)
4974 DeclMap[var] = P;
4975 break;
4976 }
4977 default:
4978 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004979 }
4980 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004981 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00004982 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004983 }
Mike Stump31feda52009-07-17 01:31:16 +00004984
Eugene Zelenko38c70522017-12-07 21:55:09 +00004985 ~StmtPrinterHelper() override = default;
Mike Stump31feda52009-07-17 01:31:16 +00004986
Chris Lattnerc61089a2009-06-30 01:26:17 +00004987 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004988 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00004989 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00004990
Craig Topperb45acb82014-03-14 06:02:07 +00004991 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004992 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004993
4994 if (I == StmtMap.end())
4995 return false;
Mike Stump31feda52009-07-17 01:31:16 +00004996
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004997 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004998 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004999 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00005000 }
Mike Stump31feda52009-07-17 01:31:16 +00005001
Ted Kremenek60983dc2010-01-19 20:52:05 +00005002 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00005003 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005004 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005005
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005006 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005007 DeclMapTy::iterator I = DeclMap.find(D);
5008
5009 if (I == DeclMap.end())
5010 return false;
5011
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00005012 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00005013 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005014 return false;
5015 }
5016
5017 OS << "[B" << I->second.first << "." << I->second.second << "]";
5018 return true;
5019 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005020};
5021
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00005022class CFGBlockTerminatorPrint
Eugene Zelenko38c70522017-12-07 21:55:09 +00005023 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005024 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005025 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00005026 PrintingPolicy Policy;
Eugene Zelenko38c70522017-12-07 21:55:09 +00005027
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005028public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005029 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00005030 const PrintingPolicy &Policy)
Eugene Zelenko38c70522017-12-07 21:55:09 +00005031 : OS(os), Helper(helper), Policy(Policy) {
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00005032 this->Policy.IncludeNewlines = false;
5033 }
Mike Stump31feda52009-07-17 01:31:16 +00005034
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005035 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00005036 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00005037 if (Stmt *C = I->getCond())
5038 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00005039 }
Mike Stump31feda52009-07-17 01:31:16 +00005040
Ted Kremenek9aae5132007-08-23 21:42:29 +00005041 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005042 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00005043 Terminator->printPretty(OS, Helper, Policy);
5044 }
5045
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00005046 void VisitDeclStmt(DeclStmt *DS) {
5047 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
5048 OS << "static init " << VD->getName();
5049 }
5050
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005051 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00005052 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00005053 if (F->getInit())
5054 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00005055 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005056 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00005057 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00005058 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00005059 if (F->getInc())
5060 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00005061 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00005062 }
Mike Stump31feda52009-07-17 01:31:16 +00005063
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005064 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00005065 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005066 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00005067 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00005068 }
Mike Stump31feda52009-07-17 01:31:16 +00005069
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005070 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00005071 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005072 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00005073 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00005074 }
Mike Stump31feda52009-07-17 01:31:16 +00005075
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005076 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00005077 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00005078 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00005079 }
Mike Stump31feda52009-07-17 01:31:16 +00005080
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005081 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005082 OS << "try ...";
5083 }
5084
Nico Weber699670e2017-08-23 15:33:16 +00005085 void VisitSEHTryStmt(SEHTryStmt *CS) {
5086 OS << "__try ...";
5087 }
5088
John McCallc07a0c72011-02-17 10:25:35 +00005089 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00005090 if (Stmt *Cond = C->getCond())
5091 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00005092 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005093 }
Mike Stump31feda52009-07-17 01:31:16 +00005094
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005095 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00005096 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00005097 if (Stmt *Cond = C->getCond())
5098 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00005099 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00005100 }
Mike Stump31feda52009-07-17 01:31:16 +00005101
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005102 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00005103 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00005104 if (Stmt *T = I->getTarget())
5105 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00005106 }
Mike Stump31feda52009-07-17 01:31:16 +00005107
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005108 void VisitBinaryOperator(BinaryOperator* B) {
5109 if (!B->isLogicalOp()) {
5110 VisitExpr(B);
5111 return;
5112 }
Mike Stump31feda52009-07-17 01:31:16 +00005113
Richard Trieuddd01ce2014-06-09 22:53:25 +00005114 if (B->getLHS())
5115 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00005116
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005117 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005118 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00005119 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005120 return;
John McCalle3027922010-08-25 11:45:40 +00005121 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00005122 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005123 return;
5124 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005125 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00005126 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005127 }
Mike Stump31feda52009-07-17 01:31:16 +00005128
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005129 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00005130 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00005131 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00005132
5133public:
5134 void print(CFGTerminator T) {
Artem Dergachev4e530322019-05-24 01:34:22 +00005135 switch (T.getKind()) {
5136 case CFGTerminator::StmtBranch:
5137 Visit(T.getStmt());
5138 break;
5139 case CFGTerminator::TemporaryDtorsBranch:
Ted Kremenekfcc14172014-03-08 02:22:29 +00005140 OS << "(Temp Dtor) ";
Artem Dergachev4e530322019-05-24 01:34:22 +00005141 Visit(T.getStmt());
5142 break;
Artem Dergachev192a7472019-05-24 23:37:08 +00005143 case CFGTerminator::VirtualBaseBranch:
5144 OS << "(See if most derived ctor has already initialized vbases)";
5145 break;
Artem Dergachev4e530322019-05-24 01:34:22 +00005146 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00005147 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00005148};
Eugene Zelenko38c70522017-12-07 21:55:09 +00005149
5150} // namespace
Chris Lattnerc61089a2009-06-30 01:26:17 +00005151
Artem Dergachev5a281bb2018-02-10 02:18:04 +00005152static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
5153 const CXXCtorInitializer *I) {
5154 if (I->isBaseInitializer())
5155 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
5156 else if (I->isDelegatingInitializer())
5157 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
5158 else
5159 OS << I->getAnyMember()->getName();
5160 OS << "(";
5161 if (Expr *IE = I->getInit())
5162 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5163 OS << ")";
5164
5165 if (I->isBaseInitializer())
5166 OS << " (Base initializer)";
5167 else if (I->isDelegatingInitializer())
5168 OS << " (Delegating initializer)";
5169 else
5170 OS << " (Member initializer)";
5171}
5172
Artem Dergachev1527dec2018-03-12 23:12:40 +00005173static void print_construction_context(raw_ostream &OS,
5174 StmtPrinterHelper &Helper,
5175 const ConstructionContext *CC) {
Artem Dergachevff267df2018-06-28 00:04:54 +00005176 SmallVector<const Stmt *, 3> Stmts;
Artem Dergachev1527dec2018-03-12 23:12:40 +00005177 switch (CC->getKind()) {
Artem Dergachev922455f2018-03-22 22:02:38 +00005178 case ConstructionContext::SimpleConstructorInitializerKind: {
Artem Dergachev1527dec2018-03-12 23:12:40 +00005179 OS << ", ";
Artem Dergachev922455f2018-03-22 22:02:38 +00005180 const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC);
5181 print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
Artem Dergacheva657a322018-07-31 20:45:53 +00005182 return;
Artem Dergachev922455f2018-03-22 22:02:38 +00005183 }
5184 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
5185 OS << ", ";
5186 const auto *CICC =
5187 cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC);
5188 print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
Artem Dergachevff267df2018-06-28 00:04:54 +00005189 Stmts.push_back(CICC->getCXXBindTemporaryExpr());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005190 break;
5191 }
5192 case ConstructionContext::SimpleVariableKind: {
Artem Dergachev317291e2018-03-22 21:37:39 +00005193 const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005194 Stmts.push_back(SDSCC->getDeclStmt());
Artem Dergachev317291e2018-03-22 21:37:39 +00005195 break;
5196 }
5197 case ConstructionContext::CXX17ElidedCopyVariableKind: {
5198 const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005199 Stmts.push_back(CDSCC->getDeclStmt());
5200 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005201 break;
5202 }
5203 case ConstructionContext::NewAllocatedObjectKind: {
5204 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005205 Stmts.push_back(NECC->getCXXNewExpr());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005206 break;
5207 }
Artem Dergachev317291e2018-03-22 21:37:39 +00005208 case ConstructionContext::SimpleReturnedValueKind: {
5209 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005210 Stmts.push_back(RSCC->getReturnStmt());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005211 break;
5212 }
Artem Dergachev317291e2018-03-22 21:37:39 +00005213 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
5214 const auto *RSCC =
5215 cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005216 Stmts.push_back(RSCC->getReturnStmt());
5217 Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
Artem Dergachev317291e2018-03-22 21:37:39 +00005218 break;
5219 }
Artem Dergachevff267df2018-06-28 00:04:54 +00005220 case ConstructionContext::SimpleTemporaryObjectKind: {
5221 const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC);
5222 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5223 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5224 break;
5225 }
5226 case ConstructionContext::ElidedTemporaryObjectKind: {
5227 const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
5228 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5229 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5230 Stmts.push_back(TOCC->getConstructorAfterElision());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005231 break;
5232 }
Artem Dergacheva657a322018-07-31 20:45:53 +00005233 case ConstructionContext::ArgumentKind: {
5234 const auto *ACC = cast<ArgumentConstructionContext>(CC);
5235 if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
5236 OS << ", ";
5237 Helper.handledStmt(const_cast<Stmt *>(BTE), OS);
5238 }
5239 OS << ", ";
5240 Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
5241 OS << "+" << ACC->getIndex();
5242 return;
5243 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00005244 }
Artem Dergachevff267df2018-06-28 00:04:54 +00005245 for (auto I: Stmts)
5246 if (I) {
5247 OS << ", ";
5248 Helper.handledStmt(const_cast<Stmt *>(I), OS);
5249 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00005250}
5251
Aaron Ballmanff924b02013-11-18 20:11:50 +00005252static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00005253 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00005254 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
5255 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00005256 assert(S != nullptr && "Expecting non-null Stmt");
5257
Aaron Ballmanff924b02013-11-18 20:11:50 +00005258 // special printing for statement-expressions.
5259 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
5260 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00005261
Benjamin Kramer5733e352015-07-18 17:09:36 +00005262 auto Children = Sub->children();
5263 if (Children.begin() != Children.end()) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00005264 OS << "({ ... ; ";
5265 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
5266 OS << " })\n";
5267 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00005268 }
5269 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00005270 // special printing for comma expressions.
5271 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
5272 if (B->getOpcode() == BO_Comma) {
5273 OS << "... , ";
5274 Helper.handledStmt(B->getRHS(),OS);
5275 OS << '\n';
5276 return;
5277 }
5278 }
5279 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00005280
Artem Dergachev1527dec2018-03-12 23:12:40 +00005281 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
5282 if (isa<CXXOperatorCallExpr>(S))
5283 OS << " (OperatorCall)";
5284 OS << " (CXXRecordTypedCall";
5285 print_construction_context(OS, Helper, VTC->getConstructionContext());
5286 OS << ")";
5287 } else if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00005288 OS << " (OperatorCall)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005289 } else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00005290 OS << " (BindTemporary)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005291 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
Artem Dergachev1527dec2018-03-12 23:12:40 +00005292 OS << " (CXXConstructExpr";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005293 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
Artem Dergachev1527dec2018-03-12 23:12:40 +00005294 print_construction_context(OS, Helper, CE->getConstructionContext());
Artem Dergachev41ffb302018-02-08 22:58:15 +00005295 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00005296 OS << ", " << CCE->getType().getAsString() << ")";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005297 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
Ted Kremenek0ffba932011-12-21 19:32:38 +00005298 OS << " (" << CE->getStmtClassName() << ", "
5299 << CE->getCastKindName()
5300 << ", " << CE->getType().getAsString()
5301 << ")";
5302 }
Mike Stump31feda52009-07-17 01:31:16 +00005303
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005304 // Expressions need a newline.
5305 if (isa<Expr>(S))
5306 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00005307 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
Artem Dergachev5a281bb2018-02-10 02:18:04 +00005308 print_initializer(OS, Helper, IE->getInitializer());
5309 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00005310 } else if (Optional<CFGAutomaticObjDtor> DE =
5311 E.getAs<CFGAutomaticObjDtor>()) {
5312 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00005313 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005314
Artem Dergacheva25809f2018-06-04 18:56:25 +00005315 ASTContext &ACtx = VD->getASTContext();
5316 QualType T = VD->getType();
5317 if (T->isReferenceType())
5318 T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
5319 if (const ArrayType *AT = ACtx.getAsArrayType(T))
5320 T = ACtx.getBaseElementType(AT);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005321
5322 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
5323 OS << " (Implicit destructor)\n";
Matthias Gehre351c2182017-07-12 07:04:19 +00005324 } else if (Optional<CFGLifetimeEnds> DE = E.getAs<CFGLifetimeEnds>()) {
5325 const VarDecl *VD = DE->getVarDecl();
5326 Helper.handleDecl(VD, OS);
5327
5328 OS << " (Lifetime ends)\n";
Peter Szecsi999a25f2017-08-19 11:19:16 +00005329 } else if (Optional<CFGLoopExit> LE = E.getAs<CFGLoopExit>()) {
5330 const Stmt *LoopStmt = LE->getLoopStmt();
5331 OS << LoopStmt->getStmtClassName() << " (LoopExit)\n";
Maxim Ostapenkodebca452018-03-12 12:26:15 +00005332 } else if (Optional<CFGScopeBegin> SB = E.getAs<CFGScopeBegin>()) {
5333 OS << "CFGScopeBegin(";
5334 if (const VarDecl *VD = SB->getVarDecl())
5335 OS << VD->getQualifiedNameAsString();
5336 OS << ")\n";
5337 } else if (Optional<CFGScopeEnd> SE = E.getAs<CFGScopeEnd>()) {
5338 OS << "CFGScopeEnd(";
5339 if (const VarDecl *VD = SE->getVarDecl())
5340 OS << VD->getQualifiedNameAsString();
5341 OS << ")\n";
Jordan Rosec9176072014-01-13 17:59:19 +00005342 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
5343 OS << "CFGNewAllocator(";
5344 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
5345 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5346 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00005347 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
5348 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
5349 if (!RD)
5350 return;
5351 CXXDeleteExpr *DelExpr =
5352 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00005353 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00005354 OS << "->~" << RD->getName().str() << "()";
5355 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00005356 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
5357 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00005358 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00005359 OS << " (Base object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00005360 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
5361 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00005362 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00005363 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00005364 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00005365 OS << " (Member object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00005366 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
5367 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00005368 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00005369 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00005370 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005371 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00005372}
Mike Stump31feda52009-07-17 01:31:16 +00005373
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005374static void print_block(raw_ostream &OS, const CFG* cfg,
5375 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00005376 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00005377 bool ShowColors) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00005378 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00005379
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005380 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005381 if (ShowColors)
5382 OS.changeColor(raw_ostream::YELLOW, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00005383
Ted Kremenek72be32a2011-12-22 23:33:52 +00005384 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00005385
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005386 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00005387 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005388 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00005389 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005390 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00005391 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00005392 else if (B.hasNoReturnElement())
5393 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005394 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00005395 OS << "]\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005396
Ted Kremenek72be32a2011-12-22 23:33:52 +00005397 if (ShowColors)
5398 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00005399
Ted Kremenek71eca012007-08-29 23:20:49 +00005400 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005401 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005402 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005403 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00005404
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005405 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00005406 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005407 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00005408 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00005409 if (C->getLHS())
5410 C->getLHS()->printPretty(OS, &Helper,
5411 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00005412 if (C->getRHS()) {
5413 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00005414 C->getRHS()->printPretty(OS, &Helper,
5415 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00005416 }
Mike Stump92244b02010-01-19 22:00:14 +00005417 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00005418 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00005419 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005420 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00005421 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00005422 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00005423 0);
5424 else
5425 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005426 OS << ")";
Nico Weber699670e2017-08-23 15:33:16 +00005427 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
5428 OS << "__except (";
5429 ES->getFilterExpr()->printPretty(OS, &Helper,
5430 PrintingPolicy(Helper.getLangOpts()), 0);
5431 OS << ")";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005432 } else
David Blaikie83d382b2011-09-23 05:06:16 +00005433 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00005434
Ted Kremenek71eca012007-08-29 23:20:49 +00005435 OS << ":\n";
5436 }
Mike Stump31feda52009-07-17 01:31:16 +00005437
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005438 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005439 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00005440
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005441 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
5442 I != E ; ++I, ++j ) {
Ted Kremenek71eca012007-08-29 23:20:49 +00005443 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005444 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005445 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00005446
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005447 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00005448
Aaron Ballmanff924b02013-11-18 20:11:50 +00005449 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00005450
Ted Kremenek72be32a2011-12-22 23:33:52 +00005451 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005452 }
Mike Stump31feda52009-07-17 01:31:16 +00005453
Ted Kremenek71eca012007-08-29 23:20:49 +00005454 // Print the terminator of this block.
Artem Dergachev4e530322019-05-24 01:34:22 +00005455 if (B.getTerminator().isValid()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00005456 if (ShowColors)
5457 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00005458
Ted Kremenek72be32a2011-12-22 23:33:52 +00005459 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00005460
Aaron Ballmanff924b02013-11-18 20:11:50 +00005461 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00005462
Aaron Ballmanff924b02013-11-18 20:11:50 +00005463 PrintingPolicy PP(Helper.getLangOpts());
5464 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00005465 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00005466 OS << '\n';
Fangrui Song6907ce22018-07-30 19:24:48 +00005467
Ted Kremenek72be32a2011-12-22 23:33:52 +00005468 if (ShowColors)
5469 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005470 }
Mike Stump31feda52009-07-17 01:31:16 +00005471
Ted Kremenek71eca012007-08-29 23:20:49 +00005472 if (print_edges) {
5473 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005474 if (!B.pred_empty()) {
5475 const raw_ostream::Colors Color = raw_ostream::BLUE;
5476 if (ShowColors)
5477 OS.changeColor(Color);
5478 OS << " Preds " ;
5479 if (ShowColors)
5480 OS.resetColor();
5481 OS << '(' << B.pred_size() << "):";
5482 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00005483
Ted Kremenek72be32a2011-12-22 23:33:52 +00005484 if (ShowColors)
5485 OS.changeColor(Color);
Fangrui Song6907ce22018-07-30 19:24:48 +00005486
Ted Kremenek72be32a2011-12-22 23:33:52 +00005487 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
5488 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00005489 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005490 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00005491
Ted Kremenek4b6fee62014-02-27 00:24:00 +00005492 CFGBlock *B = *I;
5493 bool Reachable = true;
5494 if (!B) {
5495 Reachable = false;
5496 B = I->getPossiblyUnreachableBlock();
5497 }
5498
5499 OS << " B" << B->getBlockID();
5500 if (!Reachable)
5501 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00005502 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005503
Ted Kremenek72be32a2011-12-22 23:33:52 +00005504 if (ShowColors)
5505 OS.resetColor();
5506
5507 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00005508 }
Mike Stump31feda52009-07-17 01:31:16 +00005509
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005510 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005511 if (!B.succ_empty()) {
5512 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
5513 if (ShowColors)
5514 OS.changeColor(Color);
5515 OS << " Succs ";
5516 if (ShowColors)
5517 OS.resetColor();
5518 OS << '(' << B.succ_size() << "):";
5519 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005520
Ted Kremenek72be32a2011-12-22 23:33:52 +00005521 if (ShowColors)
5522 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00005523
Ted Kremenek72be32a2011-12-22 23:33:52 +00005524 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
5525 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00005526 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005527 OS << "\n ";
5528
Ted Kremenek9238c5c2014-02-27 21:56:44 +00005529 CFGBlock *B = *I;
5530
5531 bool Reachable = true;
5532 if (!B) {
5533 Reachable = false;
5534 B = I->getPossiblyUnreachableBlock();
5535 }
5536
5537 if (B) {
5538 OS << " B" << B->getBlockID();
5539 if (!Reachable)
5540 OS << "(Unreachable)";
5541 }
5542 else {
5543 OS << " NULL";
5544 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00005545 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00005546
Ted Kremenek72be32a2011-12-22 23:33:52 +00005547 if (ShowColors)
5548 OS.resetColor();
5549 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005550 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005551 }
Mike Stump31feda52009-07-17 01:31:16 +00005552}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005553
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005554/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005555void CFG::dump(const LangOptions &LO, bool ShowColors) const {
5556 print(llvm::errs(), LO, ShowColors);
5557}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005558
5559/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005560void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00005561 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00005562
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005563 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00005564 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00005565
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005566 // Iterate through the CFGBlocks and print them one by one.
5567 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
5568 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00005569 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005570 continue;
Mike Stump31feda52009-07-17 01:31:16 +00005571
Aaron Ballmanff924b02013-11-18 20:11:50 +00005572 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005573 }
Mike Stump31feda52009-07-17 01:31:16 +00005574
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005575 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00005576 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00005577 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00005578 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00005579}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005580
5581/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005582void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
5583 bool ShowColors) const {
5584 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00005585}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005586
Yaron Kerencdae9412016-01-29 19:38:18 +00005587LLVM_DUMP_METHOD void CFGBlock::dump() const {
Anna Zaksa6fea132014-06-13 23:47:38 +00005588 dump(getParent(), LangOptions(), false);
5589}
5590
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005591/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
5592/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005593void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00005594 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00005595 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005596 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00005597 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00005598}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005599
Ted Kremenek15647632008-01-30 23:02:42 +00005600/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005601void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00005602 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00005603 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00005604 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00005605}
5606
Csaba Dabisdea605e2019-05-29 18:29:31 +00005607/// printTerminatorJson - Pretty-prints the terminator in JSON format.
5608void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
5609 bool AddQuotes) const {
5610 std::string Buf;
5611 llvm::raw_string_ostream TempOut(Buf);
5612
5613 printTerminator(TempOut, LO);
5614
5615 Out << JsonFormat(TempOut.str(), AddQuotes);
5616}
5617
Kristof Umannd5c9d9b2019-07-05 09:52:00 +00005618const Expr *CFGBlock::getLastCondition() const {
5619 // If the terminator is a temporary dtor or a virtual base, etc, we can't
5620 // retrieve a meaningful condition, bail out.
5621 if (Terminator.getKind() != CFGTerminator::StmtBranch)
5622 return nullptr;
5623
5624 // Also, if this method was called on a block that doesn't have 2 successors,
5625 // this block doesn't have retrievable condition.
5626 if (succ_size() < 2)
5627 return nullptr;
5628
5629 auto StmtElem = rbegin()->getAs<CFGStmt>();
5630 if (!StmtElem)
5631 return nullptr;
5632
5633 const Stmt *Cond = StmtElem->getStmt();
5634 if (isa<ObjCForCollectionStmt>(Cond))
5635 return nullptr;
5636
5637 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
5638 // the cast<>.
5639 return cast<Expr>(Cond)->IgnoreParens();
5640}
5641
Kristof Umann9854d772019-07-03 13:03:33 +00005642Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
5643 Stmt *Terminator = getTerminatorStmt();
5644 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00005645 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00005646
Kristof Umann9854d772019-07-03 13:03:33 +00005647 Expr *E = nullptr;
5648
5649 switch (Terminator->getStmtClass()) {
5650 default:
5651 break;
5652
5653 case Stmt::CXXForRangeStmtClass:
5654 E = cast<CXXForRangeStmt>(Terminator)->getCond();
5655 break;
5656
5657 case Stmt::ForStmtClass:
5658 E = cast<ForStmt>(Terminator)->getCond();
5659 break;
5660
5661 case Stmt::WhileStmtClass:
5662 E = cast<WhileStmt>(Terminator)->getCond();
5663 break;
5664
5665 case Stmt::DoStmtClass:
5666 E = cast<DoStmt>(Terminator)->getCond();
5667 break;
5668
5669 case Stmt::IfStmtClass:
5670 E = cast<IfStmt>(Terminator)->getCond();
5671 break;
5672
5673 case Stmt::ChooseExprClass:
5674 E = cast<ChooseExpr>(Terminator)->getCond();
5675 break;
5676
5677 case Stmt::IndirectGotoStmtClass:
5678 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
5679 break;
5680
5681 case Stmt::SwitchStmtClass:
5682 E = cast<SwitchStmt>(Terminator)->getCond();
5683 break;
5684
5685 case Stmt::BinaryConditionalOperatorClass:
5686 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
5687 break;
5688
5689 case Stmt::ConditionalOperatorClass:
5690 E = cast<ConditionalOperator>(Terminator)->getCond();
5691 break;
5692
5693 case Stmt::BinaryOperatorClass: // '&&' and '||'
5694 E = cast<BinaryOperator>(Terminator)->getLHS();
5695 break;
5696
5697 case Stmt::ObjCForCollectionStmtClass:
5698 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005699 }
Mike Stump31feda52009-07-17 01:31:16 +00005700
Kristof Umann9854d772019-07-03 13:03:33 +00005701 if (!StripParens)
5702 return E;
5703
5704 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005705}
5706
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005707//===----------------------------------------------------------------------===//
5708// CFG Graphviz Visualization
5709//===----------------------------------------------------------------------===//
5710
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005711#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00005712static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005713#endif
5714
Chris Lattnerc61089a2009-06-30 01:26:17 +00005715void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005716#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00005717 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005718 GraphHelper = &H;
5719 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00005720 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005721#endif
5722}
5723
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005724namespace llvm {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005725
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005726template<>
5727struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005728 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Tobias Grosser9fc223a2009-11-30 14:16:05 +00005729
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005730 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005731#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005732 std::string OutSStr;
5733 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005734 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005735 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005736
5737 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
5738
5739 // Process string output to make it nicer...
5740 for (unsigned i = 0; i != OutStr.length(); ++i)
5741 if (OutStr[i] == '\n') { // Left justify
5742 OutStr[i] = '\\';
5743 OutStr.insert(OutStr.begin()+i+1, 'l');
5744 }
Mike Stump31feda52009-07-17 01:31:16 +00005745
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005746 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005747#else
Eugene Zelenko38c70522017-12-07 21:55:09 +00005748 return {};
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005749#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005750 }
5751};
Eugene Zelenko38c70522017-12-07 21:55:09 +00005752
5753} // namespace llvm