blob: ce29647d41b7c0599cae784b596d53b05f43c4d7 [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.
478 ConstructionContext CurrentConstructionContext = {};
479
Eugene Zelenko38c70522017-12-07 21:55:09 +0000480 bool badCFG = false;
Ted Kremenekf9d82902011-03-10 01:14:05 +0000481 const CFG::BuildOptions &BuildOpts;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000482
483 // State to track for building switch statements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000484 bool switchExclusivelyCovered = false;
485 Expr::EvalResult *switchCond = nullptr;
Ted Kremeneka099c592011-03-10 03:50:34 +0000486
Eugene Zelenko38c70522017-12-07 21:55:09 +0000487 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
488 const Stmt *lastLookup = nullptr;
Zhongxing Xud38fb842010-09-16 03:28:18 +0000489
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000490 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
491 // during construction of branches for chained logical operators.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000492 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000493 CachedBoolEvalsTy CachedBoolEvals;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000494
Mike Stump31feda52009-07-17 01:31:16 +0000495public:
Ted Kremenekf9d82902011-03-10 01:14:05 +0000496 explicit CFGBuilder(ASTContext *astContext,
Nico Weber699670e2017-08-23 15:33:16 +0000497 const CFG::BuildOptions &buildOpts)
498 : Context(astContext), cfg(new CFG()), // crew a new CFG
Eugene Zelenko38c70522017-12-07 21:55:09 +0000499 BuildOpts(buildOpts) {}
Mike Stump31feda52009-07-17 01:31:16 +0000500
Ted Kremenek9aae5132007-08-23 21:42:29 +0000501 // buildCFG - Used by external clients to construct the CFG.
David Blaikiee90195c2014-08-29 18:53:26 +0000502 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
Mike Stump31feda52009-07-17 01:31:16 +0000503
Ted Kremeneka099c592011-03-10 03:50:34 +0000504 bool alwaysAdd(const Stmt *stmt);
505
Ted Kremenek93668002009-07-17 22:18:43 +0000506private:
507 // Visitors to walk an AST and construct the CFG.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000508 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
509 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000510 CFGBlock *VisitBreakStmt(BreakStmt *B);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000511 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000512 CFGBlock *VisitCaseStmt(CaseStmt *C);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000513 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000514 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
John McCallc07a0c72011-02-17 10:25:35 +0000515 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
516 AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000517 CFGBlock *VisitContinueStmt(ContinueStmt *C);
Ted Kremenek6f400242012-07-14 05:04:01 +0000518 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
519 AddStmtChoice asc);
520 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
521 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
Jordan Rosec9176072014-01-13 17:59:19 +0000522 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
Jordan Rosed2f40792013-09-03 17:00:57 +0000523 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000524 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
525 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
526 AddStmtChoice asc);
527 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
528 AddStmtChoice asc);
529 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
530 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000531 CFGBlock *VisitDeclStmt(DeclStmt *DS);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000532 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
Ted Kremenek21822592009-07-17 18:20:32 +0000533 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
534 CFGBlock *VisitDoStmt(DoStmt *D);
Ted Kremenek6f400242012-07-14 05:04:01 +0000535 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000536 CFGBlock *VisitForStmt(ForStmt *F);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000537 CFGBlock *VisitGotoStmt(GotoStmt *G);
Ted Kremenek93668002009-07-17 22:18:43 +0000538 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000539 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000540 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
541 CFGBlock *VisitLabelStmt(LabelStmt *L);
Devin Coughlinb6029b72015-11-25 22:35:37 +0000542 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000543 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000544 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000545 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
546 Stmt *Term,
547 CFGBlock *TrueBlock,
548 CFGBlock *FalseBlock);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000549 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000550 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
551 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
552 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
553 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000554 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000555 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
John McCallfe96e0b2011-11-06 09:01:30 +0000556 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Ted Kremenek6f400242012-07-14 05:04:01 +0000557 CFGBlock *VisitReturnStmt(ReturnStmt *R);
Nico Weber699670e2017-08-23 15:33:16 +0000558 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
559 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
560 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
561 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000562 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000563 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000564 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
565 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000566 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000567 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000568
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000569 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
570 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000571 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000572 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000573
Manuel Klimekb5616c92014-08-07 10:42:17 +0000574 /// When creating the CFG for temporary destructors, we want to mirror the
575 /// branch structure of the corresponding constructor calls.
576 /// Thus, while visiting a statement for temporary destructors, we keep a
577 /// context to keep track of the following information:
578 /// - whether a subexpression is executed unconditionally
579 /// - if a subexpression is executed conditionally, the first
580 /// CXXBindTemporaryExpr we encounter in that subexpression (which
581 /// corresponds to the last temporary destructor we have to call for this
582 /// subexpression) and the CFG block at that point (which will become the
583 /// successor block when inserting the decision point).
584 ///
585 /// That way, we can build the branch structure for temporary destructors as
586 /// follows:
587 /// 1. If a subexpression is executed unconditionally, we add the temporary
588 /// destructor calls to the current block.
589 /// 2. If a subexpression is executed conditionally, when we encounter a
590 /// CXXBindTemporaryExpr:
591 /// a) If it is the first temporary destructor call in the subexpression,
592 /// we remember the CXXBindTemporaryExpr and the current block in the
593 /// TempDtorContext; we start a new block, and insert the temporary
594 /// destructor call.
595 /// b) Otherwise, add the temporary destructor call to the current block.
596 /// 3. When we finished visiting a conditionally executed subexpression,
597 /// and we found at least one temporary constructor during the visitation
598 /// (2.a has executed), we insert a decision block that uses the
599 /// CXXBindTemporaryExpr as terminator, and branches to the current block
600 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
601 /// branches to the stored successor.
602 struct TempDtorContext {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000603 TempDtorContext() = default;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000604 TempDtorContext(TryResult KnownExecuted)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000605 : IsConditional(true), KnownExecuted(KnownExecuted) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000606
607 /// Returns whether we need to start a new branch for a temporary destructor
Eric Christopher2c4555a2015-06-19 01:52:53 +0000608 /// call. This is the case when the temporary destructor is
Manuel Klimekb5616c92014-08-07 10:42:17 +0000609 /// conditionally executed, and it is the first one we encounter while
610 /// visiting a subexpression - other temporary destructors at the same level
611 /// will be added to the same block and are executed under the same
612 /// condition.
613 bool needsTempDtorBranch() const {
614 return IsConditional && !TerminatorExpr;
615 }
616
617 /// Remember the successor S of a temporary destructor decision branch for
618 /// the corresponding CXXBindTemporaryExpr E.
619 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
620 Succ = S;
621 TerminatorExpr = E;
622 }
623
Eugene Zelenko38c70522017-12-07 21:55:09 +0000624 const bool IsConditional = false;
625 const TryResult KnownExecuted = true;
626 CFGBlock *Succ = nullptr;
627 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000628 };
629
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000630 // Visitors to walk an AST and generate destructors of temporaries in
631 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000632 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
633 TempDtorContext &Context);
634 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
635 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
636 TempDtorContext &Context);
637 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
638 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
639 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
640 AbstractConditionalOperator *E, bool BindToTemporary,
641 TempDtorContext &Context);
642 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
643 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000644
Ted Kremenek6065ef62008-04-28 18:00:46 +0000645 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000646 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000647 badCFG = true;
648 return Block;
649 }
Mike Stump31feda52009-07-17 01:31:16 +0000650
Artem Dergachev41ffb302018-02-08 22:58:15 +0000651 // Scan the child statement \p Child to find the constructor that might
652 // have been directly triggered by the current node, \p Trigger. If such
653 // constructor has been found, set current construction context to point
654 // to the trigger statement. The construction context will be unset once
655 // it is consumed when the CFG building procedure processes the
656 // construct-expression and adds the respective CFGConstructor element.
657 void EnterConstructionContextIfNecessary(Stmt *Trigger, Stmt *Child);
658 // Unset the construction context after consuming it. This is done immediately
659 // after adding the CFGConstructor element, so there's no need to
660 // do this manually in every Visit... function.
661 void ExitConstructionContext();
662
Ted Kremenek93668002009-07-17 22:18:43 +0000663 void autoCreateBlock() { if (!Block) Block = createBlock(); }
664 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000665 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000666
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000667 CFGBlock *addStmt(Stmt *S) {
668 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000669 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000670
Alexis Hunt1d792652011-01-08 20:30:50 +0000671 CFGBlock *addInitializer(CXXCtorInitializer *I);
Peter Szecsi999a25f2017-08-19 11:19:16 +0000672 void addLoopExit(const Stmt *LoopStmt);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000673 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000674 LocalScope::const_iterator E, Stmt *S);
Matthias Gehre351c2182017-07-12 07:04:19 +0000675 void addLifetimeEnds(LocalScope::const_iterator B,
676 LocalScope::const_iterator E, Stmt *S);
677 void addAutomaticObjHandling(LocalScope::const_iterator B,
678 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000679 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000680
Marcin Swiderski5e415732010-09-30 23:05:00 +0000681 // Local scopes creation.
682 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
683
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000684 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000685 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
686 LocalScope* Scope = nullptr);
687 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000688
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000689 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000690
691 // Interface to CFGBlock - adding CFGElements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000692
Ted Kremenek37881932011-04-04 23:29:12 +0000693 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000694 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000695 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000696
Jordy Rose17347372011-06-10 08:49:37 +0000697 // All block-level expressions should have already been IgnoreParens()ed.
698 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000699 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000700 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000701
Artem Dergachev41ffb302018-02-08 22:58:15 +0000702 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
703 if (BuildOpts.AddRichCXXConstructors) {
704 if (!CurrentConstructionContext.isNull()) {
705 B->appendConstructor(CE, CurrentConstructionContext,
706 cfg->getBumpVectorContext());
707 ExitConstructionContext();
708 return;
709 }
710 }
711
712 // No valid construction context found. Fall back to statement.
713 B->appendStmt(CE, cfg->getBumpVectorContext());
714 }
715
Alexis Hunt1d792652011-01-08 20:30:50 +0000716 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000717 B->appendInitializer(I, cfg->getBumpVectorContext());
718 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000719
Jordan Rosec9176072014-01-13 17:59:19 +0000720 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
721 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
722 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000723
Marcin Swiderski20b88732010-10-05 05:37:00 +0000724 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
725 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
726 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000727
Marcin Swiderski20b88732010-10-05 05:37:00 +0000728 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
729 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
730 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000731
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000732 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
733 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
734 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000735
Chandler Carruthad747252011-09-13 06:09:01 +0000736 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
737 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
738 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000739
Matthias Gehre351c2182017-07-12 07:04:19 +0000740 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
741 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
742 }
743
Peter Szecsi999a25f2017-08-19 11:19:16 +0000744 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
745 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
746 }
747
Jordan Rosed2f40792013-09-03 17:00:57 +0000748 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
749 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
750 }
751
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000752 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000753 LocalScope::const_iterator B, LocalScope::const_iterator E);
754
Matthias Gehre351c2182017-07-12 07:04:19 +0000755 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
756 LocalScope::const_iterator B,
757 LocalScope::const_iterator E);
758
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000759 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
760 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
761 cfg->getBumpVectorContext());
762 }
763
764 /// Add a reachable successor to a block, with the alternate variant that is
765 /// unreachable.
766 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
767 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
768 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000769 }
Mike Stump11289f42009-09-09 15:08:12 +0000770
Richard Trieuf935b562014-04-05 05:17:01 +0000771 /// \brief Find a relational comparison with an expression evaluating to a
772 /// boolean and a constant other than 0 and 1.
773 /// e.g. if ((x < y) == 10)
774 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
775 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
776 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
777
778 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
779 const Expr *BoolExpr = RHSExpr;
780 bool IntFirst = true;
781 if (!IntLiteral) {
782 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
783 BoolExpr = LHSExpr;
784 IntFirst = false;
785 }
786
787 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
788 return TryResult();
789
790 llvm::APInt IntValue = IntLiteral->getValue();
791 if ((IntValue == 1) || (IntValue == 0))
792 return TryResult();
793
794 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
795 !IntValue.isNegative();
796
797 BinaryOperatorKind Bok = B->getOpcode();
798 if (Bok == BO_GT || Bok == BO_GE) {
799 // Always true for 10 > bool and bool > -1
800 // Always false for -1 > bool and bool > 10
801 return TryResult(IntFirst == IntLarger);
802 } else {
803 // Always true for -1 < bool and bool < 10
804 // Always false for 10 < bool and bool < -1
805 return TryResult(IntFirst != IntLarger);
806 }
807 }
808
Jordan Rose7afd71e2014-05-20 17:31:11 +0000809 /// Find an incorrect equality comparison. Either with an expression
810 /// evaluating to a boolean and a constant other than 0 and 1.
811 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
812 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000813 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
814 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
815 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
816
817 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
818 const Expr *BoolExpr = RHSExpr;
819
820 if (!IntLiteral) {
821 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
822 BoolExpr = LHSExpr;
823 }
824
Jordan Rose7afd71e2014-05-20 17:31:11 +0000825 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000826 return TryResult();
827
Jordan Rose7afd71e2014-05-20 17:31:11 +0000828 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
829 if (BitOp && (BitOp->getOpcode() == BO_And ||
830 BitOp->getOpcode() == BO_Or)) {
831 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
832 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
833
834 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
835
836 if (!IntLiteral2)
837 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
838
839 if (!IntLiteral2)
840 return TryResult();
841
842 llvm::APInt L1 = IntLiteral->getValue();
843 llvm::APInt L2 = IntLiteral2->getValue();
844 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
845 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
846 if (BuildOpts.Observer)
847 BuildOpts.Observer->compareBitwiseEquality(B,
848 B->getOpcode() != BO_EQ);
849 TryResult(B->getOpcode() != BO_EQ);
850 }
851 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
852 llvm::APInt IntValue = IntLiteral->getValue();
853 if ((IntValue == 1) || (IntValue == 0)) {
854 return TryResult();
855 }
856 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000857 }
858
Jordan Rose7afd71e2014-05-20 17:31:11 +0000859 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000860 }
861
862 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
863 const llvm::APSInt &Value1,
864 const llvm::APSInt &Value2) {
865 assert(Value1.isSigned() == Value2.isSigned());
866 switch (Relation) {
867 default:
868 return TryResult();
869 case BO_EQ:
870 return TryResult(Value1 == Value2);
871 case BO_NE:
872 return TryResult(Value1 != Value2);
873 case BO_LT:
874 return TryResult(Value1 < Value2);
875 case BO_LE:
876 return TryResult(Value1 <= Value2);
877 case BO_GT:
878 return TryResult(Value1 > Value2);
879 case BO_GE:
880 return TryResult(Value1 >= Value2);
881 }
882 }
883
884 /// \brief Find a pair of comparison expressions with or without parentheses
885 /// with a shared variable and constants and a logical operator between them
886 /// that always evaluates to either true or false.
887 /// e.g. if (x != 3 || x != 4)
888 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
889 assert(B->isLogicalOp());
890 const BinaryOperator *LHS =
891 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
892 const BinaryOperator *RHS =
893 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
894 if (!LHS || !RHS)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000895 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000896
897 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000898 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000899
George Burgess IVced56e62015-10-01 18:47:52 +0000900 const DeclRefExpr *Decl1;
901 const Expr *Expr1;
902 BinaryOperatorKind BO1;
903 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000904
George Burgess IVced56e62015-10-01 18:47:52 +0000905 if (!Decl1 || !Expr1)
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 *Decl2;
909 const Expr *Expr2;
910 BinaryOperatorKind BO2;
911 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000912
George Burgess IVced56e62015-10-01 18:47:52 +0000913 if (!Decl2 || !Expr2)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000914 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000915
916 // Check that it is the same variable on both sides.
917 if (Decl1->getDecl() != Decl2->getDecl())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000918 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000919
George Burgess IVced56e62015-10-01 18:47:52 +0000920 // Make sure the user's intent is clear (e.g. they're comparing against two
921 // int literals, or two things from the same enum)
922 if (!areExprTypesCompatible(Expr1, Expr2))
Eugene Zelenko38c70522017-12-07 21:55:09 +0000923 return {};
George Burgess IVced56e62015-10-01 18:47:52 +0000924
Richard Trieuf935b562014-04-05 05:17:01 +0000925 llvm::APSInt L1, L2;
926
George Burgess IVced56e62015-10-01 18:47:52 +0000927 if (!Expr1->EvaluateAsInt(L1, *Context) ||
928 !Expr2->EvaluateAsInt(L2, *Context))
Eugene Zelenko38c70522017-12-07 21:55:09 +0000929 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000930
931 // Can't compare signed with unsigned or with different bit width.
932 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000933 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000934
935 // Values that will be used to determine if result of logical
936 // operator is always true/false
937 const llvm::APSInt Values[] = {
938 // Value less than both Value1 and Value2
939 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
940 // L1
941 L1,
942 // Value between Value1 and Value2
943 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
944 L1.isUnsigned()),
945 // L2
946 L2,
947 // Value greater than both Value1 and Value2
948 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
949 };
950
951 // Check whether expression is always true/false by evaluating the following
952 // * variable x is less than the smallest literal.
953 // * variable x is equal to the smallest literal.
954 // * Variable x is between smallest and largest literal.
955 // * Variable x is equal to the largest literal.
956 // * Variable x is greater than largest literal.
957 bool AlwaysTrue = true, AlwaysFalse = true;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +0000958 for (const llvm::APSInt &Value : Values) {
Richard Trieuf935b562014-04-05 05:17:01 +0000959 TryResult Res1, Res2;
960 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
961 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
962
963 if (!Res1.isKnown() || !Res2.isKnown())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000964 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000965
966 if (B->getOpcode() == BO_LAnd) {
967 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
968 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
969 } else {
970 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
971 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
972 }
973 }
974
975 if (AlwaysTrue || AlwaysFalse) {
976 if (BuildOpts.Observer)
977 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
978 return TryResult(AlwaysTrue);
979 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000980 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000981 }
982
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000983 /// Try and evaluate an expression to an integer constant.
984 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
985 if (!BuildOpts.PruneTriviallyFalseEdges)
986 return false;
987 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +0000988 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +0000989 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000990 }
Mike Stump11289f42009-09-09 15:08:12 +0000991
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000992 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +0000993 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000994 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +0000995 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000996 S->isTypeDependent() || S->isValueDependent())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000997 return {};
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000998
999 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1000 if (Bop->isLogicalOp()) {
1001 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +00001002 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1003 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001004 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +00001005
1006 // Retrieve result at first, or the map might be updated.
1007 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1008 CachedBoolEvals[S] = Result; // update or insert
1009 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001010 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001011 else {
1012 switch (Bop->getOpcode()) {
1013 default: break;
1014 // For 'x & 0' and 'x * 0', we can determine that
1015 // the value is always false.
1016 case BO_Mul:
1017 case BO_And: {
1018 // If either operand is zero, we know the value
1019 // must be false.
1020 llvm::APSInt IntVal;
1021 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00001022 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001023 return TryResult(false);
1024 }
1025 }
1026 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00001027 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001028 return TryResult(false);
1029 }
1030 }
1031 }
1032 break;
1033 }
1034 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001035 }
1036
1037 return evaluateAsBooleanConditionNoCache(S);
1038 }
1039
1040 /// \brief Evaluate as boolean \param E without using the cache.
1041 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1042 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1043 if (Bop->isLogicalOp()) {
1044 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1045 if (LHS.isKnown()) {
1046 // We were able to evaluate the LHS, see if we can get away with not
1047 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1048 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1049 return LHS.isTrue();
1050
1051 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1052 if (RHS.isKnown()) {
1053 if (Bop->getOpcode() == BO_LOr)
1054 return LHS.isTrue() || RHS.isTrue();
1055 else
1056 return LHS.isTrue() && RHS.isTrue();
1057 }
1058 } else {
1059 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1060 if (RHS.isKnown()) {
1061 // We can't evaluate the LHS; however, sometimes the result
1062 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1063 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1064 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +00001065 } else {
1066 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1067 if (BopRes.isKnown())
1068 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001069 }
1070 }
1071
Eugene Zelenko38c70522017-12-07 21:55:09 +00001072 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001073 } else if (Bop->isEqualityOp()) {
1074 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1075 if (BopRes.isKnown())
1076 return BopRes.isTrue();
1077 } else if (Bop->isRelationalOp()) {
1078 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1079 if (BopRes.isKnown())
1080 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001081 }
1082 }
1083
1084 bool Result;
1085 if (E->EvaluateAsBooleanCondition(Result, *Context))
1086 return Result;
1087
Eugene Zelenko38c70522017-12-07 21:55:09 +00001088 return {};
Mike Stump773582d2009-07-23 23:25:26 +00001089 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001090
1091 bool hasTrivialDestructor(VarDecl *VD);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00001092};
Mike Stump31feda52009-07-17 01:31:16 +00001093
Eugene Zelenko38c70522017-12-07 21:55:09 +00001094} // namespace
1095
Ted Kremeneka099c592011-03-10 03:50:34 +00001096inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1097 const Stmt *stmt) const {
1098 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1099}
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001100
Ted Kremeneka099c592011-03-10 03:50:34 +00001101bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +00001102 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1103
Ted Kremeneka099c592011-03-10 03:50:34 +00001104 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +00001105 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001106
1107 if (lastLookup == stmt) {
1108 if (cachedEntry) {
1109 assert(cachedEntry->first == stmt);
1110 return true;
1111 }
Ted Kremenek8b46c002011-07-19 14:18:43 +00001112 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001113 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001114
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001115 lastLookup = stmt;
1116
1117 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +00001118 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1119
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001120 if (!fb) {
1121 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +00001122 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +00001123 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001124 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001125
1126 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001127 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +00001128 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +00001129 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001130 }
1131
Ted Kremeneka099c592011-03-10 03:50:34 +00001132 cachedEntry = &*itr;
1133 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +00001134}
1135
Douglas Gregor4619e432008-12-05 23:32:09 +00001136// FIXME: Add support for dependent-sized array types in C++?
1137// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +00001138static const VariableArrayType *FindVA(const Type *t) {
1139 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1140 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001141 if (vat->getSizeExpr())
1142 return vat;
Mike Stump31feda52009-07-17 01:31:16 +00001143
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001144 t = vt->getElementType().getTypePtr();
1145 }
Mike Stump31feda52009-07-17 01:31:16 +00001146
Craig Topper25542942014-05-20 04:30:07 +00001147 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001148}
Mike Stump31feda52009-07-17 01:31:16 +00001149
Artem Dergachev41ffb302018-02-08 22:58:15 +00001150void CFGBuilder::EnterConstructionContextIfNecessary(Stmt *Trigger,
1151 Stmt *Child) {
1152 if (!BuildOpts.AddRichCXXConstructors)
1153 return;
1154 if (!Child)
1155 return;
Artem Dergachev675d6f42018-02-09 01:43:26 +00001156 if (isa<CXXConstructExpr>(Child)) {
Artem Dergachev41ffb302018-02-08 22:58:15 +00001157 assert(CurrentConstructionContext.isNull() &&
1158 "Already within a construction context!");
1159 CurrentConstructionContext = ConstructionContext(Trigger);
1160 }
1161}
1162
1163void CFGBuilder::ExitConstructionContext() {
1164 assert(!CurrentConstructionContext.isNull() &&
1165 "Cannot exit construction context without the context!");
1166 CurrentConstructionContext = ConstructionContext();
1167}
1168
1169
Mike Stump31feda52009-07-17 01:31:16 +00001170/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1171/// arbitrary statement. Examples include a single expression or a function
1172/// body (compound statement). The ownership of the returned CFG is
1173/// transferred to the caller. If CFG construction fails, this method returns
1174/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +00001175std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +00001176 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +00001177 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +00001178 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001179
Mike Stump31feda52009-07-17 01:31:16 +00001180 // Create an empty block that will serve as the exit block for the CFG. Since
1181 // this is the first block added to the CFG, it will be implicitly registered
1182 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +00001183 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +00001184 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +00001185 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +00001186
Matthias Gehre351c2182017-07-12 07:04:19 +00001187 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1188 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1189
Marcin Swiderski20b88732010-10-05 05:37:00 +00001190 if (BuildOpts.AddImplicitDtors)
1191 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1192 addImplicitDtorsForDestructor(DD);
1193
Ted Kremenek9aae5132007-08-23 21:42:29 +00001194 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001195 CFGBlock *B = addStmt(Statement);
1196
1197 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001198 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001199
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001200 // For C++ constructor add initializers to CFG.
1201 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
Pete Cooper57d3f142015-07-30 17:22:52 +00001202 for (auto *I : llvm::reverse(CD->inits())) {
1203 B = addInitializer(I);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001204 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001205 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001206 }
1207 }
1208
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001209 if (B)
1210 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001211
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001212 // Backpatch the gotos whose label -> block mappings we didn't know when we
1213 // encountered them.
1214 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1215 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001216
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001217 CFGBlock *B = I->block;
Rafael Espindola210de572013-03-27 15:37:54 +00001218 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001219 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00001220
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001221 // If there is no target for the goto, then we are looking at an
1222 // incomplete AST. Handle this by not registering a successor.
1223 if (LI == LabelMap.end()) continue;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001224
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001225 JumpTarget JT = LI->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00001226 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1227 JT.scopePosition);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001228 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1229 JT.scopePosition);
1230 addSuccessor(B, JT.block);
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001231 }
1232
1233 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001234 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001235 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1236 E = AddressTakenLabels.end(); I != E; ++I ) {
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001237 // Lookup the target block.
1238 LabelMapTy::iterator LI = LabelMap.find(*I);
1239
1240 // If there is no target block that contains label, then we are looking
1241 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001242 if (LI == LabelMap.end()) continue;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001243
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001244 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001245 }
Mike Stump31feda52009-07-17 01:31:16 +00001246
Mike Stump31feda52009-07-17 01:31:16 +00001247 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001248 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001249
David Blaikiee90195c2014-08-29 18:53:26 +00001250 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001251}
Mike Stump31feda52009-07-17 01:31:16 +00001252
Ted Kremenek9aae5132007-08-23 21:42:29 +00001253/// createBlock - Used to lazily create blocks that are connected
1254/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001255CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1256 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001257 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001258 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001259 return B;
1260}
Mike Stump31feda52009-07-17 01:31:16 +00001261
Chandler Carrutha70991b2011-09-13 09:13:49 +00001262/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1263/// CFG. It is *not* connected to the current (global) successor, and instead
1264/// directly tied to the exit block in order to be reachable.
1265CFGBlock *CFGBuilder::createNoReturnBlock() {
1266 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001267 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001268 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001269 return B;
1270}
1271
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001272/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001273CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001274 if (!BuildOpts.AddInitializers)
1275 return Block;
1276
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001277 bool HasTemporaries = false;
1278
1279 // Destructors of temporaries in initialization expression should be called
1280 // after initialization finishes.
1281 Expr *Init = I->getInit();
1282 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001283 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001284
Jordan Rose6d671cc2012-09-05 22:55:23 +00001285 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001286 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001287 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001288 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1289 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001290 }
1291 }
1292
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001293 autoCreateBlock();
1294 appendInitializer(Block, I);
1295
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001296 if (Init) {
Ted Kremenek8219b822010-12-16 07:46:53 +00001297 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001298 // For expression with temporaries go directly to subexpression to omit
1299 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001300 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1301 }
Enrico Pertosofaed8012015-06-03 10:12:40 +00001302 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1303 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1304 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1305 // may cause the same Expr to appear more than once in the CFG. Doing it
1306 // here is safe because there's only one initializer per field.
1307 autoCreateBlock();
1308 appendStmt(Block, Default);
1309 if (Stmt *Child = Default->getExpr())
1310 if (CFGBlock *R = Visit(Child))
1311 Block = R;
1312 return Block;
1313 }
1314 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001315 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001316 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001317
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001318 return Block;
1319}
1320
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001321/// \brief Retrieve the type of the temporary object whose lifetime was
1322/// extended by a local reference with the given initializer.
1323static QualType getReferenceInitTemporaryType(ASTContext &Context,
Richard Smithb8c0f552016-12-09 18:49:13 +00001324 const Expr *Init,
1325 bool *FoundMTE = nullptr) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001326 while (true) {
1327 // Skip parentheses.
1328 Init = Init->IgnoreParens();
1329
1330 // Skip through cleanups.
1331 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1332 Init = EWC->getSubExpr();
1333 continue;
1334 }
1335
1336 // Skip through the temporary-materialization expression.
1337 if (const MaterializeTemporaryExpr *MTE
1338 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1339 Init = MTE->GetTemporaryExpr();
Richard Smithb8c0f552016-12-09 18:49:13 +00001340 if (FoundMTE)
1341 *FoundMTE = true;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001342 continue;
1343 }
1344
1345 // Skip derived-to-base and no-op casts.
1346 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1347 if ((CE->getCastKind() == CK_DerivedToBase ||
1348 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1349 CE->getCastKind() == CK_NoOp) &&
1350 Init->getType()->isRecordType()) {
1351 Init = CE->getSubExpr();
1352 continue;
1353 }
1354 }
1355
1356 // Skip member accesses into rvalues.
1357 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1358 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1359 Init = ME->getBase();
1360 continue;
1361 }
1362 }
1363
1364 break;
1365 }
1366
1367 return Init->getType();
1368}
Matthias Gehre351c2182017-07-12 07:04:19 +00001369
Peter Szecsi999a25f2017-08-19 11:19:16 +00001370// TODO: Support adding LoopExit element to the CFG in case where the loop is
1371// ended by ReturnStmt, GotoStmt or ThrowExpr.
1372void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1373 if(!BuildOpts.AddLoopExit)
1374 return;
1375 autoCreateBlock();
1376 appendLoopExit(Block, LoopStmt);
1377}
1378
Matthias Gehre351c2182017-07-12 07:04:19 +00001379void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1380 LocalScope::const_iterator E,
1381 Stmt *S) {
1382 if (BuildOpts.AddImplicitDtors)
1383 addAutomaticObjDtors(B, E, S);
1384 if (BuildOpts.AddLifetime)
1385 addLifetimeEnds(B, E, S);
1386}
1387
1388/// Add to current block automatic objects that leave the scope.
1389void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1390 LocalScope::const_iterator E, Stmt *S) {
1391 if (!BuildOpts.AddLifetime)
1392 return;
1393
1394 if (B == E)
1395 return;
1396
1397 // To go from B to E, one first goes up the scopes from B to P
1398 // then sideways in one scope from P to P' and then down
1399 // the scopes from P' to E.
1400 // The lifetime of all objects between B and P end.
1401 LocalScope::const_iterator P = B.shared_parent(E);
1402 int dist = B.distance(P);
1403 if (dist <= 0)
1404 return;
1405
1406 // We need to perform the scope leaving in reverse order
1407 SmallVector<VarDecl *, 10> DeclsTrivial;
1408 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1409 DeclsTrivial.reserve(dist);
1410 DeclsNonTrivial.reserve(dist);
1411
1412 for (LocalScope::const_iterator I = B; I != P; ++I)
1413 if (hasTrivialDestructor(*I))
1414 DeclsTrivial.push_back(*I);
1415 else
1416 DeclsNonTrivial.push_back(*I);
1417
1418 autoCreateBlock();
1419 // object with trivial destructor end their lifetime last (when storage
1420 // duration ends)
1421 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1422 E = DeclsTrivial.rend();
1423 I != E; ++I)
1424 appendLifetimeEnds(Block, *I, S);
1425
1426 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1427 I = DeclsNonTrivial.rbegin(),
1428 E = DeclsNonTrivial.rend();
1429 I != E; ++I)
1430 appendLifetimeEnds(Block, *I, S);
1431}
1432
Marcin Swiderski5e415732010-09-30 23:05:00 +00001433/// addAutomaticObjDtors - Add to current block automatic objects destructors
1434/// for objects in range of local scope positions. Use S as trigger statement
1435/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001436void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001437 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001438 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001439 return;
1440
Marcin Swiderski5e415732010-09-30 23:05:00 +00001441 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001442 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001443
Chandler Carruthad747252011-09-13 06:09:01 +00001444 // We need to append the destructors in reverse order, but any one of them
1445 // may be a no-return destructor which changes the CFG. As a result, buffer
1446 // this sequence up and replay them in reverse order when appending onto the
1447 // CFGBlock(s).
1448 SmallVector<VarDecl*, 10> Decls;
1449 Decls.reserve(B.distance(E));
1450 for (LocalScope::const_iterator I = B; I != E; ++I)
1451 Decls.push_back(*I);
1452
1453 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1454 E = Decls.rend();
1455 I != E; ++I) {
1456 // If this destructor is marked as a no-return destructor, we need to
1457 // create a new block for the destructor which does not have as a successor
1458 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001459 QualType Ty = (*I)->getType();
1460 if (Ty->isReferenceType()) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001461 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001462 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001463 Ty = Context->getBaseElementType(Ty);
1464
Richard Trieu95a192a2015-05-28 00:14:02 +00001465 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001466 Block = createNoReturnBlock();
1467 else
Chandler Carruthad747252011-09-13 06:09:01 +00001468 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001469
1470 appendAutomaticObjDtor(Block, *I, S);
1471 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001472}
1473
Marcin Swiderski20b88732010-10-05 05:37:00 +00001474/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1475/// base and member objects in destructor.
1476void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
Eugene Zelenko38c70522017-12-07 21:55:09 +00001477 assert(BuildOpts.AddImplicitDtors &&
1478 "Can be called only when dtors should be added");
Marcin Swiderski20b88732010-10-05 05:37:00 +00001479 const CXXRecordDecl *RD = DD->getParent();
1480
1481 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001482 for (const auto &VI : RD->vbases()) {
1483 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001484 if (!CD->hasTrivialDestructor()) {
1485 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001486 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001487 }
1488 }
1489
1490 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001491 for (const auto &BI : RD->bases()) {
1492 if (!BI.isVirtual()) {
1493 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001494 if (!CD->hasTrivialDestructor()) {
1495 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001496 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001497 }
1498 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001499 }
1500
1501 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001502 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001503 // Check for constant size array. Set type to array element type.
1504 QualType QT = FI->getType();
1505 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1506 if (AT->getSize() == 0)
1507 continue;
1508 QT = AT->getElementType();
1509 }
1510
1511 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001512 if (!CD->hasTrivialDestructor()) {
1513 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001514 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001515 }
1516 }
1517}
1518
Marcin Swiderski5e415732010-09-30 23:05:00 +00001519/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1520/// way return valid LocalScope object.
1521LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
David Blaikiec1334cc2015-08-13 22:12:21 +00001522 if (Scope)
1523 return Scope;
1524 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1525 return new (alloc.Allocate<LocalScope>())
1526 LocalScope(BumpVectorContext(alloc), ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001527}
1528
1529/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Zhongxing Xu81714f22010-10-01 03:00:16 +00001530/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001531void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001532 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001533 return;
1534
Craig Topper25542942014-05-20 04:30:07 +00001535 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001536
1537 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001538 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001539 for (auto *BI : CS->body()) {
1540 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001541 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001542 Scope = addLocalScopeForDeclStmt(DS, Scope);
1543 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001544 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001545 }
1546
1547 // For any other statement scope will be implicit and as such will be
1548 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001549 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001550 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001551}
1552
1553/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1554/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001555LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001556 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001557 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001558 return Scope;
1559
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001560 for (auto *DI : DS->decls())
1561 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001562 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001563 return Scope;
1564}
1565
Matthias Gehre351c2182017-07-12 07:04:19 +00001566bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1567 // Check for const references bound to temporary. Set type to pointee.
1568 QualType QT = VD->getType();
1569 if (QT.getTypePtr()->isReferenceType()) {
1570 // Attempt to determine whether this declaration lifetime-extends a
1571 // temporary.
1572 //
1573 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1574 // temporaries, and a single declaration can extend multiple temporaries.
1575 // We should look at the storage duration on each nested
1576 // MaterializeTemporaryExpr instead.
1577
1578 const Expr *Init = VD->getInit();
1579 if (!Init)
1580 return true;
1581
1582 // Lifetime-extending a temporary.
1583 bool FoundMTE = false;
1584 QT = getReferenceInitTemporaryType(*Context, Init, &FoundMTE);
1585 if (!FoundMTE)
1586 return true;
1587 }
1588
1589 // Check for constant size array. Set type to array element type.
1590 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1591 if (AT->getSize() == 0)
1592 return true;
1593 QT = AT->getElementType();
1594 }
1595
1596 // Check if type is a C++ class with non-trivial destructor.
1597 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1598 return !CD->hasDefinition() || CD->hasTrivialDestructor();
1599 return true;
1600}
1601
Marcin Swiderski5e415732010-09-30 23:05:00 +00001602/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1603/// create add scope for automatic objects and temporary objects bound to
1604/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001605LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001606 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001607 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1608 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1609 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001610 return Scope;
1611
1612 // Check if variable is local.
1613 switch (VD->getStorageClass()) {
1614 case SC_None:
1615 case SC_Auto:
1616 case SC_Register:
1617 break;
1618 default: return Scope;
1619 }
1620
Matthias Gehre351c2182017-07-12 07:04:19 +00001621 if (BuildOpts.AddImplicitDtors) {
1622 if (!hasTrivialDestructor(VD)) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001623 // Add the variable to scope
1624 Scope = createOrReuseLocalScope(Scope);
1625 Scope->addVar(VD);
1626 ScopePos = Scope->begin();
1627 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001628 return Scope;
1629 }
1630
1631 assert(BuildOpts.AddLifetime);
1632 // Add the variable to scope
1633 Scope = createOrReuseLocalScope(Scope);
1634 Scope->addVar(VD);
1635 ScopePos = Scope->begin();
Marcin Swiderski5e415732010-09-30 23:05:00 +00001636 return Scope;
1637}
1638
1639/// addLocalScopeAndDtors - For given statement add local scope for it and
1640/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001641void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001642 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001643 addLocalScopeForStmt(S);
Matthias Gehre351c2182017-07-12 07:04:19 +00001644 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001645}
1646
Marcin Swiderski321a7072010-09-30 22:54:37 +00001647/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1648/// variables with automatic storage duration to CFGBlock's elements vector.
1649/// Elements will be prepended to physical beginning of the vector which
1650/// happens to be logical end. Use blocks terminator as statement that specifies
1651/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001652/// FIXME: This mechanism for adding automatic destructors doesn't handle
1653/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001654void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00001655 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001656 if (!BuildOpts.AddImplicitDtors)
1657 return;
Chandler Carruthad747252011-09-13 06:09:01 +00001658 BumpVectorContext &C = cfg->getBumpVectorContext();
1659 CFGBlock::iterator InsertPos
1660 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1661 for (LocalScope::const_iterator I = B; I != E; ++I)
1662 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1663 Blk->getTerminator());
Marcin Swiderski321a7072010-09-30 22:54:37 +00001664}
1665
Matthias Gehre351c2182017-07-12 07:04:19 +00001666/// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
1667/// variables with automatic storage duration to CFGBlock's elements vector.
1668/// Elements will be prepended to physical beginning of the vector which
1669/// happens to be logical end. Use blocks terminator as statement that specifies
1670/// where lifetime ends.
1671void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
1672 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
1673 if (!BuildOpts.AddLifetime)
1674 return;
1675 BumpVectorContext &C = cfg->getBumpVectorContext();
1676 CFGBlock::iterator InsertPos =
1677 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
1678 for (LocalScope::const_iterator I = B; I != E; ++I)
1679 InsertPos = Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminator());
1680}
Eugene Zelenko38c70522017-12-07 21:55:09 +00001681
Ted Kremenek93668002009-07-17 22:18:43 +00001682/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00001683/// blocks for ternary operators, &&, and ||. We also process "," and
1684/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001685CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001686 if (!S) {
1687 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00001688 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001689 }
Jordy Rose17347372011-06-10 08:49:37 +00001690
1691 if (Expr *E = dyn_cast<Expr>(S))
1692 S = E->IgnoreParens();
1693
Ted Kremenek93668002009-07-17 22:18:43 +00001694 switch (S->getStmtClass()) {
1695 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001696 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001697
1698 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001699 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001700
John McCallc07a0c72011-02-17 10:25:35 +00001701 case Stmt::BinaryConditionalOperatorClass:
1702 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1703
Ted Kremenek93668002009-07-17 22:18:43 +00001704 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001705 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001706
Ted Kremenek93668002009-07-17 22:18:43 +00001707 case Stmt::BlockExprClass:
Devin Coughlinb6029b72015-11-25 22:35:37 +00001708 return VisitBlockExpr(cast<BlockExpr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001709
Ted Kremenek93668002009-07-17 22:18:43 +00001710 case Stmt::BreakStmtClass:
1711 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001712
Ted Kremenek93668002009-07-17 22:18:43 +00001713 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00001714 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00001715 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001716 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001717 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001718
Ted Kremenek93668002009-07-17 22:18:43 +00001719 case Stmt::CaseStmtClass:
1720 return VisitCaseStmt(cast<CaseStmt>(S));
1721
1722 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001723 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001724
Ted Kremenek93668002009-07-17 22:18:43 +00001725 case Stmt::CompoundStmtClass:
1726 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001727
Ted Kremenek93668002009-07-17 22:18:43 +00001728 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001729 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001730
Ted Kremenek93668002009-07-17 22:18:43 +00001731 case Stmt::ContinueStmtClass:
1732 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001733
Ted Kremenekb27378c2010-01-19 20:40:33 +00001734 case Stmt::CXXCatchStmtClass:
1735 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1736
John McCall5d413782010-12-06 08:20:24 +00001737 case Stmt::ExprWithCleanupsClass:
1738 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00001739
Jordan Rosee5d53932012-08-23 18:10:53 +00001740 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00001741 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00001742 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1743 // called function's declaration, not by the caller. If we simply add
1744 // this expression to the CFG, we could end up with the same Expr
1745 // appearing multiple times.
1746 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00001747 //
1748 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1749 // expression to be used in the same function (through aggregate
1750 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00001751 return VisitStmt(S, asc);
1752
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001753 case Stmt::CXXBindTemporaryExprClass:
1754 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1755
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001756 case Stmt::CXXConstructExprClass:
1757 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1758
Jordan Rosec9176072014-01-13 17:59:19 +00001759 case Stmt::CXXNewExprClass:
1760 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1761
Jordan Rosed2f40792013-09-03 17:00:57 +00001762 case Stmt::CXXDeleteExprClass:
1763 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1764
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001765 case Stmt::CXXFunctionalCastExprClass:
1766 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1767
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001768 case Stmt::CXXTemporaryObjectExprClass:
1769 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1770
Ted Kremenekb27378c2010-01-19 20:40:33 +00001771 case Stmt::CXXThrowExprClass:
1772 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001773
Ted Kremenekb27378c2010-01-19 20:40:33 +00001774 case Stmt::CXXTryStmtClass:
1775 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001776
Richard Smith02e85f32011-04-14 22:09:26 +00001777 case Stmt::CXXForRangeStmtClass:
1778 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1779
Ted Kremenek93668002009-07-17 22:18:43 +00001780 case Stmt::DeclStmtClass:
1781 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001782
Ted Kremenek93668002009-07-17 22:18:43 +00001783 case Stmt::DefaultStmtClass:
1784 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001785
Ted Kremenek93668002009-07-17 22:18:43 +00001786 case Stmt::DoStmtClass:
1787 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001788
Ted Kremenek93668002009-07-17 22:18:43 +00001789 case Stmt::ForStmtClass:
1790 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001791
Ted Kremenek93668002009-07-17 22:18:43 +00001792 case Stmt::GotoStmtClass:
1793 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001794
Ted Kremenek93668002009-07-17 22:18:43 +00001795 case Stmt::IfStmtClass:
1796 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001797
Ted Kremenek8219b822010-12-16 07:46:53 +00001798 case Stmt::ImplicitCastExprClass:
1799 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001800
Ted Kremenek93668002009-07-17 22:18:43 +00001801 case Stmt::IndirectGotoStmtClass:
1802 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001803
Ted Kremenek93668002009-07-17 22:18:43 +00001804 case Stmt::LabelStmtClass:
1805 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001806
Ted Kremenekda76a942012-04-12 20:34:52 +00001807 case Stmt::LambdaExprClass:
1808 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1809
Ted Kremenek5868ec62010-04-11 17:02:10 +00001810 case Stmt::MemberExprClass:
1811 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1812
Ted Kremenek04268232011-11-05 00:10:15 +00001813 case Stmt::NullStmtClass:
1814 return Block;
1815
Ted Kremenek93668002009-07-17 22:18:43 +00001816 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00001817 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1818
Ted Kremenek5022f1d2012-03-06 23:40:47 +00001819 case Stmt::ObjCAutoreleasePoolStmtClass:
1820 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1821
Ted Kremenek93668002009-07-17 22:18:43 +00001822 case Stmt::ObjCAtSynchronizedStmtClass:
1823 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001824
Ted Kremenek93668002009-07-17 22:18:43 +00001825 case Stmt::ObjCAtThrowStmtClass:
1826 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001827
Ted Kremenek93668002009-07-17 22:18:43 +00001828 case Stmt::ObjCAtTryStmtClass:
1829 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001830
Ted Kremenek93668002009-07-17 22:18:43 +00001831 case Stmt::ObjCForCollectionStmtClass:
1832 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001833
Ted Kremenek04268232011-11-05 00:10:15 +00001834 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00001835 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00001836
John McCallfe96e0b2011-11-06 09:01:30 +00001837 case Stmt::PseudoObjectExprClass:
1838 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1839
Ted Kremenek93668002009-07-17 22:18:43 +00001840 case Stmt::ReturnStmtClass:
1841 return VisitReturnStmt(cast<ReturnStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001842
Nico Weber699670e2017-08-23 15:33:16 +00001843 case Stmt::SEHExceptStmtClass:
1844 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
1845
1846 case Stmt::SEHFinallyStmtClass:
1847 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
1848
1849 case Stmt::SEHLeaveStmtClass:
1850 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
1851
1852 case Stmt::SEHTryStmtClass:
1853 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
1854
Peter Collingbournee190dee2011-03-11 19:24:49 +00001855 case Stmt::UnaryExprOrTypeTraitExprClass:
1856 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1857 asc);
Mike Stump11289f42009-09-09 15:08:12 +00001858
Ted Kremenek93668002009-07-17 22:18:43 +00001859 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001860 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Ted Kremenek93668002009-07-17 22:18:43 +00001862 case Stmt::SwitchStmtClass:
1863 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001864
Zhanyong Wan6dace612010-11-22 08:45:56 +00001865 case Stmt::UnaryOperatorClass:
1866 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1867
Ted Kremenek93668002009-07-17 22:18:43 +00001868 case Stmt::WhileStmtClass:
1869 return VisitWhileStmt(cast<WhileStmt>(S));
1870 }
1871}
Mike Stump11289f42009-09-09 15:08:12 +00001872
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001873CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001874 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001875 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001876 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00001877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
Ted Kremenek93668002009-07-17 22:18:43 +00001879 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00001880}
Mike Stump31feda52009-07-17 01:31:16 +00001881
Ted Kremenek93668002009-07-17 22:18:43 +00001882/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00001883CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1884 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00001885
Ted Kremenek8ae67872013-02-05 22:00:19 +00001886 // Visit the children in their reverse order so that they appear in
1887 // left-to-right (natural) order in the CFG.
1888 reverse_children RChildren(S);
1889 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1890 I != E; ++I) {
1891 if (Stmt *Child = *I)
1892 if (CFGBlock *R = Visit(Child))
1893 B = R;
1894 }
1895 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00001896}
Mike Stump11289f42009-09-09 15:08:12 +00001897
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001898CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1899 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00001900 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00001901
Ted Kremenek7c58d352011-03-10 01:14:11 +00001902 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001903 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001904 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00001905 }
Ted Kremenek81e14852007-08-27 19:46:09 +00001906
Ted Kremenek9aae5132007-08-23 21:42:29 +00001907 return Block;
1908}
Mike Stump11289f42009-09-09 15:08:12 +00001909
Zhanyong Wan6dace612010-11-22 08:45:56 +00001910CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00001911 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001912 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00001913 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001914 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00001915 }
1916
Ted Kremenek8219b822010-12-16 07:46:53 +00001917 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00001918}
1919
Ted Kremeneka16436f2012-07-14 05:04:06 +00001920CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1921 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1922 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00001923
Ted Kremeneka16436f2012-07-14 05:04:06 +00001924 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001925 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00001926
Craig Topper25542942014-05-20 04:30:07 +00001927 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1928 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001929}
1930
1931std::pair<CFGBlock*, CFGBlock*>
1932CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1933 Stmt *Term,
1934 CFGBlock *TrueBlock,
1935 CFGBlock *FalseBlock) {
Ted Kremenekb50e7162012-07-14 05:04:10 +00001936 // Introspect the RHS. If it is a nested logical operation, we recursively
1937 // build the CFG using this function. Otherwise, resort to default
1938 // CFG construction behavior.
1939 Expr *RHS = B->getRHS()->IgnoreParens();
1940 CFGBlock *RHSBlock, *ExitBlock;
1941
1942 do {
1943 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1944 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001945 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00001946 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1947 break;
1948 }
1949
1950 // The RHS is not a nested logical operation. Don't push the terminator
1951 // down further, but instead visit RHS and construct the respective
1952 // pieces of the CFG, and link up the RHSBlock with the terminator
1953 // we have been provided.
1954 ExitBlock = RHSBlock = createBlock(false);
1955
Richard Trieu6a6af522017-01-04 00:46:30 +00001956 // Even though KnownVal is only used in the else branch of the next
1957 // conditional, tryEvaluateBool performs additional checking on the
1958 // Expr, so it should be called unconditionally.
1959 TryResult KnownVal = tryEvaluateBool(RHS);
1960 if (!KnownVal.isKnown())
1961 KnownVal = tryEvaluateBool(B);
1962
Ted Kremenekb50e7162012-07-14 05:04:10 +00001963 if (!Term) {
1964 assert(TrueBlock == FalseBlock);
1965 addSuccessor(RHSBlock, TrueBlock);
1966 }
1967 else {
1968 RHSBlock->setTerminator(Term);
Ted Kremenek782f0032014-03-07 02:25:53 +00001969 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1970 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00001971 }
1972
1973 Block = RHSBlock;
1974 RHSBlock = addStmt(RHS);
1975 }
1976 while (false);
1977
1978 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001979 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00001980
1981 // Generate the blocks for evaluating the LHS.
1982 Expr *LHS = B->getLHS()->IgnoreParens();
1983
1984 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1985 if (B_LHS->isLogicalOp()) {
1986 if (B->getOpcode() == BO_LOr)
1987 FalseBlock = RHSBlock;
1988 else
1989 TrueBlock = RHSBlock;
1990
1991 // For the LHS, treat 'B' as the terminator that we want to sink
1992 // into the nested branch. The RHS always gets the top-most
1993 // terminator.
1994 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1995 }
1996
1997 // Create the block evaluating the LHS.
1998 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00001999 CFGBlock *LHSBlock = createBlock(false);
2000 LHSBlock->setTerminator(B);
2001
Ted Kremeneka16436f2012-07-14 05:04:06 +00002002 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002003 CFGBlock *EntryLHSBlock = addStmt(LHS);
2004
2005 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002006 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002007
2008 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002009 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002010
2011 // Now link the LHSBlock with RHSBlock.
2012 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00002013 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2014 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002015 } else {
2016 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00002017 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2018 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002019 }
2020
Ted Kremenekb50e7162012-07-14 05:04:10 +00002021 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002022}
2023
2024CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2025 AddStmtChoice asc) {
2026 // && or ||
2027 if (B->isLogicalOp())
2028 return VisitLogicalOperator(B);
2029
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002030 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00002031 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002032 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00002033 addStmt(B->getRHS());
2034 return addStmt(B->getLHS());
2035 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002036
2037 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002038 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002039 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002040 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002041 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002042 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00002043 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002044 }
Mike Stump11289f42009-09-09 15:08:12 +00002045
Ted Kremenek7c58d352011-03-10 01:14:11 +00002046 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00002047 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002048 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00002049 }
2050
Zhongxing Xud95ccd52010-10-27 03:23:10 +00002051 CFGBlock *RBlock = Visit(B->getRHS());
2052 CFGBlock *LBlock = Visit(B->getLHS());
2053 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2054 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2055 // return RBlock. Otherwise we'll incorrectly return NULL.
2056 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00002057}
2058
Ted Kremeneke2499842012-04-12 20:03:44 +00002059CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002060 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00002061 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002062 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00002063 }
2064 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002065}
2066
Ted Kremenek93668002009-07-17 22:18:43 +00002067CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2068 // "break" is a control-flow statement. Thus we stop processing the current
2069 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002070 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002071 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002072
Ted Kremenek93668002009-07-17 22:18:43 +00002073 // Now create a new block that ends with the break statement.
2074 Block = createBlock(false);
2075 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00002076
Ted Kremenek93668002009-07-17 22:18:43 +00002077 // If there is no target for the break, then we are looking at an incomplete
2078 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002079 if (BreakJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00002080 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002081 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002082 } else
Ted Kremenek93668002009-07-17 22:18:43 +00002083 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00002084
Ted Kremenek9aae5132007-08-23 21:42:29 +00002085 return Block;
2086}
Mike Stump11289f42009-09-09 15:08:12 +00002087
Sebastian Redl31ad7542011-03-13 17:09:40 +00002088static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00002089 QualType Ty = E->getType();
2090 if (Ty->isFunctionPointerType())
2091 Ty = Ty->getAs<PointerType>()->getPointeeType();
2092 else if (Ty->isBlockPointerType())
2093 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002094
Mike Stump04c68512010-01-21 15:20:48 +00002095 const FunctionType *FT = Ty->getAs<FunctionType>();
2096 if (FT) {
2097 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00002098 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smithf623c962012-04-17 00:58:00 +00002099 Proto->isNothrow(Ctx))
Mike Stump04c68512010-01-21 15:20:48 +00002100 return false;
2101 }
2102 return true;
2103}
2104
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002105CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00002106 // Compute the callee type.
2107 QualType calleeType = C->getCallee()->getType();
2108 if (calleeType == Context->BoundMemberTy) {
2109 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2110
2111 // We should only get a null bound type if processing a dependent
2112 // CFG. Recover by assuming nothing.
2113 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00002114 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002115
John McCallc67067f2011-05-11 07:19:11 +00002116 // If this is a call to a no-return function, this stops the block here.
2117 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2118
Mike Stump04c68512010-01-21 15:20:48 +00002119 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00002120
2121 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002122 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00002123 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00002124 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00002125 }
2126
Jordan Rose5374c072013-08-19 16:27:28 +00002127 // If this is a call to a builtin function, it might not actually evaluate
2128 // its arguments. Don't add them to the CFG if this is the case.
2129 bool OmitArguments = false;
2130
Mike Stump92244b02010-01-19 22:00:14 +00002131 if (FunctionDecl *FD = C->getDirectCallee()) {
Richard Smith10876ef2013-01-17 01:30:42 +00002132 if (FD->isNoReturn())
Mike Stump8c5d7992009-07-25 21:26:53 +00002133 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00002134 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00002135 AddEHEdge = false;
Jordan Rose5374c072013-08-19 16:27:28 +00002136 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
2137 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00002138 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002139
Sebastian Redl31ad7542011-03-13 17:09:40 +00002140 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00002141 AddEHEdge = false;
2142
Jordan Rose5374c072013-08-19 16:27:28 +00002143 if (OmitArguments) {
2144 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2145 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2146 autoCreateBlock();
2147 appendStmt(Block, C);
2148 return Visit(C->getCallee());
2149 }
2150
2151 if (!NoReturn && !AddEHEdge) {
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002152 return VisitStmt(C, asc.withAlwaysAdd(true));
Jordan Rose5374c072013-08-19 16:27:28 +00002153 }
Mike Stump11289f42009-09-09 15:08:12 +00002154
Mike Stump92244b02010-01-19 22:00:14 +00002155 if (Block) {
2156 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002157 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002158 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00002159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160
Chandler Carrutha70991b2011-09-13 09:13:49 +00002161 if (NoReturn)
2162 Block = createNoReturnBlock();
2163 else
2164 Block = createBlock();
2165
Ted Kremenek2866bab2011-03-10 01:14:08 +00002166 appendStmt(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00002167
Mike Stump04c68512010-01-21 15:20:48 +00002168 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00002169 // Add exceptional edges.
2170 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002171 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00002172 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002173 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00002174 }
Mike Stump11289f42009-09-09 15:08:12 +00002175
Mike Stump8c5d7992009-07-25 21:26:53 +00002176 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00002177}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002178
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002179CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2180 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002181 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002182 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002183 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002184 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002185
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002186 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00002187 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002188 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002189 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002190 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002191 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002192
Ted Kremenek21822592009-07-17 18:20:32 +00002193 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002194 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002195 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002196 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002197 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002198
Ted Kremenek21822592009-07-17 18:20:32 +00002199 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00002200 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002201 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00002202 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2203 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00002204 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00002205 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00002206}
Mike Stump11289f42009-09-09 15:08:12 +00002207
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002208CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Matthias Gehre09a134e2015-11-14 00:36:50 +00002209 LocalScope::const_iterator scopeBeginPos = ScopePos;
Matthias Gehre351c2182017-07-12 07:04:19 +00002210 addLocalScopeForStmt(C);
2211
Matthias Gehre09a134e2015-11-14 00:36:50 +00002212 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
Richard Smitha547eb22016-07-14 00:11:03 +00002213 // If the body ends with a ReturnStmt, the dtors will be added in
2214 // VisitReturnStmt.
Matthias Gehre351c2182017-07-12 07:04:19 +00002215 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
Matthias Gehre09a134e2015-11-14 00:36:50 +00002216 }
2217
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002218 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002219
2220 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2221 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00002222 // If we hit a segment of code just containing ';' (NullStmts), we can
2223 // get a null block back. In such cases, just use the LastBlock
2224 if (CFGBlock *newBlock = addStmt(*I))
2225 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002226
Ted Kremenekce499c22009-08-27 23:16:26 +00002227 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002228 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002229 }
Mike Stump92244b02010-01-19 22:00:14 +00002230
Ted Kremenek93668002009-07-17 22:18:43 +00002231 return LastBlock;
2232}
Mike Stump11289f42009-09-09 15:08:12 +00002233
John McCallc07a0c72011-02-17 10:25:35 +00002234CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002235 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00002236 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00002237 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00002238
Ted Kremenek51d40b02009-07-17 18:15:54 +00002239 // Create the confluence block that will "merge" the results of the ternary
2240 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002241 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002242 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002243 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002244 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002245
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002246 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002247
Ted Kremenek51d40b02009-07-17 18:15:54 +00002248 // Create a block for the LHS expression if there is an LHS expression. A
2249 // GCC extension allows LHS to be NULL, causing the condition to be the
2250 // value that is returned instead.
2251 // e.g: x ?: y is shorthand for: x ? x : y;
2252 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002253 Block = nullptr;
2254 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00002255 const Expr *trueExpr = C->getTrueExpr();
2256 if (trueExpr != opaqueValue) {
2257 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002258 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002259 return nullptr;
2260 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00002261 }
Ted Kremenekd8138012011-02-24 03:09:15 +00002262 else
2263 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002264
Ted Kremenek51d40b02009-07-17 18:15:54 +00002265 // Create the block for the RHS expression.
2266 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002267 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002268 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002269 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002270
Richard Smithf676e452012-07-24 21:02:14 +00002271 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2272 if (BinaryOperator *Cond =
2273 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2274 if (Cond->isLogicalOp())
2275 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2276
Ted Kremenek51d40b02009-07-17 18:15:54 +00002277 // Create the block that will contain the condition.
2278 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00002279
Mike Stump773582d2009-07-23 23:25:26 +00002280 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002281 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00002282 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2283 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00002284 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00002285 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00002286
Ted Kremenekd8138012011-02-24 03:09:15 +00002287 if (opaqueValue) {
2288 // Run the condition expression if it's not trivially expressed in
2289 // terms of the opaque value (or if there is no opaque value).
2290 if (condExpr != opaqueValue)
2291 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00002292
Ted Kremenekd8138012011-02-24 03:09:15 +00002293 // Before that, run the common subexpression if there was one.
2294 // At least one of this or the above will be run.
2295 return addStmt(BCO->getCommon());
2296 }
2297
2298 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00002299}
2300
Ted Kremenek93668002009-07-17 22:18:43 +00002301CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00002302 // Check if the Decl is for an __label__. If so, elide it from the
2303 // CFG entirely.
2304 if (isa<LabelDecl>(*DS->decl_begin()))
2305 return Block;
2306
Ted Kremenek3a601142011-05-24 20:41:31 +00002307 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002308 if (DS->isSingleDecl())
2309 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00002310
Craig Topper25542942014-05-20 04:30:07 +00002311 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002312
Jordan Rose8c6c8a92012-07-20 18:50:48 +00002313 // Build an individual DeclStmt for each decl.
2314 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2315 E = DS->decl_rend();
2316 I != E; ++I) {
Ted Kremenek93668002009-07-17 22:18:43 +00002317 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
Benjamin Kramerc3f89252016-10-20 14:27:22 +00002318 unsigned A = alignof(DeclStmt) < 8 ? 8 : alignof(DeclStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002319
Ted Kremenek93668002009-07-17 22:18:43 +00002320 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2321 // automatically freed with the CFG.
2322 DeclGroupRef DG(*I);
2323 Decl *D = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002324 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
Ted Kremenek93668002009-07-17 22:18:43 +00002325 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00002326 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00002327
Ted Kremenek93668002009-07-17 22:18:43 +00002328 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002329 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002330 }
Mike Stump11289f42009-09-09 15:08:12 +00002331
2332 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002333}
Mike Stump11289f42009-09-09 15:08:12 +00002334
Ted Kremenek93668002009-07-17 22:18:43 +00002335/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002336/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002337CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002338 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002339 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002340
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002341 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002342 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2343 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002344 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002345 }
Mike Stump11289f42009-09-09 15:08:12 +00002346
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002347 bool HasTemporaries = false;
2348
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002349 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002350 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002351
2352 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2353 // For static variables, we need to create a branch to track
2354 // whether or not they are initialized.
2355 if (Block) {
2356 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002357 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002358 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002359 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002360 }
2361 blockAfterStaticInit = Succ;
2362 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002363
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002364 // Destructors of temporaries in initialization expression should be called
2365 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002366 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002367 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002368 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002369
Jordan Rose6d671cc2012-09-05 22:55:23 +00002370 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002371 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002372 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002373 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2374 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002375 }
2376 }
2377
2378 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002379 appendStmt(Block, DS);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002380
2381 EnterConstructionContextIfNecessary(DS, Init);
2382
Ted Kremenek213d0532012-03-22 05:57:43 +00002383 // Keep track of the last non-null block, as 'Block' can be nulled out
2384 // if the initializer expression is something like a 'while' in a
2385 // statement-expression.
2386 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002387
Ted Kremenek93668002009-07-17 22:18:43 +00002388 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002389 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002390 // For expression with temporaries go directly to subexpression to omit
2391 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002392 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2393 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2394 LastBlock = newBlock;
2395 }
2396 else {
2397 if (CFGBlock *newBlock = Visit(Init))
2398 LastBlock = newBlock;
2399 }
Ted Kremenek93668002009-07-17 22:18:43 +00002400 }
Mike Stump11289f42009-09-09 15:08:12 +00002401
Ted Kremenek93668002009-07-17 22:18:43 +00002402 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002403 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002404 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002405 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2406 LastBlock = newBlock;
2407 }
Mike Stump11289f42009-09-09 15:08:12 +00002408
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002409 // Remove variable from local scope.
2410 if (ScopePos && VD == *ScopePos)
2411 ++ScopePos;
2412
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002413 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002414 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002415 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002416 Block = createBlock(false);
2417 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002418 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002419 addSuccessor(Block, B);
2420 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002421 }
2422
2423 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002424}
2425
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002426CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002427 // We may see an if statement in the middle of a basic block, or it may be the
2428 // first statement we are processing. In either case, we create a new basic
2429 // block. First, we create the blocks for the then...else statements, and
2430 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002431 // middle of a block, we stop processing that block. That block is then the
2432 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002433
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002434 // Save local scope position because in case of condition variable ScopePos
2435 // won't be restored when traversing AST.
2436 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2437
Richard Smitha547eb22016-07-14 00:11:03 +00002438 // Create local scope for C++17 if init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00002439 if (Stmt *Init = I->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00002440 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00002441
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002442 // Create local scope for possible condition variable.
2443 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00002444 if (VarDecl *VD = I->getConditionVariable())
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002445 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00002446
Matthias Gehre351c2182017-07-12 07:04:19 +00002447 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002448
Chris Lattner57540c52011-04-15 05:22:18 +00002449 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002450 // block.
2451 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002452 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002453 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002454 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002455 }
Mike Stump31feda52009-07-17 01:31:16 +00002456
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002457 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002458 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002459
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002460 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002461 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002462
Ted Kremenek9aae5132007-08-23 21:42:29 +00002463 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002464 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002465 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002466
2467 // If branch is not a compound statement create implicit scope
2468 // and add destructors.
2469 if (!isa<CompoundStmt>(Else))
2470 addLocalScopeAndDtors(Else);
2471
Ted Kremenek93668002009-07-17 22:18:43 +00002472 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002473
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002474 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2475 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002476 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002477 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002478 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002479 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002480 }
Mike Stump31feda52009-07-17 01:31:16 +00002481
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002482 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002483 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002484 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002485 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002486 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002487 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002488 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002489
2490 // If branch is not a compound statement create implicit scope
2491 // and add destructors.
2492 if (!isa<CompoundStmt>(Then))
2493 addLocalScopeAndDtors(Then);
2494
Ted Kremenek93668002009-07-17 22:18:43 +00002495 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002496
Ted Kremenek1b379512009-04-01 03:52:47 +00002497 if (!ThenBlock) {
2498 // We can reach here if the "then" body has all NullStmts.
2499 // Create an empty block so we can distinguish between true and false
2500 // branches in path-sensitive analyses.
2501 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002502 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002503 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002504 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002505 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002506 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002507 }
2508
Ted Kremenekb50e7162012-07-14 05:04:10 +00002509 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2510 // having these handle the actual control-flow jump. Note that
2511 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2512 // we resort to the old control-flow behavior. This special handling
2513 // removes infeasible paths from the control-flow graph by having the
2514 // control-flow transfer of '&&' or '||' go directly into the then/else
2515 // blocks directly.
Richard Smith509bbd12017-01-13 22:16:41 +00002516 BinaryOperator *Cond =
2517 I->getConditionVariable()
2518 ? nullptr
2519 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
2520 CFGBlock *LastBlock;
2521 if (Cond && Cond->isLogicalOp())
2522 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2523 else {
2524 // Now create a new block containing the if statement.
2525 Block = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002526
Richard Smith509bbd12017-01-13 22:16:41 +00002527 // Set the terminator of the new block to the If statement.
2528 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002529
Richard Smith509bbd12017-01-13 22:16:41 +00002530 // See if this is a known constant.
2531 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002532
Richard Smith509bbd12017-01-13 22:16:41 +00002533 // Add the successors. If we know that specific branches are
2534 // unreachable, inform addSuccessor() of that knowledge.
2535 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2536 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump773582d2009-07-23 23:25:26 +00002537
Richard Smith509bbd12017-01-13 22:16:41 +00002538 // Add the condition as the last statement in the new block. This may
2539 // create new blocks as the condition may contain control-flow. Any newly
2540 // created blocks will be pointed to be "Block".
2541 LastBlock = addStmt(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002542
Richard Smith509bbd12017-01-13 22:16:41 +00002543 // If the IfStmt contains a condition variable, add it and its
2544 // initializer to the CFG.
2545 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2546 autoCreateBlock();
2547 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2548 }
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002549 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002550
Richard Smitha547eb22016-07-14 00:11:03 +00002551 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2552 if (Stmt *Init = I->getInit()) {
2553 autoCreateBlock();
2554 LastBlock = addStmt(Init);
2555 }
2556
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002557 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002558}
Mike Stump31feda52009-07-17 01:31:16 +00002559
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002560CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002561 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002562 //
Mike Stump31feda52009-07-17 01:31:16 +00002563 // NOTE: If a "return" appears in the middle of a block, this means that the
2564 // code afterwards is DEAD (unreachable). We still keep a basic block
2565 // for that code; a simple "mark-and-sweep" from the entry block will be
2566 // able to report such dead blocks.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002567
2568 // Create the new block.
2569 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002570
Matthias Gehre351c2182017-07-12 07:04:19 +00002571 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), R);
Pavel Labath921e7652013-09-06 08:12:48 +00002572
2573 // If the one of the destructors does not return, we already have the Exit
2574 // block as a successor.
2575 if (!Block->hasNoReturnElement())
2576 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002577
2578 // Add the return statement to the block. This may create new blocks if R
2579 // contains control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002580 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002581}
2582
Nico Weber699670e2017-08-23 15:33:16 +00002583CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
2584 // SEHExceptStmt are treated like labels, so they are the first statement in a
2585 // block.
2586
2587 // Save local scope position because in case of exception variable ScopePos
2588 // won't be restored when traversing AST.
2589 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2590
2591 addStmt(ES->getBlock());
2592 CFGBlock *SEHExceptBlock = Block;
2593 if (!SEHExceptBlock)
2594 SEHExceptBlock = createBlock();
2595
2596 appendStmt(SEHExceptBlock, ES);
2597
2598 // Also add the SEHExceptBlock as a label, like with regular labels.
2599 SEHExceptBlock->setLabel(ES);
2600
2601 // Bail out if the CFG is bad.
2602 if (badCFG)
2603 return nullptr;
2604
2605 // We set Block to NULL to allow lazy creation of a new block (if necessary).
2606 Block = nullptr;
2607
2608 return SEHExceptBlock;
2609}
2610
2611CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
2612 return VisitCompoundStmt(FS->getBlock());
2613}
2614
2615CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
2616 // "__leave" is a control-flow statement. Thus we stop processing the current
2617 // block.
2618 if (badCFG)
2619 return nullptr;
2620
2621 // Now create a new block that ends with the __leave statement.
2622 Block = createBlock(false);
2623 Block->setTerminator(LS);
2624
2625 // If there is no target for the __leave, then we are looking at an incomplete
2626 // AST. This means that the CFG cannot be constructed.
2627 if (SEHLeaveJumpTarget.block) {
2628 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
2629 addSuccessor(Block, SEHLeaveJumpTarget.block);
2630 } else
2631 badCFG = true;
2632
2633 return Block;
2634}
2635
2636CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
2637 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
2638 // processing the current block.
2639 CFGBlock *SEHTrySuccessor = nullptr;
2640
2641 if (Block) {
2642 if (badCFG)
2643 return nullptr;
2644 SEHTrySuccessor = Block;
2645 } else SEHTrySuccessor = Succ;
2646
2647 // FIXME: Implement __finally support.
2648 if (Terminator->getFinallyHandler())
2649 return NYS();
2650
2651 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
2652
2653 // Create a new block that will contain the __try statement.
2654 CFGBlock *NewTryTerminatedBlock = createBlock(false);
2655
2656 // Add the terminator in the __try block.
2657 NewTryTerminatedBlock->setTerminator(Terminator);
2658
2659 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
2660 // The code after the try is the implicit successor if there's an __except.
2661 Succ = SEHTrySuccessor;
2662 Block = nullptr;
2663 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
2664 if (!ExceptBlock)
2665 return nullptr;
2666 // Add this block to the list of successors for the block with the try
2667 // statement.
2668 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
2669 }
2670 if (PrevSEHTryTerminatedBlock)
2671 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
2672 else
2673 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2674
2675 // The code after the try is the implicit successor.
2676 Succ = SEHTrySuccessor;
2677
2678 // Save the current "__try" context.
2679 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
2680 NewTryTerminatedBlock);
2681 cfg->addTryDispatchBlock(TryTerminatedBlock);
2682
2683 // Save the current value for the __leave target.
2684 // All __leaves should go to the code following the __try
2685 // (FIXME: or if the __try has a __finally, to the __finally.)
2686 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
2687 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
2688
2689 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
2690 Block = nullptr;
2691 return addStmt(Terminator->getTryBlock());
2692}
2693
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002694CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002695 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00002696 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002697 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002698
Ted Kremenek93668002009-07-17 22:18:43 +00002699 if (!LabelBlock) // This can happen when the body is empty, i.e.
2700 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00002701
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002702 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2703 "label already in map");
2704 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002705
2706 // Labels partition blocks, so this is the end of the basic block we were
2707 // processing (L is the block's label). Because this is label (and we have
2708 // already processed the substatement) there is no extra control-flow to worry
2709 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00002710 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002711 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002712 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002713
2714 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00002715 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002716
Ted Kremenek9aae5132007-08-23 21:42:29 +00002717 // This block is now the implicit successor of other blocks.
2718 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002719
Ted Kremenek9aae5132007-08-23 21:42:29 +00002720 return LabelBlock;
2721}
2722
Devin Coughlinb6029b72015-11-25 22:35:37 +00002723CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
2724 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2725 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
2726 if (Expr *CopyExpr = CI.getCopyExpr()) {
2727 CFGBlock *Tmp = Visit(CopyExpr);
2728 if (Tmp)
2729 LastBlock = Tmp;
2730 }
2731 }
2732 return LastBlock;
2733}
2734
Ted Kremenekda76a942012-04-12 20:34:52 +00002735CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2736 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2737 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2738 et = E->capture_init_end(); it != et; ++it) {
2739 if (Expr *Init = *it) {
2740 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00002741 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00002742 LastBlock = Tmp;
2743 }
2744 }
2745 return LastBlock;
2746}
2747
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002748CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00002749 // Goto is a control-flow statement. Thus we stop processing the current
2750 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00002751
Ted Kremenek9aae5132007-08-23 21:42:29 +00002752 Block = createBlock(false);
2753 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00002754
2755 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002756 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00002757
Ted Kremenek9aae5132007-08-23 21:42:29 +00002758 if (I == LabelMap.end())
2759 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002760 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2761 else {
2762 JumpTarget JT = I->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00002763 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002764 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002765 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002766
Mike Stump31feda52009-07-17 01:31:16 +00002767 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002768}
2769
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002770CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00002771 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002772
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002773 // Save local scope position because in case of condition variable ScopePos
2774 // won't be restored when traversing AST.
2775 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2776
2777 // Create local scope for init statement and possible condition variable.
2778 // Add destructor for init statement and condition variable.
2779 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002780 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002781 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002782 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2783
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002784 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002785 addLocalScopeForVarDecl(VD);
2786 LocalScope::const_iterator ContinueScopePos = ScopePos;
2787
Matthias Gehre351c2182017-07-12 07:04:19 +00002788 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002789
Peter Szecsi999a25f2017-08-19 11:19:16 +00002790 addLoopExit(F);
2791
Mike Stump014b3ea2009-07-21 01:12:51 +00002792 // "for" is a control-flow statement. Thus we stop processing the current
2793 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002794 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002795 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002796 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002797 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002798 } else
2799 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002800
Ted Kremenek304a9532010-05-21 20:30:15 +00002801 // Save the current value for the break targets.
2802 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002803 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002804 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00002805
Craig Topper25542942014-05-20 04:30:07 +00002806 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002807
Ted Kremenek9aae5132007-08-23 21:42:29 +00002808 // Now create the loop body.
2809 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002810 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002811
Ted Kremenekb50e7162012-07-14 05:04:10 +00002812 // Save the current values for Block, Succ, continue and break targets.
2813 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2814 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002815
Ted Kremenekb50e7162012-07-14 05:04:10 +00002816 // Create an empty block to represent the transition block for looping back
2817 // to the head of the loop. If we have increment code, it will
2818 // go in this block as well.
2819 Block = Succ = TransitionBlock = createBlock(false);
2820 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002821
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002822 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00002823 // Generate increment code in its own basic block. This is the target of
2824 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00002825 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00002826 }
Mike Stump31feda52009-07-17 01:31:16 +00002827
Ted Kremenek902393b2009-04-28 00:51:56 +00002828 // Finish up the increment (or empty) block if it hasn't been already.
2829 if (Block) {
2830 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002831 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002832 return nullptr;
2833 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00002834 }
Mike Stump31feda52009-07-17 01:31:16 +00002835
Ted Kremenekb50e7162012-07-14 05:04:10 +00002836 // The starting block for the loop increment is the block that should
2837 // represent the 'loop target' for looping back to the start of the loop.
2838 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2839 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002840
Ted Kremenekb50e7162012-07-14 05:04:10 +00002841 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00002842 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00002843
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002844 // If body is not a compound statement create implicit scope
2845 // and add destructors.
2846 if (!isa<CompoundStmt>(F->getBody()))
2847 addLocalScopeAndDtors(F->getBody());
2848
Mike Stump31feda52009-07-17 01:31:16 +00002849 // Now populate the body block, and in the process create new blocks as we
2850 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002851 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00002852
Ted Kremenekb50e7162012-07-14 05:04:10 +00002853 if (!BodyBlock) {
2854 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2855 // Use the continue jump target as the proxy for the body.
2856 BodyBlock = ContinueJumpTarget.block;
2857 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002858 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002859 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002860 }
Ted Kremenekb50e7162012-07-14 05:04:10 +00002861
2862 // Because of short-circuit evaluation, the condition of the loop can span
2863 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2864 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002865 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002866
Ted Kremenekb50e7162012-07-14 05:04:10 +00002867 do {
2868 Expr *C = F->getCond();
2869
2870 // Specially handle logical operators, which have a slightly
2871 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002872 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00002873 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002874 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002875 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002876 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2877 break;
2878 }
2879
2880 // The default case when not handling logical operators.
2881 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2882 ExitConditionBlock->setTerminator(F);
2883
2884 // See if this is a known constant.
2885 TryResult KnownVal(true);
2886
2887 if (C) {
2888 // Now add the actual condition to the condition block.
2889 // Because the condition itself may contain control-flow, new blocks may
2890 // be created. Thus we update "Succ" after adding the condition.
2891 Block = ExitConditionBlock;
2892 EntryConditionBlock = addStmt(C);
2893
2894 // If this block contains a condition variable, add both the condition
2895 // variable and initializer to the CFG.
2896 if (VarDecl *VD = F->getConditionVariable()) {
2897 if (Expr *Init = VD->getInit()) {
2898 autoCreateBlock();
2899 appendStmt(Block, F->getConditionVariableDeclStmt());
2900 EntryConditionBlock = addStmt(Init);
2901 assert(Block == EntryConditionBlock);
2902 }
2903 }
2904
2905 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002906 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002907
2908 KnownVal = tryEvaluateBool(C);
2909 }
2910
2911 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002912 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002913 // Link up the condition block with the code that follows the loop. (the
2914 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002915 addSuccessor(ExitConditionBlock,
2916 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002917 } while (false);
2918
2919 // Link up the loop-back block to the entry condition block.
2920 addSuccessor(TransitionBlock, EntryConditionBlock);
2921
2922 // The condition block is the implicit successor for any code above the loop.
2923 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002924
Ted Kremenek9aae5132007-08-23 21:42:29 +00002925 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00002926 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002927 if (Stmt *I = F->getInit()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002928 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00002929 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002930 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002931
2932 // There is no loop initialization. We are thus basically a while loop.
2933 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00002934 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002935 Succ = EntryConditionBlock;
2936 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002937}
2938
Ted Kremenek5868ec62010-04-11 17:02:10 +00002939CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002940 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00002941 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002942 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002943 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002944 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00002945}
2946
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002947CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00002948 // Objective-C fast enumeration 'for' statements:
2949 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2950 //
2951 // for ( Type newVariable in collection_expression ) { statements }
2952 //
2953 // becomes:
2954 //
2955 // prologue:
2956 // 1. collection_expression
2957 // T. jump to loop_entry
2958 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002959 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00002960 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2961 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2962 // TB:
2963 // statements
2964 // T. jump to loop_entry
2965 // FB:
2966 // what comes after
2967 //
2968 // and
2969 //
2970 // Type existingItem;
2971 // for ( existingItem in expression ) { statements }
2972 //
2973 // becomes:
2974 //
Mike Stump31feda52009-07-17 01:31:16 +00002975 // the same with newVariable replaced with existingItem; the binding works
2976 // the same except that for one ObjCForCollectionStmt::getElement() returns
2977 // a DeclStmt and the other returns a DeclRefExpr.
Mike Stump31feda52009-07-17 01:31:16 +00002978
Craig Topper25542942014-05-20 04:30:07 +00002979 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002980
Ted Kremenek9d56e642008-11-11 17:10:00 +00002981 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002982 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002983 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00002984 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002985 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00002986 } else
2987 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002988
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002989 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002990 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002991
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002992 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002993 ExitConditionBlock->setTerminator(S);
2994
2995 // The last statement in the block should be the ObjCForCollectionStmt, which
2996 // performs the actual binding to 'element' and determines if there are any
2997 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00002998 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002999 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003000
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003001 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00003002 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00003003 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00003004 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3005 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00003006 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003007 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003008 return nullptr;
3009 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003010 }
Mike Stump31feda52009-07-17 01:31:16 +00003011
3012 // The condition block is the implicit successor for the loop body as well as
3013 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003014 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003015
Ted Kremenek9d56e642008-11-11 17:10:00 +00003016 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00003017 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003018 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00003019 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003020 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00003021 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003022
Anna Zaks56b49752013-06-22 00:23:20 +00003023 // Add an intermediate block between the BodyBlock and the
3024 // EntryConditionBlock to represent the "loop back" transition, for looping
3025 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00003026 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00003027 Succ = LoopBackBlock = createBlock();
3028 LoopBackBlock->setLoopTarget(S);
3029
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003030 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00003031 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003032
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003033 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003034
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003035 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00003036 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00003037 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003038 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003039 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003040 }
Mike Stump31feda52009-07-17 01:31:16 +00003041
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003042 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003043 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003044 }
Mike Stump31feda52009-07-17 01:31:16 +00003045
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003046 // Link up the condition block with the code that follows the loop.
3047 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003048 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003049
Ted Kremenek9d56e642008-11-11 17:10:00 +00003050 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003051 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00003052 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00003053}
3054
Ted Kremenek5022f1d2012-03-06 23:40:47 +00003055CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3056 // Inline the body.
3057 return addStmt(S->getSubStmt());
3058 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3059}
3060
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003061CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00003062 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00003063
Ted Kremenek49805452009-05-02 01:49:13 +00003064 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00003065 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00003066
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003067 // The sync body starts its own basic block. This makes it a little easier
3068 // for diagnostic clients.
3069 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003070 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003071 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003072
Craig Topper25542942014-05-20 04:30:07 +00003073 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00003074 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003075 }
Mike Stump31feda52009-07-17 01:31:16 +00003076
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003077 // Add the @synchronized to the CFG.
3078 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003079 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003080
Ted Kremenek49805452009-05-02 01:49:13 +00003081 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00003082 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00003083}
Mike Stump31feda52009-07-17 01:31:16 +00003084
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003085CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003086 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00003087 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00003088}
Ted Kremenek9d56e642008-11-11 17:10:00 +00003089
John McCallfe96e0b2011-11-06 09:01:30 +00003090CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3091 autoCreateBlock();
3092
3093 // Add the PseudoObject as the last thing.
3094 appendStmt(Block, E);
3095
3096 CFGBlock *lastBlock = Block;
3097
3098 // Before that, evaluate all of the semantics in order. In
3099 // CFG-land, that means appending them in reverse order.
3100 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3101 Expr *Semantic = E->getSemanticExpr(--i);
3102
3103 // If the semantic is an opaque value, we're being asked to bind
3104 // it to its source expression.
3105 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3106 Semantic = OVE->getSourceExpr();
3107
3108 if (CFGBlock *B = Visit(Semantic))
3109 lastBlock = B;
3110 }
3111
3112 return lastBlock;
3113}
3114
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003115CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00003116 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003117
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003118 // Save local scope position because in case of condition variable ScopePos
3119 // won't be restored when traversing AST.
3120 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3121
3122 // Create local scope for possible condition variable.
3123 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003124 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003125 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003126 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003127 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003128 }
Peter Szecsi999a25f2017-08-19 11:19:16 +00003129 addLoopExit(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003130
Mike Stump014b3ea2009-07-21 01:12:51 +00003131 // "while" is a control-flow statement. Thus we stop processing the current
3132 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003133 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003134 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003135 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003136 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003137 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003138 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00003139 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00003140 }
Mike Stump31feda52009-07-17 01:31:16 +00003141
Craig Topper25542942014-05-20 04:30:07 +00003142 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00003143
Ted Kremenek9aae5132007-08-23 21:42:29 +00003144 // Process the loop body.
3145 {
Ted Kremenek49936f72009-04-28 03:09:44 +00003146 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00003147
Ted Kremenekb50e7162012-07-14 05:04:10 +00003148 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003149 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3150 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00003151 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00003152
Mike Stump31feda52009-07-17 01:31:16 +00003153 // Create an empty block to represent the transition block for looping back
3154 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003155 Succ = TransitionBlock = createBlock(false);
3156 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003157 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003158
Ted Kremenek9aae5132007-08-23 21:42:29 +00003159 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003160 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003161
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003162 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00003163 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003164
3165 // If body is not a compound statement create implicit scope
3166 // and add destructors.
3167 if (!isa<CompoundStmt>(W->getBody()))
3168 addLocalScopeAndDtors(W->getBody());
3169
Ted Kremenek9aae5132007-08-23 21:42:29 +00003170 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003171 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003172
Ted Kremeneke9610502007-08-30 18:39:40 +00003173 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003174 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00003175 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003176 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003177 }
3178
3179 // Because of short-circuit evaluation, the condition of the loop can span
3180 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3181 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00003182 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003183
3184 do {
3185 Expr *C = W->getCond();
3186
3187 // Specially handle logical operators, which have a slightly
3188 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00003189 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00003190 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003191 std::tie(EntryConditionBlock, ExitConditionBlock) =
3192 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003193 break;
3194 }
3195
3196 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00003197 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003198 ExitConditionBlock->setTerminator(W);
3199
3200 // Now add the actual condition to the condition block.
3201 // Because the condition itself may contain control-flow, new blocks may
3202 // be created. Thus we update "Succ" after adding the condition.
3203 Block = ExitConditionBlock;
3204 Block = EntryConditionBlock = addStmt(C);
3205
3206 // If this block contains a condition variable, add both the condition
3207 // variable and initializer to the CFG.
3208 if (VarDecl *VD = W->getConditionVariable()) {
3209 if (Expr *Init = VD->getInit()) {
3210 autoCreateBlock();
3211 appendStmt(Block, W->getConditionVariableDeclStmt());
3212 EntryConditionBlock = addStmt(Init);
3213 assert(Block == EntryConditionBlock);
3214 }
Ted Kremenek55957a82009-05-02 00:13:27 +00003215 }
Mike Stump31feda52009-07-17 01:31:16 +00003216
Ted Kremenekb50e7162012-07-14 05:04:10 +00003217 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003218 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003219
3220 // See if this is a known constant.
3221 const TryResult& KnownVal = tryEvaluateBool(C);
3222
Ted Kremenek30754282009-07-24 04:47:11 +00003223 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00003224 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003225 // Link up the condition block with the code that follows the loop. (the
3226 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003227 addSuccessor(ExitConditionBlock,
3228 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003229 } while(false);
3230
3231 // Link up the loop-back block to the entry condition block.
3232 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00003233
3234 // There can be no more statements in the condition block since we loop back
3235 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003236 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003237
Ted Kremenek1ce53c42009-12-24 01:34:10 +00003238 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003239 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00003240 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003241}
Mike Stump11289f42009-09-09 15:08:12 +00003242
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003243CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003244 // FIXME: For now we pretend that @catch and the code it contains does not
3245 // exit.
3246 return Block;
3247}
Mike Stump31feda52009-07-17 01:31:16 +00003248
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003249CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00003250 // FIXME: This isn't complete. We basically treat @throw like a return
3251 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00003252
Ted Kremenek0868eea2009-09-24 18:45:41 +00003253 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003254 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003255 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003256
Ted Kremenek93041ba2008-12-09 20:20:09 +00003257 // Create the new block.
3258 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003259
Ted Kremenek93041ba2008-12-09 20:20:09 +00003260 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003261 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00003262
3263 // Add the statement to the block. This may create new blocks if S contains
3264 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003265 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00003266}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003267
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003268CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00003269 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003270 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003271 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003272
3273 // Create the new block.
3274 Block = createBlock(false);
3275
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003276 if (TryTerminatedBlock)
3277 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003278 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003279 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003280 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003281 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003282
3283 // Add the statement to the block. This may create new blocks if S contains
3284 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003285 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003286}
3287
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003288CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00003289 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003290
Peter Szecsi999a25f2017-08-19 11:19:16 +00003291 addLoopExit(D);
3292
Mike Stump8d50b6a2009-07-21 01:27:50 +00003293 // "do...while" is a control-flow statement. Thus we stop processing the
3294 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003295 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003296 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003297 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003298 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003299 } else
3300 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003301
3302 // Because of short-circuit evaluation, the condition of the loop can span
3303 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3304 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003305 CFGBlock *ExitConditionBlock = createBlock(false);
3306 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003307
Ted Kremenek81e14852007-08-27 19:46:09 +00003308 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003309 ExitConditionBlock->setTerminator(D);
3310
3311 // Now add the actual condition to the condition block. Because the condition
3312 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003313 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00003314 Block = ExitConditionBlock;
3315 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00003316 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003317 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003318 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003319 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003320 }
Mike Stump31feda52009-07-17 01:31:16 +00003321
Ted Kremeneka1523a32008-02-27 07:20:00 +00003322 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00003323 Succ = EntryConditionBlock;
3324
Mike Stump773582d2009-07-23 23:25:26 +00003325 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003326 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00003327
Ted Kremenek9aae5132007-08-23 21:42:29 +00003328 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00003329 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003330 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003331 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003332
Ted Kremenek9aae5132007-08-23 21:42:29 +00003333 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003334 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3335 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3336 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003337
Ted Kremenek9aae5132007-08-23 21:42:29 +00003338 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003339 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003340
Ted Kremenek9aae5132007-08-23 21:42:29 +00003341 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003342 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003343
Ted Kremenek9aae5132007-08-23 21:42:29 +00003344 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00003345 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003346
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003347 // If body is not a compound statement create implicit scope
3348 // and add destructors.
3349 if (!isa<CompoundStmt>(D->getBody()))
3350 addLocalScopeAndDtors(D->getBody());
3351
Ted Kremenek9aae5132007-08-23 21:42:29 +00003352 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00003353 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003354
Ted Kremeneke9610502007-08-30 18:39:40 +00003355 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00003356 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00003357 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003358 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003359 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003360 }
Mike Stump31feda52009-07-17 01:31:16 +00003361
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003362 // Add an intermediate block between the BodyBlock and the
3363 // ExitConditionBlock to represent the "loop back" transition. Create an
3364 // empty block to represent the transition block for looping back to the
3365 // head of the loop.
3366 // FIXME: Can we do this more efficiently without adding another block?
3367 Block = nullptr;
3368 Succ = BodyBlock;
3369 CFGBlock *LoopBackBlock = createBlock();
3370 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00003371
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003372 if (!KnownVal.isFalse())
Ted Kremenek110974d2010-08-17 20:59:56 +00003373 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003374 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00003375 else
Craig Topper25542942014-05-20 04:30:07 +00003376 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003377 }
Mike Stump31feda52009-07-17 01:31:16 +00003378
Ted Kremenek30754282009-07-24 04:47:11 +00003379 // Link up the condition block with the code that follows the loop.
3380 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00003381 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003382
3383 // There can be no more statements in the body block(s) since we loop back to
3384 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003385 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003386
Ted Kremenek9aae5132007-08-23 21:42:29 +00003387 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003388 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003389 return BodyBlock;
3390}
3391
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003392CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003393 // "continue" is a control-flow statement. Thus we stop processing the
3394 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003395 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003396 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003397
Ted Kremenek9aae5132007-08-23 21:42:29 +00003398 // Now create a new block that ends with the continue statement.
3399 Block = createBlock(false);
3400 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00003401
Ted Kremenek9aae5132007-08-23 21:42:29 +00003402 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00003403 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003404 if (ContinueJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00003405 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003406 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003407 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00003408 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00003409
Ted Kremenek9aae5132007-08-23 21:42:29 +00003410 return Block;
3411}
Mike Stump11289f42009-09-09 15:08:12 +00003412
Peter Collingbournee190dee2011-03-11 19:24:49 +00003413CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3414 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003415 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003416 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003417 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00003418 }
Mike Stump11289f42009-09-09 15:08:12 +00003419
Ted Kremenek93668002009-07-17 22:18:43 +00003420 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003421 CFGBlock *lastBlock = Block;
3422
Ted Kremenek93668002009-07-17 22:18:43 +00003423 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003424 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00003425 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003426 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00003427 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003428 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003429}
Mike Stump11289f42009-09-09 15:08:12 +00003430
Ted Kremenek93668002009-07-17 22:18:43 +00003431/// VisitStmtExpr - Utility method to handle (nested) statement
3432/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003433CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003434 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003435 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003436 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00003437 }
Ted Kremenek93668002009-07-17 22:18:43 +00003438 return VisitCompoundStmt(SE->getSubStmt());
3439}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003440
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003441CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00003442 // "switch" is a control-flow statement. Thus we stop processing the current
3443 // block.
Craig Topper25542942014-05-20 04:30:07 +00003444 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003445
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003446 // Save local scope position because in case of condition variable ScopePos
3447 // won't be restored when traversing AST.
3448 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3449
Richard Smitha547eb22016-07-14 00:11:03 +00003450 // Create local scope for C++17 switch init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00003451 if (Stmt *Init = Terminator->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00003452 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00003453
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003454 // Create local scope for possible condition variable.
3455 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00003456 if (VarDecl *VD = Terminator->getConditionVariable())
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003457 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00003458
Matthias Gehre351c2182017-07-12 07:04:19 +00003459 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003460
Ted Kremenek9aae5132007-08-23 21:42:29 +00003461 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003462 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003463 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003464 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003465 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003466
3467 // Save the current "switch" context.
3468 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003469 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003470 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003471
Mike Stump31feda52009-07-17 01:31:16 +00003472 // Set the "default" case to be the block after the switch statement. If the
3473 // switch statement contains a "default:", this value will be overwritten with
3474 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003475 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003476
Ted Kremenek9aae5132007-08-23 21:42:29 +00003477 // Create a new block that will contain the switch statement.
3478 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003479
Ted Kremenek9aae5132007-08-23 21:42:29 +00003480 // Now process the switch body. The code after the switch is the implicit
3481 // successor.
3482 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003483 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003484
3485 // When visiting the body, the case statements should automatically get linked
3486 // up to the switch. We also don't keep a pointer to the body, since all
3487 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003488 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003489 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003490
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003491 // For pruning unreachable case statements, save the current state
3492 // for tracking the condition value.
3493 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3494 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003495
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003496 // Determine if the switch condition can be explicitly evaluated.
3497 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003498 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003499 bool b = tryEvaluate(Terminator->getCond(), result);
3500 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003501 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003502
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003503 // If body is not a compound statement create implicit scope
3504 // and add destructors.
3505 if (!isa<CompoundStmt>(Terminator->getBody()))
3506 addLocalScopeAndDtors(Terminator->getBody());
3507
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003508 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003509 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003510 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003511 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003512 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003513
Mike Stump31feda52009-07-17 01:31:16 +00003514 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003515 // following the switch body. Moreover, take into account if all the
3516 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003517 //
3518 // Note: We add a successor to a switch that is considered covered yet has no
3519 // case statements if the enumeration has no enumerators.
3520 bool SwitchAlwaysHasSuccessor = false;
3521 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3522 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3523 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003524 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3525 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003526
Ted Kremenek81e14852007-08-27 19:46:09 +00003527 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003528 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003529 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003530 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003531
Richard Smitha547eb22016-07-14 00:11:03 +00003532 // If the SwitchStmt contains a condition variable, add both the
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003533 // SwitchStmt and the condition variable initialization to the CFG.
3534 if (VarDecl *VD = Terminator->getConditionVariable()) {
3535 if (Expr *Init = VD->getInit()) {
3536 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003537 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003538 LastBlock = addStmt(Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003539 }
3540 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003541
Richard Smitha547eb22016-07-14 00:11:03 +00003542 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
3543 if (Stmt *Init = Terminator->getInit()) {
3544 autoCreateBlock();
3545 LastBlock = addStmt(Init);
3546 }
3547
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003548 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003549}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003550
3551static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00003552 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003553 const CaseStmt *CS,
3554 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003555 if (!switchCond)
3556 return true;
3557
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003558 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00003559
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003560 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003561 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003562 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003563 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00003564 const llvm::APSInt &condInt = switchCond->Val.getInt();
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003565
3566 if (condInt == lhsInt) {
3567 addCase = true;
3568 switchExclusivelyCovered = true;
3569 }
Devin Coughlineb538ab2015-09-22 20:31:19 +00003570 else if (condInt > lhsInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003571 if (const Expr *RHS = CS->getRHS()) {
3572 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003573 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
Devin Coughlineb538ab2015-09-22 20:31:19 +00003574 if (V2 >= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003575 addCase = true;
3576 switchExclusivelyCovered = true;
3577 }
3578 }
3579 }
3580 }
3581 else
3582 addCase = true;
3583 }
3584 return addCase;
3585}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003586
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003587CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00003588 // CaseStmts are essentially labels, so they are the first statement in a
3589 // block.
Craig Topper25542942014-05-20 04:30:07 +00003590 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00003591
Ted Kremenek60fa6572010-08-04 23:54:30 +00003592 if (Stmt *Sub = CS->getSubStmt()) {
3593 // For deeply nested chains of CaseStmts, instead of doing a recursion
3594 // (which can blow out the stack), manually unroll and create blocks
3595 // along the way.
3596 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003597 CFGBlock *currentBlock = createBlock(false);
3598 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00003599
Ted Kremenek60fa6572010-08-04 23:54:30 +00003600 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003601 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003602 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003603 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003604
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003605 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003606 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003607 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00003608 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003609
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003610 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003611 CS = cast<CaseStmt>(Sub);
3612 Sub = CS->getSubStmt();
3613 }
3614
3615 addStmt(Sub);
3616 }
Mike Stump11289f42009-09-09 15:08:12 +00003617
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003618 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003619 if (!CaseBlock)
3620 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003621
3622 // Cases statements partition blocks, so this is the top of the basic block we
3623 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00003624 CaseBlock->setLabel(CS);
3625
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003626 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003627 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003628
3629 // Add this block to the list of successors for the block with the switch
3630 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00003631 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003632 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003633 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003634 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00003635
Ted Kremenek9aae5132007-08-23 21:42:29 +00003636 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003637 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003638
Ted Kremenek60fa6572010-08-04 23:54:30 +00003639 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003640 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003641 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003642 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00003643 // This block is now the implicit successor of other blocks.
3644 Succ = CaseBlock;
3645 }
Mike Stump31feda52009-07-17 01:31:16 +00003646
Ted Kremenek60fa6572010-08-04 23:54:30 +00003647 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003648}
Mike Stump31feda52009-07-17 01:31:16 +00003649
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003650CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00003651 if (Terminator->getSubStmt())
3652 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00003653
Ted Kremenek654c78f2008-02-13 22:05:39 +00003654 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003655
3656 if (!DefaultCaseBlock)
3657 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003658
3659 // Default statements partition blocks, so this is the top of the basic block
3660 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003661 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00003662
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003663 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003664 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00003665
Mike Stump31feda52009-07-17 01:31:16 +00003666 // Unlike case statements, we don't add the default block to the successors
3667 // for the switch statement immediately. This is done when we finish
3668 // processing the switch statement. This allows for the default case
3669 // (including a fall-through to the code after the switch statement) to always
3670 // be the last successor of a switch-terminated block.
3671
Ted Kremenek654c78f2008-02-13 22:05:39 +00003672 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003673 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003674
Ted Kremenek654c78f2008-02-13 22:05:39 +00003675 // This block is now the implicit successor of other blocks.
3676 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003677
3678 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00003679}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003680
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003681CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3682 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3683 // current block.
Craig Topper25542942014-05-20 04:30:07 +00003684 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003685
3686 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003687 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003688 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003689 TrySuccessor = Block;
3690 } else TrySuccessor = Succ;
3691
Mike Stump0bdba6c2010-01-20 01:15:34 +00003692 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003693
3694 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00003695 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003696 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00003697 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003698
Mike Stump0bdba6c2010-01-20 01:15:34 +00003699 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003700 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3701 // The code after the try is the implicit successor.
3702 Succ = TrySuccessor;
3703 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00003704 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00003705 HasCatchAll = true;
3706 }
Craig Topper25542942014-05-20 04:30:07 +00003707 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003708 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00003709 if (!CatchBlock)
3710 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003711 // Add this block to the list of successors for the block with the try
3712 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003713 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003714 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00003715 if (!HasCatchAll) {
3716 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003717 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00003718 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003719 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00003720 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003721
3722 // The code after the try is the implicit successor.
3723 Succ = TrySuccessor;
3724
Mike Stump845384a2010-01-20 01:30:58 +00003725 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00003726 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3727 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00003728
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003729 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003730 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003731 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003732}
3733
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003734CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003735 // CXXCatchStmt are treated like labels, so they are the first statement in a
3736 // block.
3737
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003738 // Save local scope position because in case of exception variable ScopePos
3739 // won't be restored when traversing AST.
3740 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3741
3742 // Create local scope for possible exception variable.
3743 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003744 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003745 LocalScope::const_iterator BeginScopePos = ScopePos;
3746 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003747 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003748 }
3749
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003750 if (CS->getHandlerBlock())
3751 addStmt(CS->getHandlerBlock());
3752
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003753 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003754 if (!CatchBlock)
3755 CatchBlock = createBlock();
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003756
3757 // CXXCatchStmt is more than just a label. They have semantic meaning
3758 // as well, as they implicitly "initialize" the catch variable. Add
3759 // it to the CFG as a CFGElement so that the control-flow of these
3760 // semantics gets captured.
3761 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003762
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003763 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3764 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003765 CatchBlock->setLabel(CS);
3766
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003767 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003768 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003769 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003770
3771 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003772 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003773
3774 return CatchBlock;
3775}
3776
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003777CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00003778 // C++0x for-range statements are specified as [stmt.ranged]:
3779 //
3780 // {
3781 // auto && __range = range-init;
3782 // for ( auto __begin = begin-expr,
3783 // __end = end-expr;
3784 // __begin != __end;
3785 // ++__begin ) {
3786 // for-range-declaration = *__begin;
3787 // statement
3788 // }
3789 // }
3790
3791 // Save local scope position before the addition of the implicit variables.
3792 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3793
3794 // Create local scopes and destructors for range, begin and end variables.
3795 if (Stmt *Range = S->getRangeStmt())
3796 addLocalScopeForStmt(Range);
Richard Smith01694c32016-03-20 10:33:40 +00003797 if (Stmt *Begin = S->getBeginStmt())
3798 addLocalScopeForStmt(Begin);
3799 if (Stmt *End = S->getEndStmt())
3800 addLocalScopeForStmt(End);
Matthias Gehre351c2182017-07-12 07:04:19 +00003801 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
Richard Smith02e85f32011-04-14 22:09:26 +00003802
3803 LocalScope::const_iterator ContinueScopePos = ScopePos;
3804
3805 // "for" is a control-flow statement. Thus we stop processing the current
3806 // block.
Craig Topper25542942014-05-20 04:30:07 +00003807 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003808 if (Block) {
3809 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003810 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003811 LoopSuccessor = Block;
3812 } else
3813 LoopSuccessor = Succ;
3814
3815 // Save the current value for the break targets.
3816 // All breaks should go to the code following the loop.
3817 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3818 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3819
3820 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003821 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00003822 ConditionBlock->setTerminator(S);
3823
3824 // Now add the actual condition to the condition block.
3825 if (Expr *C = S->getCond()) {
3826 Block = ConditionBlock;
3827 CFGBlock *BeginConditionBlock = addStmt(C);
3828 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003829 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003830 assert(BeginConditionBlock == ConditionBlock &&
3831 "condition block in for-range was unexpectedly complex");
3832 (void)BeginConditionBlock;
3833 }
3834
3835 // The condition block is the implicit successor for the loop body as well as
3836 // any code above the loop.
3837 Succ = ConditionBlock;
3838
3839 // See if this is a known constant.
3840 TryResult KnownVal(true);
3841
3842 if (S->getCond())
3843 KnownVal = tryEvaluateBool(S->getCond());
3844
3845 // Now create the loop body.
3846 {
3847 assert(S->getBody());
3848
3849 // Save the current values for Block, Succ, and continue targets.
3850 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3851 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3852
3853 // Generate increment code in its own basic block. This is the target of
3854 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00003855 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003856 Succ = addStmt(S->getInc());
Alexander Kornienkoff2046a2016-07-08 10:50:51 +00003857 if (badCFG)
3858 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003859 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3860
3861 // The starting block for the loop increment is the block that should
3862 // represent the 'loop target' for looping back to the start of the loop.
3863 ContinueJumpTarget.block->setLoopTarget(S);
3864
3865 // Finish up the increment block and prepare to start the loop body.
3866 assert(Block);
3867 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003868 return nullptr;
3869 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003870
3871 // Add implicit scope and dtors for loop variable.
3872 addLocalScopeAndDtors(S->getLoopVarStmt());
3873
3874 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003875 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00003876 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003877 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003878 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003879 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003880 return nullptr;
3881
Richard Smith02e85f32011-04-14 22:09:26 +00003882 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00003883 addSuccessor(ConditionBlock,
3884 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00003885 }
3886
3887 // Link up the condition block with the code that follows the loop (the
3888 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003889 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00003890
3891 // Add the initialization statements.
3892 Block = createBlock();
Richard Smith01694c32016-03-20 10:33:40 +00003893 addStmt(S->getBeginStmt());
3894 addStmt(S->getEndStmt());
Richard Smith0c502d22011-04-18 15:49:25 +00003895 return addStmt(S->getRangeStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003896}
3897
John McCall5d413782010-12-06 08:20:24 +00003898CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003899 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003900 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003901 // If adding implicit destructors visit the full expression for adding
3902 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003903 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00003904 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003905
3906 // Full expression has to be added as CFGStmt so it will be sequenced
3907 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003908 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003909 }
3910 return Visit(E->getSubExpr(), asc);
3911}
3912
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003913CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3914 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003915 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003916 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003917 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003918
3919 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003920 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003921 }
3922 return Visit(E->getSubExpr(), asc);
3923}
3924
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003925CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3926 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003927 autoCreateBlock();
Artem Dergachev41ffb302018-02-08 22:58:15 +00003928 appendConstructor(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003929
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003930 return VisitChildren(C);
3931}
3932
Jordan Rosec9176072014-01-13 17:59:19 +00003933CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3934 AddStmtChoice asc) {
Jordan Rosec9176072014-01-13 17:59:19 +00003935 autoCreateBlock();
3936 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00003937
Artem Dergachev41ffb302018-02-08 22:58:15 +00003938 EnterConstructionContextIfNecessary(
3939 NE, const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
3940
Jordan Rosec9176072014-01-13 17:59:19 +00003941 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003942 Block = Visit(NE->getInitializer());
Artem Dergachev41ffb302018-02-08 22:58:15 +00003943
Jordan Rosec9176072014-01-13 17:59:19 +00003944 if (BuildOpts.AddCXXNewAllocator)
3945 appendNewAllocator(Block, NE);
Artem Dergachev41ffb302018-02-08 22:58:15 +00003946
Jordan Rosec9176072014-01-13 17:59:19 +00003947 if (NE->isArray())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003948 Block = Visit(NE->getArraySize());
Artem Dergachev41ffb302018-02-08 22:58:15 +00003949
Jordan Rosec9176072014-01-13 17:59:19 +00003950 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3951 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00003952 Block = Visit(*I);
Artem Dergachev41ffb302018-02-08 22:58:15 +00003953
Jordan Rosec9176072014-01-13 17:59:19 +00003954 return Block;
3955}
Jordan Rosed2f40792013-09-03 17:00:57 +00003956
3957CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3958 AddStmtChoice asc) {
3959 autoCreateBlock();
3960 appendStmt(Block, DE);
3961 QualType DTy = DE->getDestroyedType();
Martin Bohmef44cde82016-12-05 11:33:19 +00003962 if (!DTy.isNull()) {
3963 DTy = DTy.getNonReferenceType();
3964 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3965 if (RD) {
3966 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
3967 appendDeleteDtor(Block, RD, DE);
3968 }
Jordan Rosed2f40792013-09-03 17:00:57 +00003969 }
3970
3971 return VisitChildren(DE);
3972}
3973
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003974CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3975 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003976 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003977 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003978 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003979 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003980 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003981 }
3982 return Visit(E->getSubExpr(), asc);
3983}
3984
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003985CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3986 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003987 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003988 appendStmt(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003989 return VisitChildren(C);
3990}
3991
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003992CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3993 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003994 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003995 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003996 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003997 }
Ted Kremenek8219b822010-12-16 07:46:53 +00003998 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003999}
4000
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004001CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00004002 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004003 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004004
Ted Kremenekeda180e22007-08-28 19:26:49 +00004005 if (!IBlock) {
4006 IBlock = createBlock(false);
4007 cfg->setIndirectGotoBlock(IBlock);
4008 }
Mike Stump31feda52009-07-17 01:31:16 +00004009
Ted Kremenekeda180e22007-08-28 19:26:49 +00004010 // IndirectGoto is a control-flow statement. Thus we stop processing the
4011 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004012 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004013 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00004014
Ted Kremenekeda180e22007-08-28 19:26:49 +00004015 Block = createBlock(false);
4016 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004017 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00004018 return addStmt(I->getTarget());
4019}
4020
Manuel Klimekb5616c92014-08-07 10:42:17 +00004021CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
4022 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00004023 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4024
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004025tryAgain:
4026 if (!E) {
4027 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00004028 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004029 }
4030 switch (E->getStmtClass()) {
4031 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004032 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004033
4034 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004035 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4036 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004037
4038 case Stmt::CXXBindTemporaryExprClass:
4039 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004040 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004041
John McCallc07a0c72011-02-17 10:25:35 +00004042 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004043 case Stmt::ConditionalOperatorClass:
4044 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004045 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004046
4047 case Stmt::ImplicitCastExprClass:
4048 // For implicit cast we want BindToTemporary to be passed further.
4049 E = cast<CastExpr>(E)->getSubExpr();
4050 goto tryAgain;
4051
Manuel Klimekb0042c42014-07-30 08:34:42 +00004052 case Stmt::CXXFunctionalCastExprClass:
4053 // For functional cast we want BindToTemporary to be passed further.
4054 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4055 goto tryAgain;
4056
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004057 case Stmt::ParenExprClass:
4058 E = cast<ParenExpr>(E)->getSubExpr();
4059 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00004060
Manuel Klimekb0042c42014-07-30 08:34:42 +00004061 case Stmt::MaterializeTemporaryExprClass: {
4062 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4063 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
4064 SmallVector<const Expr *, 2> CommaLHSs;
4065 SmallVector<SubobjectAdjustment, 2> Adjustments;
4066 // Find the expression whose lifetime needs to be extended.
4067 E = const_cast<Expr *>(
4068 cast<MaterializeTemporaryExpr>(E)
4069 ->GetTemporaryExpr()
4070 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4071 // Visit the skipped comma operator left-hand sides for other temporaries.
4072 for (const Expr *CommaLHS : CommaLHSs) {
4073 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00004074 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00004075 }
Douglas Gregorfe314812011-06-21 17:03:29 +00004076 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00004077 }
Richard Smith4137af22014-07-27 05:12:49 +00004078
4079 case Stmt::BlockExprClass:
4080 // Don't recurse into blocks; their subexpressions don't get evaluated
4081 // here.
4082 return Block;
4083
4084 case Stmt::LambdaExprClass: {
4085 // For lambda expressions, only recurse into the capture initializers,
4086 // and not the body.
4087 auto *LE = cast<LambdaExpr>(E);
4088 CFGBlock *B = Block;
4089 for (Expr *Init : LE->capture_inits()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004090 if (CFGBlock *R = VisitForTemporaryDtors(
4091 Init, /*BindToTemporary=*/false, Context))
Richard Smith4137af22014-07-27 05:12:49 +00004092 B = R;
4093 }
4094 return B;
4095 }
4096
4097 case Stmt::CXXDefaultArgExprClass:
4098 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4099 goto tryAgain;
4100
4101 case Stmt::CXXDefaultInitExprClass:
4102 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4103 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004104 }
4105}
4106
Manuel Klimekb5616c92014-08-07 10:42:17 +00004107CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
4108 TempDtorContext &Context) {
4109 if (isa<LambdaExpr>(E)) {
4110 // Do not visit the children of lambdas; they have their own CFGs.
4111 return Block;
4112 }
4113
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004114 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00004115 // order that they will appear in the CFG. Because the CFG is built
4116 // bottom-up, this means we visit them in their natural order, which
4117 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004118 CFGBlock *B = Block;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004119 for (Stmt *Child : E->children())
4120 if (Child)
Manuel Klimekb5616c92014-08-07 10:42:17 +00004121 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00004122 B = R;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004123
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004124 return B;
4125}
4126
Manuel Klimekb5616c92014-08-07 10:42:17 +00004127CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
4128 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004129 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004130 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00004131 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
4132 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
4133 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00004134
Manuel Klimekedf925b92014-08-07 18:44:19 +00004135 // We do not know at CFG-construction time whether the right-hand-side was
4136 // executed, thus we add a branch node that depends on the temporary
4137 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00004138 TempDtorContext RHSContext(
4139 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00004140 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00004141 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00004142
Manuel Klimekb5616c92014-08-07 10:42:17 +00004143 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004144 }
4145
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004146 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004147 // For assignment operator (=) LHS expression is visited
4148 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004149 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4150 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004151 return LHSBlock ? LHSBlock : RHSBlock;
4152 }
4153
4154 // For any other binary operator RHS expression is visited before
4155 // LHS expression (order of children). For destructors visit them in reverse
4156 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004157 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4158 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004159 return RHSBlock ? RHSBlock : LHSBlock;
4160}
4161
4162CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004163 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004164 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004165 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00004166 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004167 // If lifetime of temporary is not prolonged (by assigning to constant
4168 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00004169
Chandler Carruthad747252011-09-13 06:09:01 +00004170 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004171
Richard Trieu95a192a2015-05-28 00:14:02 +00004172 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004173 // If the destructor is marked as a no-return destructor, we need to
4174 // create a new block for the destructor which does not have as a
4175 // successor anything built thus far. Control won't flow out of this
4176 // block.
4177 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00004178 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004179 } else if (Context.needsTempDtorBranch()) {
4180 // If we need to introduce a branch, we add a new block that we will hook
4181 // up to a decision block later.
4182 if (B) Succ = B;
4183 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004184 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00004185 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004186 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00004187 if (Context.needsTempDtorBranch()) {
4188 Context.setDecisionPoint(Succ, E);
4189 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004190 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004191
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004192 B = Block;
4193 }
4194 return B;
4195}
4196
Manuel Klimekb5616c92014-08-07 10:42:17 +00004197void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
4198 CFGBlock *FalseSucc) {
4199 if (!Context.TerminatorExpr) {
4200 // If no temporary was found, we do not need to insert a decision point.
4201 return;
4202 }
4203 assert(Context.TerminatorExpr);
4204 CFGBlock *Decision = createBlock(false);
4205 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
Manuel Klimekdeb02622014-08-08 07:37:13 +00004206 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004207 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00004208 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00004209 Block = Decision;
4210}
4211
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004212CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004213 AbstractConditionalOperator *E, bool BindToTemporary,
4214 TempDtorContext &Context) {
4215 VisitForTemporaryDtors(E->getCond(), false, Context);
4216 CFGBlock *ConditionBlock = Block;
4217 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00004218 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004219 TryResult NegatedVal = ConditionVal;
4220 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00004221
Manuel Klimekdeb02622014-08-08 07:37:13 +00004222 TempDtorContext TrueContext(
4223 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004224 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004225 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004226
Manuel Klimekb5616c92014-08-07 10:42:17 +00004227 Block = ConditionBlock;
4228 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004229 TempDtorContext FalseContext(
4230 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004231 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004232
Manuel Klimekb5616c92014-08-07 10:42:17 +00004233 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004234 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004235 } else if (TrueContext.TerminatorExpr) {
4236 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004237 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004238 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004239 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004240 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004241 return Block;
4242}
4243
Mike Stump31feda52009-07-17 01:31:16 +00004244/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
4245/// no successors or predecessors. If this is the first block created in the
4246/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004247CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00004248 bool first_block = begin() == end();
4249
4250 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004251 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00004252 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004253 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00004254
4255 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004256 if (first_block)
4257 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00004258
4259 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004260 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004261}
4262
David Blaikiee90195c2014-08-29 18:53:26 +00004263/// buildCFG - Constructs a CFG from an AST.
4264std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4265 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00004266 CFGBuilder Builder(C, BO);
4267 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00004268}
4269
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004270const CXXDestructorDecl *
4271CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004272 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004273 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00004274 case CFGElement::NewAllocator:
Peter Szecsi999a25f2017-08-19 11:19:16 +00004275 case CFGElement::LoopExit:
Matthias Gehre351c2182017-07-12 07:04:19 +00004276 case CFGElement::LifetimeEnds:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004277 case CFGElement::Statement:
4278 case CFGElement::Constructor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004279 llvm_unreachable("getDestructorDecl should only be used with "
4280 "ImplicitDtors");
4281 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00004282 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004283 QualType ty = var->getType();
Devin Coughlin6eb1ca72016-08-02 21:07:23 +00004284
4285 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4286 //
4287 // Lifetime-extending constructs are handled here. This works for a single
4288 // temporary in an initializer expression.
4289 if (ty->isReferenceType()) {
4290 if (const Expr *Init = var->getInit()) {
4291 ty = getReferenceInitTemporaryType(astContext, Init);
4292 }
4293 }
4294
Ted Kremeneke7d78882012-03-19 23:48:41 +00004295 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004296 ty = arrayType->getElementType();
4297 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004298 const RecordType *recordType = ty->getAs<RecordType>();
4299 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00004300 cast<CXXRecordDecl>(recordType->getDecl());
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004301 return classDecl->getDestructor();
4302 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004303 case CFGElement::DeleteDtor: {
4304 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
4305 QualType DTy = DE->getDestroyedType();
4306 DTy = DTy.getNonReferenceType();
4307 const CXXRecordDecl *classDecl =
4308 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
4309 return classDecl->getDestructor();
4310 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004311 case CFGElement::TemporaryDtor: {
4312 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00004313 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004314 const CXXTemporary *temp = bindExpr->getTemporary();
4315 return temp->getDestructor();
4316 }
4317 case CFGElement::BaseDtor:
4318 case CFGElement::MemberDtor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004319 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00004320 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004321 }
Ted Kremenek1676a042011-03-03 01:01:03 +00004322 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004323}
4324
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004325bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00004326 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
4327 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004328 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004329}
4330
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00004331//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004332// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00004333//===----------------------------------------------------------------------===//
4334
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004335CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004336 : ReachableBlock(IsReachable ? B : nullptr),
4337 UnreachableBlock(!IsReachable ? B : nullptr,
4338 B && IsReachable ? AB_Normal : AB_Unreachable) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004339
4340CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004341 : ReachableBlock(B),
4342 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
4343 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004344
4345void CFGBlock::addSuccessor(AdjacentBlock Succ,
4346 BumpVectorContext &C) {
4347 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004348 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004349
4350 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004351 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004352
4353 Succs.push_back(Succ, C);
4354}
4355
Ted Kremenekb0371852010-09-09 00:06:04 +00004356bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00004357 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004358 if (F.IgnoreNullPredecessors && !From)
4359 return true;
4360
4361 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004362 // If the 'To' has no label or is labeled but the label isn't a
4363 // CaseStmt then filter this edge.
4364 if (const SwitchStmt *S =
Ted Kremenek89794742011-03-07 22:04:39 +00004365 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004366 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00004367 const Stmt *L = To->getLabel();
4368 if (!L || !isa<CaseStmt>(L))
4369 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00004370 }
4371 }
4372 }
4373
4374 return false;
4375}
4376
4377//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004378// CFG pretty printing
4379//===----------------------------------------------------------------------===//
4380
Ted Kremenek7e776b12007-08-22 18:22:34 +00004381namespace {
4382
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004383class StmtPrinterHelper : public PrinterHelper {
Eugene Zelenko38c70522017-12-07 21:55:09 +00004384 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
4385 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
4386
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004387 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004388 DeclMapTy DeclMap;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004389 signed currentBlock = 0;
4390 unsigned currStmt = 0;
Chris Lattnerc61089a2009-06-30 01:26:17 +00004391 const LangOptions &LangOpts;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004392
Eugene Zelenko38c70522017-12-07 21:55:09 +00004393public:
Chris Lattnerc61089a2009-06-30 01:26:17 +00004394 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004395 : LangOpts(LO) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004396 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4397 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004398 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004399 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00004400 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4401 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004402 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00004403 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004404
Ted Kremenek96a7a592011-03-01 03:15:10 +00004405 switch (stmt->getStmtClass()) {
4406 case Stmt::DeclStmtClass:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004407 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4408 break;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004409 case Stmt::IfStmtClass: {
4410 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4411 if (var)
4412 DeclMap[var] = P;
4413 break;
4414 }
4415 case Stmt::ForStmtClass: {
4416 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4417 if (var)
4418 DeclMap[var] = P;
4419 break;
4420 }
4421 case Stmt::WhileStmtClass: {
4422 const VarDecl *var =
4423 cast<WhileStmt>(stmt)->getConditionVariable();
4424 if (var)
4425 DeclMap[var] = P;
4426 break;
4427 }
4428 case Stmt::SwitchStmtClass: {
4429 const VarDecl *var =
4430 cast<SwitchStmt>(stmt)->getConditionVariable();
4431 if (var)
4432 DeclMap[var] = P;
4433 break;
4434 }
4435 case Stmt::CXXCatchStmtClass: {
4436 const VarDecl *var =
4437 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4438 if (var)
4439 DeclMap[var] = P;
4440 break;
4441 }
4442 default:
4443 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004444 }
4445 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004446 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00004447 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004448 }
Mike Stump31feda52009-07-17 01:31:16 +00004449
Eugene Zelenko38c70522017-12-07 21:55:09 +00004450 ~StmtPrinterHelper() override = default;
Mike Stump31feda52009-07-17 01:31:16 +00004451
Chris Lattnerc61089a2009-06-30 01:26:17 +00004452 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004453 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00004454 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00004455
Craig Topperb45acb82014-03-14 06:02:07 +00004456 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004457 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004458
4459 if (I == StmtMap.end())
4460 return false;
Mike Stump31feda52009-07-17 01:31:16 +00004461
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004462 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004463 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004464 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004465 }
Mike Stump31feda52009-07-17 01:31:16 +00004466
Ted Kremenek60983dc2010-01-19 20:52:05 +00004467 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004468 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004469 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004470
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004471 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004472 DeclMapTy::iterator I = DeclMap.find(D);
4473
4474 if (I == DeclMap.end())
4475 return false;
4476
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004477 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004478 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004479 return false;
4480 }
4481
4482 OS << "[B" << I->second.first << "." << I->second.second << "]";
4483 return true;
4484 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004485};
4486
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004487class CFGBlockTerminatorPrint
Eugene Zelenko38c70522017-12-07 21:55:09 +00004488 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004489 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004490 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00004491 PrintingPolicy Policy;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004492
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004493public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004494 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00004495 const PrintingPolicy &Policy)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004496 : OS(os), Helper(helper), Policy(Policy) {
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00004497 this->Policy.IncludeNewlines = false;
4498 }
Mike Stump31feda52009-07-17 01:31:16 +00004499
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004500 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004501 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004502 if (Stmt *C = I->getCond())
4503 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004504 }
Mike Stump31feda52009-07-17 01:31:16 +00004505
Ted Kremenek9aae5132007-08-23 21:42:29 +00004506 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004507 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00004508 Terminator->printPretty(OS, Helper, Policy);
4509 }
4510
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00004511 void VisitDeclStmt(DeclStmt *DS) {
4512 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4513 OS << "static init " << VD->getName();
4514 }
4515
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004516 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004517 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004518 if (F->getInit())
4519 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004520 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004521 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004522 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004523 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00004524 if (F->getInc())
4525 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00004526 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00004527 }
Mike Stump31feda52009-07-17 01:31:16 +00004528
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004529 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004530 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004531 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004532 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004533 }
Mike Stump31feda52009-07-17 01:31:16 +00004534
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004535 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004536 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004537 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004538 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004539 }
Mike Stump31feda52009-07-17 01:31:16 +00004540
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004541 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00004542 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00004543 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004544 }
Mike Stump31feda52009-07-17 01:31:16 +00004545
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004546 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004547 OS << "try ...";
4548 }
4549
Nico Weber699670e2017-08-23 15:33:16 +00004550 void VisitSEHTryStmt(SEHTryStmt *CS) {
4551 OS << "__try ...";
4552 }
4553
John McCallc07a0c72011-02-17 10:25:35 +00004554 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00004555 if (Stmt *Cond = C->getCond())
4556 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004557 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004558 }
Mike Stump31feda52009-07-17 01:31:16 +00004559
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004560 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00004561 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004562 if (Stmt *Cond = C->getCond())
4563 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00004564 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00004565 }
Mike Stump31feda52009-07-17 01:31:16 +00004566
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004567 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004568 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004569 if (Stmt *T = I->getTarget())
4570 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004571 }
Mike Stump31feda52009-07-17 01:31:16 +00004572
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004573 void VisitBinaryOperator(BinaryOperator* B) {
4574 if (!B->isLogicalOp()) {
4575 VisitExpr(B);
4576 return;
4577 }
Mike Stump31feda52009-07-17 01:31:16 +00004578
Richard Trieuddd01ce2014-06-09 22:53:25 +00004579 if (B->getLHS())
4580 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004581
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004582 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004583 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00004584 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004585 return;
John McCalle3027922010-08-25 11:45:40 +00004586 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00004587 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004588 return;
4589 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004590 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00004591 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004592 }
Mike Stump31feda52009-07-17 01:31:16 +00004593
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004594 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00004595 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004596 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00004597
4598public:
4599 void print(CFGTerminator T) {
4600 if (T.isTemporaryDtorsBranch())
4601 OS << "(Temp Dtor) ";
4602 Visit(T.getStmt());
4603 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00004604};
Eugene Zelenko38c70522017-12-07 21:55:09 +00004605
4606} // namespace
Chris Lattnerc61089a2009-06-30 01:26:17 +00004607
Aaron Ballmanff924b02013-11-18 20:11:50 +00004608static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00004609 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00004610 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4611 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00004612 assert(S != nullptr && "Expecting non-null Stmt");
4613
Aaron Ballmanff924b02013-11-18 20:11:50 +00004614 // special printing for statement-expressions.
4615 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4616 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00004617
Benjamin Kramer5733e352015-07-18 17:09:36 +00004618 auto Children = Sub->children();
4619 if (Children.begin() != Children.end()) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00004620 OS << "({ ... ; ";
4621 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4622 OS << " })\n";
4623 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004624 }
4625 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00004626 // special printing for comma expressions.
4627 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4628 if (B->getOpcode() == BO_Comma) {
4629 OS << "... , ";
4630 Helper.handledStmt(B->getRHS(),OS);
4631 OS << '\n';
4632 return;
4633 }
4634 }
4635 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00004636
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004637 if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004638 OS << " (OperatorCall)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00004639 } else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004640 OS << " (BindTemporary)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00004641 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4642 OS << " (CXXConstructExpr, ";
4643 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
4644 if (const Stmt *S = CE->getTriggerStmt())
4645 Helper.handledStmt((const_cast<Stmt *>(S)), OS);
4646 else
4647 llvm_unreachable("Unexpected trigger kind!");
4648 OS << ", ";
4649 }
4650 OS << CCE->getType().getAsString() << ")";
4651 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
Ted Kremenek0ffba932011-12-21 19:32:38 +00004652 OS << " (" << CE->getStmtClassName() << ", "
4653 << CE->getCastKindName()
4654 << ", " << CE->getType().getAsString()
4655 << ")";
4656 }
Mike Stump31feda52009-07-17 01:31:16 +00004657
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004658 // Expressions need a newline.
4659 if (isa<Expr>(S))
4660 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00004661 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
4662 const CXXCtorInitializer *I = IE->getInitializer();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004663 if (I->isBaseInitializer())
4664 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
Jordan Rose69d0aed2013-10-22 23:19:47 +00004665 else if (I->isDelegatingInitializer())
4666 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
Francois Pichetd583da02010-12-04 09:14:42 +00004667 else OS << I->getAnyMember()->getName();
Mike Stump31feda52009-07-17 01:31:16 +00004668
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004669 OS << "(";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004670 if (Expr *IE = I->getInit())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004671 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004672 OS << ")";
4673
4674 if (I->isBaseInitializer())
4675 OS << " (Base initializer)\n";
Jordan Rose69d0aed2013-10-22 23:19:47 +00004676 else if (I->isDelegatingInitializer())
4677 OS << " (Delegating initializer)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004678 else OS << " (Member initializer)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004679 } else if (Optional<CFGAutomaticObjDtor> DE =
4680 E.getAs<CFGAutomaticObjDtor>()) {
4681 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00004682 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004683
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00004684 const Type* T = VD->getType().getTypePtr();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004685 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4686 T = RT->getPointeeType().getTypePtr();
Richard Smithf676e452012-07-24 21:02:14 +00004687 T = T->getBaseElementTypeUnsafe();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004688
4689 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4690 OS << " (Implicit destructor)\n";
Matthias Gehre351c2182017-07-12 07:04:19 +00004691 } else if (Optional<CFGLifetimeEnds> DE = E.getAs<CFGLifetimeEnds>()) {
4692 const VarDecl *VD = DE->getVarDecl();
4693 Helper.handleDecl(VD, OS);
4694
4695 OS << " (Lifetime ends)\n";
Peter Szecsi999a25f2017-08-19 11:19:16 +00004696 } else if (Optional<CFGLoopExit> LE = E.getAs<CFGLoopExit>()) {
4697 const Stmt *LoopStmt = LE->getLoopStmt();
4698 OS << LoopStmt->getStmtClassName() << " (LoopExit)\n";
Jordan Rosec9176072014-01-13 17:59:19 +00004699 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4700 OS << "CFGNewAllocator(";
4701 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4702 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4703 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00004704 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4705 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4706 if (!RD)
4707 return;
4708 CXXDeleteExpr *DelExpr =
4709 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00004710 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00004711 OS << "->~" << RD->getName().str() << "()";
4712 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004713 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4714 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004715 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004716 OS << " (Base object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004717 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4718 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00004719 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004720 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00004721 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004722 OS << " (Member object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004723 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4724 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00004725 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004726 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00004727 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004728 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004729}
Mike Stump31feda52009-07-17 01:31:16 +00004730
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004731static void print_block(raw_ostream &OS, const CFG* cfg,
4732 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00004733 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004734 bool ShowColors) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00004735 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00004736
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004737 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004738 if (ShowColors)
4739 OS.changeColor(raw_ostream::YELLOW, true);
4740
4741 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00004742
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004743 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004744 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004745 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004746 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004747 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004748 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00004749 else if (B.hasNoReturnElement())
4750 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004751 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00004752 OS << "]\n";
4753
4754 if (ShowColors)
4755 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00004756
Ted Kremenek71eca012007-08-29 23:20:49 +00004757 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004758 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004759 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004760 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004761
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004762 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004763 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004764 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004765 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004766 if (C->getLHS())
4767 C->getLHS()->printPretty(OS, &Helper,
4768 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004769 if (C->getRHS()) {
4770 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004771 C->getRHS()->printPretty(OS, &Helper,
4772 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004773 }
Mike Stump92244b02010-01-19 22:00:14 +00004774 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004775 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00004776 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004777 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00004778 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004779 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00004780 0);
4781 else
4782 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004783 OS << ")";
Nico Weber699670e2017-08-23 15:33:16 +00004784 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
4785 OS << "__except (";
4786 ES->getFilterExpr()->printPretty(OS, &Helper,
4787 PrintingPolicy(Helper.getLangOpts()), 0);
4788 OS << ")";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004789 } else
David Blaikie83d382b2011-09-23 05:06:16 +00004790 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00004791
Ted Kremenek71eca012007-08-29 23:20:49 +00004792 OS << ":\n";
4793 }
Mike Stump31feda52009-07-17 01:31:16 +00004794
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004795 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004796 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00004797
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004798 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4799 I != E ; ++I, ++j ) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004800 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004801 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004802 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004803
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004804 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00004805
Aaron Ballmanff924b02013-11-18 20:11:50 +00004806 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00004807
Ted Kremenek72be32a2011-12-22 23:33:52 +00004808 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004809 }
Mike Stump31feda52009-07-17 01:31:16 +00004810
Ted Kremenek71eca012007-08-29 23:20:49 +00004811 // Print the terminator of this block.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004812 if (B.getTerminator()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00004813 if (ShowColors)
4814 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00004815
Ted Kremenek72be32a2011-12-22 23:33:52 +00004816 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00004817
Aaron Ballmanff924b02013-11-18 20:11:50 +00004818 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00004819
Aaron Ballmanff924b02013-11-18 20:11:50 +00004820 PrintingPolicy PP(Helper.getLangOpts());
4821 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00004822 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004823 OS << '\n';
Ted Kremenek72be32a2011-12-22 23:33:52 +00004824
4825 if (ShowColors)
4826 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004827 }
Mike Stump31feda52009-07-17 01:31:16 +00004828
Ted Kremenek71eca012007-08-29 23:20:49 +00004829 if (print_edges) {
4830 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004831 if (!B.pred_empty()) {
4832 const raw_ostream::Colors Color = raw_ostream::BLUE;
4833 if (ShowColors)
4834 OS.changeColor(Color);
4835 OS << " Preds " ;
4836 if (ShowColors)
4837 OS.resetColor();
4838 OS << '(' << B.pred_size() << "):";
4839 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00004840
Ted Kremenek72be32a2011-12-22 23:33:52 +00004841 if (ShowColors)
4842 OS.changeColor(Color);
4843
4844 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4845 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004846 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004847 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00004848
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004849 CFGBlock *B = *I;
4850 bool Reachable = true;
4851 if (!B) {
4852 Reachable = false;
4853 B = I->getPossiblyUnreachableBlock();
4854 }
4855
4856 OS << " B" << B->getBlockID();
4857 if (!Reachable)
4858 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00004859 }
4860
4861 if (ShowColors)
4862 OS.resetColor();
4863
4864 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00004865 }
Mike Stump31feda52009-07-17 01:31:16 +00004866
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004867 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004868 if (!B.succ_empty()) {
4869 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4870 if (ShowColors)
4871 OS.changeColor(Color);
4872 OS << " Succs ";
4873 if (ShowColors)
4874 OS.resetColor();
4875 OS << '(' << B.succ_size() << "):";
4876 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004877
Ted Kremenek72be32a2011-12-22 23:33:52 +00004878 if (ShowColors)
4879 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00004880
Ted Kremenek72be32a2011-12-22 23:33:52 +00004881 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4882 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004883 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004884 OS << "\n ";
4885
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004886 CFGBlock *B = *I;
4887
4888 bool Reachable = true;
4889 if (!B) {
4890 Reachable = false;
4891 B = I->getPossiblyUnreachableBlock();
4892 }
4893
4894 if (B) {
4895 OS << " B" << B->getBlockID();
4896 if (!Reachable)
4897 OS << "(Unreachable)";
4898 }
4899 else {
4900 OS << " NULL";
4901 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00004902 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004903
Ted Kremenek72be32a2011-12-22 23:33:52 +00004904 if (ShowColors)
4905 OS.resetColor();
4906 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004907 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004908 }
Mike Stump31feda52009-07-17 01:31:16 +00004909}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004910
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004911/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004912void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4913 print(llvm::errs(), LO, ShowColors);
4914}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004915
4916/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004917void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004918 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00004919
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004920 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004921 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00004922
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004923 // Iterate through the CFGBlocks and print them one by one.
4924 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4925 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004926 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004927 continue;
Mike Stump31feda52009-07-17 01:31:16 +00004928
Aaron Ballmanff924b02013-11-18 20:11:50 +00004929 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004930 }
Mike Stump31feda52009-07-17 01:31:16 +00004931
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004932 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004933 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004934 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00004935 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00004936}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004937
4938/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004939void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4940 bool ShowColors) const {
4941 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00004942}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004943
Yaron Kerencdae9412016-01-29 19:38:18 +00004944LLVM_DUMP_METHOD void CFGBlock::dump() const {
Anna Zaksa6fea132014-06-13 23:47:38 +00004945 dump(getParent(), LangOptions(), false);
4946}
4947
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004948/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4949/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004950void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004951 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004952 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004953 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004954 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00004955}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004956
Ted Kremenek15647632008-01-30 23:02:42 +00004957/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004958void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00004959 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00004960 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00004961 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004962}
4963
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004964Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Marcin Swiderskia7d84a72010-10-29 05:21:47 +00004965 Stmt *Terminator = this->Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004966 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00004967 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004968
Craig Topper25542942014-05-20 04:30:07 +00004969 Expr *E = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004970
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004971 switch (Terminator->getStmtClass()) {
4972 default:
4973 break;
Mike Stump31feda52009-07-17 01:31:16 +00004974
Jordan Rosecf10ea82013-06-06 21:53:45 +00004975 case Stmt::CXXForRangeStmtClass:
4976 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4977 break;
4978
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004979 case Stmt::ForStmtClass:
4980 E = cast<ForStmt>(Terminator)->getCond();
4981 break;
Mike Stump31feda52009-07-17 01:31:16 +00004982
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004983 case Stmt::WhileStmtClass:
4984 E = cast<WhileStmt>(Terminator)->getCond();
4985 break;
Mike Stump31feda52009-07-17 01:31:16 +00004986
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004987 case Stmt::DoStmtClass:
4988 E = cast<DoStmt>(Terminator)->getCond();
4989 break;
Mike Stump31feda52009-07-17 01:31:16 +00004990
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004991 case Stmt::IfStmtClass:
4992 E = cast<IfStmt>(Terminator)->getCond();
4993 break;
Mike Stump31feda52009-07-17 01:31:16 +00004994
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004995 case Stmt::ChooseExprClass:
4996 E = cast<ChooseExpr>(Terminator)->getCond();
4997 break;
Mike Stump31feda52009-07-17 01:31:16 +00004998
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004999 case Stmt::IndirectGotoStmtClass:
5000 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
5001 break;
Mike Stump31feda52009-07-17 01:31:16 +00005002
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005003 case Stmt::SwitchStmtClass:
5004 E = cast<SwitchStmt>(Terminator)->getCond();
5005 break;
Mike Stump31feda52009-07-17 01:31:16 +00005006
John McCallc07a0c72011-02-17 10:25:35 +00005007 case Stmt::BinaryConditionalOperatorClass:
5008 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
5009 break;
5010
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005011 case Stmt::ConditionalOperatorClass:
5012 E = cast<ConditionalOperator>(Terminator)->getCond();
5013 break;
Mike Stump31feda52009-07-17 01:31:16 +00005014
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005015 case Stmt::BinaryOperatorClass: // '&&' and '||'
5016 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00005017 break;
Mike Stump31feda52009-07-17 01:31:16 +00005018
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00005019 case Stmt::ObjCForCollectionStmtClass:
Mike Stump31feda52009-07-17 01:31:16 +00005020 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005021 }
Mike Stump31feda52009-07-17 01:31:16 +00005022
Ted Kremenekec3bbf42014-03-29 00:35:20 +00005023 if (!StripParens)
5024 return E;
5025
Craig Topper25542942014-05-20 04:30:07 +00005026 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005027}
5028
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005029//===----------------------------------------------------------------------===//
5030// CFG Graphviz Visualization
5031//===----------------------------------------------------------------------===//
5032
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005033#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00005034static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005035#endif
5036
Chris Lattnerc61089a2009-06-30 01:26:17 +00005037void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005038#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00005039 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005040 GraphHelper = &H;
5041 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00005042 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005043#endif
5044}
5045
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005046namespace llvm {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005047
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005048template<>
5049struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005050 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Tobias Grosser9fc223a2009-11-30 14:16:05 +00005051
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005052 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005053#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005054 std::string OutSStr;
5055 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005056 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005057 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005058
5059 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
5060
5061 // Process string output to make it nicer...
5062 for (unsigned i = 0; i != OutStr.length(); ++i)
5063 if (OutStr[i] == '\n') { // Left justify
5064 OutStr[i] = '\\';
5065 OutStr.insert(OutStr.begin()+i+1, 'l');
5066 }
Mike Stump31feda52009-07-17 01:31:16 +00005067
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005068 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005069#else
Eugene Zelenko38c70522017-12-07 21:55:09 +00005070 return {};
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005071#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005072 }
5073};
Eugene Zelenko38c70522017-12-07 21:55:09 +00005074
5075} // namespace llvm