blob: 13804746b276c8f16df67acd85c976ce862f11be [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the CFG and CFGBuilder classes for representing and
11// building Control-Flow Graphs (CFGs) from ASTs.
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek6796fbd2009-07-16 18:13:04 +000015#include "clang/Analysis/CFG.h"
Benjamin Kramer1ea8e092012-07-04 17:04:04 +000016#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/AST/DeclCXX.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000021#include "clang/AST/DeclGroup.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/OperationKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "clang/AST/PrettyPrinter.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000026#include "clang/AST/Stmt.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/AST/StmtObjC.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/StmtVisitor.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000030#include "clang/AST/Type.h"
31#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"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/SourceLocation.h"
37#include "clang/Basic/Specifiers.h"
38#include "llvm/ADT/APInt.h"
39#include "llvm/ADT/APSInt.h"
40#include "llvm/ADT/ArrayRef.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000041#include "llvm/ADT/DenseMap.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000042#include "llvm/ADT/Optional.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/SetVector.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000045#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000046#include "llvm/ADT/SmallVector.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000047#include "llvm/Support/Allocator.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000048#include "llvm/Support/Casting.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/DOTGraphTraits.h"
51#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000052#include "llvm/Support/Format.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000053#include "llvm/Support/GraphWriter.h"
54#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000055#include "llvm/Support/raw_ostream.h"
56#include <cassert>
57#include <memory>
58#include <string>
59#include <tuple>
60#include <utility>
61#include <vector>
Ted Kremeneke5ccf9a2008-01-11 00:40:29 +000062
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +000063using namespace clang;
64
Ted Kremenek5ef32db2011-08-12 23:37:29 +000065static SourceLocation GetEndLoc(Decl *D) {
66 if (VarDecl *VD = dyn_cast<VarDecl>(D))
67 if (Expr *Ex = VD->getInit())
Ted Kremenek8889bb32008-08-06 23:20:50 +000068 return Ex->getSourceRange().getEnd();
Mike Stump31feda52009-07-17 01:31:16 +000069 return D->getLocation();
Ted Kremenek8889bb32008-08-06 23:20:50 +000070}
Ted Kremenekdc03bd02010-08-02 23:46:59 +000071
George Burgess IVced56e62015-10-01 18:47:52 +000072/// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
73/// or EnumConstantDecl from the given Expr. If it fails, returns nullptr.
Eugene Zelenko38c70522017-12-07 21:55:09 +000074static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
George Burgess IVced56e62015-10-01 18:47:52 +000075 E = E->IgnoreParens();
76 if (isa<IntegerLiteral>(E))
77 return E;
78 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
79 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
80 return nullptr;
81}
82
83/// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is
84/// an integer literal or an enum constant.
85///
86/// If this fails, at least one of the returned DeclRefExpr or Expr will be
87/// null.
88static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *>
89tryNormalizeBinaryOperator(const BinaryOperator *B) {
90 BinaryOperatorKind Op = B->getOpcode();
91
92 const Expr *MaybeDecl = B->getLHS();
93 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
94 // Expr looked like `0 == Foo` instead of `Foo == 0`
95 if (Constant == nullptr) {
96 // Flip the operator
97 if (Op == BO_GT)
98 Op = BO_LT;
99 else if (Op == BO_GE)
100 Op = BO_LE;
101 else if (Op == BO_LT)
102 Op = BO_GT;
103 else if (Op == BO_LE)
104 Op = BO_GE;
105
106 MaybeDecl = B->getRHS();
107 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
108 }
109
110 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts());
111 return std::make_tuple(D, Op, Constant);
112}
113
114/// For an expression `x == Foo && x == Bar`, this determines whether the
115/// `Foo` and `Bar` are either of the same enumeration type, or both integer
116/// literals.
117///
118/// It's an error to pass this arguments that are not either IntegerLiterals
119/// or DeclRefExprs (that have decls of type EnumConstantDecl)
120static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
121 // User intent isn't clear if they're mixing int literals with enum
122 // constants.
123 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2))
124 return false;
125
126 // Integer literal comparisons, regardless of literal type, are acceptable.
127 if (isa<IntegerLiteral>(E1))
128 return true;
129
130 // IntegerLiterals are handled above and only EnumConstantDecls are expected
131 // beyond this point
132 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
133 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
134 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
135
136 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
137 const DeclContext *DC1 = Decl1->getDeclContext();
138 const DeclContext *DC2 = Decl2->getDeclContext();
139
140 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
141 return DC1 == DC2;
142}
143
Eugene Zelenko38c70522017-12-07 21:55:09 +0000144namespace {
145
Ted Kremenek7c58d352011-03-10 01:14:11 +0000146class CFGBuilder;
147
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000148/// The CFG builder uses a recursive algorithm to build the CFG. When
149/// we process an expression, sometimes we know that we must add the
150/// subexpressions as block-level expressions. For example:
151///
152/// exp1 || exp2
153///
154/// When processing the '||' expression, we know that exp1 and exp2
155/// need to be added as block-level expressions, even though they
156/// might not normally need to be. AddStmtChoice records this
157/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
158/// the builder has an option not to add a subexpression as a
159/// block-level expression.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000160class AddStmtChoice {
161public:
Ted Kremenek8219b822010-12-16 07:46:53 +0000162 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000163
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000164 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000165
Ted Kremenek7c58d352011-03-10 01:14:11 +0000166 bool alwaysAdd(CFGBuilder &builder,
167 const Stmt *stmt) const;
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000168
169 /// Return a copy of this object, except with the 'always-add' bit
170 /// set as specified.
171 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
Ted Kremenek7c58d352011-03-10 01:14:11 +0000172 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000173 }
174
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000175private:
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000176 Kind kind;
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000177};
Mike Stump31feda52009-07-17 01:31:16 +0000178
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000179/// LocalScope - Node in tree of local scopes created for C++ implicit
180/// destructor calls generation. It contains list of automatic variables
181/// declared in the scope and link to position in previous scope this scope
182/// began in.
183///
184/// The process of creating local scopes is as follows:
185/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
186/// - Before processing statements in scope (e.g. CompoundStmt) create
187/// LocalScope object using CFGBuilder::ScopePos as link to previous scope
188/// and set CFGBuilder::ScopePos to the end of new scope,
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000189/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000190/// at this VarDecl,
191/// - For every normal (without jump) end of scope add to CFGBlock destructors
192/// for objects in the current scope,
193/// - For every jump add to CFGBlock destructors for objects
194/// between CFGBuilder::ScopePos and local scope position saved for jump
195/// target. Thanks to C++ restrictions on goto jumps we can be sure that
196/// jump target position will be on the path to root from CFGBuilder::ScopePos
197/// (adding any variable that doesn't need constructor to be called to
198/// LocalScope can break this assumption),
199///
200class LocalScope {
201public:
Eugene Zelenko38c70522017-12-07 21:55:09 +0000202 friend class const_iterator;
203
204 using AutomaticVarsTy = BumpVector<VarDecl *>;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000205
206 /// const_iterator - Iterates local scope backwards and jumps to previous
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000207 /// scope on reaching the beginning of currently iterated scope.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000208 class const_iterator {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000209 const LocalScope* Scope = nullptr;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000210
211 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
212 /// Invalid iterator (with null Scope) has VarIter equal to 0.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000213 unsigned VarIter = 0;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000214
215 public:
216 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
217 /// Incrementing invalid iterator is allowed and will result in invalid
218 /// iterator.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000219 const_iterator() = default;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000220
221 /// Create valid iterator. In case when S.Prev is an invalid iterator and
222 /// I is equal to 0, this will create invalid iterator.
223 const_iterator(const LocalScope& S, unsigned I)
224 : Scope(&S), VarIter(I) {
225 // Iterator to "end" of scope is not allowed. Handle it by going up
226 // in scopes tree possibly up to invalid iterator in the root.
227 if (VarIter == 0 && Scope)
228 *this = Scope->Prev;
229 }
230
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000231 VarDecl *const* operator->() const {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000232 assert(Scope && "Dereferencing invalid iterator is not allowed");
233 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000234 return &Scope->Vars[VarIter - 1];
235 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000236 VarDecl *operator*() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000237 return *this->operator->();
238 }
239
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000240 const_iterator &operator++() {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000241 if (!Scope)
242 return *this;
243
Eugene Zelenko38c70522017-12-07 21:55:09 +0000244 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000245 --VarIter;
246 if (VarIter == 0)
247 *this = Scope->Prev;
248 return *this;
249 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000250 const_iterator operator++(int) {
251 const_iterator P = *this;
252 ++*this;
253 return P;
254 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000255
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000256 bool operator==(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000257 return Scope == rhs.Scope && VarIter == rhs.VarIter;
258 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000259 bool operator!=(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000260 return !(*this == rhs);
261 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000262
Aaron Ballman67347662015-02-15 22:00:28 +0000263 explicit operator bool() const {
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000264 return *this != const_iterator();
265 }
266
267 int distance(const_iterator L);
Matthias Gehre351c2182017-07-12 07:04:19 +0000268 const_iterator shared_parent(const_iterator L);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000269 };
270
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000271private:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000272 BumpVectorContext ctx;
273
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000274 /// Automatic variables in order of declaration.
275 AutomaticVarsTy Vars;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000276
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000277 /// Iterator to variable in previous scope that was declared just before
278 /// begin of this scope.
279 const_iterator Prev;
280
281public:
282 /// Constructs empty scope linked to previous scope in specified place.
David Blaikiec1334cc2015-08-13 22:12:21 +0000283 LocalScope(BumpVectorContext ctx, const_iterator P)
284 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000285
286 /// Begin of scope in direction of CFG building (backwards).
287 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000288
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000289 void addVar(VarDecl *VD) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000290 Vars.push_back(VD, ctx);
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000291 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000292};
293
Eugene Zelenko38c70522017-12-07 21:55:09 +0000294} // namespace
295
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000296/// distance - Calculates distance from this to L. L must be reachable from this
297/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
298/// number of scopes between this and L.
299int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
300 int D = 0;
301 const_iterator F = *this;
302 while (F.Scope != L.Scope) {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000303 assert(F != const_iterator() &&
304 "L iterator is not reachable from F iterator.");
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000305 D += F.VarIter;
306 F = F.Scope->Prev;
307 }
308 D += F.VarIter - L.VarIter;
309 return D;
310}
311
Matthias Gehre351c2182017-07-12 07:04:19 +0000312/// Calculates the closest parent of this iterator
313/// that is in a scope reachable through the parents of L.
314/// I.e. when using 'goto' from this to L, the lifetime of all variables
315/// between this and shared_parent(L) end.
316LocalScope::const_iterator
317LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
318 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
319 while (true) {
320 ScopesOfL.insert(L.Scope);
321 if (L == const_iterator())
322 break;
323 L = L.Scope->Prev;
324 }
325
326 const_iterator F = *this;
327 while (true) {
328 if (ScopesOfL.count(F.Scope))
329 return F;
330 assert(F != const_iterator() &&
331 "L iterator is not reachable from F iterator.");
332 F = F.Scope->Prev;
333 }
334}
335
Eugene Zelenko38c70522017-12-07 21:55:09 +0000336namespace {
337
Jonathan Roelofs99bdd982015-05-19 18:51:56 +0000338/// Structure for specifying position in CFG during its build process. It
339/// consists of CFGBlock that specifies position in CFG and
340/// LocalScope::const_iterator that specifies position in LocalScope graph.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000341struct BlockScopePosPair {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000342 CFGBlock *block = nullptr;
343 LocalScope::const_iterator scopePosition;
344
345 BlockScopePosPair() = default;
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000346 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000347 : block(b), scopePosition(scopePos) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000348};
349
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000350/// TryResult - a class representing a variant over the values
351/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
352/// and is used by the CFGBuilder to decide if a branch condition
353/// can be decided up front during CFG construction.
354class TryResult {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000355 int X = -1;
356
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000357public:
Eugene Zelenko38c70522017-12-07 21:55:09 +0000358 TryResult() = default;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000359 TryResult(bool b) : X(b ? 1 : 0) {}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000360
361 bool isTrue() const { return X == 1; }
362 bool isFalse() const { return X == 0; }
363 bool isKnown() const { return X >= 0; }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000364
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000365 void negate() {
366 assert(isKnown());
367 X ^= 0x1;
368 }
369};
370
Eugene Zelenko38c70522017-12-07 21:55:09 +0000371} // namespace
372
373static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
Manuel Klimekdeb02622014-08-08 07:37:13 +0000374 if (!R1.isKnown() || !R2.isKnown())
375 return TryResult();
376 return TryResult(R1.isTrue() && R2.isTrue());
377}
378
Eugene Zelenko38c70522017-12-07 21:55:09 +0000379namespace {
380
Ted Kremenek8ae67872013-02-05 22:00:19 +0000381class reverse_children {
382 llvm::SmallVector<Stmt *, 12> childrenBuf;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000383 ArrayRef<Stmt *> children;
384
Ted Kremenek8ae67872013-02-05 22:00:19 +0000385public:
386 reverse_children(Stmt *S);
387
Eugene Zelenko38c70522017-12-07 21:55:09 +0000388 using iterator = ArrayRef<Stmt *>::reverse_iterator;
389
Ted Kremenek8ae67872013-02-05 22:00:19 +0000390 iterator begin() const { return children.rbegin(); }
391 iterator end() const { return children.rend(); }
392};
393
Eugene Zelenko38c70522017-12-07 21:55:09 +0000394} // namespace
Ted Kremenek8ae67872013-02-05 22:00:19 +0000395
396reverse_children::reverse_children(Stmt *S) {
397 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
398 children = CE->getRawSubExprs();
399 return;
400 }
401 switch (S->getStmtClass()) {
Ted Kremenek7d86b9c2013-02-05 22:03:14 +0000402 // Note: Fill in this switch with more cases we want to optimize.
Ted Kremenek8ae67872013-02-05 22:00:19 +0000403 case Stmt::InitListExprClass: {
404 InitListExpr *IE = cast<InitListExpr>(S);
405 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
406 IE->getNumInits());
407 return;
408 }
409 default:
410 break;
411 }
412
413 // Default case for all other statements.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000414 for (Stmt *SubStmt : S->children())
415 childrenBuf.push_back(SubStmt);
Ted Kremenek8ae67872013-02-05 22:00:19 +0000416
417 // This needs to be done *after* childrenBuf has been populated.
418 children = childrenBuf;
419}
420
Eugene Zelenko38c70522017-12-07 21:55:09 +0000421namespace {
422
Ted Kremenekbe9b33b2008-08-04 22:51:42 +0000423/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000424/// The builder is stateful: an instance of the builder should be used to only
425/// construct a single CFG.
426///
427/// Example usage:
428///
429/// CFGBuilder builder;
Jonathan Roelofsab046c52015-07-27 16:05:36 +0000430/// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000431///
Mike Stump31feda52009-07-17 01:31:16 +0000432/// CFG construction is done via a recursive walk of an AST. We actually parse
433/// the AST in reverse order so that the successor of a basic block is
434/// constructed prior to its predecessor. This allows us to nicely capture
435/// implicit fall-throughs without extra basic blocks.
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000436class CFGBuilder {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000437 using JumpTarget = BlockScopePosPair;
438 using JumpSource = BlockScopePosPair;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000439
Mike Stump0d76d072009-07-20 23:24:15 +0000440 ASTContext *Context;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000441 std::unique_ptr<CFG> cfg;
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000442
Eugene Zelenko38c70522017-12-07 21:55:09 +0000443 // Current block.
444 CFGBlock *Block = nullptr;
445
446 // Block after the current block.
447 CFGBlock *Succ = nullptr;
448
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000449 JumpTarget ContinueJumpTarget;
450 JumpTarget BreakJumpTarget;
Nico Weber699670e2017-08-23 15:33:16 +0000451 JumpTarget SEHLeaveJumpTarget;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000452 CFGBlock *SwitchTerminatedBlock = nullptr;
453 CFGBlock *DefaultCaseBlock = nullptr;
Nico Weber699670e2017-08-23 15:33:16 +0000454
455 // This can point either to a try or a __try block. The frontend forbids
456 // mixing both kinds in one function, so having one for both is enough.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000457 CFGBlock *TryTerminatedBlock = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000458
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000459 // Current position in local scope.
460 LocalScope::const_iterator ScopePos;
461
462 // LabelMap records the mapping from Label expressions to their jump targets.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000463 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
Ted Kremenek8a632182007-08-21 23:26:17 +0000464 LabelMapTy LabelMap;
Mike Stump31feda52009-07-17 01:31:16 +0000465
466 // A list of blocks that end with a "goto" that must be backpatched to their
467 // resolved targets upon completion of CFG construction.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000468 using BackpatchBlocksTy = std::vector<JumpSource>;
Ted Kremenek8a632182007-08-21 23:26:17 +0000469 BackpatchBlocksTy BackpatchBlocks;
Mike Stump31feda52009-07-17 01:31:16 +0000470
Ted Kremenekeda180e22007-08-28 19:26:49 +0000471 // A list of labels whose address has been taken (for indirect gotos).
Eugene Zelenko38c70522017-12-07 21:55:09 +0000472 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
Ted Kremenekeda180e22007-08-28 19:26:49 +0000473 LabelSetTy AddressTakenLabels;
Mike Stump31feda52009-07-17 01:31:16 +0000474
Artem Dergachev41ffb302018-02-08 22:58:15 +0000475 // Information about the currently visited C++ object construction site.
476 // This is set in the construction trigger and read when the constructor
477 // itself is being visited.
Artem Dergachev783a4572018-02-23 22:20:39 +0000478 llvm::DenseMap<CXXConstructExpr *, const ConstructionContext *>
Artem Dergachev5e2f6ba2018-02-23 22:49:25 +0000479 ConstructionContextMap;
Artem Dergachev41ffb302018-02-08 22:58:15 +0000480
Eugene Zelenko38c70522017-12-07 21:55:09 +0000481 bool badCFG = false;
Ted Kremenekf9d82902011-03-10 01:14:05 +0000482 const CFG::BuildOptions &BuildOpts;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000483
484 // State to track for building switch statements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000485 bool switchExclusivelyCovered = false;
486 Expr::EvalResult *switchCond = nullptr;
Ted Kremeneka099c592011-03-10 03:50:34 +0000487
Eugene Zelenko38c70522017-12-07 21:55:09 +0000488 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
489 const Stmt *lastLookup = nullptr;
Zhongxing Xud38fb842010-09-16 03:28:18 +0000490
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000491 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
492 // during construction of branches for chained logical operators.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000493 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000494 CachedBoolEvalsTy CachedBoolEvals;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000495
Mike Stump31feda52009-07-17 01:31:16 +0000496public:
Ted Kremenekf9d82902011-03-10 01:14:05 +0000497 explicit CFGBuilder(ASTContext *astContext,
Nico Weber699670e2017-08-23 15:33:16 +0000498 const CFG::BuildOptions &buildOpts)
499 : Context(astContext), cfg(new CFG()), // crew a new CFG
Artem Dergachev5e2f6ba2018-02-23 22:49:25 +0000500 ConstructionContextMap(), BuildOpts(buildOpts) {}
501
Mike Stump31feda52009-07-17 01:31:16 +0000502
Ted Kremenek9aae5132007-08-23 21:42:29 +0000503 // buildCFG - Used by external clients to construct the CFG.
David Blaikiee90195c2014-08-29 18:53:26 +0000504 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
Mike Stump31feda52009-07-17 01:31:16 +0000505
Ted Kremeneka099c592011-03-10 03:50:34 +0000506 bool alwaysAdd(const Stmt *stmt);
507
Ted Kremenek93668002009-07-17 22:18:43 +0000508private:
509 // Visitors to walk an AST and construct the CFG.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000510 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
511 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000512 CFGBlock *VisitBreakStmt(BreakStmt *B);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000513 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000514 CFGBlock *VisitCaseStmt(CaseStmt *C);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000515 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000516 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
John McCallc07a0c72011-02-17 10:25:35 +0000517 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
518 AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000519 CFGBlock *VisitContinueStmt(ContinueStmt *C);
Ted Kremenek6f400242012-07-14 05:04:01 +0000520 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
521 AddStmtChoice asc);
522 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
523 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
Jordan Rosec9176072014-01-13 17:59:19 +0000524 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
Jordan Rosed2f40792013-09-03 17:00:57 +0000525 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000526 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
527 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
528 AddStmtChoice asc);
529 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
530 AddStmtChoice asc);
531 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
532 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000533 CFGBlock *VisitDeclStmt(DeclStmt *DS);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000534 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
Ted Kremenek21822592009-07-17 18:20:32 +0000535 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
536 CFGBlock *VisitDoStmt(DoStmt *D);
Ted Kremenek6f400242012-07-14 05:04:01 +0000537 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000538 CFGBlock *VisitForStmt(ForStmt *F);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000539 CFGBlock *VisitGotoStmt(GotoStmt *G);
Ted Kremenek93668002009-07-17 22:18:43 +0000540 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000541 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000542 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
543 CFGBlock *VisitLabelStmt(LabelStmt *L);
Devin Coughlinb6029b72015-11-25 22:35:37 +0000544 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000545 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000546 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000547 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
548 Stmt *Term,
549 CFGBlock *TrueBlock,
550 CFGBlock *FalseBlock);
Artem Dergachevf43ac4c2018-02-24 02:00:30 +0000551 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
552 AddStmtChoice asc);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000553 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000554 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
555 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
556 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
557 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000558 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000559 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
John McCallfe96e0b2011-11-06 09:01:30 +0000560 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Ted Kremenek6f400242012-07-14 05:04:01 +0000561 CFGBlock *VisitReturnStmt(ReturnStmt *R);
Nico Weber699670e2017-08-23 15:33:16 +0000562 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
563 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
564 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
565 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000566 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000567 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000568 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
569 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000570 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000571 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000572
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000573 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
574 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000575 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000576 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000577
Manuel Klimekb5616c92014-08-07 10:42:17 +0000578 /// When creating the CFG for temporary destructors, we want to mirror the
579 /// branch structure of the corresponding constructor calls.
580 /// Thus, while visiting a statement for temporary destructors, we keep a
581 /// context to keep track of the following information:
582 /// - whether a subexpression is executed unconditionally
583 /// - if a subexpression is executed conditionally, the first
584 /// CXXBindTemporaryExpr we encounter in that subexpression (which
585 /// corresponds to the last temporary destructor we have to call for this
586 /// subexpression) and the CFG block at that point (which will become the
587 /// successor block when inserting the decision point).
588 ///
589 /// That way, we can build the branch structure for temporary destructors as
590 /// follows:
591 /// 1. If a subexpression is executed unconditionally, we add the temporary
592 /// destructor calls to the current block.
593 /// 2. If a subexpression is executed conditionally, when we encounter a
594 /// CXXBindTemporaryExpr:
595 /// a) If it is the first temporary destructor call in the subexpression,
596 /// we remember the CXXBindTemporaryExpr and the current block in the
597 /// TempDtorContext; we start a new block, and insert the temporary
598 /// destructor call.
599 /// b) Otherwise, add the temporary destructor call to the current block.
600 /// 3. When we finished visiting a conditionally executed subexpression,
601 /// and we found at least one temporary constructor during the visitation
602 /// (2.a has executed), we insert a decision block that uses the
603 /// CXXBindTemporaryExpr as terminator, and branches to the current block
604 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
605 /// branches to the stored successor.
606 struct TempDtorContext {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000607 TempDtorContext() = default;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000608 TempDtorContext(TryResult KnownExecuted)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000609 : IsConditional(true), KnownExecuted(KnownExecuted) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000610
611 /// Returns whether we need to start a new branch for a temporary destructor
Eric Christopher2c4555a2015-06-19 01:52:53 +0000612 /// call. This is the case when the temporary destructor is
Manuel Klimekb5616c92014-08-07 10:42:17 +0000613 /// conditionally executed, and it is the first one we encounter while
614 /// visiting a subexpression - other temporary destructors at the same level
615 /// will be added to the same block and are executed under the same
616 /// condition.
617 bool needsTempDtorBranch() const {
618 return IsConditional && !TerminatorExpr;
619 }
620
621 /// Remember the successor S of a temporary destructor decision branch for
622 /// the corresponding CXXBindTemporaryExpr E.
623 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
624 Succ = S;
625 TerminatorExpr = E;
626 }
627
Eugene Zelenko38c70522017-12-07 21:55:09 +0000628 const bool IsConditional = false;
629 const TryResult KnownExecuted = true;
630 CFGBlock *Succ = nullptr;
631 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000632 };
633
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000634 // Visitors to walk an AST and generate destructors of temporaries in
635 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000636 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
637 TempDtorContext &Context);
638 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
639 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
640 TempDtorContext &Context);
641 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
642 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
643 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
644 AbstractConditionalOperator *E, bool BindToTemporary,
645 TempDtorContext &Context);
646 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
647 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000648
Ted Kremenek6065ef62008-04-28 18:00:46 +0000649 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000650 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000651 badCFG = true;
652 return Block;
653 }
Mike Stump31feda52009-07-17 01:31:16 +0000654
Artem Dergachevc1b07bd2018-02-23 23:38:41 +0000655 // Remember to apply \p CC when constructing the CFG element for \p CE.
656 void consumeConstructionContext(const ConstructionContext *CC,
657 CXXConstructExpr *CE);
658
Artem Dergachev41ffb302018-02-08 22:58:15 +0000659 // Scan the child statement \p Child to find the constructor that might
660 // have been directly triggered by the current node, \p Trigger. If such
661 // constructor has been found, set current construction context to point
662 // to the trigger statement. The construction context will be unset once
663 // it is consumed when the CFG building procedure processes the
664 // construct-expression and adds the respective CFGConstructor element.
Artem Dergachev783a4572018-02-23 22:20:39 +0000665 void findConstructionContexts(const ConstructionContext *ContextSoFar,
666 Stmt *Child);
Artem Dergachev41ffb302018-02-08 22:58:15 +0000667 // Unset the construction context after consuming it. This is done immediately
668 // after adding the CFGConstructor element, so there's no need to
669 // do this manually in every Visit... function.
Artem Dergachev783a4572018-02-23 22:20:39 +0000670 void cleanupConstructionContext(CXXConstructExpr *CE);
Artem Dergachev41ffb302018-02-08 22:58:15 +0000671
Ted Kremenek93668002009-07-17 22:18:43 +0000672 void autoCreateBlock() { if (!Block) Block = createBlock(); }
673 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000674 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000675
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000676 CFGBlock *addStmt(Stmt *S) {
677 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000678 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000679
Alexis Hunt1d792652011-01-08 20:30:50 +0000680 CFGBlock *addInitializer(CXXCtorInitializer *I);
Peter Szecsi999a25f2017-08-19 11:19:16 +0000681 void addLoopExit(const Stmt *LoopStmt);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000682 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000683 LocalScope::const_iterator E, Stmt *S);
Matthias Gehre351c2182017-07-12 07:04:19 +0000684 void addLifetimeEnds(LocalScope::const_iterator B,
685 LocalScope::const_iterator E, Stmt *S);
686 void addAutomaticObjHandling(LocalScope::const_iterator B,
687 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000688 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000689
Marcin Swiderski5e415732010-09-30 23:05:00 +0000690 // Local scopes creation.
691 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
692
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000693 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000694 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
695 LocalScope* Scope = nullptr);
696 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000697
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000698 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000699
700 // Interface to CFGBlock - adding CFGElements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000701
Ted Kremenek37881932011-04-04 23:29:12 +0000702 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000703 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000704 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000705
Jordy Rose17347372011-06-10 08:49:37 +0000706 // All block-level expressions should have already been IgnoreParens()ed.
707 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000708 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000709 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000710
Artem Dergachev41ffb302018-02-08 22:58:15 +0000711 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
712 if (BuildOpts.AddRichCXXConstructors) {
Artem Dergachev783a4572018-02-23 22:20:39 +0000713 if (const ConstructionContext *CC = ConstructionContextMap.lookup(CE)) {
714 B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
715 cleanupConstructionContext(CE);
Artem Dergachev41ffb302018-02-08 22:58:15 +0000716 return;
717 }
718 }
719
720 // No valid construction context found. Fall back to statement.
721 B->appendStmt(CE, cfg->getBumpVectorContext());
722 }
723
Alexis Hunt1d792652011-01-08 20:30:50 +0000724 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000725 B->appendInitializer(I, cfg->getBumpVectorContext());
726 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000727
Jordan Rosec9176072014-01-13 17:59:19 +0000728 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
729 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
730 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000731
Marcin Swiderski20b88732010-10-05 05:37:00 +0000732 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
733 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
734 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000735
Marcin Swiderski20b88732010-10-05 05:37:00 +0000736 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
737 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
738 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000739
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000740 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
741 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
742 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000743
Chandler Carruthad747252011-09-13 06:09:01 +0000744 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
745 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
746 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000747
Matthias Gehre351c2182017-07-12 07:04:19 +0000748 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
749 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
750 }
751
Peter Szecsi999a25f2017-08-19 11:19:16 +0000752 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
753 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
754 }
755
Jordan Rosed2f40792013-09-03 17:00:57 +0000756 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
757 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
758 }
759
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000760 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000761 LocalScope::const_iterator B, LocalScope::const_iterator E);
762
Matthias Gehre351c2182017-07-12 07:04:19 +0000763 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
764 LocalScope::const_iterator B,
765 LocalScope::const_iterator E);
766
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000767 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
768 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
769 cfg->getBumpVectorContext());
770 }
771
772 /// Add a reachable successor to a block, with the alternate variant that is
773 /// unreachable.
774 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
775 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
776 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000777 }
Mike Stump11289f42009-09-09 15:08:12 +0000778
Richard Trieuf935b562014-04-05 05:17:01 +0000779 /// \brief Find a relational comparison with an expression evaluating to a
780 /// boolean and a constant other than 0 and 1.
781 /// e.g. if ((x < y) == 10)
782 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
783 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
784 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
785
786 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
787 const Expr *BoolExpr = RHSExpr;
788 bool IntFirst = true;
789 if (!IntLiteral) {
790 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
791 BoolExpr = LHSExpr;
792 IntFirst = false;
793 }
794
795 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
796 return TryResult();
797
798 llvm::APInt IntValue = IntLiteral->getValue();
799 if ((IntValue == 1) || (IntValue == 0))
800 return TryResult();
801
802 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
803 !IntValue.isNegative();
804
805 BinaryOperatorKind Bok = B->getOpcode();
806 if (Bok == BO_GT || Bok == BO_GE) {
807 // Always true for 10 > bool and bool > -1
808 // Always false for -1 > bool and bool > 10
809 return TryResult(IntFirst == IntLarger);
810 } else {
811 // Always true for -1 < bool and bool < 10
812 // Always false for 10 < bool and bool < -1
813 return TryResult(IntFirst != IntLarger);
814 }
815 }
816
Jordan Rose7afd71e2014-05-20 17:31:11 +0000817 /// Find an incorrect equality comparison. Either with an expression
818 /// evaluating to a boolean and a constant other than 0 and 1.
819 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
820 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000821 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
822 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
823 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
824
825 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
826 const Expr *BoolExpr = RHSExpr;
827
828 if (!IntLiteral) {
829 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
830 BoolExpr = LHSExpr;
831 }
832
Jordan Rose7afd71e2014-05-20 17:31:11 +0000833 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000834 return TryResult();
835
Jordan Rose7afd71e2014-05-20 17:31:11 +0000836 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
837 if (BitOp && (BitOp->getOpcode() == BO_And ||
838 BitOp->getOpcode() == BO_Or)) {
839 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
840 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
841
842 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
843
844 if (!IntLiteral2)
845 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
846
847 if (!IntLiteral2)
848 return TryResult();
849
850 llvm::APInt L1 = IntLiteral->getValue();
851 llvm::APInt L2 = IntLiteral2->getValue();
852 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
853 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
854 if (BuildOpts.Observer)
855 BuildOpts.Observer->compareBitwiseEquality(B,
856 B->getOpcode() != BO_EQ);
857 TryResult(B->getOpcode() != BO_EQ);
858 }
859 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
860 llvm::APInt IntValue = IntLiteral->getValue();
861 if ((IntValue == 1) || (IntValue == 0)) {
862 return TryResult();
863 }
864 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000865 }
866
Jordan Rose7afd71e2014-05-20 17:31:11 +0000867 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000868 }
869
870 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
871 const llvm::APSInt &Value1,
872 const llvm::APSInt &Value2) {
873 assert(Value1.isSigned() == Value2.isSigned());
874 switch (Relation) {
875 default:
876 return TryResult();
877 case BO_EQ:
878 return TryResult(Value1 == Value2);
879 case BO_NE:
880 return TryResult(Value1 != Value2);
881 case BO_LT:
882 return TryResult(Value1 < Value2);
883 case BO_LE:
884 return TryResult(Value1 <= Value2);
885 case BO_GT:
886 return TryResult(Value1 > Value2);
887 case BO_GE:
888 return TryResult(Value1 >= Value2);
889 }
890 }
891
892 /// \brief Find a pair of comparison expressions with or without parentheses
893 /// with a shared variable and constants and a logical operator between them
894 /// that always evaluates to either true or false.
895 /// e.g. if (x != 3 || x != 4)
896 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
897 assert(B->isLogicalOp());
898 const BinaryOperator *LHS =
899 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
900 const BinaryOperator *RHS =
901 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
902 if (!LHS || !RHS)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000903 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000904
905 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000906 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000907
George Burgess IVced56e62015-10-01 18:47:52 +0000908 const DeclRefExpr *Decl1;
909 const Expr *Expr1;
910 BinaryOperatorKind BO1;
911 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000912
George Burgess IVced56e62015-10-01 18:47:52 +0000913 if (!Decl1 || !Expr1)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000914 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000915
George Burgess IVced56e62015-10-01 18:47:52 +0000916 const DeclRefExpr *Decl2;
917 const Expr *Expr2;
918 BinaryOperatorKind BO2;
919 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000920
George Burgess IVced56e62015-10-01 18:47:52 +0000921 if (!Decl2 || !Expr2)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000922 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000923
924 // Check that it is the same variable on both sides.
925 if (Decl1->getDecl() != Decl2->getDecl())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000926 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000927
George Burgess IVced56e62015-10-01 18:47:52 +0000928 // Make sure the user's intent is clear (e.g. they're comparing against two
929 // int literals, or two things from the same enum)
930 if (!areExprTypesCompatible(Expr1, Expr2))
Eugene Zelenko38c70522017-12-07 21:55:09 +0000931 return {};
George Burgess IVced56e62015-10-01 18:47:52 +0000932
Richard Trieuf935b562014-04-05 05:17:01 +0000933 llvm::APSInt L1, L2;
934
George Burgess IVced56e62015-10-01 18:47:52 +0000935 if (!Expr1->EvaluateAsInt(L1, *Context) ||
936 !Expr2->EvaluateAsInt(L2, *Context))
Eugene Zelenko38c70522017-12-07 21:55:09 +0000937 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000938
939 // Can't compare signed with unsigned or with different bit width.
940 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000941 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000942
943 // Values that will be used to determine if result of logical
944 // operator is always true/false
945 const llvm::APSInt Values[] = {
946 // Value less than both Value1 and Value2
947 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
948 // L1
949 L1,
950 // Value between Value1 and Value2
951 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
952 L1.isUnsigned()),
953 // L2
954 L2,
955 // Value greater than both Value1 and Value2
956 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
957 };
958
959 // Check whether expression is always true/false by evaluating the following
960 // * variable x is less than the smallest literal.
961 // * variable x is equal to the smallest literal.
962 // * Variable x is between smallest and largest literal.
963 // * Variable x is equal to the largest literal.
964 // * Variable x is greater than largest literal.
965 bool AlwaysTrue = true, AlwaysFalse = true;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +0000966 for (const llvm::APSInt &Value : Values) {
Richard Trieuf935b562014-04-05 05:17:01 +0000967 TryResult Res1, Res2;
968 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
969 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
970
971 if (!Res1.isKnown() || !Res2.isKnown())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000972 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000973
974 if (B->getOpcode() == BO_LAnd) {
975 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
976 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
977 } else {
978 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
979 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
980 }
981 }
982
983 if (AlwaysTrue || AlwaysFalse) {
984 if (BuildOpts.Observer)
985 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
986 return TryResult(AlwaysTrue);
987 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000988 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000989 }
990
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000991 /// Try and evaluate an expression to an integer constant.
992 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
993 if (!BuildOpts.PruneTriviallyFalseEdges)
994 return false;
995 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +0000996 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +0000997 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000998 }
Mike Stump11289f42009-09-09 15:08:12 +0000999
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001000 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +00001001 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001002 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +00001003 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001004 S->isTypeDependent() || S->isValueDependent())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001005 return {};
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001006
1007 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1008 if (Bop->isLogicalOp()) {
1009 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +00001010 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1011 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001012 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +00001013
1014 // Retrieve result at first, or the map might be updated.
1015 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1016 CachedBoolEvals[S] = Result; // update or insert
1017 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001018 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001019 else {
1020 switch (Bop->getOpcode()) {
1021 default: break;
1022 // For 'x & 0' and 'x * 0', we can determine that
1023 // the value is always false.
1024 case BO_Mul:
1025 case BO_And: {
1026 // If either operand is zero, we know the value
1027 // must be false.
1028 llvm::APSInt IntVal;
1029 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00001030 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001031 return TryResult(false);
1032 }
1033 }
1034 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00001035 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001036 return TryResult(false);
1037 }
1038 }
1039 }
1040 break;
1041 }
1042 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001043 }
1044
1045 return evaluateAsBooleanConditionNoCache(S);
1046 }
1047
1048 /// \brief Evaluate as boolean \param E without using the cache.
1049 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1050 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1051 if (Bop->isLogicalOp()) {
1052 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1053 if (LHS.isKnown()) {
1054 // We were able to evaluate the LHS, see if we can get away with not
1055 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1056 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1057 return LHS.isTrue();
1058
1059 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1060 if (RHS.isKnown()) {
1061 if (Bop->getOpcode() == BO_LOr)
1062 return LHS.isTrue() || RHS.isTrue();
1063 else
1064 return LHS.isTrue() && RHS.isTrue();
1065 }
1066 } else {
1067 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1068 if (RHS.isKnown()) {
1069 // We can't evaluate the LHS; however, sometimes the result
1070 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1071 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1072 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +00001073 } else {
1074 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1075 if (BopRes.isKnown())
1076 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001077 }
1078 }
1079
Eugene Zelenko38c70522017-12-07 21:55:09 +00001080 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001081 } else if (Bop->isEqualityOp()) {
1082 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1083 if (BopRes.isKnown())
1084 return BopRes.isTrue();
1085 } else if (Bop->isRelationalOp()) {
1086 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1087 if (BopRes.isKnown())
1088 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001089 }
1090 }
1091
1092 bool Result;
1093 if (E->EvaluateAsBooleanCondition(Result, *Context))
1094 return Result;
1095
Eugene Zelenko38c70522017-12-07 21:55:09 +00001096 return {};
Mike Stump773582d2009-07-23 23:25:26 +00001097 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001098
1099 bool hasTrivialDestructor(VarDecl *VD);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00001100};
Mike Stump31feda52009-07-17 01:31:16 +00001101
Eugene Zelenko38c70522017-12-07 21:55:09 +00001102} // namespace
1103
Ted Kremeneka099c592011-03-10 03:50:34 +00001104inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1105 const Stmt *stmt) const {
1106 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1107}
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001108
Ted Kremeneka099c592011-03-10 03:50:34 +00001109bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +00001110 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1111
Ted Kremeneka099c592011-03-10 03:50:34 +00001112 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +00001113 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001114
1115 if (lastLookup == stmt) {
1116 if (cachedEntry) {
1117 assert(cachedEntry->first == stmt);
1118 return true;
1119 }
Ted Kremenek8b46c002011-07-19 14:18:43 +00001120 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001121 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001122
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001123 lastLookup = stmt;
1124
1125 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +00001126 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1127
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001128 if (!fb) {
1129 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +00001130 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +00001131 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001132 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001133
1134 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001135 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +00001136 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +00001137 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001138 }
1139
Ted Kremeneka099c592011-03-10 03:50:34 +00001140 cachedEntry = &*itr;
1141 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +00001142}
1143
Douglas Gregor4619e432008-12-05 23:32:09 +00001144// FIXME: Add support for dependent-sized array types in C++?
1145// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +00001146static const VariableArrayType *FindVA(const Type *t) {
1147 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1148 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001149 if (vat->getSizeExpr())
1150 return vat;
Mike Stump31feda52009-07-17 01:31:16 +00001151
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001152 t = vt->getElementType().getTypePtr();
1153 }
Mike Stump31feda52009-07-17 01:31:16 +00001154
Craig Topper25542942014-05-20 04:30:07 +00001155 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001156}
Mike Stump31feda52009-07-17 01:31:16 +00001157
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001158void CFGBuilder::consumeConstructionContext(const ConstructionContext *CC, CXXConstructExpr *CE) {
1159 if (const ConstructionContext *PreviousContext =
1160 ConstructionContextMap.lookup(CE)) {
1161 // We might have visited this child when we were finding construction
1162 // contexts within its parents.
1163 assert(PreviousContext->isStrictlyMoreSpecificThan(CC) &&
1164 "Already within a different construction context!");
1165 } else {
1166 ConstructionContextMap[CE] = CC;
1167 }
1168}
1169
Artem Dergachev783a4572018-02-23 22:20:39 +00001170void CFGBuilder::findConstructionContexts(
1171 const ConstructionContext *ContextSoFar, Stmt *Child) {
Artem Dergachev41ffb302018-02-08 22:58:15 +00001172 if (!BuildOpts.AddRichCXXConstructors)
1173 return;
1174 if (!Child)
1175 return;
Artem Dergachev783a4572018-02-23 22:20:39 +00001176 if (auto *CE = dyn_cast<CXXConstructExpr>(Child)) {
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001177 consumeConstructionContext(ContextSoFar, CE);
Artem Dergachev08225bb2018-02-10 02:46:14 +00001178 } else if (auto *Cleanups = dyn_cast<ExprWithCleanups>(Child)) {
Artem Dergachev783a4572018-02-23 22:20:39 +00001179 findConstructionContexts(ContextSoFar, Cleanups->getSubExpr());
1180 } else if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Child)) {
1181 findConstructionContexts(
1182 ConstructionContext::create(cfg->getBumpVectorContext(), BTE,
1183 ContextSoFar),
1184 BTE->getSubExpr());
Artem Dergachev41ffb302018-02-08 22:58:15 +00001185 }
1186}
1187
Artem Dergachev783a4572018-02-23 22:20:39 +00001188void CFGBuilder::cleanupConstructionContext(CXXConstructExpr *CE) {
1189 assert(BuildOpts.AddRichCXXConstructors &&
1190 "We should not be managing construction contexts!");
1191 assert(ConstructionContextMap.count(CE) &&
Artem Dergachev41ffb302018-02-08 22:58:15 +00001192 "Cannot exit construction context without the context!");
Artem Dergachev783a4572018-02-23 22:20:39 +00001193 ConstructionContextMap.erase(CE);
Artem Dergachev41ffb302018-02-08 22:58:15 +00001194}
1195
1196
Mike Stump31feda52009-07-17 01:31:16 +00001197/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1198/// arbitrary statement. Examples include a single expression or a function
1199/// body (compound statement). The ownership of the returned CFG is
1200/// transferred to the caller. If CFG construction fails, this method returns
1201/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +00001202std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +00001203 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +00001204 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +00001205 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001206
Mike Stump31feda52009-07-17 01:31:16 +00001207 // Create an empty block that will serve as the exit block for the CFG. Since
1208 // this is the first block added to the CFG, it will be implicitly registered
1209 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +00001210 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +00001211 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +00001212 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +00001213
Matthias Gehre351c2182017-07-12 07:04:19 +00001214 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1215 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1216
Marcin Swiderski20b88732010-10-05 05:37:00 +00001217 if (BuildOpts.AddImplicitDtors)
1218 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1219 addImplicitDtorsForDestructor(DD);
1220
Ted Kremenek9aae5132007-08-23 21:42:29 +00001221 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001222 CFGBlock *B = addStmt(Statement);
1223
1224 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001225 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001226
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001227 // For C++ constructor add initializers to CFG.
1228 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
Pete Cooper57d3f142015-07-30 17:22:52 +00001229 for (auto *I : llvm::reverse(CD->inits())) {
1230 B = addInitializer(I);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001231 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001232 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001233 }
1234 }
1235
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001236 if (B)
1237 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001238
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001239 // Backpatch the gotos whose label -> block mappings we didn't know when we
1240 // encountered them.
1241 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1242 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001243
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001244 CFGBlock *B = I->block;
Rafael Espindola210de572013-03-27 15:37:54 +00001245 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001246 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00001247
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001248 // If there is no target for the goto, then we are looking at an
1249 // incomplete AST. Handle this by not registering a successor.
1250 if (LI == LabelMap.end()) continue;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001251
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001252 JumpTarget JT = LI->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00001253 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1254 JT.scopePosition);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001255 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1256 JT.scopePosition);
1257 addSuccessor(B, JT.block);
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001258 }
1259
1260 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001261 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001262 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1263 E = AddressTakenLabels.end(); I != E; ++I ) {
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001264 // Lookup the target block.
1265 LabelMapTy::iterator LI = LabelMap.find(*I);
1266
1267 // If there is no target block that contains label, then we are looking
1268 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001269 if (LI == LabelMap.end()) continue;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001270
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001271 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001272 }
Mike Stump31feda52009-07-17 01:31:16 +00001273
Mike Stump31feda52009-07-17 01:31:16 +00001274 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001275 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001276
Artem Dergachev783a4572018-02-23 22:20:39 +00001277 if (BuildOpts.AddRichCXXConstructors)
1278 assert(ConstructionContextMap.empty() &&
1279 "Not all construction contexts were cleaned up!");
1280
David Blaikiee90195c2014-08-29 18:53:26 +00001281 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001282}
Mike Stump31feda52009-07-17 01:31:16 +00001283
Ted Kremenek9aae5132007-08-23 21:42:29 +00001284/// createBlock - Used to lazily create blocks that are connected
1285/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001286CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1287 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001288 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001289 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001290 return B;
1291}
Mike Stump31feda52009-07-17 01:31:16 +00001292
Chandler Carrutha70991b2011-09-13 09:13:49 +00001293/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1294/// CFG. It is *not* connected to the current (global) successor, and instead
1295/// directly tied to the exit block in order to be reachable.
1296CFGBlock *CFGBuilder::createNoReturnBlock() {
1297 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001298 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001299 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001300 return B;
1301}
1302
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001303/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001304CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001305 if (!BuildOpts.AddInitializers)
1306 return Block;
1307
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001308 bool HasTemporaries = false;
1309
1310 // Destructors of temporaries in initialization expression should be called
1311 // after initialization finishes.
1312 Expr *Init = I->getInit();
1313 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001314 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001315
Jordan Rose6d671cc2012-09-05 22:55:23 +00001316 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001317 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001318 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001319 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1320 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001321 }
1322 }
1323
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001324 autoCreateBlock();
1325 appendInitializer(Block, I);
1326
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001327 if (Init) {
Artem Dergachev783a4572018-02-23 22:20:39 +00001328 findConstructionContexts(
1329 ConstructionContext::create(cfg->getBumpVectorContext(), I),
1330 Init);
Artem Dergachev5a281bb2018-02-10 02:18:04 +00001331
Ted Kremenek8219b822010-12-16 07:46:53 +00001332 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001333 // For expression with temporaries go directly to subexpression to omit
1334 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001335 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1336 }
Enrico Pertosofaed8012015-06-03 10:12:40 +00001337 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1338 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1339 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1340 // may cause the same Expr to appear more than once in the CFG. Doing it
1341 // here is safe because there's only one initializer per field.
1342 autoCreateBlock();
1343 appendStmt(Block, Default);
1344 if (Stmt *Child = Default->getExpr())
1345 if (CFGBlock *R = Visit(Child))
1346 Block = R;
1347 return Block;
1348 }
1349 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001350 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001351 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001352
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001353 return Block;
1354}
1355
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001356/// \brief Retrieve the type of the temporary object whose lifetime was
1357/// extended by a local reference with the given initializer.
1358static QualType getReferenceInitTemporaryType(ASTContext &Context,
Richard Smithb8c0f552016-12-09 18:49:13 +00001359 const Expr *Init,
1360 bool *FoundMTE = nullptr) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001361 while (true) {
1362 // Skip parentheses.
1363 Init = Init->IgnoreParens();
1364
1365 // Skip through cleanups.
1366 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1367 Init = EWC->getSubExpr();
1368 continue;
1369 }
1370
1371 // Skip through the temporary-materialization expression.
1372 if (const MaterializeTemporaryExpr *MTE
1373 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1374 Init = MTE->GetTemporaryExpr();
Richard Smithb8c0f552016-12-09 18:49:13 +00001375 if (FoundMTE)
1376 *FoundMTE = true;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001377 continue;
1378 }
1379
1380 // Skip derived-to-base and no-op casts.
1381 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1382 if ((CE->getCastKind() == CK_DerivedToBase ||
1383 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1384 CE->getCastKind() == CK_NoOp) &&
1385 Init->getType()->isRecordType()) {
1386 Init = CE->getSubExpr();
1387 continue;
1388 }
1389 }
1390
1391 // Skip member accesses into rvalues.
1392 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1393 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1394 Init = ME->getBase();
1395 continue;
1396 }
1397 }
1398
1399 break;
1400 }
1401
1402 return Init->getType();
1403}
Matthias Gehre351c2182017-07-12 07:04:19 +00001404
Peter Szecsi999a25f2017-08-19 11:19:16 +00001405// TODO: Support adding LoopExit element to the CFG in case where the loop is
1406// ended by ReturnStmt, GotoStmt or ThrowExpr.
1407void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1408 if(!BuildOpts.AddLoopExit)
1409 return;
1410 autoCreateBlock();
1411 appendLoopExit(Block, LoopStmt);
1412}
1413
Matthias Gehre351c2182017-07-12 07:04:19 +00001414void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1415 LocalScope::const_iterator E,
1416 Stmt *S) {
1417 if (BuildOpts.AddImplicitDtors)
1418 addAutomaticObjDtors(B, E, S);
1419 if (BuildOpts.AddLifetime)
1420 addLifetimeEnds(B, E, S);
1421}
1422
1423/// Add to current block automatic objects that leave the scope.
1424void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1425 LocalScope::const_iterator E, Stmt *S) {
1426 if (!BuildOpts.AddLifetime)
1427 return;
1428
1429 if (B == E)
1430 return;
1431
1432 // To go from B to E, one first goes up the scopes from B to P
1433 // then sideways in one scope from P to P' and then down
1434 // the scopes from P' to E.
1435 // The lifetime of all objects between B and P end.
1436 LocalScope::const_iterator P = B.shared_parent(E);
1437 int dist = B.distance(P);
1438 if (dist <= 0)
1439 return;
1440
1441 // We need to perform the scope leaving in reverse order
1442 SmallVector<VarDecl *, 10> DeclsTrivial;
1443 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1444 DeclsTrivial.reserve(dist);
1445 DeclsNonTrivial.reserve(dist);
1446
1447 for (LocalScope::const_iterator I = B; I != P; ++I)
1448 if (hasTrivialDestructor(*I))
1449 DeclsTrivial.push_back(*I);
1450 else
1451 DeclsNonTrivial.push_back(*I);
1452
1453 autoCreateBlock();
1454 // object with trivial destructor end their lifetime last (when storage
1455 // duration ends)
1456 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1457 E = DeclsTrivial.rend();
1458 I != E; ++I)
1459 appendLifetimeEnds(Block, *I, S);
1460
1461 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1462 I = DeclsNonTrivial.rbegin(),
1463 E = DeclsNonTrivial.rend();
1464 I != E; ++I)
1465 appendLifetimeEnds(Block, *I, S);
1466}
1467
Marcin Swiderski5e415732010-09-30 23:05:00 +00001468/// addAutomaticObjDtors - Add to current block automatic objects destructors
1469/// for objects in range of local scope positions. Use S as trigger statement
1470/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001471void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001472 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001473 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001474 return;
1475
Marcin Swiderski5e415732010-09-30 23:05:00 +00001476 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001477 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001478
Chandler Carruthad747252011-09-13 06:09:01 +00001479 // We need to append the destructors in reverse order, but any one of them
1480 // may be a no-return destructor which changes the CFG. As a result, buffer
1481 // this sequence up and replay them in reverse order when appending onto the
1482 // CFGBlock(s).
1483 SmallVector<VarDecl*, 10> Decls;
1484 Decls.reserve(B.distance(E));
1485 for (LocalScope::const_iterator I = B; I != E; ++I)
1486 Decls.push_back(*I);
1487
1488 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1489 E = Decls.rend();
1490 I != E; ++I) {
1491 // If this destructor is marked as a no-return destructor, we need to
1492 // create a new block for the destructor which does not have as a successor
1493 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001494 QualType Ty = (*I)->getType();
1495 if (Ty->isReferenceType()) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001496 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001497 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001498 Ty = Context->getBaseElementType(Ty);
1499
Richard Trieu95a192a2015-05-28 00:14:02 +00001500 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001501 Block = createNoReturnBlock();
1502 else
Chandler Carruthad747252011-09-13 06:09:01 +00001503 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001504
1505 appendAutomaticObjDtor(Block, *I, S);
1506 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001507}
1508
Marcin Swiderski20b88732010-10-05 05:37:00 +00001509/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1510/// base and member objects in destructor.
1511void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
Eugene Zelenko38c70522017-12-07 21:55:09 +00001512 assert(BuildOpts.AddImplicitDtors &&
1513 "Can be called only when dtors should be added");
Marcin Swiderski20b88732010-10-05 05:37:00 +00001514 const CXXRecordDecl *RD = DD->getParent();
1515
1516 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001517 for (const auto &VI : RD->vbases()) {
1518 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001519 if (!CD->hasTrivialDestructor()) {
1520 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001521 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001522 }
1523 }
1524
1525 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001526 for (const auto &BI : RD->bases()) {
1527 if (!BI.isVirtual()) {
1528 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001529 if (!CD->hasTrivialDestructor()) {
1530 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001531 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001532 }
1533 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001534 }
1535
1536 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001537 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001538 // Check for constant size array. Set type to array element type.
1539 QualType QT = FI->getType();
1540 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1541 if (AT->getSize() == 0)
1542 continue;
1543 QT = AT->getElementType();
1544 }
1545
1546 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001547 if (!CD->hasTrivialDestructor()) {
1548 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001549 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001550 }
1551 }
1552}
1553
Marcin Swiderski5e415732010-09-30 23:05:00 +00001554/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1555/// way return valid LocalScope object.
1556LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
David Blaikiec1334cc2015-08-13 22:12:21 +00001557 if (Scope)
1558 return Scope;
1559 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1560 return new (alloc.Allocate<LocalScope>())
1561 LocalScope(BumpVectorContext(alloc), ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001562}
1563
1564/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Zhongxing Xu81714f22010-10-01 03:00:16 +00001565/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001566void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001567 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001568 return;
1569
Craig Topper25542942014-05-20 04:30:07 +00001570 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001571
1572 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001573 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001574 for (auto *BI : CS->body()) {
1575 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001576 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001577 Scope = addLocalScopeForDeclStmt(DS, Scope);
1578 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001579 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001580 }
1581
1582 // For any other statement scope will be implicit and as such will be
1583 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001584 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001585 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001586}
1587
1588/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1589/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001590LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001591 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001592 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001593 return Scope;
1594
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001595 for (auto *DI : DS->decls())
1596 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001597 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001598 return Scope;
1599}
1600
Matthias Gehre351c2182017-07-12 07:04:19 +00001601bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1602 // Check for const references bound to temporary. Set type to pointee.
1603 QualType QT = VD->getType();
1604 if (QT.getTypePtr()->isReferenceType()) {
1605 // Attempt to determine whether this declaration lifetime-extends a
1606 // temporary.
1607 //
1608 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1609 // temporaries, and a single declaration can extend multiple temporaries.
1610 // We should look at the storage duration on each nested
1611 // MaterializeTemporaryExpr instead.
1612
1613 const Expr *Init = VD->getInit();
1614 if (!Init)
1615 return true;
1616
1617 // Lifetime-extending a temporary.
1618 bool FoundMTE = false;
1619 QT = getReferenceInitTemporaryType(*Context, Init, &FoundMTE);
1620 if (!FoundMTE)
1621 return true;
1622 }
1623
1624 // Check for constant size array. Set type to array element type.
1625 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1626 if (AT->getSize() == 0)
1627 return true;
1628 QT = AT->getElementType();
1629 }
1630
1631 // Check if type is a C++ class with non-trivial destructor.
1632 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1633 return !CD->hasDefinition() || CD->hasTrivialDestructor();
1634 return true;
1635}
1636
Marcin Swiderski5e415732010-09-30 23:05:00 +00001637/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1638/// create add scope for automatic objects and temporary objects bound to
1639/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001640LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001641 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001642 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1643 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1644 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001645 return Scope;
1646
1647 // Check if variable is local.
1648 switch (VD->getStorageClass()) {
1649 case SC_None:
1650 case SC_Auto:
1651 case SC_Register:
1652 break;
1653 default: return Scope;
1654 }
1655
Matthias Gehre351c2182017-07-12 07:04:19 +00001656 if (BuildOpts.AddImplicitDtors) {
1657 if (!hasTrivialDestructor(VD)) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001658 // Add the variable to scope
1659 Scope = createOrReuseLocalScope(Scope);
1660 Scope->addVar(VD);
1661 ScopePos = Scope->begin();
1662 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001663 return Scope;
1664 }
1665
1666 assert(BuildOpts.AddLifetime);
1667 // Add the variable to scope
1668 Scope = createOrReuseLocalScope(Scope);
1669 Scope->addVar(VD);
1670 ScopePos = Scope->begin();
Marcin Swiderski5e415732010-09-30 23:05:00 +00001671 return Scope;
1672}
1673
1674/// addLocalScopeAndDtors - For given statement add local scope for it and
1675/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001676void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001677 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001678 addLocalScopeForStmt(S);
Matthias Gehre351c2182017-07-12 07:04:19 +00001679 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001680}
1681
Marcin Swiderski321a7072010-09-30 22:54:37 +00001682/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1683/// variables with automatic storage duration to CFGBlock's elements vector.
1684/// Elements will be prepended to physical beginning of the vector which
1685/// happens to be logical end. Use blocks terminator as statement that specifies
1686/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001687/// FIXME: This mechanism for adding automatic destructors doesn't handle
1688/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001689void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00001690 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001691 if (!BuildOpts.AddImplicitDtors)
1692 return;
Chandler Carruthad747252011-09-13 06:09:01 +00001693 BumpVectorContext &C = cfg->getBumpVectorContext();
1694 CFGBlock::iterator InsertPos
1695 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1696 for (LocalScope::const_iterator I = B; I != E; ++I)
1697 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1698 Blk->getTerminator());
Marcin Swiderski321a7072010-09-30 22:54:37 +00001699}
1700
Matthias Gehre351c2182017-07-12 07:04:19 +00001701/// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
1702/// variables with automatic storage duration to CFGBlock's elements vector.
1703/// Elements will be prepended to physical beginning of the vector which
1704/// happens to be logical end. Use blocks terminator as statement that specifies
1705/// where lifetime ends.
1706void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
1707 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
1708 if (!BuildOpts.AddLifetime)
1709 return;
1710 BumpVectorContext &C = cfg->getBumpVectorContext();
1711 CFGBlock::iterator InsertPos =
1712 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
1713 for (LocalScope::const_iterator I = B; I != E; ++I)
1714 InsertPos = Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminator());
1715}
Eugene Zelenko38c70522017-12-07 21:55:09 +00001716
Ted Kremenek93668002009-07-17 22:18:43 +00001717/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00001718/// blocks for ternary operators, &&, and ||. We also process "," and
1719/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001720CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001721 if (!S) {
1722 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00001723 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001724 }
Jordy Rose17347372011-06-10 08:49:37 +00001725
1726 if (Expr *E = dyn_cast<Expr>(S))
1727 S = E->IgnoreParens();
1728
Ted Kremenek93668002009-07-17 22:18:43 +00001729 switch (S->getStmtClass()) {
1730 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001731 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001732
1733 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001734 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001735
John McCallc07a0c72011-02-17 10:25:35 +00001736 case Stmt::BinaryConditionalOperatorClass:
1737 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1738
Ted Kremenek93668002009-07-17 22:18:43 +00001739 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001740 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001741
Ted Kremenek93668002009-07-17 22:18:43 +00001742 case Stmt::BlockExprClass:
Devin Coughlinb6029b72015-11-25 22:35:37 +00001743 return VisitBlockExpr(cast<BlockExpr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001744
Ted Kremenek93668002009-07-17 22:18:43 +00001745 case Stmt::BreakStmtClass:
1746 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001747
Ted Kremenek93668002009-07-17 22:18:43 +00001748 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00001749 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00001750 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001751 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001752 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001753
Ted Kremenek93668002009-07-17 22:18:43 +00001754 case Stmt::CaseStmtClass:
1755 return VisitCaseStmt(cast<CaseStmt>(S));
1756
1757 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001758 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001759
Ted Kremenek93668002009-07-17 22:18:43 +00001760 case Stmt::CompoundStmtClass:
1761 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001762
Ted Kremenek93668002009-07-17 22:18:43 +00001763 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001764 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001765
Ted Kremenek93668002009-07-17 22:18:43 +00001766 case Stmt::ContinueStmtClass:
1767 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001768
Ted Kremenekb27378c2010-01-19 20:40:33 +00001769 case Stmt::CXXCatchStmtClass:
1770 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1771
John McCall5d413782010-12-06 08:20:24 +00001772 case Stmt::ExprWithCleanupsClass:
1773 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00001774
Jordan Rosee5d53932012-08-23 18:10:53 +00001775 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00001776 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00001777 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1778 // called function's declaration, not by the caller. If we simply add
1779 // this expression to the CFG, we could end up with the same Expr
1780 // appearing multiple times.
1781 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00001782 //
1783 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1784 // expression to be used in the same function (through aggregate
1785 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00001786 return VisitStmt(S, asc);
1787
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001788 case Stmt::CXXBindTemporaryExprClass:
1789 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1790
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001791 case Stmt::CXXConstructExprClass:
1792 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1793
Jordan Rosec9176072014-01-13 17:59:19 +00001794 case Stmt::CXXNewExprClass:
1795 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1796
Jordan Rosed2f40792013-09-03 17:00:57 +00001797 case Stmt::CXXDeleteExprClass:
1798 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1799
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001800 case Stmt::CXXFunctionalCastExprClass:
1801 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1802
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001803 case Stmt::CXXTemporaryObjectExprClass:
1804 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1805
Ted Kremenekb27378c2010-01-19 20:40:33 +00001806 case Stmt::CXXThrowExprClass:
1807 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001808
Ted Kremenekb27378c2010-01-19 20:40:33 +00001809 case Stmt::CXXTryStmtClass:
1810 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001811
Richard Smith02e85f32011-04-14 22:09:26 +00001812 case Stmt::CXXForRangeStmtClass:
1813 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1814
Ted Kremenek93668002009-07-17 22:18:43 +00001815 case Stmt::DeclStmtClass:
1816 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001817
Ted Kremenek93668002009-07-17 22:18:43 +00001818 case Stmt::DefaultStmtClass:
1819 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001820
Ted Kremenek93668002009-07-17 22:18:43 +00001821 case Stmt::DoStmtClass:
1822 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001823
Ted Kremenek93668002009-07-17 22:18:43 +00001824 case Stmt::ForStmtClass:
1825 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001826
Ted Kremenek93668002009-07-17 22:18:43 +00001827 case Stmt::GotoStmtClass:
1828 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001829
Ted Kremenek93668002009-07-17 22:18:43 +00001830 case Stmt::IfStmtClass:
1831 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001832
Ted Kremenek8219b822010-12-16 07:46:53 +00001833 case Stmt::ImplicitCastExprClass:
1834 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001835
Ted Kremenek93668002009-07-17 22:18:43 +00001836 case Stmt::IndirectGotoStmtClass:
1837 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001838
Ted Kremenek93668002009-07-17 22:18:43 +00001839 case Stmt::LabelStmtClass:
1840 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001841
Ted Kremenekda76a942012-04-12 20:34:52 +00001842 case Stmt::LambdaExprClass:
1843 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1844
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00001845 case Stmt::MaterializeTemporaryExprClass:
1846 return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
1847 asc);
1848
Ted Kremenek5868ec62010-04-11 17:02:10 +00001849 case Stmt::MemberExprClass:
1850 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1851
Ted Kremenek04268232011-11-05 00:10:15 +00001852 case Stmt::NullStmtClass:
1853 return Block;
1854
Ted Kremenek93668002009-07-17 22:18:43 +00001855 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00001856 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1857
Ted Kremenek5022f1d2012-03-06 23:40:47 +00001858 case Stmt::ObjCAutoreleasePoolStmtClass:
1859 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1860
Ted Kremenek93668002009-07-17 22:18:43 +00001861 case Stmt::ObjCAtSynchronizedStmtClass:
1862 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001863
Ted Kremenek93668002009-07-17 22:18:43 +00001864 case Stmt::ObjCAtThrowStmtClass:
1865 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001866
Ted Kremenek93668002009-07-17 22:18:43 +00001867 case Stmt::ObjCAtTryStmtClass:
1868 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001869
Ted Kremenek93668002009-07-17 22:18:43 +00001870 case Stmt::ObjCForCollectionStmtClass:
1871 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001872
Ted Kremenek04268232011-11-05 00:10:15 +00001873 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00001874 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00001875
John McCallfe96e0b2011-11-06 09:01:30 +00001876 case Stmt::PseudoObjectExprClass:
1877 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1878
Ted Kremenek93668002009-07-17 22:18:43 +00001879 case Stmt::ReturnStmtClass:
1880 return VisitReturnStmt(cast<ReturnStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001881
Nico Weber699670e2017-08-23 15:33:16 +00001882 case Stmt::SEHExceptStmtClass:
1883 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
1884
1885 case Stmt::SEHFinallyStmtClass:
1886 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
1887
1888 case Stmt::SEHLeaveStmtClass:
1889 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
1890
1891 case Stmt::SEHTryStmtClass:
1892 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
1893
Peter Collingbournee190dee2011-03-11 19:24:49 +00001894 case Stmt::UnaryExprOrTypeTraitExprClass:
1895 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1896 asc);
Mike Stump11289f42009-09-09 15:08:12 +00001897
Ted Kremenek93668002009-07-17 22:18:43 +00001898 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001899 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001900
Ted Kremenek93668002009-07-17 22:18:43 +00001901 case Stmt::SwitchStmtClass:
1902 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001903
Zhanyong Wan6dace612010-11-22 08:45:56 +00001904 case Stmt::UnaryOperatorClass:
1905 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1906
Ted Kremenek93668002009-07-17 22:18:43 +00001907 case Stmt::WhileStmtClass:
1908 return VisitWhileStmt(cast<WhileStmt>(S));
1909 }
1910}
Mike Stump11289f42009-09-09 15:08:12 +00001911
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001912CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001913 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001914 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001915 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00001916 }
Mike Stump11289f42009-09-09 15:08:12 +00001917
Ted Kremenek93668002009-07-17 22:18:43 +00001918 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00001919}
Mike Stump31feda52009-07-17 01:31:16 +00001920
Ted Kremenek93668002009-07-17 22:18:43 +00001921/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00001922CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1923 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00001924
Ted Kremenek8ae67872013-02-05 22:00:19 +00001925 // Visit the children in their reverse order so that they appear in
1926 // left-to-right (natural) order in the CFG.
1927 reverse_children RChildren(S);
1928 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1929 I != E; ++I) {
1930 if (Stmt *Child = *I)
1931 if (CFGBlock *R = Visit(Child))
1932 B = R;
1933 }
1934 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00001935}
Mike Stump11289f42009-09-09 15:08:12 +00001936
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001937CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1938 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00001939 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00001940
Ted Kremenek7c58d352011-03-10 01:14:11 +00001941 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001942 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001943 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00001944 }
Ted Kremenek81e14852007-08-27 19:46:09 +00001945
Ted Kremenek9aae5132007-08-23 21:42:29 +00001946 return Block;
1947}
Mike Stump11289f42009-09-09 15:08:12 +00001948
Zhanyong Wan6dace612010-11-22 08:45:56 +00001949CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00001950 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001951 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00001952 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001953 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00001954 }
1955
Ted Kremenek8219b822010-12-16 07:46:53 +00001956 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00001957}
1958
Ted Kremeneka16436f2012-07-14 05:04:06 +00001959CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1960 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1961 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00001962
Ted Kremeneka16436f2012-07-14 05:04:06 +00001963 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001964 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00001965
Craig Topper25542942014-05-20 04:30:07 +00001966 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1967 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001968}
1969
1970std::pair<CFGBlock*, CFGBlock*>
1971CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1972 Stmt *Term,
1973 CFGBlock *TrueBlock,
1974 CFGBlock *FalseBlock) {
Ted Kremenekb50e7162012-07-14 05:04:10 +00001975 // Introspect the RHS. If it is a nested logical operation, we recursively
1976 // build the CFG using this function. Otherwise, resort to default
1977 // CFG construction behavior.
1978 Expr *RHS = B->getRHS()->IgnoreParens();
1979 CFGBlock *RHSBlock, *ExitBlock;
1980
1981 do {
1982 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1983 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001984 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00001985 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1986 break;
1987 }
1988
1989 // The RHS is not a nested logical operation. Don't push the terminator
1990 // down further, but instead visit RHS and construct the respective
1991 // pieces of the CFG, and link up the RHSBlock with the terminator
1992 // we have been provided.
1993 ExitBlock = RHSBlock = createBlock(false);
1994
Richard Trieu6a6af522017-01-04 00:46:30 +00001995 // Even though KnownVal is only used in the else branch of the next
1996 // conditional, tryEvaluateBool performs additional checking on the
1997 // Expr, so it should be called unconditionally.
1998 TryResult KnownVal = tryEvaluateBool(RHS);
1999 if (!KnownVal.isKnown())
2000 KnownVal = tryEvaluateBool(B);
2001
Ted Kremenekb50e7162012-07-14 05:04:10 +00002002 if (!Term) {
2003 assert(TrueBlock == FalseBlock);
2004 addSuccessor(RHSBlock, TrueBlock);
2005 }
2006 else {
2007 RHSBlock->setTerminator(Term);
Ted Kremenek782f0032014-03-07 02:25:53 +00002008 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
2009 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00002010 }
2011
2012 Block = RHSBlock;
2013 RHSBlock = addStmt(RHS);
2014 }
2015 while (false);
2016
2017 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002018 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002019
2020 // Generate the blocks for evaluating the LHS.
2021 Expr *LHS = B->getLHS()->IgnoreParens();
2022
2023 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
2024 if (B_LHS->isLogicalOp()) {
2025 if (B->getOpcode() == BO_LOr)
2026 FalseBlock = RHSBlock;
2027 else
2028 TrueBlock = RHSBlock;
2029
2030 // For the LHS, treat 'B' as the terminator that we want to sink
2031 // into the nested branch. The RHS always gets the top-most
2032 // terminator.
2033 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
2034 }
2035
2036 // Create the block evaluating the LHS.
2037 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00002038 CFGBlock *LHSBlock = createBlock(false);
2039 LHSBlock->setTerminator(B);
2040
Ted Kremeneka16436f2012-07-14 05:04:06 +00002041 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002042 CFGBlock *EntryLHSBlock = addStmt(LHS);
2043
2044 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002045 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002046
2047 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002048 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002049
2050 // Now link the LHSBlock with RHSBlock.
2051 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00002052 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2053 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002054 } else {
2055 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00002056 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2057 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002058 }
2059
Ted Kremenekb50e7162012-07-14 05:04:10 +00002060 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002061}
2062
2063CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2064 AddStmtChoice asc) {
2065 // && or ||
2066 if (B->isLogicalOp())
2067 return VisitLogicalOperator(B);
2068
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002069 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00002070 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002071 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00002072 addStmt(B->getRHS());
2073 return addStmt(B->getLHS());
2074 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002075
2076 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002077 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002078 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002079 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002080 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002081 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00002082 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002083 }
Mike Stump11289f42009-09-09 15:08:12 +00002084
Ted Kremenek7c58d352011-03-10 01:14:11 +00002085 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00002086 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002087 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00002088 }
2089
Zhongxing Xud95ccd52010-10-27 03:23:10 +00002090 CFGBlock *RBlock = Visit(B->getRHS());
2091 CFGBlock *LBlock = Visit(B->getLHS());
2092 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2093 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2094 // return RBlock. Otherwise we'll incorrectly return NULL.
2095 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00002096}
2097
Ted Kremeneke2499842012-04-12 20:03:44 +00002098CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002099 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00002100 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002101 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00002102 }
2103 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002104}
2105
Ted Kremenek93668002009-07-17 22:18:43 +00002106CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2107 // "break" is a control-flow statement. Thus we stop processing the current
2108 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002109 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002110 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002111
Ted Kremenek93668002009-07-17 22:18:43 +00002112 // Now create a new block that ends with the break statement.
2113 Block = createBlock(false);
2114 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00002115
Ted Kremenek93668002009-07-17 22:18:43 +00002116 // If there is no target for the break, then we are looking at an incomplete
2117 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002118 if (BreakJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00002119 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002120 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002121 } else
Ted Kremenek93668002009-07-17 22:18:43 +00002122 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00002123
Ted Kremenek9aae5132007-08-23 21:42:29 +00002124 return Block;
2125}
Mike Stump11289f42009-09-09 15:08:12 +00002126
Sebastian Redl31ad7542011-03-13 17:09:40 +00002127static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00002128 QualType Ty = E->getType();
2129 if (Ty->isFunctionPointerType())
2130 Ty = Ty->getAs<PointerType>()->getPointeeType();
2131 else if (Ty->isBlockPointerType())
2132 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002133
Mike Stump04c68512010-01-21 15:20:48 +00002134 const FunctionType *FT = Ty->getAs<FunctionType>();
2135 if (FT) {
2136 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00002137 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smithf623c962012-04-17 00:58:00 +00002138 Proto->isNothrow(Ctx))
Mike Stump04c68512010-01-21 15:20:48 +00002139 return false;
2140 }
2141 return true;
2142}
2143
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002144CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00002145 // Compute the callee type.
2146 QualType calleeType = C->getCallee()->getType();
2147 if (calleeType == Context->BoundMemberTy) {
2148 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2149
2150 // We should only get a null bound type if processing a dependent
2151 // CFG. Recover by assuming nothing.
2152 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00002153 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002154
John McCallc67067f2011-05-11 07:19:11 +00002155 // If this is a call to a no-return function, this stops the block here.
2156 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2157
Mike Stump04c68512010-01-21 15:20:48 +00002158 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00002159
2160 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002161 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00002162 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00002163 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00002164 }
2165
Jordan Rose5374c072013-08-19 16:27:28 +00002166 // If this is a call to a builtin function, it might not actually evaluate
2167 // its arguments. Don't add them to the CFG if this is the case.
2168 bool OmitArguments = false;
2169
Mike Stump92244b02010-01-19 22:00:14 +00002170 if (FunctionDecl *FD = C->getDirectCallee()) {
Nico Weber758fbac2018-02-13 21:31:47 +00002171 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
Mike Stump8c5d7992009-07-25 21:26:53 +00002172 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00002173 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00002174 AddEHEdge = false;
Jordan Rose5374c072013-08-19 16:27:28 +00002175 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
2176 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00002177 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002178
Sebastian Redl31ad7542011-03-13 17:09:40 +00002179 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00002180 AddEHEdge = false;
2181
Jordan Rose5374c072013-08-19 16:27:28 +00002182 if (OmitArguments) {
2183 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2184 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2185 autoCreateBlock();
2186 appendStmt(Block, C);
2187 return Visit(C->getCallee());
2188 }
2189
2190 if (!NoReturn && !AddEHEdge) {
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002191 return VisitStmt(C, asc.withAlwaysAdd(true));
Jordan Rose5374c072013-08-19 16:27:28 +00002192 }
Mike Stump11289f42009-09-09 15:08:12 +00002193
Mike Stump92244b02010-01-19 22:00:14 +00002194 if (Block) {
2195 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002196 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002197 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00002198 }
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chandler Carrutha70991b2011-09-13 09:13:49 +00002200 if (NoReturn)
2201 Block = createNoReturnBlock();
2202 else
2203 Block = createBlock();
2204
Ted Kremenek2866bab2011-03-10 01:14:08 +00002205 appendStmt(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00002206
Mike Stump04c68512010-01-21 15:20:48 +00002207 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00002208 // Add exceptional edges.
2209 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002210 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00002211 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002212 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00002213 }
Mike Stump11289f42009-09-09 15:08:12 +00002214
Mike Stump8c5d7992009-07-25 21:26:53 +00002215 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00002216}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002217
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002218CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2219 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002220 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002221 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002222 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002223 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002224
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002225 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00002226 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002227 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002228 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002229 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002230 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002231
Ted Kremenek21822592009-07-17 18:20:32 +00002232 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002233 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002234 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002235 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002236 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002237
Ted Kremenek21822592009-07-17 18:20:32 +00002238 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00002239 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002240 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00002241 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2242 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00002243 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00002244 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00002245}
Mike Stump11289f42009-09-09 15:08:12 +00002246
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002247CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Matthias Gehre09a134e2015-11-14 00:36:50 +00002248 LocalScope::const_iterator scopeBeginPos = ScopePos;
Matthias Gehre351c2182017-07-12 07:04:19 +00002249 addLocalScopeForStmt(C);
2250
Matthias Gehre09a134e2015-11-14 00:36:50 +00002251 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
Richard Smitha547eb22016-07-14 00:11:03 +00002252 // If the body ends with a ReturnStmt, the dtors will be added in
2253 // VisitReturnStmt.
Matthias Gehre351c2182017-07-12 07:04:19 +00002254 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
Matthias Gehre09a134e2015-11-14 00:36:50 +00002255 }
2256
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002257 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002258
2259 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2260 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00002261 // If we hit a segment of code just containing ';' (NullStmts), we can
2262 // get a null block back. In such cases, just use the LastBlock
2263 if (CFGBlock *newBlock = addStmt(*I))
2264 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002265
Ted Kremenekce499c22009-08-27 23:16:26 +00002266 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002267 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002268 }
Mike Stump92244b02010-01-19 22:00:14 +00002269
Ted Kremenek93668002009-07-17 22:18:43 +00002270 return LastBlock;
2271}
Mike Stump11289f42009-09-09 15:08:12 +00002272
John McCallc07a0c72011-02-17 10:25:35 +00002273CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002274 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00002275 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00002276 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00002277
Ted Kremenek51d40b02009-07-17 18:15:54 +00002278 // Create the confluence block that will "merge" the results of the ternary
2279 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002280 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002281 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002282 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002283 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002284
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002285 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002286
Ted Kremenek51d40b02009-07-17 18:15:54 +00002287 // Create a block for the LHS expression if there is an LHS expression. A
2288 // GCC extension allows LHS to be NULL, causing the condition to be the
2289 // value that is returned instead.
2290 // e.g: x ?: y is shorthand for: x ? x : y;
2291 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002292 Block = nullptr;
2293 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00002294 const Expr *trueExpr = C->getTrueExpr();
2295 if (trueExpr != opaqueValue) {
2296 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002297 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002298 return nullptr;
2299 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00002300 }
Ted Kremenekd8138012011-02-24 03:09:15 +00002301 else
2302 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002303
Ted Kremenek51d40b02009-07-17 18:15:54 +00002304 // Create the block for the RHS expression.
2305 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002306 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002307 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002308 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002309
Richard Smithf676e452012-07-24 21:02:14 +00002310 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2311 if (BinaryOperator *Cond =
2312 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2313 if (Cond->isLogicalOp())
2314 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2315
Ted Kremenek51d40b02009-07-17 18:15:54 +00002316 // Create the block that will contain the condition.
2317 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00002318
Mike Stump773582d2009-07-23 23:25:26 +00002319 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002320 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00002321 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2322 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00002323 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00002324 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00002325
Ted Kremenekd8138012011-02-24 03:09:15 +00002326 if (opaqueValue) {
2327 // Run the condition expression if it's not trivially expressed in
2328 // terms of the opaque value (or if there is no opaque value).
2329 if (condExpr != opaqueValue)
2330 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00002331
Ted Kremenekd8138012011-02-24 03:09:15 +00002332 // Before that, run the common subexpression if there was one.
2333 // At least one of this or the above will be run.
2334 return addStmt(BCO->getCommon());
2335 }
2336
2337 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00002338}
2339
Ted Kremenek93668002009-07-17 22:18:43 +00002340CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00002341 // Check if the Decl is for an __label__. If so, elide it from the
2342 // CFG entirely.
2343 if (isa<LabelDecl>(*DS->decl_begin()))
2344 return Block;
2345
Ted Kremenek3a601142011-05-24 20:41:31 +00002346 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002347 if (DS->isSingleDecl())
2348 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00002349
Craig Topper25542942014-05-20 04:30:07 +00002350 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002351
Jordan Rose8c6c8a92012-07-20 18:50:48 +00002352 // Build an individual DeclStmt for each decl.
2353 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2354 E = DS->decl_rend();
2355 I != E; ++I) {
Ted Kremenek93668002009-07-17 22:18:43 +00002356 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
Benjamin Kramerc3f89252016-10-20 14:27:22 +00002357 unsigned A = alignof(DeclStmt) < 8 ? 8 : alignof(DeclStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002358
Ted Kremenek93668002009-07-17 22:18:43 +00002359 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2360 // automatically freed with the CFG.
2361 DeclGroupRef DG(*I);
2362 Decl *D = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002363 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
Ted Kremenek93668002009-07-17 22:18:43 +00002364 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00002365 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00002366
Ted Kremenek93668002009-07-17 22:18:43 +00002367 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002368 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002369 }
Mike Stump11289f42009-09-09 15:08:12 +00002370
2371 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002372}
Mike Stump11289f42009-09-09 15:08:12 +00002373
Ted Kremenek93668002009-07-17 22:18:43 +00002374/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002375/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002376CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002377 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002378 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002379
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002380 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002381 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2382 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002383 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002384 }
Mike Stump11289f42009-09-09 15:08:12 +00002385
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002386 bool HasTemporaries = false;
2387
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002388 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002389 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002390
2391 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2392 // For static variables, we need to create a branch to track
2393 // whether or not they are initialized.
2394 if (Block) {
2395 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002396 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002397 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002398 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002399 }
2400 blockAfterStaticInit = Succ;
2401 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002402
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002403 // Destructors of temporaries in initialization expression should be called
2404 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002405 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002406 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002407 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002408
Jordan Rose6d671cc2012-09-05 22:55:23 +00002409 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002410 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002411 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002412 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2413 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002414 }
2415 }
2416
2417 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002418 appendStmt(Block, DS);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002419
Artem Dergachev783a4572018-02-23 22:20:39 +00002420 findConstructionContexts(
2421 ConstructionContext::create(cfg->getBumpVectorContext(), DS),
2422 Init);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002423
Ted Kremenek213d0532012-03-22 05:57:43 +00002424 // Keep track of the last non-null block, as 'Block' can be nulled out
2425 // if the initializer expression is something like a 'while' in a
2426 // statement-expression.
2427 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002428
Ted Kremenek93668002009-07-17 22:18:43 +00002429 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002430 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002431 // For expression with temporaries go directly to subexpression to omit
2432 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002433 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2434 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2435 LastBlock = newBlock;
2436 }
2437 else {
2438 if (CFGBlock *newBlock = Visit(Init))
2439 LastBlock = newBlock;
2440 }
Ted Kremenek93668002009-07-17 22:18:43 +00002441 }
Mike Stump11289f42009-09-09 15:08:12 +00002442
Ted Kremenek93668002009-07-17 22:18:43 +00002443 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002444 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002445 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002446 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2447 LastBlock = newBlock;
2448 }
Mike Stump11289f42009-09-09 15:08:12 +00002449
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002450 // Remove variable from local scope.
2451 if (ScopePos && VD == *ScopePos)
2452 ++ScopePos;
2453
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002454 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002455 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002456 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002457 Block = createBlock(false);
2458 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002459 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002460 addSuccessor(Block, B);
2461 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002462 }
2463
2464 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002465}
2466
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002467CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002468 // We may see an if statement in the middle of a basic block, or it may be the
2469 // first statement we are processing. In either case, we create a new basic
2470 // block. First, we create the blocks for the then...else statements, and
2471 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002472 // middle of a block, we stop processing that block. That block is then the
2473 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002474
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002475 // Save local scope position because in case of condition variable ScopePos
2476 // won't be restored when traversing AST.
2477 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2478
Richard Smitha547eb22016-07-14 00:11:03 +00002479 // Create local scope for C++17 if init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00002480 if (Stmt *Init = I->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00002481 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00002482
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002483 // Create local scope for possible condition variable.
2484 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00002485 if (VarDecl *VD = I->getConditionVariable())
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002486 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00002487
Matthias Gehre351c2182017-07-12 07:04:19 +00002488 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002489
Chris Lattner57540c52011-04-15 05:22:18 +00002490 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002491 // block.
2492 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002493 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002494 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002495 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002496 }
Mike Stump31feda52009-07-17 01:31:16 +00002497
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002498 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002499 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002500
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002501 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002502 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002503
Ted Kremenek9aae5132007-08-23 21:42:29 +00002504 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002505 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002506 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002507
2508 // If branch is not a compound statement create implicit scope
2509 // and add destructors.
2510 if (!isa<CompoundStmt>(Else))
2511 addLocalScopeAndDtors(Else);
2512
Ted Kremenek93668002009-07-17 22:18:43 +00002513 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002514
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002515 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2516 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002517 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002518 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002519 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002520 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002521 }
Mike Stump31feda52009-07-17 01:31:16 +00002522
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002523 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002524 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002525 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002526 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002527 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002528 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002529 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002530
2531 // If branch is not a compound statement create implicit scope
2532 // and add destructors.
2533 if (!isa<CompoundStmt>(Then))
2534 addLocalScopeAndDtors(Then);
2535
Ted Kremenek93668002009-07-17 22:18:43 +00002536 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002537
Ted Kremenek1b379512009-04-01 03:52:47 +00002538 if (!ThenBlock) {
2539 // We can reach here if the "then" body has all NullStmts.
2540 // Create an empty block so we can distinguish between true and false
2541 // branches in path-sensitive analyses.
2542 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002543 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002544 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002545 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002546 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002547 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002548 }
2549
Ted Kremenekb50e7162012-07-14 05:04:10 +00002550 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2551 // having these handle the actual control-flow jump. Note that
2552 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2553 // we resort to the old control-flow behavior. This special handling
2554 // removes infeasible paths from the control-flow graph by having the
2555 // control-flow transfer of '&&' or '||' go directly into the then/else
2556 // blocks directly.
Richard Smith509bbd12017-01-13 22:16:41 +00002557 BinaryOperator *Cond =
2558 I->getConditionVariable()
2559 ? nullptr
2560 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
2561 CFGBlock *LastBlock;
2562 if (Cond && Cond->isLogicalOp())
2563 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2564 else {
2565 // Now create a new block containing the if statement.
2566 Block = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002567
Richard Smith509bbd12017-01-13 22:16:41 +00002568 // Set the terminator of the new block to the If statement.
2569 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002570
Richard Smith509bbd12017-01-13 22:16:41 +00002571 // See if this is a known constant.
2572 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002573
Richard Smith509bbd12017-01-13 22:16:41 +00002574 // Add the successors. If we know that specific branches are
2575 // unreachable, inform addSuccessor() of that knowledge.
2576 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2577 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump773582d2009-07-23 23:25:26 +00002578
Richard Smith509bbd12017-01-13 22:16:41 +00002579 // Add the condition as the last statement in the new block. This may
2580 // create new blocks as the condition may contain control-flow. Any newly
2581 // created blocks will be pointed to be "Block".
2582 LastBlock = addStmt(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002583
Richard Smith509bbd12017-01-13 22:16:41 +00002584 // If the IfStmt contains a condition variable, add it and its
2585 // initializer to the CFG.
2586 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2587 autoCreateBlock();
2588 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2589 }
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002590 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002591
Richard Smitha547eb22016-07-14 00:11:03 +00002592 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2593 if (Stmt *Init = I->getInit()) {
2594 autoCreateBlock();
2595 LastBlock = addStmt(Init);
2596 }
2597
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002598 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002599}
Mike Stump31feda52009-07-17 01:31:16 +00002600
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002601CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002602 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002603 //
Mike Stump31feda52009-07-17 01:31:16 +00002604 // NOTE: If a "return" appears in the middle of a block, this means that the
2605 // code afterwards is DEAD (unreachable). We still keep a basic block
2606 // for that code; a simple "mark-and-sweep" from the entry block will be
2607 // able to report such dead blocks.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002608
2609 // Create the new block.
2610 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002611
Matthias Gehre351c2182017-07-12 07:04:19 +00002612 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), R);
Pavel Labath921e7652013-09-06 08:12:48 +00002613
Artem Dergachev783a4572018-02-23 22:20:39 +00002614 findConstructionContexts(
2615 ConstructionContext::create(cfg->getBumpVectorContext(), R),
2616 R->getRetValue());
Artem Dergachev9ac2e112018-02-12 22:36:36 +00002617
Pavel Labath921e7652013-09-06 08:12:48 +00002618 // If the one of the destructors does not return, we already have the Exit
2619 // block as a successor.
2620 if (!Block->hasNoReturnElement())
2621 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002622
2623 // Add the return statement to the block. This may create new blocks if R
2624 // contains control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002625 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002626}
2627
Nico Weber699670e2017-08-23 15:33:16 +00002628CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
2629 // SEHExceptStmt are treated like labels, so they are the first statement in a
2630 // block.
2631
2632 // Save local scope position because in case of exception variable ScopePos
2633 // won't be restored when traversing AST.
2634 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2635
2636 addStmt(ES->getBlock());
2637 CFGBlock *SEHExceptBlock = Block;
2638 if (!SEHExceptBlock)
2639 SEHExceptBlock = createBlock();
2640
2641 appendStmt(SEHExceptBlock, ES);
2642
2643 // Also add the SEHExceptBlock as a label, like with regular labels.
2644 SEHExceptBlock->setLabel(ES);
2645
2646 // Bail out if the CFG is bad.
2647 if (badCFG)
2648 return nullptr;
2649
2650 // We set Block to NULL to allow lazy creation of a new block (if necessary).
2651 Block = nullptr;
2652
2653 return SEHExceptBlock;
2654}
2655
2656CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
2657 return VisitCompoundStmt(FS->getBlock());
2658}
2659
2660CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
2661 // "__leave" is a control-flow statement. Thus we stop processing the current
2662 // block.
2663 if (badCFG)
2664 return nullptr;
2665
2666 // Now create a new block that ends with the __leave statement.
2667 Block = createBlock(false);
2668 Block->setTerminator(LS);
2669
2670 // If there is no target for the __leave, then we are looking at an incomplete
2671 // AST. This means that the CFG cannot be constructed.
2672 if (SEHLeaveJumpTarget.block) {
2673 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
2674 addSuccessor(Block, SEHLeaveJumpTarget.block);
2675 } else
2676 badCFG = true;
2677
2678 return Block;
2679}
2680
2681CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
2682 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
2683 // processing the current block.
2684 CFGBlock *SEHTrySuccessor = nullptr;
2685
2686 if (Block) {
2687 if (badCFG)
2688 return nullptr;
2689 SEHTrySuccessor = Block;
2690 } else SEHTrySuccessor = Succ;
2691
2692 // FIXME: Implement __finally support.
2693 if (Terminator->getFinallyHandler())
2694 return NYS();
2695
2696 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
2697
2698 // Create a new block that will contain the __try statement.
2699 CFGBlock *NewTryTerminatedBlock = createBlock(false);
2700
2701 // Add the terminator in the __try block.
2702 NewTryTerminatedBlock->setTerminator(Terminator);
2703
2704 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
2705 // The code after the try is the implicit successor if there's an __except.
2706 Succ = SEHTrySuccessor;
2707 Block = nullptr;
2708 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
2709 if (!ExceptBlock)
2710 return nullptr;
2711 // Add this block to the list of successors for the block with the try
2712 // statement.
2713 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
2714 }
2715 if (PrevSEHTryTerminatedBlock)
2716 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
2717 else
2718 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2719
2720 // The code after the try is the implicit successor.
2721 Succ = SEHTrySuccessor;
2722
2723 // Save the current "__try" context.
2724 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
2725 NewTryTerminatedBlock);
2726 cfg->addTryDispatchBlock(TryTerminatedBlock);
2727
2728 // Save the current value for the __leave target.
2729 // All __leaves should go to the code following the __try
2730 // (FIXME: or if the __try has a __finally, to the __finally.)
2731 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
2732 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
2733
2734 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
2735 Block = nullptr;
2736 return addStmt(Terminator->getTryBlock());
2737}
2738
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002739CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002740 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00002741 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002742 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002743
Ted Kremenek93668002009-07-17 22:18:43 +00002744 if (!LabelBlock) // This can happen when the body is empty, i.e.
2745 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00002746
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002747 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2748 "label already in map");
2749 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002750
2751 // Labels partition blocks, so this is the end of the basic block we were
2752 // processing (L is the block's label). Because this is label (and we have
2753 // already processed the substatement) there is no extra control-flow to worry
2754 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00002755 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002756 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002757 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002758
2759 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00002760 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002761
Ted Kremenek9aae5132007-08-23 21:42:29 +00002762 // This block is now the implicit successor of other blocks.
2763 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002764
Ted Kremenek9aae5132007-08-23 21:42:29 +00002765 return LabelBlock;
2766}
2767
Devin Coughlinb6029b72015-11-25 22:35:37 +00002768CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
2769 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2770 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
2771 if (Expr *CopyExpr = CI.getCopyExpr()) {
2772 CFGBlock *Tmp = Visit(CopyExpr);
2773 if (Tmp)
2774 LastBlock = Tmp;
2775 }
2776 }
2777 return LastBlock;
2778}
2779
Ted Kremenekda76a942012-04-12 20:34:52 +00002780CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2781 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2782 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2783 et = E->capture_init_end(); it != et; ++it) {
2784 if (Expr *Init = *it) {
2785 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00002786 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00002787 LastBlock = Tmp;
2788 }
2789 }
2790 return LastBlock;
2791}
2792
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002793CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00002794 // Goto is a control-flow statement. Thus we stop processing the current
2795 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00002796
Ted Kremenek9aae5132007-08-23 21:42:29 +00002797 Block = createBlock(false);
2798 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00002799
2800 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002801 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00002802
Ted Kremenek9aae5132007-08-23 21:42:29 +00002803 if (I == LabelMap.end())
2804 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002805 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2806 else {
2807 JumpTarget JT = I->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00002808 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002809 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002810 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002811
Mike Stump31feda52009-07-17 01:31:16 +00002812 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002813}
2814
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002815CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00002816 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002817
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002818 // Save local scope position because in case of condition variable ScopePos
2819 // won't be restored when traversing AST.
2820 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2821
2822 // Create local scope for init statement and possible condition variable.
2823 // Add destructor for init statement and condition variable.
2824 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002825 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002826 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002827 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2828
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002829 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002830 addLocalScopeForVarDecl(VD);
2831 LocalScope::const_iterator ContinueScopePos = ScopePos;
2832
Matthias Gehre351c2182017-07-12 07:04:19 +00002833 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002834
Peter Szecsi999a25f2017-08-19 11:19:16 +00002835 addLoopExit(F);
2836
Mike Stump014b3ea2009-07-21 01:12:51 +00002837 // "for" is a control-flow statement. Thus we stop processing the current
2838 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002839 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002840 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002841 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002842 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002843 } else
2844 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002845
Ted Kremenek304a9532010-05-21 20:30:15 +00002846 // Save the current value for the break targets.
2847 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002848 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002849 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00002850
Craig Topper25542942014-05-20 04:30:07 +00002851 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002852
Ted Kremenek9aae5132007-08-23 21:42:29 +00002853 // Now create the loop body.
2854 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002855 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002856
Ted Kremenekb50e7162012-07-14 05:04:10 +00002857 // Save the current values for Block, Succ, continue and break targets.
2858 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2859 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002860
Ted Kremenekb50e7162012-07-14 05:04:10 +00002861 // Create an empty block to represent the transition block for looping back
2862 // to the head of the loop. If we have increment code, it will
2863 // go in this block as well.
2864 Block = Succ = TransitionBlock = createBlock(false);
2865 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002866
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002867 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00002868 // Generate increment code in its own basic block. This is the target of
2869 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00002870 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00002871 }
Mike Stump31feda52009-07-17 01:31:16 +00002872
Ted Kremenek902393b2009-04-28 00:51:56 +00002873 // Finish up the increment (or empty) block if it hasn't been already.
2874 if (Block) {
2875 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002876 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002877 return nullptr;
2878 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00002879 }
Mike Stump31feda52009-07-17 01:31:16 +00002880
Ted Kremenekb50e7162012-07-14 05:04:10 +00002881 // The starting block for the loop increment is the block that should
2882 // represent the 'loop target' for looping back to the start of the loop.
2883 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2884 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002885
Ted Kremenekb50e7162012-07-14 05:04:10 +00002886 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00002887 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00002888
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002889 // If body is not a compound statement create implicit scope
2890 // and add destructors.
2891 if (!isa<CompoundStmt>(F->getBody()))
2892 addLocalScopeAndDtors(F->getBody());
2893
Mike Stump31feda52009-07-17 01:31:16 +00002894 // Now populate the body block, and in the process create new blocks as we
2895 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002896 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00002897
Ted Kremenekb50e7162012-07-14 05:04:10 +00002898 if (!BodyBlock) {
2899 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2900 // Use the continue jump target as the proxy for the body.
2901 BodyBlock = ContinueJumpTarget.block;
2902 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002903 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002904 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002905 }
Ted Kremenekb50e7162012-07-14 05:04:10 +00002906
2907 // Because of short-circuit evaluation, the condition of the loop can span
2908 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2909 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002910 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002911
Ted Kremenekb50e7162012-07-14 05:04:10 +00002912 do {
2913 Expr *C = F->getCond();
2914
2915 // Specially handle logical operators, which have a slightly
2916 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002917 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00002918 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002919 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002920 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002921 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2922 break;
2923 }
2924
2925 // The default case when not handling logical operators.
2926 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2927 ExitConditionBlock->setTerminator(F);
2928
2929 // See if this is a known constant.
2930 TryResult KnownVal(true);
2931
2932 if (C) {
2933 // Now add the actual condition to the condition block.
2934 // Because the condition itself may contain control-flow, new blocks may
2935 // be created. Thus we update "Succ" after adding the condition.
2936 Block = ExitConditionBlock;
2937 EntryConditionBlock = addStmt(C);
2938
2939 // If this block contains a condition variable, add both the condition
2940 // variable and initializer to the CFG.
2941 if (VarDecl *VD = F->getConditionVariable()) {
2942 if (Expr *Init = VD->getInit()) {
2943 autoCreateBlock();
2944 appendStmt(Block, F->getConditionVariableDeclStmt());
2945 EntryConditionBlock = addStmt(Init);
2946 assert(Block == EntryConditionBlock);
2947 }
2948 }
2949
2950 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002951 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002952
2953 KnownVal = tryEvaluateBool(C);
2954 }
2955
2956 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002957 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002958 // Link up the condition block with the code that follows the loop. (the
2959 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002960 addSuccessor(ExitConditionBlock,
2961 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002962 } while (false);
2963
2964 // Link up the loop-back block to the entry condition block.
2965 addSuccessor(TransitionBlock, EntryConditionBlock);
2966
2967 // The condition block is the implicit successor for any code above the loop.
2968 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002969
Ted Kremenek9aae5132007-08-23 21:42:29 +00002970 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00002971 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002972 if (Stmt *I = F->getInit()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002973 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00002974 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002975 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002976
2977 // There is no loop initialization. We are thus basically a while loop.
2978 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00002979 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002980 Succ = EntryConditionBlock;
2981 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002982}
2983
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00002984CFGBlock *
2985CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
2986 AddStmtChoice asc) {
2987 findConstructionContexts(
2988 ConstructionContext::create(cfg->getBumpVectorContext(), MTE),
2989 MTE->getTemporary());
2990
2991 return VisitStmt(MTE, asc);
2992}
2993
Ted Kremenek5868ec62010-04-11 17:02:10 +00002994CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002995 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00002996 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002997 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002998 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002999 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00003000}
3001
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003002CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00003003 // Objective-C fast enumeration 'for' statements:
3004 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3005 //
3006 // for ( Type newVariable in collection_expression ) { statements }
3007 //
3008 // becomes:
3009 //
3010 // prologue:
3011 // 1. collection_expression
3012 // T. jump to loop_entry
3013 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003014 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00003015 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3016 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3017 // TB:
3018 // statements
3019 // T. jump to loop_entry
3020 // FB:
3021 // what comes after
3022 //
3023 // and
3024 //
3025 // Type existingItem;
3026 // for ( existingItem in expression ) { statements }
3027 //
3028 // becomes:
3029 //
Mike Stump31feda52009-07-17 01:31:16 +00003030 // the same with newVariable replaced with existingItem; the binding works
3031 // the same except that for one ObjCForCollectionStmt::getElement() returns
3032 // a DeclStmt and the other returns a DeclRefExpr.
Mike Stump31feda52009-07-17 01:31:16 +00003033
Craig Topper25542942014-05-20 04:30:07 +00003034 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003035
Ted Kremenek9d56e642008-11-11 17:10:00 +00003036 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003037 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003038 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00003039 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003040 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00003041 } else
3042 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003043
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003044 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003045 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003046
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003047 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003048 ExitConditionBlock->setTerminator(S);
3049
3050 // The last statement in the block should be the ObjCForCollectionStmt, which
3051 // performs the actual binding to 'element' and determines if there are any
3052 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00003053 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003054 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003055
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003056 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00003057 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00003058 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00003059 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3060 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00003061 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003062 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003063 return nullptr;
3064 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003065 }
Mike Stump31feda52009-07-17 01:31:16 +00003066
3067 // The condition block is the implicit successor for the loop body as well as
3068 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003069 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003070
Ted Kremenek9d56e642008-11-11 17:10:00 +00003071 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00003072 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003073 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00003074 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003075 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00003076 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003077
Anna Zaks56b49752013-06-22 00:23:20 +00003078 // Add an intermediate block between the BodyBlock and the
3079 // EntryConditionBlock to represent the "loop back" transition, for looping
3080 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00003081 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00003082 Succ = LoopBackBlock = createBlock();
3083 LoopBackBlock->setLoopTarget(S);
3084
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003085 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00003086 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003087
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003088 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003089
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003090 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00003091 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00003092 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003093 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003094 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003095 }
Mike Stump31feda52009-07-17 01:31:16 +00003096
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003097 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003098 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003099 }
Mike Stump31feda52009-07-17 01:31:16 +00003100
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003101 // Link up the condition block with the code that follows the loop.
3102 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003103 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003104
Ted Kremenek9d56e642008-11-11 17:10:00 +00003105 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003106 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00003107 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00003108}
3109
Ted Kremenek5022f1d2012-03-06 23:40:47 +00003110CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3111 // Inline the body.
3112 return addStmt(S->getSubStmt());
3113 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3114}
3115
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003116CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00003117 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00003118
Ted Kremenek49805452009-05-02 01:49:13 +00003119 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00003120 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00003121
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003122 // The sync body starts its own basic block. This makes it a little easier
3123 // for diagnostic clients.
3124 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003125 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003126 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003127
Craig Topper25542942014-05-20 04:30:07 +00003128 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00003129 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003130 }
Mike Stump31feda52009-07-17 01:31:16 +00003131
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003132 // Add the @synchronized to the CFG.
3133 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003134 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003135
Ted Kremenek49805452009-05-02 01:49:13 +00003136 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00003137 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00003138}
Mike Stump31feda52009-07-17 01:31:16 +00003139
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003140CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003141 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00003142 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00003143}
Ted Kremenek9d56e642008-11-11 17:10:00 +00003144
John McCallfe96e0b2011-11-06 09:01:30 +00003145CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3146 autoCreateBlock();
3147
3148 // Add the PseudoObject as the last thing.
3149 appendStmt(Block, E);
3150
3151 CFGBlock *lastBlock = Block;
3152
3153 // Before that, evaluate all of the semantics in order. In
3154 // CFG-land, that means appending them in reverse order.
3155 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3156 Expr *Semantic = E->getSemanticExpr(--i);
3157
3158 // If the semantic is an opaque value, we're being asked to bind
3159 // it to its source expression.
3160 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3161 Semantic = OVE->getSourceExpr();
3162
3163 if (CFGBlock *B = Visit(Semantic))
3164 lastBlock = B;
3165 }
3166
3167 return lastBlock;
3168}
3169
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003170CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00003171 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003172
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003173 // Save local scope position because in case of condition variable ScopePos
3174 // won't be restored when traversing AST.
3175 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3176
3177 // Create local scope for possible condition variable.
3178 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003179 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003180 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003181 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003182 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003183 }
Peter Szecsi999a25f2017-08-19 11:19:16 +00003184 addLoopExit(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003185
Mike Stump014b3ea2009-07-21 01:12:51 +00003186 // "while" is a control-flow statement. Thus we stop processing the current
3187 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003188 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003189 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003190 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003191 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003192 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003193 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00003194 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00003195 }
Mike Stump31feda52009-07-17 01:31:16 +00003196
Craig Topper25542942014-05-20 04:30:07 +00003197 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00003198
Ted Kremenek9aae5132007-08-23 21:42:29 +00003199 // Process the loop body.
3200 {
Ted Kremenek49936f72009-04-28 03:09:44 +00003201 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00003202
Ted Kremenekb50e7162012-07-14 05:04:10 +00003203 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003204 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3205 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00003206 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00003207
Mike Stump31feda52009-07-17 01:31:16 +00003208 // Create an empty block to represent the transition block for looping back
3209 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003210 Succ = TransitionBlock = createBlock(false);
3211 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003212 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003213
Ted Kremenek9aae5132007-08-23 21:42:29 +00003214 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003215 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003216
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003217 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00003218 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003219
3220 // If body is not a compound statement create implicit scope
3221 // and add destructors.
3222 if (!isa<CompoundStmt>(W->getBody()))
3223 addLocalScopeAndDtors(W->getBody());
3224
Ted Kremenek9aae5132007-08-23 21:42:29 +00003225 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003226 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003227
Ted Kremeneke9610502007-08-30 18:39:40 +00003228 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003229 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00003230 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003231 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003232 }
3233
3234 // Because of short-circuit evaluation, the condition of the loop can span
3235 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3236 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00003237 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003238
3239 do {
3240 Expr *C = W->getCond();
3241
3242 // Specially handle logical operators, which have a slightly
3243 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00003244 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00003245 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003246 std::tie(EntryConditionBlock, ExitConditionBlock) =
3247 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003248 break;
3249 }
3250
3251 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00003252 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003253 ExitConditionBlock->setTerminator(W);
3254
3255 // Now add the actual condition to the condition block.
3256 // Because the condition itself may contain control-flow, new blocks may
3257 // be created. Thus we update "Succ" after adding the condition.
3258 Block = ExitConditionBlock;
3259 Block = EntryConditionBlock = addStmt(C);
3260
3261 // If this block contains a condition variable, add both the condition
3262 // variable and initializer to the CFG.
3263 if (VarDecl *VD = W->getConditionVariable()) {
3264 if (Expr *Init = VD->getInit()) {
3265 autoCreateBlock();
3266 appendStmt(Block, W->getConditionVariableDeclStmt());
3267 EntryConditionBlock = addStmt(Init);
3268 assert(Block == EntryConditionBlock);
3269 }
Ted Kremenek55957a82009-05-02 00:13:27 +00003270 }
Mike Stump31feda52009-07-17 01:31:16 +00003271
Ted Kremenekb50e7162012-07-14 05:04:10 +00003272 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003273 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003274
3275 // See if this is a known constant.
3276 const TryResult& KnownVal = tryEvaluateBool(C);
3277
Ted Kremenek30754282009-07-24 04:47:11 +00003278 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00003279 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003280 // Link up the condition block with the code that follows the loop. (the
3281 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003282 addSuccessor(ExitConditionBlock,
3283 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003284 } while(false);
3285
3286 // Link up the loop-back block to the entry condition block.
3287 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00003288
3289 // There can be no more statements in the condition block since we loop back
3290 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003291 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003292
Ted Kremenek1ce53c42009-12-24 01:34:10 +00003293 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003294 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00003295 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003296}
Mike Stump11289f42009-09-09 15:08:12 +00003297
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003298CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003299 // FIXME: For now we pretend that @catch and the code it contains does not
3300 // exit.
3301 return Block;
3302}
Mike Stump31feda52009-07-17 01:31:16 +00003303
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003304CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00003305 // FIXME: This isn't complete. We basically treat @throw like a return
3306 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00003307
Ted Kremenek0868eea2009-09-24 18:45:41 +00003308 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003309 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003310 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003311
Ted Kremenek93041ba2008-12-09 20:20:09 +00003312 // Create the new block.
3313 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003314
Ted Kremenek93041ba2008-12-09 20:20:09 +00003315 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003316 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00003317
3318 // Add the statement to the block. This may create new blocks if S contains
3319 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003320 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00003321}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003322
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003323CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00003324 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003325 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003326 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003327
3328 // Create the new block.
3329 Block = createBlock(false);
3330
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003331 if (TryTerminatedBlock)
3332 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003333 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003334 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003335 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003336 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003337
3338 // Add the statement to the block. This may create new blocks if S contains
3339 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003340 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003341}
3342
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003343CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00003344 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003345
Peter Szecsi999a25f2017-08-19 11:19:16 +00003346 addLoopExit(D);
3347
Mike Stump8d50b6a2009-07-21 01:27:50 +00003348 // "do...while" is a control-flow statement. Thus we stop processing the
3349 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003350 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003351 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003352 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003353 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003354 } else
3355 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003356
3357 // Because of short-circuit evaluation, the condition of the loop can span
3358 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3359 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003360 CFGBlock *ExitConditionBlock = createBlock(false);
3361 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003362
Ted Kremenek81e14852007-08-27 19:46:09 +00003363 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003364 ExitConditionBlock->setTerminator(D);
3365
3366 // Now add the actual condition to the condition block. Because the condition
3367 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003368 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00003369 Block = ExitConditionBlock;
3370 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00003371 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003372 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003373 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003374 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003375 }
Mike Stump31feda52009-07-17 01:31:16 +00003376
Ted Kremeneka1523a32008-02-27 07:20:00 +00003377 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00003378 Succ = EntryConditionBlock;
3379
Mike Stump773582d2009-07-23 23:25:26 +00003380 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003381 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00003382
Ted Kremenek9aae5132007-08-23 21:42:29 +00003383 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00003384 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003385 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003386 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003387
Ted Kremenek9aae5132007-08-23 21:42:29 +00003388 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003389 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3390 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3391 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003392
Ted Kremenek9aae5132007-08-23 21:42:29 +00003393 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003394 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003395
Ted Kremenek9aae5132007-08-23 21:42:29 +00003396 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003397 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003398
Ted Kremenek9aae5132007-08-23 21:42:29 +00003399 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00003400 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003401
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003402 // If body is not a compound statement create implicit scope
3403 // and add destructors.
3404 if (!isa<CompoundStmt>(D->getBody()))
3405 addLocalScopeAndDtors(D->getBody());
3406
Ted Kremenek9aae5132007-08-23 21:42:29 +00003407 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00003408 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003409
Ted Kremeneke9610502007-08-30 18:39:40 +00003410 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00003411 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00003412 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003413 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003414 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003415 }
Mike Stump31feda52009-07-17 01:31:16 +00003416
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003417 // Add an intermediate block between the BodyBlock and the
3418 // ExitConditionBlock to represent the "loop back" transition. Create an
3419 // empty block to represent the transition block for looping back to the
3420 // head of the loop.
3421 // FIXME: Can we do this more efficiently without adding another block?
3422 Block = nullptr;
3423 Succ = BodyBlock;
3424 CFGBlock *LoopBackBlock = createBlock();
3425 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00003426
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003427 if (!KnownVal.isFalse())
Ted Kremenek110974d2010-08-17 20:59:56 +00003428 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003429 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00003430 else
Craig Topper25542942014-05-20 04:30:07 +00003431 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003432 }
Mike Stump31feda52009-07-17 01:31:16 +00003433
Ted Kremenek30754282009-07-24 04:47:11 +00003434 // Link up the condition block with the code that follows the loop.
3435 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00003436 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003437
3438 // There can be no more statements in the body block(s) since we loop back to
3439 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003440 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003441
Ted Kremenek9aae5132007-08-23 21:42:29 +00003442 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003443 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003444 return BodyBlock;
3445}
3446
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003447CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003448 // "continue" is a control-flow statement. Thus we stop processing the
3449 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003450 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003451 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003452
Ted Kremenek9aae5132007-08-23 21:42:29 +00003453 // Now create a new block that ends with the continue statement.
3454 Block = createBlock(false);
3455 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00003456
Ted Kremenek9aae5132007-08-23 21:42:29 +00003457 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00003458 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003459 if (ContinueJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00003460 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003461 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003462 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00003463 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00003464
Ted Kremenek9aae5132007-08-23 21:42:29 +00003465 return Block;
3466}
Mike Stump11289f42009-09-09 15:08:12 +00003467
Peter Collingbournee190dee2011-03-11 19:24:49 +00003468CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3469 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003470 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003471 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003472 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00003473 }
Mike Stump11289f42009-09-09 15:08:12 +00003474
Ted Kremenek93668002009-07-17 22:18:43 +00003475 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003476 CFGBlock *lastBlock = Block;
3477
Ted Kremenek93668002009-07-17 22:18:43 +00003478 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003479 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00003480 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003481 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00003482 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003483 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003484}
Mike Stump11289f42009-09-09 15:08:12 +00003485
Ted Kremenek93668002009-07-17 22:18:43 +00003486/// VisitStmtExpr - Utility method to handle (nested) statement
3487/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003488CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003489 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003490 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003491 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00003492 }
Ted Kremenek93668002009-07-17 22:18:43 +00003493 return VisitCompoundStmt(SE->getSubStmt());
3494}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003495
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003496CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00003497 // "switch" is a control-flow statement. Thus we stop processing the current
3498 // block.
Craig Topper25542942014-05-20 04:30:07 +00003499 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003500
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003501 // Save local scope position because in case of condition variable ScopePos
3502 // won't be restored when traversing AST.
3503 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3504
Richard Smitha547eb22016-07-14 00:11:03 +00003505 // Create local scope for C++17 switch init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00003506 if (Stmt *Init = Terminator->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00003507 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00003508
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003509 // Create local scope for possible condition variable.
3510 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00003511 if (VarDecl *VD = Terminator->getConditionVariable())
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003512 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00003513
Matthias Gehre351c2182017-07-12 07:04:19 +00003514 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003515
Ted Kremenek9aae5132007-08-23 21:42:29 +00003516 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003517 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003518 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003519 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003520 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003521
3522 // Save the current "switch" context.
3523 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003524 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003525 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003526
Mike Stump31feda52009-07-17 01:31:16 +00003527 // Set the "default" case to be the block after the switch statement. If the
3528 // switch statement contains a "default:", this value will be overwritten with
3529 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003530 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003531
Ted Kremenek9aae5132007-08-23 21:42:29 +00003532 // Create a new block that will contain the switch statement.
3533 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003534
Ted Kremenek9aae5132007-08-23 21:42:29 +00003535 // Now process the switch body. The code after the switch is the implicit
3536 // successor.
3537 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003538 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003539
3540 // When visiting the body, the case statements should automatically get linked
3541 // up to the switch. We also don't keep a pointer to the body, since all
3542 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003543 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003544 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003545
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003546 // For pruning unreachable case statements, save the current state
3547 // for tracking the condition value.
3548 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3549 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003550
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003551 // Determine if the switch condition can be explicitly evaluated.
3552 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003553 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003554 bool b = tryEvaluate(Terminator->getCond(), result);
3555 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003556 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003557
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003558 // If body is not a compound statement create implicit scope
3559 // and add destructors.
3560 if (!isa<CompoundStmt>(Terminator->getBody()))
3561 addLocalScopeAndDtors(Terminator->getBody());
3562
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003563 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003564 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003565 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003566 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003567 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003568
Mike Stump31feda52009-07-17 01:31:16 +00003569 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003570 // following the switch body. Moreover, take into account if all the
3571 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003572 //
3573 // Note: We add a successor to a switch that is considered covered yet has no
3574 // case statements if the enumeration has no enumerators.
3575 bool SwitchAlwaysHasSuccessor = false;
3576 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3577 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3578 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003579 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3580 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003581
Ted Kremenek81e14852007-08-27 19:46:09 +00003582 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003583 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003584 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003585 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003586
Richard Smitha547eb22016-07-14 00:11:03 +00003587 // If the SwitchStmt contains a condition variable, add both the
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003588 // SwitchStmt and the condition variable initialization to the CFG.
3589 if (VarDecl *VD = Terminator->getConditionVariable()) {
3590 if (Expr *Init = VD->getInit()) {
3591 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003592 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003593 LastBlock = addStmt(Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003594 }
3595 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003596
Richard Smitha547eb22016-07-14 00:11:03 +00003597 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
3598 if (Stmt *Init = Terminator->getInit()) {
3599 autoCreateBlock();
3600 LastBlock = addStmt(Init);
3601 }
3602
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003603 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003604}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003605
3606static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00003607 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003608 const CaseStmt *CS,
3609 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003610 if (!switchCond)
3611 return true;
3612
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003613 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00003614
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003615 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003616 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003617 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003618 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00003619 const llvm::APSInt &condInt = switchCond->Val.getInt();
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003620
3621 if (condInt == lhsInt) {
3622 addCase = true;
3623 switchExclusivelyCovered = true;
3624 }
Devin Coughlineb538ab2015-09-22 20:31:19 +00003625 else if (condInt > lhsInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003626 if (const Expr *RHS = CS->getRHS()) {
3627 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003628 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
Devin Coughlineb538ab2015-09-22 20:31:19 +00003629 if (V2 >= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003630 addCase = true;
3631 switchExclusivelyCovered = true;
3632 }
3633 }
3634 }
3635 }
3636 else
3637 addCase = true;
3638 }
3639 return addCase;
3640}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003641
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003642CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00003643 // CaseStmts are essentially labels, so they are the first statement in a
3644 // block.
Craig Topper25542942014-05-20 04:30:07 +00003645 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00003646
Ted Kremenek60fa6572010-08-04 23:54:30 +00003647 if (Stmt *Sub = CS->getSubStmt()) {
3648 // For deeply nested chains of CaseStmts, instead of doing a recursion
3649 // (which can blow out the stack), manually unroll and create blocks
3650 // along the way.
3651 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003652 CFGBlock *currentBlock = createBlock(false);
3653 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00003654
Ted Kremenek60fa6572010-08-04 23:54:30 +00003655 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003656 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003657 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003658 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003659
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003660 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003661 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003662 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00003663 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003664
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003665 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003666 CS = cast<CaseStmt>(Sub);
3667 Sub = CS->getSubStmt();
3668 }
3669
3670 addStmt(Sub);
3671 }
Mike Stump11289f42009-09-09 15:08:12 +00003672
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003673 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003674 if (!CaseBlock)
3675 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003676
3677 // Cases statements partition blocks, so this is the top of the basic block we
3678 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00003679 CaseBlock->setLabel(CS);
3680
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003681 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003682 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003683
3684 // Add this block to the list of successors for the block with the switch
3685 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00003686 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003687 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003688 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003689 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00003690
Ted Kremenek9aae5132007-08-23 21:42:29 +00003691 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003692 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003693
Ted Kremenek60fa6572010-08-04 23:54:30 +00003694 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003695 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003696 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003697 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00003698 // This block is now the implicit successor of other blocks.
3699 Succ = CaseBlock;
3700 }
Mike Stump31feda52009-07-17 01:31:16 +00003701
Ted Kremenek60fa6572010-08-04 23:54:30 +00003702 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003703}
Mike Stump31feda52009-07-17 01:31:16 +00003704
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003705CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00003706 if (Terminator->getSubStmt())
3707 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00003708
Ted Kremenek654c78f2008-02-13 22:05:39 +00003709 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003710
3711 if (!DefaultCaseBlock)
3712 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003713
3714 // Default statements partition blocks, so this is the top of the basic block
3715 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003716 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00003717
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003718 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003719 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00003720
Mike Stump31feda52009-07-17 01:31:16 +00003721 // Unlike case statements, we don't add the default block to the successors
3722 // for the switch statement immediately. This is done when we finish
3723 // processing the switch statement. This allows for the default case
3724 // (including a fall-through to the code after the switch statement) to always
3725 // be the last successor of a switch-terminated block.
3726
Ted Kremenek654c78f2008-02-13 22:05:39 +00003727 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003728 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003729
Ted Kremenek654c78f2008-02-13 22:05:39 +00003730 // This block is now the implicit successor of other blocks.
3731 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003732
3733 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00003734}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003735
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003736CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3737 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3738 // current block.
Craig Topper25542942014-05-20 04:30:07 +00003739 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003740
3741 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003742 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003743 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003744 TrySuccessor = Block;
3745 } else TrySuccessor = Succ;
3746
Mike Stump0bdba6c2010-01-20 01:15:34 +00003747 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003748
3749 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00003750 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003751 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00003752 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003753
Mike Stump0bdba6c2010-01-20 01:15:34 +00003754 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003755 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3756 // The code after the try is the implicit successor.
3757 Succ = TrySuccessor;
3758 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00003759 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00003760 HasCatchAll = true;
3761 }
Craig Topper25542942014-05-20 04:30:07 +00003762 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003763 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00003764 if (!CatchBlock)
3765 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003766 // Add this block to the list of successors for the block with the try
3767 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003768 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003769 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00003770 if (!HasCatchAll) {
3771 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003772 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00003773 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003774 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00003775 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003776
3777 // The code after the try is the implicit successor.
3778 Succ = TrySuccessor;
3779
Mike Stump845384a2010-01-20 01:30:58 +00003780 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00003781 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3782 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00003783
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003784 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003785 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003786 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003787}
3788
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003789CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003790 // CXXCatchStmt are treated like labels, so they are the first statement in a
3791 // block.
3792
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003793 // Save local scope position because in case of exception variable ScopePos
3794 // won't be restored when traversing AST.
3795 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3796
3797 // Create local scope for possible exception variable.
3798 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003799 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003800 LocalScope::const_iterator BeginScopePos = ScopePos;
3801 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003802 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003803 }
3804
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003805 if (CS->getHandlerBlock())
3806 addStmt(CS->getHandlerBlock());
3807
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003808 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003809 if (!CatchBlock)
3810 CatchBlock = createBlock();
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003811
3812 // CXXCatchStmt is more than just a label. They have semantic meaning
3813 // as well, as they implicitly "initialize" the catch variable. Add
3814 // it to the CFG as a CFGElement so that the control-flow of these
3815 // semantics gets captured.
3816 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003817
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003818 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3819 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003820 CatchBlock->setLabel(CS);
3821
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003822 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003823 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003824 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003825
3826 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003827 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003828
3829 return CatchBlock;
3830}
3831
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003832CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00003833 // C++0x for-range statements are specified as [stmt.ranged]:
3834 //
3835 // {
3836 // auto && __range = range-init;
3837 // for ( auto __begin = begin-expr,
3838 // __end = end-expr;
3839 // __begin != __end;
3840 // ++__begin ) {
3841 // for-range-declaration = *__begin;
3842 // statement
3843 // }
3844 // }
3845
3846 // Save local scope position before the addition of the implicit variables.
3847 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3848
3849 // Create local scopes and destructors for range, begin and end variables.
3850 if (Stmt *Range = S->getRangeStmt())
3851 addLocalScopeForStmt(Range);
Richard Smith01694c32016-03-20 10:33:40 +00003852 if (Stmt *Begin = S->getBeginStmt())
3853 addLocalScopeForStmt(Begin);
3854 if (Stmt *End = S->getEndStmt())
3855 addLocalScopeForStmt(End);
Matthias Gehre351c2182017-07-12 07:04:19 +00003856 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
Richard Smith02e85f32011-04-14 22:09:26 +00003857
3858 LocalScope::const_iterator ContinueScopePos = ScopePos;
3859
3860 // "for" is a control-flow statement. Thus we stop processing the current
3861 // block.
Craig Topper25542942014-05-20 04:30:07 +00003862 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003863 if (Block) {
3864 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003865 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003866 LoopSuccessor = Block;
3867 } else
3868 LoopSuccessor = Succ;
3869
3870 // Save the current value for the break targets.
3871 // All breaks should go to the code following the loop.
3872 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3873 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3874
3875 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003876 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00003877 ConditionBlock->setTerminator(S);
3878
3879 // Now add the actual condition to the condition block.
3880 if (Expr *C = S->getCond()) {
3881 Block = ConditionBlock;
3882 CFGBlock *BeginConditionBlock = addStmt(C);
3883 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003884 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003885 assert(BeginConditionBlock == ConditionBlock &&
3886 "condition block in for-range was unexpectedly complex");
3887 (void)BeginConditionBlock;
3888 }
3889
3890 // The condition block is the implicit successor for the loop body as well as
3891 // any code above the loop.
3892 Succ = ConditionBlock;
3893
3894 // See if this is a known constant.
3895 TryResult KnownVal(true);
3896
3897 if (S->getCond())
3898 KnownVal = tryEvaluateBool(S->getCond());
3899
3900 // Now create the loop body.
3901 {
3902 assert(S->getBody());
3903
3904 // Save the current values for Block, Succ, and continue targets.
3905 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3906 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3907
3908 // Generate increment code in its own basic block. This is the target of
3909 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00003910 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003911 Succ = addStmt(S->getInc());
Alexander Kornienkoff2046a2016-07-08 10:50:51 +00003912 if (badCFG)
3913 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003914 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3915
3916 // The starting block for the loop increment is the block that should
3917 // represent the 'loop target' for looping back to the start of the loop.
3918 ContinueJumpTarget.block->setLoopTarget(S);
3919
3920 // Finish up the increment block and prepare to start the loop body.
3921 assert(Block);
3922 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003923 return nullptr;
3924 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003925
3926 // Add implicit scope and dtors for loop variable.
3927 addLocalScopeAndDtors(S->getLoopVarStmt());
3928
3929 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003930 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00003931 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003932 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003933 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003934 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003935 return nullptr;
3936
Richard Smith02e85f32011-04-14 22:09:26 +00003937 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00003938 addSuccessor(ConditionBlock,
3939 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00003940 }
3941
3942 // Link up the condition block with the code that follows the loop (the
3943 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003944 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00003945
3946 // Add the initialization statements.
3947 Block = createBlock();
Richard Smith01694c32016-03-20 10:33:40 +00003948 addStmt(S->getBeginStmt());
3949 addStmt(S->getEndStmt());
Richard Smith0c502d22011-04-18 15:49:25 +00003950 return addStmt(S->getRangeStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003951}
3952
John McCall5d413782010-12-06 08:20:24 +00003953CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003954 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003955 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003956 // If adding implicit destructors visit the full expression for adding
3957 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003958 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00003959 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003960
3961 // Full expression has to be added as CFGStmt so it will be sequenced
3962 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003963 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003964 }
3965 return Visit(E->getSubExpr(), asc);
3966}
3967
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003968CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3969 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003970 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003971 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003972 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003973
Artem Dergachev783a4572018-02-23 22:20:39 +00003974 findConstructionContexts(
3975 ConstructionContext::create(cfg->getBumpVectorContext(), E),
3976 E->getSubExpr());
Artem Dergachev1f68d9d2018-02-15 03:13:36 +00003977
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003978 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003979 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003980 }
3981 return Visit(E->getSubExpr(), asc);
3982}
3983
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003984CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3985 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003986 autoCreateBlock();
Artem Dergachev41ffb302018-02-08 22:58:15 +00003987 appendConstructor(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003988
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003989 return VisitChildren(C);
3990}
3991
Jordan Rosec9176072014-01-13 17:59:19 +00003992CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3993 AddStmtChoice asc) {
Jordan Rosec9176072014-01-13 17:59:19 +00003994 autoCreateBlock();
3995 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00003996
Artem Dergachev783a4572018-02-23 22:20:39 +00003997 findConstructionContexts(
3998 ConstructionContext::create(cfg->getBumpVectorContext(), NE),
3999 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
Artem Dergachev41ffb302018-02-08 22:58:15 +00004000
Jordan Rosec9176072014-01-13 17:59:19 +00004001 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00004002 Block = Visit(NE->getInitializer());
Artem Dergachev41ffb302018-02-08 22:58:15 +00004003
Jordan Rosec9176072014-01-13 17:59:19 +00004004 if (BuildOpts.AddCXXNewAllocator)
4005 appendNewAllocator(Block, NE);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004006
Jordan Rosec9176072014-01-13 17:59:19 +00004007 if (NE->isArray())
Jordan Rose6f5f7192014-01-14 17:29:12 +00004008 Block = Visit(NE->getArraySize());
Artem Dergachev41ffb302018-02-08 22:58:15 +00004009
Jordan Rosec9176072014-01-13 17:59:19 +00004010 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
4011 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00004012 Block = Visit(*I);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004013
Jordan Rosec9176072014-01-13 17:59:19 +00004014 return Block;
4015}
Jordan Rosed2f40792013-09-03 17:00:57 +00004016
4017CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
4018 AddStmtChoice asc) {
4019 autoCreateBlock();
4020 appendStmt(Block, DE);
4021 QualType DTy = DE->getDestroyedType();
Martin Bohmef44cde82016-12-05 11:33:19 +00004022 if (!DTy.isNull()) {
4023 DTy = DTy.getNonReferenceType();
4024 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
4025 if (RD) {
4026 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
4027 appendDeleteDtor(Block, RD, DE);
4028 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004029 }
4030
4031 return VisitChildren(DE);
4032}
4033
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004034CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
4035 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004036 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004037 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004038 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004039 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004040 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004041 }
4042 return Visit(E->getSubExpr(), asc);
4043}
4044
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004045CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
4046 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004047 autoCreateBlock();
Artem Dergachev1f68d9d2018-02-15 03:13:36 +00004048 appendConstructor(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004049 return VisitChildren(C);
4050}
4051
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004052CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
4053 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004054 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004055 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004056 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004057 }
Ted Kremenek8219b822010-12-16 07:46:53 +00004058 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004059}
4060
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004061CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00004062 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004063 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004064
Ted Kremenekeda180e22007-08-28 19:26:49 +00004065 if (!IBlock) {
4066 IBlock = createBlock(false);
4067 cfg->setIndirectGotoBlock(IBlock);
4068 }
Mike Stump31feda52009-07-17 01:31:16 +00004069
Ted Kremenekeda180e22007-08-28 19:26:49 +00004070 // IndirectGoto is a control-flow statement. Thus we stop processing the
4071 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004072 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004073 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00004074
Ted Kremenekeda180e22007-08-28 19:26:49 +00004075 Block = createBlock(false);
4076 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004077 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00004078 return addStmt(I->getTarget());
4079}
4080
Manuel Klimekb5616c92014-08-07 10:42:17 +00004081CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
4082 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00004083 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4084
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004085tryAgain:
4086 if (!E) {
4087 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00004088 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004089 }
4090 switch (E->getStmtClass()) {
4091 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004092 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004093
4094 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004095 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4096 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004097
4098 case Stmt::CXXBindTemporaryExprClass:
4099 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004100 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004101
John McCallc07a0c72011-02-17 10:25:35 +00004102 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004103 case Stmt::ConditionalOperatorClass:
4104 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004105 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004106
4107 case Stmt::ImplicitCastExprClass:
4108 // For implicit cast we want BindToTemporary to be passed further.
4109 E = cast<CastExpr>(E)->getSubExpr();
4110 goto tryAgain;
4111
Manuel Klimekb0042c42014-07-30 08:34:42 +00004112 case Stmt::CXXFunctionalCastExprClass:
4113 // For functional cast we want BindToTemporary to be passed further.
4114 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4115 goto tryAgain;
4116
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004117 case Stmt::ParenExprClass:
4118 E = cast<ParenExpr>(E)->getSubExpr();
4119 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00004120
Manuel Klimekb0042c42014-07-30 08:34:42 +00004121 case Stmt::MaterializeTemporaryExprClass: {
4122 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4123 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
4124 SmallVector<const Expr *, 2> CommaLHSs;
4125 SmallVector<SubobjectAdjustment, 2> Adjustments;
4126 // Find the expression whose lifetime needs to be extended.
4127 E = const_cast<Expr *>(
4128 cast<MaterializeTemporaryExpr>(E)
4129 ->GetTemporaryExpr()
4130 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4131 // Visit the skipped comma operator left-hand sides for other temporaries.
4132 for (const Expr *CommaLHS : CommaLHSs) {
4133 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00004134 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00004135 }
Douglas Gregorfe314812011-06-21 17:03:29 +00004136 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00004137 }
Richard Smith4137af22014-07-27 05:12:49 +00004138
4139 case Stmt::BlockExprClass:
4140 // Don't recurse into blocks; their subexpressions don't get evaluated
4141 // here.
4142 return Block;
4143
4144 case Stmt::LambdaExprClass: {
4145 // For lambda expressions, only recurse into the capture initializers,
4146 // and not the body.
4147 auto *LE = cast<LambdaExpr>(E);
4148 CFGBlock *B = Block;
4149 for (Expr *Init : LE->capture_inits()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004150 if (CFGBlock *R = VisitForTemporaryDtors(
4151 Init, /*BindToTemporary=*/false, Context))
Richard Smith4137af22014-07-27 05:12:49 +00004152 B = R;
4153 }
4154 return B;
4155 }
4156
4157 case Stmt::CXXDefaultArgExprClass:
4158 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4159 goto tryAgain;
4160
4161 case Stmt::CXXDefaultInitExprClass:
4162 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4163 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004164 }
4165}
4166
Manuel Klimekb5616c92014-08-07 10:42:17 +00004167CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
4168 TempDtorContext &Context) {
4169 if (isa<LambdaExpr>(E)) {
4170 // Do not visit the children of lambdas; they have their own CFGs.
4171 return Block;
4172 }
4173
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004174 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00004175 // order that they will appear in the CFG. Because the CFG is built
4176 // bottom-up, this means we visit them in their natural order, which
4177 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004178 CFGBlock *B = Block;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004179 for (Stmt *Child : E->children())
4180 if (Child)
Manuel Klimekb5616c92014-08-07 10:42:17 +00004181 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00004182 B = R;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004183
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004184 return B;
4185}
4186
Manuel Klimekb5616c92014-08-07 10:42:17 +00004187CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
4188 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004189 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004190 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00004191 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
4192 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
4193 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00004194
Manuel Klimekedf925b92014-08-07 18:44:19 +00004195 // We do not know at CFG-construction time whether the right-hand-side was
4196 // executed, thus we add a branch node that depends on the temporary
4197 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00004198 TempDtorContext RHSContext(
4199 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00004200 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00004201 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00004202
Manuel Klimekb5616c92014-08-07 10:42:17 +00004203 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004204 }
4205
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004206 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004207 // For assignment operator (=) LHS expression is visited
4208 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004209 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4210 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004211 return LHSBlock ? LHSBlock : RHSBlock;
4212 }
4213
4214 // For any other binary operator RHS expression is visited before
4215 // LHS expression (order of children). For destructors visit them in reverse
4216 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004217 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4218 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004219 return RHSBlock ? RHSBlock : LHSBlock;
4220}
4221
4222CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004223 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004224 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004225 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00004226 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004227 // If lifetime of temporary is not prolonged (by assigning to constant
4228 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00004229
Chandler Carruthad747252011-09-13 06:09:01 +00004230 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004231
Richard Trieu95a192a2015-05-28 00:14:02 +00004232 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004233 // If the destructor is marked as a no-return destructor, we need to
4234 // create a new block for the destructor which does not have as a
4235 // successor anything built thus far. Control won't flow out of this
4236 // block.
4237 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00004238 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004239 } else if (Context.needsTempDtorBranch()) {
4240 // If we need to introduce a branch, we add a new block that we will hook
4241 // up to a decision block later.
4242 if (B) Succ = B;
4243 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004244 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00004245 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004246 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00004247 if (Context.needsTempDtorBranch()) {
4248 Context.setDecisionPoint(Succ, E);
4249 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004250 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004251
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004252 B = Block;
4253 }
4254 return B;
4255}
4256
Manuel Klimekb5616c92014-08-07 10:42:17 +00004257void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
4258 CFGBlock *FalseSucc) {
4259 if (!Context.TerminatorExpr) {
4260 // If no temporary was found, we do not need to insert a decision point.
4261 return;
4262 }
4263 assert(Context.TerminatorExpr);
4264 CFGBlock *Decision = createBlock(false);
4265 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
Manuel Klimekdeb02622014-08-08 07:37:13 +00004266 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004267 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00004268 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00004269 Block = Decision;
4270}
4271
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004272CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004273 AbstractConditionalOperator *E, bool BindToTemporary,
4274 TempDtorContext &Context) {
4275 VisitForTemporaryDtors(E->getCond(), false, Context);
4276 CFGBlock *ConditionBlock = Block;
4277 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00004278 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004279 TryResult NegatedVal = ConditionVal;
4280 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00004281
Manuel Klimekdeb02622014-08-08 07:37:13 +00004282 TempDtorContext TrueContext(
4283 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004284 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004285 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004286
Manuel Klimekb5616c92014-08-07 10:42:17 +00004287 Block = ConditionBlock;
4288 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004289 TempDtorContext FalseContext(
4290 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004291 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004292
Manuel Klimekb5616c92014-08-07 10:42:17 +00004293 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004294 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004295 } else if (TrueContext.TerminatorExpr) {
4296 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004297 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004298 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004299 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004300 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004301 return Block;
4302}
4303
Mike Stump31feda52009-07-17 01:31:16 +00004304/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
4305/// no successors or predecessors. If this is the first block created in the
4306/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004307CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00004308 bool first_block = begin() == end();
4309
4310 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004311 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00004312 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004313 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00004314
4315 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004316 if (first_block)
4317 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00004318
4319 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004320 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004321}
4322
David Blaikiee90195c2014-08-29 18:53:26 +00004323/// buildCFG - Constructs a CFG from an AST.
4324std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4325 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00004326 CFGBuilder Builder(C, BO);
4327 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00004328}
4329
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004330const CXXDestructorDecl *
4331CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004332 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004333 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00004334 case CFGElement::NewAllocator:
Peter Szecsi999a25f2017-08-19 11:19:16 +00004335 case CFGElement::LoopExit:
Matthias Gehre351c2182017-07-12 07:04:19 +00004336 case CFGElement::LifetimeEnds:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004337 case CFGElement::Statement:
4338 case CFGElement::Constructor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004339 llvm_unreachable("getDestructorDecl should only be used with "
4340 "ImplicitDtors");
4341 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00004342 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004343 QualType ty = var->getType();
Devin Coughlin6eb1ca72016-08-02 21:07:23 +00004344
4345 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4346 //
4347 // Lifetime-extending constructs are handled here. This works for a single
4348 // temporary in an initializer expression.
4349 if (ty->isReferenceType()) {
4350 if (const Expr *Init = var->getInit()) {
4351 ty = getReferenceInitTemporaryType(astContext, Init);
4352 }
4353 }
4354
Ted Kremeneke7d78882012-03-19 23:48:41 +00004355 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004356 ty = arrayType->getElementType();
4357 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004358 const RecordType *recordType = ty->getAs<RecordType>();
4359 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00004360 cast<CXXRecordDecl>(recordType->getDecl());
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004361 return classDecl->getDestructor();
4362 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004363 case CFGElement::DeleteDtor: {
4364 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
4365 QualType DTy = DE->getDestroyedType();
4366 DTy = DTy.getNonReferenceType();
4367 const CXXRecordDecl *classDecl =
4368 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
4369 return classDecl->getDestructor();
4370 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004371 case CFGElement::TemporaryDtor: {
4372 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00004373 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004374 const CXXTemporary *temp = bindExpr->getTemporary();
4375 return temp->getDestructor();
4376 }
4377 case CFGElement::BaseDtor:
4378 case CFGElement::MemberDtor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004379 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00004380 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004381 }
Ted Kremenek1676a042011-03-03 01:01:03 +00004382 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004383}
4384
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004385bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00004386 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
4387 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004388 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004389}
4390
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00004391//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004392// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00004393//===----------------------------------------------------------------------===//
4394
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004395CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004396 : ReachableBlock(IsReachable ? B : nullptr),
4397 UnreachableBlock(!IsReachable ? B : nullptr,
4398 B && IsReachable ? AB_Normal : AB_Unreachable) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004399
4400CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004401 : ReachableBlock(B),
4402 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
4403 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004404
4405void CFGBlock::addSuccessor(AdjacentBlock Succ,
4406 BumpVectorContext &C) {
4407 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004408 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004409
4410 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004411 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004412
4413 Succs.push_back(Succ, C);
4414}
4415
Ted Kremenekb0371852010-09-09 00:06:04 +00004416bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00004417 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004418 if (F.IgnoreNullPredecessors && !From)
4419 return true;
4420
4421 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004422 // If the 'To' has no label or is labeled but the label isn't a
4423 // CaseStmt then filter this edge.
4424 if (const SwitchStmt *S =
Ted Kremenek89794742011-03-07 22:04:39 +00004425 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004426 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00004427 const Stmt *L = To->getLabel();
4428 if (!L || !isa<CaseStmt>(L))
4429 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00004430 }
4431 }
4432 }
4433
4434 return false;
4435}
4436
4437//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004438// CFG pretty printing
4439//===----------------------------------------------------------------------===//
4440
Ted Kremenek7e776b12007-08-22 18:22:34 +00004441namespace {
4442
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004443class StmtPrinterHelper : public PrinterHelper {
Eugene Zelenko38c70522017-12-07 21:55:09 +00004444 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
4445 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
4446
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004447 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004448 DeclMapTy DeclMap;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004449 signed currentBlock = 0;
4450 unsigned currStmt = 0;
Chris Lattnerc61089a2009-06-30 01:26:17 +00004451 const LangOptions &LangOpts;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004452
Eugene Zelenko38c70522017-12-07 21:55:09 +00004453public:
Chris Lattnerc61089a2009-06-30 01:26:17 +00004454 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004455 : LangOpts(LO) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004456 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4457 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004458 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004459 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00004460 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4461 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004462 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00004463 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004464
Ted Kremenek96a7a592011-03-01 03:15:10 +00004465 switch (stmt->getStmtClass()) {
4466 case Stmt::DeclStmtClass:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004467 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4468 break;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004469 case Stmt::IfStmtClass: {
4470 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4471 if (var)
4472 DeclMap[var] = P;
4473 break;
4474 }
4475 case Stmt::ForStmtClass: {
4476 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4477 if (var)
4478 DeclMap[var] = P;
4479 break;
4480 }
4481 case Stmt::WhileStmtClass: {
4482 const VarDecl *var =
4483 cast<WhileStmt>(stmt)->getConditionVariable();
4484 if (var)
4485 DeclMap[var] = P;
4486 break;
4487 }
4488 case Stmt::SwitchStmtClass: {
4489 const VarDecl *var =
4490 cast<SwitchStmt>(stmt)->getConditionVariable();
4491 if (var)
4492 DeclMap[var] = P;
4493 break;
4494 }
4495 case Stmt::CXXCatchStmtClass: {
4496 const VarDecl *var =
4497 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4498 if (var)
4499 DeclMap[var] = P;
4500 break;
4501 }
4502 default:
4503 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004504 }
4505 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004506 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00004507 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004508 }
Mike Stump31feda52009-07-17 01:31:16 +00004509
Eugene Zelenko38c70522017-12-07 21:55:09 +00004510 ~StmtPrinterHelper() override = default;
Mike Stump31feda52009-07-17 01:31:16 +00004511
Chris Lattnerc61089a2009-06-30 01:26:17 +00004512 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004513 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00004514 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00004515
Craig Topperb45acb82014-03-14 06:02:07 +00004516 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004517 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004518
4519 if (I == StmtMap.end())
4520 return false;
Mike Stump31feda52009-07-17 01:31:16 +00004521
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004522 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004523 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004524 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004525 }
Mike Stump31feda52009-07-17 01:31:16 +00004526
Ted Kremenek60983dc2010-01-19 20:52:05 +00004527 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004528 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004529 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004530
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004531 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004532 DeclMapTy::iterator I = DeclMap.find(D);
4533
4534 if (I == DeclMap.end())
4535 return false;
4536
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004537 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004538 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004539 return false;
4540 }
4541
4542 OS << "[B" << I->second.first << "." << I->second.second << "]";
4543 return true;
4544 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004545};
4546
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004547class CFGBlockTerminatorPrint
Eugene Zelenko38c70522017-12-07 21:55:09 +00004548 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004549 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004550 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00004551 PrintingPolicy Policy;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004552
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004553public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004554 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00004555 const PrintingPolicy &Policy)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004556 : OS(os), Helper(helper), Policy(Policy) {
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00004557 this->Policy.IncludeNewlines = false;
4558 }
Mike Stump31feda52009-07-17 01:31:16 +00004559
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004560 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004561 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004562 if (Stmt *C = I->getCond())
4563 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004564 }
Mike Stump31feda52009-07-17 01:31:16 +00004565
Ted Kremenek9aae5132007-08-23 21:42:29 +00004566 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004567 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00004568 Terminator->printPretty(OS, Helper, Policy);
4569 }
4570
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00004571 void VisitDeclStmt(DeclStmt *DS) {
4572 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4573 OS << "static init " << VD->getName();
4574 }
4575
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004576 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004577 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004578 if (F->getInit())
4579 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004580 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004581 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004582 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004583 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00004584 if (F->getInc())
4585 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00004586 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00004587 }
Mike Stump31feda52009-07-17 01:31:16 +00004588
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004589 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004590 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004591 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004592 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004593 }
Mike Stump31feda52009-07-17 01:31:16 +00004594
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004595 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004596 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004597 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004598 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004599 }
Mike Stump31feda52009-07-17 01:31:16 +00004600
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004601 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00004602 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00004603 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004604 }
Mike Stump31feda52009-07-17 01:31:16 +00004605
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004606 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004607 OS << "try ...";
4608 }
4609
Nico Weber699670e2017-08-23 15:33:16 +00004610 void VisitSEHTryStmt(SEHTryStmt *CS) {
4611 OS << "__try ...";
4612 }
4613
John McCallc07a0c72011-02-17 10:25:35 +00004614 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00004615 if (Stmt *Cond = C->getCond())
4616 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004617 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004618 }
Mike Stump31feda52009-07-17 01:31:16 +00004619
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004620 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00004621 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004622 if (Stmt *Cond = C->getCond())
4623 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00004624 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00004625 }
Mike Stump31feda52009-07-17 01:31:16 +00004626
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004627 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004628 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004629 if (Stmt *T = I->getTarget())
4630 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004631 }
Mike Stump31feda52009-07-17 01:31:16 +00004632
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004633 void VisitBinaryOperator(BinaryOperator* B) {
4634 if (!B->isLogicalOp()) {
4635 VisitExpr(B);
4636 return;
4637 }
Mike Stump31feda52009-07-17 01:31:16 +00004638
Richard Trieuddd01ce2014-06-09 22:53:25 +00004639 if (B->getLHS())
4640 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004641
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004642 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004643 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00004644 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004645 return;
John McCalle3027922010-08-25 11:45:40 +00004646 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00004647 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004648 return;
4649 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004650 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00004651 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004652 }
Mike Stump31feda52009-07-17 01:31:16 +00004653
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004654 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00004655 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004656 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00004657
4658public:
4659 void print(CFGTerminator T) {
4660 if (T.isTemporaryDtorsBranch())
4661 OS << "(Temp Dtor) ";
4662 Visit(T.getStmt());
4663 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00004664};
Eugene Zelenko38c70522017-12-07 21:55:09 +00004665
4666} // namespace
Chris Lattnerc61089a2009-06-30 01:26:17 +00004667
Artem Dergachev5a281bb2018-02-10 02:18:04 +00004668static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
4669 const CXXCtorInitializer *I) {
4670 if (I->isBaseInitializer())
4671 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
4672 else if (I->isDelegatingInitializer())
4673 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
4674 else
4675 OS << I->getAnyMember()->getName();
4676 OS << "(";
4677 if (Expr *IE = I->getInit())
4678 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4679 OS << ")";
4680
4681 if (I->isBaseInitializer())
4682 OS << " (Base initializer)";
4683 else if (I->isDelegatingInitializer())
4684 OS << " (Delegating initializer)";
4685 else
4686 OS << " (Member initializer)";
4687}
4688
Aaron Ballmanff924b02013-11-18 20:11:50 +00004689static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00004690 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00004691 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4692 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00004693 assert(S != nullptr && "Expecting non-null Stmt");
4694
Aaron Ballmanff924b02013-11-18 20:11:50 +00004695 // special printing for statement-expressions.
4696 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4697 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00004698
Benjamin Kramer5733e352015-07-18 17:09:36 +00004699 auto Children = Sub->children();
4700 if (Children.begin() != Children.end()) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00004701 OS << "({ ... ; ";
4702 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4703 OS << " })\n";
4704 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004705 }
4706 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00004707 // special printing for comma expressions.
4708 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4709 if (B->getOpcode() == BO_Comma) {
4710 OS << "... , ";
4711 Helper.handledStmt(B->getRHS(),OS);
4712 OS << '\n';
4713 return;
4714 }
4715 }
4716 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00004717
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004718 if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004719 OS << " (OperatorCall)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00004720 } else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004721 OS << " (BindTemporary)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00004722 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4723 OS << " (CXXConstructExpr, ";
4724 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00004725 // TODO: Refactor into ConstructionContext::print().
Artem Dergachev41ffb302018-02-08 22:58:15 +00004726 if (const Stmt *S = CE->getTriggerStmt())
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00004727 Helper.handledStmt(const_cast<Stmt *>(S), OS);
Artem Dergachev5a281bb2018-02-10 02:18:04 +00004728 else if (const CXXCtorInitializer *I = CE->getTriggerInit())
4729 print_initializer(OS, Helper, I);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004730 else
4731 llvm_unreachable("Unexpected trigger kind!");
4732 OS << ", ";
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00004733 if (const Stmt *S = CE->getMaterializedTemporary()) {
4734 if (S != CE->getTriggerStmt()) {
4735 Helper.handledStmt(const_cast<Stmt *>(S), OS);
4736 OS << ", ";
4737 }
4738 }
Artem Dergachev41ffb302018-02-08 22:58:15 +00004739 }
4740 OS << CCE->getType().getAsString() << ")";
4741 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
Ted Kremenek0ffba932011-12-21 19:32:38 +00004742 OS << " (" << CE->getStmtClassName() << ", "
4743 << CE->getCastKindName()
4744 << ", " << CE->getType().getAsString()
4745 << ")";
4746 }
Mike Stump31feda52009-07-17 01:31:16 +00004747
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004748 // Expressions need a newline.
4749 if (isa<Expr>(S))
4750 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00004751 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
Artem Dergachev5a281bb2018-02-10 02:18:04 +00004752 print_initializer(OS, Helper, IE->getInitializer());
4753 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00004754 } else if (Optional<CFGAutomaticObjDtor> DE =
4755 E.getAs<CFGAutomaticObjDtor>()) {
4756 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00004757 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004758
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00004759 const Type* T = VD->getType().getTypePtr();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004760 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4761 T = RT->getPointeeType().getTypePtr();
Richard Smithf676e452012-07-24 21:02:14 +00004762 T = T->getBaseElementTypeUnsafe();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004763
4764 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4765 OS << " (Implicit destructor)\n";
Matthias Gehre351c2182017-07-12 07:04:19 +00004766 } else if (Optional<CFGLifetimeEnds> DE = E.getAs<CFGLifetimeEnds>()) {
4767 const VarDecl *VD = DE->getVarDecl();
4768 Helper.handleDecl(VD, OS);
4769
4770 OS << " (Lifetime ends)\n";
Peter Szecsi999a25f2017-08-19 11:19:16 +00004771 } else if (Optional<CFGLoopExit> LE = E.getAs<CFGLoopExit>()) {
4772 const Stmt *LoopStmt = LE->getLoopStmt();
4773 OS << LoopStmt->getStmtClassName() << " (LoopExit)\n";
Jordan Rosec9176072014-01-13 17:59:19 +00004774 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4775 OS << "CFGNewAllocator(";
4776 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4777 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4778 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00004779 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4780 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4781 if (!RD)
4782 return;
4783 CXXDeleteExpr *DelExpr =
4784 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00004785 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00004786 OS << "->~" << RD->getName().str() << "()";
4787 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004788 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4789 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004790 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004791 OS << " (Base object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004792 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4793 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00004794 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004795 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00004796 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004797 OS << " (Member object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004798 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4799 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00004800 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004801 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00004802 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004803 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004804}
Mike Stump31feda52009-07-17 01:31:16 +00004805
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004806static void print_block(raw_ostream &OS, const CFG* cfg,
4807 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00004808 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004809 bool ShowColors) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00004810 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00004811
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004812 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004813 if (ShowColors)
4814 OS.changeColor(raw_ostream::YELLOW, true);
4815
4816 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00004817
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004818 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004819 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004820 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004821 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004822 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004823 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00004824 else if (B.hasNoReturnElement())
4825 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004826 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00004827 OS << "]\n";
4828
4829 if (ShowColors)
4830 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00004831
Ted Kremenek71eca012007-08-29 23:20:49 +00004832 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004833 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004834 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004835 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004836
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004837 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004838 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004839 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004840 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004841 if (C->getLHS())
4842 C->getLHS()->printPretty(OS, &Helper,
4843 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004844 if (C->getRHS()) {
4845 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004846 C->getRHS()->printPretty(OS, &Helper,
4847 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004848 }
Mike Stump92244b02010-01-19 22:00:14 +00004849 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004850 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00004851 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004852 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00004853 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004854 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00004855 0);
4856 else
4857 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004858 OS << ")";
Nico Weber699670e2017-08-23 15:33:16 +00004859 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
4860 OS << "__except (";
4861 ES->getFilterExpr()->printPretty(OS, &Helper,
4862 PrintingPolicy(Helper.getLangOpts()), 0);
4863 OS << ")";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004864 } else
David Blaikie83d382b2011-09-23 05:06:16 +00004865 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00004866
Ted Kremenek71eca012007-08-29 23:20:49 +00004867 OS << ":\n";
4868 }
Mike Stump31feda52009-07-17 01:31:16 +00004869
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004870 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004871 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00004872
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004873 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4874 I != E ; ++I, ++j ) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004875 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004876 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004877 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004878
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004879 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00004880
Aaron Ballmanff924b02013-11-18 20:11:50 +00004881 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00004882
Ted Kremenek72be32a2011-12-22 23:33:52 +00004883 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004884 }
Mike Stump31feda52009-07-17 01:31:16 +00004885
Ted Kremenek71eca012007-08-29 23:20:49 +00004886 // Print the terminator of this block.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004887 if (B.getTerminator()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00004888 if (ShowColors)
4889 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00004890
Ted Kremenek72be32a2011-12-22 23:33:52 +00004891 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00004892
Aaron Ballmanff924b02013-11-18 20:11:50 +00004893 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00004894
Aaron Ballmanff924b02013-11-18 20:11:50 +00004895 PrintingPolicy PP(Helper.getLangOpts());
4896 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00004897 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004898 OS << '\n';
Ted Kremenek72be32a2011-12-22 23:33:52 +00004899
4900 if (ShowColors)
4901 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004902 }
Mike Stump31feda52009-07-17 01:31:16 +00004903
Ted Kremenek71eca012007-08-29 23:20:49 +00004904 if (print_edges) {
4905 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004906 if (!B.pred_empty()) {
4907 const raw_ostream::Colors Color = raw_ostream::BLUE;
4908 if (ShowColors)
4909 OS.changeColor(Color);
4910 OS << " Preds " ;
4911 if (ShowColors)
4912 OS.resetColor();
4913 OS << '(' << B.pred_size() << "):";
4914 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00004915
Ted Kremenek72be32a2011-12-22 23:33:52 +00004916 if (ShowColors)
4917 OS.changeColor(Color);
4918
4919 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4920 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004921 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004922 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00004923
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004924 CFGBlock *B = *I;
4925 bool Reachable = true;
4926 if (!B) {
4927 Reachable = false;
4928 B = I->getPossiblyUnreachableBlock();
4929 }
4930
4931 OS << " B" << B->getBlockID();
4932 if (!Reachable)
4933 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00004934 }
4935
4936 if (ShowColors)
4937 OS.resetColor();
4938
4939 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00004940 }
Mike Stump31feda52009-07-17 01:31:16 +00004941
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004942 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004943 if (!B.succ_empty()) {
4944 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4945 if (ShowColors)
4946 OS.changeColor(Color);
4947 OS << " Succs ";
4948 if (ShowColors)
4949 OS.resetColor();
4950 OS << '(' << B.succ_size() << "):";
4951 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004952
Ted Kremenek72be32a2011-12-22 23:33:52 +00004953 if (ShowColors)
4954 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00004955
Ted Kremenek72be32a2011-12-22 23:33:52 +00004956 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4957 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004958 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004959 OS << "\n ";
4960
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004961 CFGBlock *B = *I;
4962
4963 bool Reachable = true;
4964 if (!B) {
4965 Reachable = false;
4966 B = I->getPossiblyUnreachableBlock();
4967 }
4968
4969 if (B) {
4970 OS << " B" << B->getBlockID();
4971 if (!Reachable)
4972 OS << "(Unreachable)";
4973 }
4974 else {
4975 OS << " NULL";
4976 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00004977 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004978
Ted Kremenek72be32a2011-12-22 23:33:52 +00004979 if (ShowColors)
4980 OS.resetColor();
4981 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004982 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004983 }
Mike Stump31feda52009-07-17 01:31:16 +00004984}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004985
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004986/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004987void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4988 print(llvm::errs(), LO, ShowColors);
4989}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004990
4991/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004992void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004993 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00004994
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004995 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004996 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00004997
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004998 // Iterate through the CFGBlocks and print them one by one.
4999 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
5000 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00005001 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005002 continue;
Mike Stump31feda52009-07-17 01:31:16 +00005003
Aaron Ballmanff924b02013-11-18 20:11:50 +00005004 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005005 }
Mike Stump31feda52009-07-17 01:31:16 +00005006
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005007 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00005008 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00005009 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00005010 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00005011}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005012
5013/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005014void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
5015 bool ShowColors) const {
5016 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00005017}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005018
Yaron Kerencdae9412016-01-29 19:38:18 +00005019LLVM_DUMP_METHOD void CFGBlock::dump() const {
Anna Zaksa6fea132014-06-13 23:47:38 +00005020 dump(getParent(), LangOptions(), false);
5021}
5022
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005023/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
5024/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005025void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00005026 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00005027 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005028 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00005029 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00005030}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005031
Ted Kremenek15647632008-01-30 23:02:42 +00005032/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005033void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00005034 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00005035 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00005036 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00005037}
5038
Ted Kremenekec3bbf42014-03-29 00:35:20 +00005039Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Marcin Swiderskia7d84a72010-10-29 05:21:47 +00005040 Stmt *Terminator = this->Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005041 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00005042 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00005043
Craig Topper25542942014-05-20 04:30:07 +00005044 Expr *E = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00005045
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005046 switch (Terminator->getStmtClass()) {
5047 default:
5048 break;
Mike Stump31feda52009-07-17 01:31:16 +00005049
Jordan Rosecf10ea82013-06-06 21:53:45 +00005050 case Stmt::CXXForRangeStmtClass:
5051 E = cast<CXXForRangeStmt>(Terminator)->getCond();
5052 break;
5053
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005054 case Stmt::ForStmtClass:
5055 E = cast<ForStmt>(Terminator)->getCond();
5056 break;
Mike Stump31feda52009-07-17 01:31:16 +00005057
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005058 case Stmt::WhileStmtClass:
5059 E = cast<WhileStmt>(Terminator)->getCond();
5060 break;
Mike Stump31feda52009-07-17 01:31:16 +00005061
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005062 case Stmt::DoStmtClass:
5063 E = cast<DoStmt>(Terminator)->getCond();
5064 break;
Mike Stump31feda52009-07-17 01:31:16 +00005065
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005066 case Stmt::IfStmtClass:
5067 E = cast<IfStmt>(Terminator)->getCond();
5068 break;
Mike Stump31feda52009-07-17 01:31:16 +00005069
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005070 case Stmt::ChooseExprClass:
5071 E = cast<ChooseExpr>(Terminator)->getCond();
5072 break;
Mike Stump31feda52009-07-17 01:31:16 +00005073
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005074 case Stmt::IndirectGotoStmtClass:
5075 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
5076 break;
Mike Stump31feda52009-07-17 01:31:16 +00005077
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005078 case Stmt::SwitchStmtClass:
5079 E = cast<SwitchStmt>(Terminator)->getCond();
5080 break;
Mike Stump31feda52009-07-17 01:31:16 +00005081
John McCallc07a0c72011-02-17 10:25:35 +00005082 case Stmt::BinaryConditionalOperatorClass:
5083 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
5084 break;
5085
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005086 case Stmt::ConditionalOperatorClass:
5087 E = cast<ConditionalOperator>(Terminator)->getCond();
5088 break;
Mike Stump31feda52009-07-17 01:31:16 +00005089
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005090 case Stmt::BinaryOperatorClass: // '&&' and '||'
5091 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00005092 break;
Mike Stump31feda52009-07-17 01:31:16 +00005093
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00005094 case Stmt::ObjCForCollectionStmtClass:
Mike Stump31feda52009-07-17 01:31:16 +00005095 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005096 }
Mike Stump31feda52009-07-17 01:31:16 +00005097
Ted Kremenekec3bbf42014-03-29 00:35:20 +00005098 if (!StripParens)
5099 return E;
5100
Craig Topper25542942014-05-20 04:30:07 +00005101 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005102}
5103
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005104//===----------------------------------------------------------------------===//
5105// CFG Graphviz Visualization
5106//===----------------------------------------------------------------------===//
5107
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005108#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00005109static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005110#endif
5111
Chris Lattnerc61089a2009-06-30 01:26:17 +00005112void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005113#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00005114 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005115 GraphHelper = &H;
5116 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00005117 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005118#endif
5119}
5120
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005121namespace llvm {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005122
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005123template<>
5124struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005125 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Tobias Grosser9fc223a2009-11-30 14:16:05 +00005126
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005127 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005128#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005129 std::string OutSStr;
5130 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005131 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005132 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005133
5134 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
5135
5136 // Process string output to make it nicer...
5137 for (unsigned i = 0; i != OutStr.length(); ++i)
5138 if (OutStr[i] == '\n') { // Left justify
5139 OutStr[i] = '\\';
5140 OutStr.insert(OutStr.begin()+i+1, 'l');
5141 }
Mike Stump31feda52009-07-17 01:31:16 +00005142
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005143 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005144#else
Eugene Zelenko38c70522017-12-07 21:55:09 +00005145 return {};
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005146#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005147 }
5148};
Eugene Zelenko38c70522017-12-07 21:55:09 +00005149
5150} // namespace llvm