blob: 6cb63f2b175512c4d30b4568051f9829fd925981 [file] [log] [blame]
Ted Kremenek6f400242012-07-14 05:04:01 +00001 //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
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"
Ted Kremenek1a241d12011-02-23 05:11:46 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/PrettyPrinter.h"
21#include "clang/AST/StmtVisitor.h"
Jordan Rose5374c072013-08-19 16:27:28 +000022#include "clang/Basic/Builtins.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000023#include "llvm/ADT/DenseMap.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000024#include <memory>
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000026#include "llvm/Support/Allocator.h"
27#include "llvm/Support/Format.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "llvm/Support/GraphWriter.h"
29#include "llvm/Support/SaveAndRestore.h"
Ted Kremeneke5ccf9a2008-01-11 00:40:29 +000030
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +000031using namespace clang;
32
33namespace {
34
Ted Kremenek5ef32db2011-08-12 23:37:29 +000035static SourceLocation GetEndLoc(Decl *D) {
36 if (VarDecl *VD = dyn_cast<VarDecl>(D))
37 if (Expr *Ex = VD->getInit())
Ted Kremenek8889bb32008-08-06 23:20:50 +000038 return Ex->getSourceRange().getEnd();
Mike Stump31feda52009-07-17 01:31:16 +000039 return D->getLocation();
Ted Kremenek8889bb32008-08-06 23:20:50 +000040}
Ted Kremenekdc03bd02010-08-02 23:46:59 +000041
George Burgess IVced56e62015-10-01 18:47:52 +000042/// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
43/// or EnumConstantDecl from the given Expr. If it fails, returns nullptr.
44const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
45 E = E->IgnoreParens();
46 if (isa<IntegerLiteral>(E))
47 return E;
48 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
49 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
50 return nullptr;
51}
52
53/// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is
54/// an integer literal or an enum constant.
55///
56/// If this fails, at least one of the returned DeclRefExpr or Expr will be
57/// null.
58static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *>
59tryNormalizeBinaryOperator(const BinaryOperator *B) {
60 BinaryOperatorKind Op = B->getOpcode();
61
62 const Expr *MaybeDecl = B->getLHS();
63 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
64 // Expr looked like `0 == Foo` instead of `Foo == 0`
65 if (Constant == nullptr) {
66 // Flip the operator
67 if (Op == BO_GT)
68 Op = BO_LT;
69 else if (Op == BO_GE)
70 Op = BO_LE;
71 else if (Op == BO_LT)
72 Op = BO_GT;
73 else if (Op == BO_LE)
74 Op = BO_GE;
75
76 MaybeDecl = B->getRHS();
77 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
78 }
79
80 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts());
81 return std::make_tuple(D, Op, Constant);
82}
83
84/// For an expression `x == Foo && x == Bar`, this determines whether the
85/// `Foo` and `Bar` are either of the same enumeration type, or both integer
86/// literals.
87///
88/// It's an error to pass this arguments that are not either IntegerLiterals
89/// or DeclRefExprs (that have decls of type EnumConstantDecl)
90static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
91 // User intent isn't clear if they're mixing int literals with enum
92 // constants.
93 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2))
94 return false;
95
96 // Integer literal comparisons, regardless of literal type, are acceptable.
97 if (isa<IntegerLiteral>(E1))
98 return true;
99
100 // IntegerLiterals are handled above and only EnumConstantDecls are expected
101 // beyond this point
102 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
103 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
104 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
105
106 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
107 const DeclContext *DC1 = Decl1->getDeclContext();
108 const DeclContext *DC2 = Decl2->getDeclContext();
109
110 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
111 return DC1 == DC2;
112}
113
Ted Kremenek7c58d352011-03-10 01:14:11 +0000114class CFGBuilder;
115
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000116/// The CFG builder uses a recursive algorithm to build the CFG. When
117/// we process an expression, sometimes we know that we must add the
118/// subexpressions as block-level expressions. For example:
119///
120/// exp1 || exp2
121///
122/// When processing the '||' expression, we know that exp1 and exp2
123/// need to be added as block-level expressions, even though they
124/// might not normally need to be. AddStmtChoice records this
125/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
126/// the builder has an option not to add a subexpression as a
127/// block-level expression.
128///
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000129class AddStmtChoice {
130public:
Ted Kremenek8219b822010-12-16 07:46:53 +0000131 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000132
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000133 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000134
Ted Kremenek7c58d352011-03-10 01:14:11 +0000135 bool alwaysAdd(CFGBuilder &builder,
136 const Stmt *stmt) const;
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000137
138 /// Return a copy of this object, except with the 'always-add' bit
139 /// set as specified.
140 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
Ted Kremenek7c58d352011-03-10 01:14:11 +0000141 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000142 }
143
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000144private:
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000145 Kind kind;
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000146};
Mike Stump31feda52009-07-17 01:31:16 +0000147
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000148/// LocalScope - Node in tree of local scopes created for C++ implicit
149/// destructor calls generation. It contains list of automatic variables
150/// declared in the scope and link to position in previous scope this scope
151/// began in.
152///
153/// The process of creating local scopes is as follows:
154/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
155/// - Before processing statements in scope (e.g. CompoundStmt) create
156/// LocalScope object using CFGBuilder::ScopePos as link to previous scope
157/// and set CFGBuilder::ScopePos to the end of new scope,
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000158/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000159/// at this VarDecl,
160/// - For every normal (without jump) end of scope add to CFGBlock destructors
161/// for objects in the current scope,
162/// - For every jump add to CFGBlock destructors for objects
163/// between CFGBuilder::ScopePos and local scope position saved for jump
164/// target. Thanks to C++ restrictions on goto jumps we can be sure that
165/// jump target position will be on the path to root from CFGBuilder::ScopePos
166/// (adding any variable that doesn't need constructor to be called to
167/// LocalScope can break this assumption),
168///
169class LocalScope {
170public:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000171 typedef BumpVector<VarDecl*> AutomaticVarsTy;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000172
173 /// const_iterator - Iterates local scope backwards and jumps to previous
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000174 /// scope on reaching the beginning of currently iterated scope.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000175 class const_iterator {
176 const LocalScope* Scope;
177
178 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
179 /// Invalid iterator (with null Scope) has VarIter equal to 0.
180 unsigned VarIter;
181
182 public:
183 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
184 /// Incrementing invalid iterator is allowed and will result in invalid
185 /// iterator.
186 const_iterator()
Craig Topper25542942014-05-20 04:30:07 +0000187 : Scope(nullptr), VarIter(0) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000188
189 /// Create valid iterator. In case when S.Prev is an invalid iterator and
190 /// I is equal to 0, this will create invalid iterator.
191 const_iterator(const LocalScope& S, unsigned I)
192 : Scope(&S), VarIter(I) {
193 // Iterator to "end" of scope is not allowed. Handle it by going up
194 // in scopes tree possibly up to invalid iterator in the root.
195 if (VarIter == 0 && Scope)
196 *this = Scope->Prev;
197 }
198
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000199 VarDecl *const* operator->() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000200 assert (Scope && "Dereferencing invalid iterator is not allowed");
201 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
202 return &Scope->Vars[VarIter - 1];
203 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000204 VarDecl *operator*() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000205 return *this->operator->();
206 }
207
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000208 const_iterator &operator++() {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000209 if (!Scope)
210 return *this;
211
212 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
213 --VarIter;
214 if (VarIter == 0)
215 *this = Scope->Prev;
216 return *this;
217 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000218 const_iterator operator++(int) {
219 const_iterator P = *this;
220 ++*this;
221 return P;
222 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000223
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000224 bool operator==(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000225 return Scope == rhs.Scope && VarIter == rhs.VarIter;
226 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000227 bool operator!=(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000228 return !(*this == rhs);
229 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000230
Aaron Ballman67347662015-02-15 22:00:28 +0000231 explicit operator bool() const {
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000232 return *this != const_iterator();
233 }
234
235 int distance(const_iterator L);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000236 };
237
238 friend class const_iterator;
239
240private:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000241 BumpVectorContext ctx;
242
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000243 /// Automatic variables in order of declaration.
244 AutomaticVarsTy Vars;
245 /// Iterator to variable in previous scope that was declared just before
246 /// begin of this scope.
247 const_iterator Prev;
248
249public:
250 /// Constructs empty scope linked to previous scope in specified place.
David Blaikiec1334cc2015-08-13 22:12:21 +0000251 LocalScope(BumpVectorContext ctx, const_iterator P)
252 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000253
254 /// Begin of scope in direction of CFG building (backwards).
255 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000256
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000257 void addVar(VarDecl *VD) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000258 Vars.push_back(VD, ctx);
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000259 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000260};
261
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000262/// distance - Calculates distance from this to L. L must be reachable from this
263/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
264/// number of scopes between this and L.
265int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
266 int D = 0;
267 const_iterator F = *this;
268 while (F.Scope != L.Scope) {
Ted Kremenek50aa2d42011-08-12 14:41:23 +0000269 assert (F != const_iterator()
270 && "L iterator is not reachable from F iterator.");
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000271 D += F.VarIter;
272 F = F.Scope->Prev;
273 }
274 D += F.VarIter - L.VarIter;
275 return D;
276}
277
Jonathan Roelofs99bdd982015-05-19 18:51:56 +0000278/// Structure for specifying position in CFG during its build process. It
279/// consists of CFGBlock that specifies position in CFG and
280/// LocalScope::const_iterator that specifies position in LocalScope graph.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000281struct BlockScopePosPair {
Craig Topper25542942014-05-20 04:30:07 +0000282 BlockScopePosPair() : block(nullptr) {}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000283 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000284 : block(b), scopePosition(scopePos) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000285
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000286 CFGBlock *block;
287 LocalScope::const_iterator scopePosition;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000288};
289
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000290/// TryResult - a class representing a variant over the values
291/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
292/// and is used by the CFGBuilder to decide if a branch condition
293/// can be decided up front during CFG construction.
294class TryResult {
295 int X;
296public:
297 TryResult(bool b) : X(b ? 1 : 0) {}
298 TryResult() : X(-1) {}
299
300 bool isTrue() const { return X == 1; }
301 bool isFalse() const { return X == 0; }
302 bool isKnown() const { return X >= 0; }
303 void negate() {
304 assert(isKnown());
305 X ^= 0x1;
306 }
307};
308
Manuel Klimekdeb02622014-08-08 07:37:13 +0000309TryResult bothKnownTrue(TryResult R1, TryResult R2) {
310 if (!R1.isKnown() || !R2.isKnown())
311 return TryResult();
312 return TryResult(R1.isTrue() && R2.isTrue());
313}
314
Ted Kremenek8ae67872013-02-05 22:00:19 +0000315class reverse_children {
316 llvm::SmallVector<Stmt *, 12> childrenBuf;
317 ArrayRef<Stmt*> children;
318public:
319 reverse_children(Stmt *S);
320
321 typedef ArrayRef<Stmt*>::reverse_iterator iterator;
322 iterator begin() const { return children.rbegin(); }
323 iterator end() const { return children.rend(); }
324};
325
326
327reverse_children::reverse_children(Stmt *S) {
328 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
329 children = CE->getRawSubExprs();
330 return;
331 }
332 switch (S->getStmtClass()) {
Ted Kremenek7d86b9c2013-02-05 22:03:14 +0000333 // Note: Fill in this switch with more cases we want to optimize.
Ted Kremenek8ae67872013-02-05 22:00:19 +0000334 case Stmt::InitListExprClass: {
335 InitListExpr *IE = cast<InitListExpr>(S);
336 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
337 IE->getNumInits());
338 return;
339 }
340 default:
341 break;
342 }
343
344 // Default case for all other statements.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000345 for (Stmt *SubStmt : S->children())
346 childrenBuf.push_back(SubStmt);
Ted Kremenek8ae67872013-02-05 22:00:19 +0000347
348 // This needs to be done *after* childrenBuf has been populated.
349 children = childrenBuf;
350}
351
Ted Kremenekbe9b33b2008-08-04 22:51:42 +0000352/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000353/// The builder is stateful: an instance of the builder should be used to only
354/// construct a single CFG.
355///
356/// Example usage:
357///
358/// CFGBuilder builder;
Jonathan Roelofsab046c52015-07-27 16:05:36 +0000359/// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000360///
Mike Stump31feda52009-07-17 01:31:16 +0000361/// CFG construction is done via a recursive walk of an AST. We actually parse
362/// the AST in reverse order so that the successor of a basic block is
363/// constructed prior to its predecessor. This allows us to nicely capture
364/// implicit fall-throughs without extra basic blocks.
Ted Kremenek1b8ac852007-08-21 22:06:14 +0000365///
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000366class CFGBuilder {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000367 typedef BlockScopePosPair JumpTarget;
368 typedef BlockScopePosPair JumpSource;
369
Mike Stump0d76d072009-07-20 23:24:15 +0000370 ASTContext *Context;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000371 std::unique_ptr<CFG> cfg;
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000372
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000373 CFGBlock *Block;
374 CFGBlock *Succ;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000375 JumpTarget ContinueJumpTarget;
376 JumpTarget BreakJumpTarget;
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000377 CFGBlock *SwitchTerminatedBlock;
378 CFGBlock *DefaultCaseBlock;
379 CFGBlock *TryTerminatedBlock;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000380
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000381 // Current position in local scope.
382 LocalScope::const_iterator ScopePos;
383
384 // LabelMap records the mapping from Label expressions to their jump targets.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000385 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
Ted Kremenek8a632182007-08-21 23:26:17 +0000386 LabelMapTy LabelMap;
Mike Stump31feda52009-07-17 01:31:16 +0000387
388 // A list of blocks that end with a "goto" that must be backpatched to their
389 // resolved targets upon completion of CFG construction.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000390 typedef std::vector<JumpSource> BackpatchBlocksTy;
Ted Kremenek8a632182007-08-21 23:26:17 +0000391 BackpatchBlocksTy BackpatchBlocks;
Mike Stump31feda52009-07-17 01:31:16 +0000392
Ted Kremenekeda180e22007-08-28 19:26:49 +0000393 // A list of labels whose address has been taken (for indirect gotos).
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000394 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
Ted Kremenekeda180e22007-08-28 19:26:49 +0000395 LabelSetTy AddressTakenLabels;
Mike Stump31feda52009-07-17 01:31:16 +0000396
Zhongxing Xud38fb842010-09-16 03:28:18 +0000397 bool badCFG;
Ted Kremenekf9d82902011-03-10 01:14:05 +0000398 const CFG::BuildOptions &BuildOpts;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000399
400 // State to track for building switch statements.
401 bool switchExclusivelyCovered;
Ted Kremenekbe528712011-03-04 01:03:41 +0000402 Expr::EvalResult *switchCond;
Ted Kremeneka099c592011-03-10 03:50:34 +0000403
404 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000405 const Stmt *lastLookup;
Zhongxing Xud38fb842010-09-16 03:28:18 +0000406
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000407 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
408 // during construction of branches for chained logical operators.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000409 typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
410 CachedBoolEvalsTy CachedBoolEvals;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000411
Mike Stump31feda52009-07-17 01:31:16 +0000412public:
Ted Kremenekf9d82902011-03-10 01:14:05 +0000413 explicit CFGBuilder(ASTContext *astContext,
414 const CFG::BuildOptions &buildOpts)
415 : Context(astContext), cfg(new CFG()), // crew a new CFG
Craig Topper25542942014-05-20 04:30:07 +0000416 Block(nullptr), Succ(nullptr),
417 SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr),
418 TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts),
419 switchExclusivelyCovered(false), switchCond(nullptr),
420 cachedEntry(nullptr), lastLookup(nullptr) {}
Mike Stump31feda52009-07-17 01:31:16 +0000421
Ted Kremenek9aae5132007-08-23 21:42:29 +0000422 // buildCFG - Used by external clients to construct the CFG.
David Blaikiee90195c2014-08-29 18:53:26 +0000423 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
Mike Stump31feda52009-07-17 01:31:16 +0000424
Ted Kremeneka099c592011-03-10 03:50:34 +0000425 bool alwaysAdd(const Stmt *stmt);
426
Ted Kremenek93668002009-07-17 22:18:43 +0000427private:
428 // Visitors to walk an AST and construct the CFG.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000429 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
430 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000431 CFGBlock *VisitBreakStmt(BreakStmt *B);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000432 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000433 CFGBlock *VisitCaseStmt(CaseStmt *C);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000434 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000435 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
John McCallc07a0c72011-02-17 10:25:35 +0000436 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
437 AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000438 CFGBlock *VisitContinueStmt(ContinueStmt *C);
Ted Kremenek6f400242012-07-14 05:04:01 +0000439 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
440 AddStmtChoice asc);
441 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
442 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
Jordan Rosec9176072014-01-13 17:59:19 +0000443 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
Jordan Rosed2f40792013-09-03 17:00:57 +0000444 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000445 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
446 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
447 AddStmtChoice asc);
448 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
449 AddStmtChoice asc);
450 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
451 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000452 CFGBlock *VisitDeclStmt(DeclStmt *DS);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000453 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
Ted Kremenek21822592009-07-17 18:20:32 +0000454 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
455 CFGBlock *VisitDoStmt(DoStmt *D);
Ted Kremenek6f400242012-07-14 05:04:01 +0000456 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000457 CFGBlock *VisitForStmt(ForStmt *F);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000458 CFGBlock *VisitGotoStmt(GotoStmt *G);
Ted Kremenek93668002009-07-17 22:18:43 +0000459 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000460 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000461 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
462 CFGBlock *VisitLabelStmt(LabelStmt *L);
Ted Kremenek6f400242012-07-14 05:04:01 +0000463 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000464 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000465 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
466 Stmt *Term,
467 CFGBlock *TrueBlock,
468 CFGBlock *FalseBlock);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000469 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000470 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
471 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
472 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
473 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000474 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000475 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
John McCallfe96e0b2011-11-06 09:01:30 +0000476 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Ted Kremenek6f400242012-07-14 05:04:01 +0000477 CFGBlock *VisitReturnStmt(ReturnStmt *R);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000478 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000479 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000480 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
481 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000482 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000483 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000484
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000485 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
486 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000487 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000488 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000489
Manuel Klimekb5616c92014-08-07 10:42:17 +0000490 /// When creating the CFG for temporary destructors, we want to mirror the
491 /// branch structure of the corresponding constructor calls.
492 /// Thus, while visiting a statement for temporary destructors, we keep a
493 /// context to keep track of the following information:
494 /// - whether a subexpression is executed unconditionally
495 /// - if a subexpression is executed conditionally, the first
496 /// CXXBindTemporaryExpr we encounter in that subexpression (which
497 /// corresponds to the last temporary destructor we have to call for this
498 /// subexpression) and the CFG block at that point (which will become the
499 /// successor block when inserting the decision point).
500 ///
501 /// That way, we can build the branch structure for temporary destructors as
502 /// follows:
503 /// 1. If a subexpression is executed unconditionally, we add the temporary
504 /// destructor calls to the current block.
505 /// 2. If a subexpression is executed conditionally, when we encounter a
506 /// CXXBindTemporaryExpr:
507 /// a) If it is the first temporary destructor call in the subexpression,
508 /// we remember the CXXBindTemporaryExpr and the current block in the
509 /// TempDtorContext; we start a new block, and insert the temporary
510 /// destructor call.
511 /// b) Otherwise, add the temporary destructor call to the current block.
512 /// 3. When we finished visiting a conditionally executed subexpression,
513 /// and we found at least one temporary constructor during the visitation
514 /// (2.a has executed), we insert a decision block that uses the
515 /// CXXBindTemporaryExpr as terminator, and branches to the current block
516 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
517 /// branches to the stored successor.
518 struct TempDtorContext {
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000519 TempDtorContext()
520 : IsConditional(false), KnownExecuted(true), Succ(nullptr),
521 TerminatorExpr(nullptr) {}
Manuel Klimekdeb02622014-08-08 07:37:13 +0000522
523 TempDtorContext(TryResult KnownExecuted)
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000524 : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr),
525 TerminatorExpr(nullptr) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000526
527 /// Returns whether we need to start a new branch for a temporary destructor
Eric Christopher2c4555a2015-06-19 01:52:53 +0000528 /// call. This is the case when the temporary destructor is
Manuel Klimekb5616c92014-08-07 10:42:17 +0000529 /// conditionally executed, and it is the first one we encounter while
530 /// visiting a subexpression - other temporary destructors at the same level
531 /// will be added to the same block and are executed under the same
532 /// condition.
533 bool needsTempDtorBranch() const {
534 return IsConditional && !TerminatorExpr;
535 }
536
537 /// Remember the successor S of a temporary destructor decision branch for
538 /// the corresponding CXXBindTemporaryExpr E.
539 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
540 Succ = S;
541 TerminatorExpr = E;
542 }
543
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000544 const bool IsConditional;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000545 const TryResult KnownExecuted;
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000546 CFGBlock *Succ;
547 CXXBindTemporaryExpr *TerminatorExpr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000548 };
549
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000550 // Visitors to walk an AST and generate destructors of temporaries in
551 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000552 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
553 TempDtorContext &Context);
554 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
555 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
556 TempDtorContext &Context);
557 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
558 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
559 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
560 AbstractConditionalOperator *E, bool BindToTemporary,
561 TempDtorContext &Context);
562 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
563 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000564
Ted Kremenek6065ef62008-04-28 18:00:46 +0000565 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000566 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000567 badCFG = true;
568 return Block;
569 }
Mike Stump31feda52009-07-17 01:31:16 +0000570
Ted Kremenek93668002009-07-17 22:18:43 +0000571 void autoCreateBlock() { if (!Block) Block = createBlock(); }
572 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000573 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000574
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000575 CFGBlock *addStmt(Stmt *S) {
576 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000577 }
Alexis Hunt1d792652011-01-08 20:30:50 +0000578 CFGBlock *addInitializer(CXXCtorInitializer *I);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000579 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000580 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000581 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000582
Marcin Swiderski5e415732010-09-30 23:05:00 +0000583 // Local scopes creation.
584 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
585
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000586 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000587 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
588 LocalScope* Scope = nullptr);
589 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000590
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000591 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000592
593 // Interface to CFGBlock - adding CFGElements.
Ted Kremenek37881932011-04-04 23:29:12 +0000594 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000595 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000596 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000597
Jordy Rose17347372011-06-10 08:49:37 +0000598 // All block-level expressions should have already been IgnoreParens()ed.
599 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000600 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000601 }
Alexis Hunt1d792652011-01-08 20:30:50 +0000602 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000603 B->appendInitializer(I, cfg->getBumpVectorContext());
604 }
Jordan Rosec9176072014-01-13 17:59:19 +0000605 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
606 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
607 }
Marcin Swiderski20b88732010-10-05 05:37:00 +0000608 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
609 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
610 }
611 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
612 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
613 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000614 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
615 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
616 }
Chandler Carruthad747252011-09-13 06:09:01 +0000617 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
618 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
619 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000620
Jordan Rosed2f40792013-09-03 17:00:57 +0000621 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
622 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
623 }
624
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000625 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000626 LocalScope::const_iterator B, LocalScope::const_iterator E);
627
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000628 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
629 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
630 cfg->getBumpVectorContext());
631 }
632
633 /// Add a reachable successor to a block, with the alternate variant that is
634 /// unreachable.
635 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
636 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
637 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000638 }
Mike Stump11289f42009-09-09 15:08:12 +0000639
Richard Trieuf935b562014-04-05 05:17:01 +0000640 /// \brief Find a relational comparison with an expression evaluating to a
641 /// boolean and a constant other than 0 and 1.
642 /// e.g. if ((x < y) == 10)
643 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
644 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
645 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
646
647 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
648 const Expr *BoolExpr = RHSExpr;
649 bool IntFirst = true;
650 if (!IntLiteral) {
651 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
652 BoolExpr = LHSExpr;
653 IntFirst = false;
654 }
655
656 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
657 return TryResult();
658
659 llvm::APInt IntValue = IntLiteral->getValue();
660 if ((IntValue == 1) || (IntValue == 0))
661 return TryResult();
662
663 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
664 !IntValue.isNegative();
665
666 BinaryOperatorKind Bok = B->getOpcode();
667 if (Bok == BO_GT || Bok == BO_GE) {
668 // Always true for 10 > bool and bool > -1
669 // Always false for -1 > bool and bool > 10
670 return TryResult(IntFirst == IntLarger);
671 } else {
672 // Always true for -1 < bool and bool < 10
673 // Always false for 10 < bool and bool < -1
674 return TryResult(IntFirst != IntLarger);
675 }
676 }
677
Jordan Rose7afd71e2014-05-20 17:31:11 +0000678 /// Find an incorrect equality comparison. Either with an expression
679 /// evaluating to a boolean and a constant other than 0 and 1.
680 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
681 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000682 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
683 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
684 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
685
686 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
687 const Expr *BoolExpr = RHSExpr;
688
689 if (!IntLiteral) {
690 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
691 BoolExpr = LHSExpr;
692 }
693
Jordan Rose7afd71e2014-05-20 17:31:11 +0000694 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000695 return TryResult();
696
Jordan Rose7afd71e2014-05-20 17:31:11 +0000697 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
698 if (BitOp && (BitOp->getOpcode() == BO_And ||
699 BitOp->getOpcode() == BO_Or)) {
700 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
701 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
702
703 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
704
705 if (!IntLiteral2)
706 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
707
708 if (!IntLiteral2)
709 return TryResult();
710
711 llvm::APInt L1 = IntLiteral->getValue();
712 llvm::APInt L2 = IntLiteral2->getValue();
713 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
714 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
715 if (BuildOpts.Observer)
716 BuildOpts.Observer->compareBitwiseEquality(B,
717 B->getOpcode() != BO_EQ);
718 TryResult(B->getOpcode() != BO_EQ);
719 }
720 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
721 llvm::APInt IntValue = IntLiteral->getValue();
722 if ((IntValue == 1) || (IntValue == 0)) {
723 return TryResult();
724 }
725 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000726 }
727
Jordan Rose7afd71e2014-05-20 17:31:11 +0000728 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000729 }
730
731 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
732 const llvm::APSInt &Value1,
733 const llvm::APSInt &Value2) {
734 assert(Value1.isSigned() == Value2.isSigned());
735 switch (Relation) {
736 default:
737 return TryResult();
738 case BO_EQ:
739 return TryResult(Value1 == Value2);
740 case BO_NE:
741 return TryResult(Value1 != Value2);
742 case BO_LT:
743 return TryResult(Value1 < Value2);
744 case BO_LE:
745 return TryResult(Value1 <= Value2);
746 case BO_GT:
747 return TryResult(Value1 > Value2);
748 case BO_GE:
749 return TryResult(Value1 >= Value2);
750 }
751 }
752
753 /// \brief Find a pair of comparison expressions with or without parentheses
754 /// with a shared variable and constants and a logical operator between them
755 /// that always evaluates to either true or false.
756 /// e.g. if (x != 3 || x != 4)
757 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
758 assert(B->isLogicalOp());
759 const BinaryOperator *LHS =
760 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
761 const BinaryOperator *RHS =
762 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
763 if (!LHS || !RHS)
764 return TryResult();
765
766 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
767 return TryResult();
768
George Burgess IVced56e62015-10-01 18:47:52 +0000769 const DeclRefExpr *Decl1;
770 const Expr *Expr1;
771 BinaryOperatorKind BO1;
772 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000773
George Burgess IVced56e62015-10-01 18:47:52 +0000774 if (!Decl1 || !Expr1)
Richard Trieuf935b562014-04-05 05:17:01 +0000775 return TryResult();
776
George Burgess IVced56e62015-10-01 18:47:52 +0000777 const DeclRefExpr *Decl2;
778 const Expr *Expr2;
779 BinaryOperatorKind BO2;
780 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000781
George Burgess IVced56e62015-10-01 18:47:52 +0000782 if (!Decl2 || !Expr2)
Richard Trieuf935b562014-04-05 05:17:01 +0000783 return TryResult();
784
785 // Check that it is the same variable on both sides.
786 if (Decl1->getDecl() != Decl2->getDecl())
787 return TryResult();
788
George Burgess IVced56e62015-10-01 18:47:52 +0000789 // Make sure the user's intent is clear (e.g. they're comparing against two
790 // int literals, or two things from the same enum)
791 if (!areExprTypesCompatible(Expr1, Expr2))
792 return TryResult();
793
Richard Trieuf935b562014-04-05 05:17:01 +0000794 llvm::APSInt L1, L2;
795
George Burgess IVced56e62015-10-01 18:47:52 +0000796 if (!Expr1->EvaluateAsInt(L1, *Context) ||
797 !Expr2->EvaluateAsInt(L2, *Context))
Richard Trieuf935b562014-04-05 05:17:01 +0000798 return TryResult();
799
800 // Can't compare signed with unsigned or with different bit width.
801 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
802 return TryResult();
803
804 // Values that will be used to determine if result of logical
805 // operator is always true/false
806 const llvm::APSInt Values[] = {
807 // Value less than both Value1 and Value2
808 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
809 // L1
810 L1,
811 // Value between Value1 and Value2
812 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
813 L1.isUnsigned()),
814 // L2
815 L2,
816 // Value greater than both Value1 and Value2
817 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
818 };
819
820 // Check whether expression is always true/false by evaluating the following
821 // * variable x is less than the smallest literal.
822 // * variable x is equal to the smallest literal.
823 // * Variable x is between smallest and largest literal.
824 // * Variable x is equal to the largest literal.
825 // * Variable x is greater than largest literal.
826 bool AlwaysTrue = true, AlwaysFalse = true;
827 for (unsigned int ValueIndex = 0;
828 ValueIndex < sizeof(Values) / sizeof(Values[0]);
829 ++ValueIndex) {
830 llvm::APSInt Value = Values[ValueIndex];
831 TryResult Res1, Res2;
832 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
833 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
834
835 if (!Res1.isKnown() || !Res2.isKnown())
836 return TryResult();
837
838 if (B->getOpcode() == BO_LAnd) {
839 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
840 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
841 } else {
842 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
843 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
844 }
845 }
846
847 if (AlwaysTrue || AlwaysFalse) {
848 if (BuildOpts.Observer)
849 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
850 return TryResult(AlwaysTrue);
851 }
852 return TryResult();
853 }
854
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000855 /// Try and evaluate an expression to an integer constant.
856 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
857 if (!BuildOpts.PruneTriviallyFalseEdges)
858 return false;
859 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +0000860 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +0000861 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000862 }
Mike Stump11289f42009-09-09 15:08:12 +0000863
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000864 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +0000865 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000866 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +0000867 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000868 S->isTypeDependent() || S->isValueDependent())
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000869 return TryResult();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000870
871 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
872 if (Bop->isLogicalOp()) {
873 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000874 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
875 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000876 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +0000877
878 // Retrieve result at first, or the map might be updated.
879 TryResult Result = evaluateAsBooleanConditionNoCache(S);
880 CachedBoolEvals[S] = Result; // update or insert
881 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000882 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000883 else {
884 switch (Bop->getOpcode()) {
885 default: break;
886 // For 'x & 0' and 'x * 0', we can determine that
887 // the value is always false.
888 case BO_Mul:
889 case BO_And: {
890 // If either operand is zero, we know the value
891 // must be false.
892 llvm::APSInt IntVal;
893 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +0000894 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000895 return TryResult(false);
896 }
897 }
898 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +0000899 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000900 return TryResult(false);
901 }
902 }
903 }
904 break;
905 }
906 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000907 }
908
909 return evaluateAsBooleanConditionNoCache(S);
910 }
911
912 /// \brief Evaluate as boolean \param E without using the cache.
913 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
914 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
915 if (Bop->isLogicalOp()) {
916 TryResult LHS = tryEvaluateBool(Bop->getLHS());
917 if (LHS.isKnown()) {
918 // We were able to evaluate the LHS, see if we can get away with not
919 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
920 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
921 return LHS.isTrue();
922
923 TryResult RHS = tryEvaluateBool(Bop->getRHS());
924 if (RHS.isKnown()) {
925 if (Bop->getOpcode() == BO_LOr)
926 return LHS.isTrue() || RHS.isTrue();
927 else
928 return LHS.isTrue() && RHS.isTrue();
929 }
930 } else {
931 TryResult RHS = tryEvaluateBool(Bop->getRHS());
932 if (RHS.isKnown()) {
933 // We can't evaluate the LHS; however, sometimes the result
934 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
935 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
936 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +0000937 } else {
938 TryResult BopRes = checkIncorrectLogicOperator(Bop);
939 if (BopRes.isKnown())
940 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000941 }
942 }
943
944 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000945 } else if (Bop->isEqualityOp()) {
946 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
947 if (BopRes.isKnown())
948 return BopRes.isTrue();
949 } else if (Bop->isRelationalOp()) {
950 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
951 if (BopRes.isKnown())
952 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000953 }
954 }
955
956 bool Result;
957 if (E->EvaluateAsBooleanCondition(Result, *Context))
958 return Result;
959
960 return TryResult();
Mike Stump773582d2009-07-23 23:25:26 +0000961 }
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000962
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000963};
Mike Stump31feda52009-07-17 01:31:16 +0000964
Ted Kremeneka099c592011-03-10 03:50:34 +0000965inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
966 const Stmt *stmt) const {
967 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
968}
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000969
Ted Kremeneka099c592011-03-10 03:50:34 +0000970bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000971 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
972
Ted Kremeneka099c592011-03-10 03:50:34 +0000973 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +0000974 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000975
976 if (lastLookup == stmt) {
977 if (cachedEntry) {
978 assert(cachedEntry->first == stmt);
979 return true;
980 }
Ted Kremenek8b46c002011-07-19 14:18:43 +0000981 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000982 }
Ted Kremeneka099c592011-03-10 03:50:34 +0000983
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000984 lastLookup = stmt;
985
986 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +0000987 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
988
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000989 if (!fb) {
990 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +0000991 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +0000992 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000993 }
Ted Kremeneka099c592011-03-10 03:50:34 +0000994
995 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000996 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +0000997 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +0000998 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000999 }
1000
Ted Kremeneka099c592011-03-10 03:50:34 +00001001 cachedEntry = &*itr;
1002 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +00001003}
1004
Douglas Gregor4619e432008-12-05 23:32:09 +00001005// FIXME: Add support for dependent-sized array types in C++?
1006// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +00001007static const VariableArrayType *FindVA(const Type *t) {
1008 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1009 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001010 if (vat->getSizeExpr())
1011 return vat;
Mike Stump31feda52009-07-17 01:31:16 +00001012
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001013 t = vt->getElementType().getTypePtr();
1014 }
Mike Stump31feda52009-07-17 01:31:16 +00001015
Craig Topper25542942014-05-20 04:30:07 +00001016 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001017}
Mike Stump31feda52009-07-17 01:31:16 +00001018
1019/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1020/// arbitrary statement. Examples include a single expression or a function
1021/// body (compound statement). The ownership of the returned CFG is
1022/// transferred to the caller. If CFG construction fails, this method returns
1023/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +00001024std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +00001025 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +00001026 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +00001027 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001028
Mike Stump31feda52009-07-17 01:31:16 +00001029 // Create an empty block that will serve as the exit block for the CFG. Since
1030 // this is the first block added to the CFG, it will be implicitly registered
1031 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +00001032 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +00001033 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +00001034 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +00001035
Marcin Swiderski20b88732010-10-05 05:37:00 +00001036 if (BuildOpts.AddImplicitDtors)
1037 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1038 addImplicitDtorsForDestructor(DD);
1039
Ted Kremenek9aae5132007-08-23 21:42:29 +00001040 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001041 CFGBlock *B = addStmt(Statement);
1042
1043 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001044 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001045
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001046 // For C++ constructor add initializers to CFG.
1047 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
Pete Cooper57d3f142015-07-30 17:22:52 +00001048 for (auto *I : llvm::reverse(CD->inits())) {
1049 B = addInitializer(I);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001050 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001051 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001052 }
1053 }
1054
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001055 if (B)
1056 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001057
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001058 // Backpatch the gotos whose label -> block mappings we didn't know when we
1059 // encountered them.
1060 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1061 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001062
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001063 CFGBlock *B = I->block;
Rafael Espindola210de572013-03-27 15:37:54 +00001064 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001065 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00001066
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001067 // If there is no target for the goto, then we are looking at an
1068 // incomplete AST. Handle this by not registering a successor.
1069 if (LI == LabelMap.end()) continue;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001070
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001071 JumpTarget JT = LI->second;
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001072 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1073 JT.scopePosition);
1074 addSuccessor(B, JT.block);
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001075 }
1076
1077 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001078 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001079 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1080 E = AddressTakenLabels.end(); I != E; ++I ) {
1081
1082 // Lookup the target block.
1083 LabelMapTy::iterator LI = LabelMap.find(*I);
1084
1085 // If there is no target block that contains label, then we are looking
1086 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001087 if (LI == LabelMap.end()) continue;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001088
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001089 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001090 }
Mike Stump31feda52009-07-17 01:31:16 +00001091
Mike Stump31feda52009-07-17 01:31:16 +00001092 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001093 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001094
David Blaikiee90195c2014-08-29 18:53:26 +00001095 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001096}
Mike Stump31feda52009-07-17 01:31:16 +00001097
Ted Kremenek9aae5132007-08-23 21:42:29 +00001098/// createBlock - Used to lazily create blocks that are connected
1099/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001100CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1101 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001102 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001103 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001104 return B;
1105}
Mike Stump31feda52009-07-17 01:31:16 +00001106
Chandler Carrutha70991b2011-09-13 09:13:49 +00001107/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1108/// CFG. It is *not* connected to the current (global) successor, and instead
1109/// directly tied to the exit block in order to be reachable.
1110CFGBlock *CFGBuilder::createNoReturnBlock() {
1111 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001112 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001113 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001114 return B;
1115}
1116
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001117/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001118CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001119 if (!BuildOpts.AddInitializers)
1120 return Block;
1121
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001122 bool HasTemporaries = false;
1123
1124 // Destructors of temporaries in initialization expression should be called
1125 // after initialization finishes.
1126 Expr *Init = I->getInit();
1127 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001128 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001129
Jordan Rose6d671cc2012-09-05 22:55:23 +00001130 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001131 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001132 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001133 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1134 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001135 }
1136 }
1137
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001138 autoCreateBlock();
1139 appendInitializer(Block, I);
1140
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001141 if (Init) {
Ted Kremenek8219b822010-12-16 07:46:53 +00001142 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001143 // For expression with temporaries go directly to subexpression to omit
1144 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001145 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1146 }
Enrico Pertosofaed8012015-06-03 10:12:40 +00001147 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1148 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1149 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1150 // may cause the same Expr to appear more than once in the CFG. Doing it
1151 // here is safe because there's only one initializer per field.
1152 autoCreateBlock();
1153 appendStmt(Block, Default);
1154 if (Stmt *Child = Default->getExpr())
1155 if (CFGBlock *R = Visit(Child))
1156 Block = R;
1157 return Block;
1158 }
1159 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001160 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001161 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001162
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001163 return Block;
1164}
1165
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001166/// \brief Retrieve the type of the temporary object whose lifetime was
1167/// extended by a local reference with the given initializer.
1168static QualType getReferenceInitTemporaryType(ASTContext &Context,
1169 const Expr *Init) {
1170 while (true) {
1171 // Skip parentheses.
1172 Init = Init->IgnoreParens();
1173
1174 // Skip through cleanups.
1175 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1176 Init = EWC->getSubExpr();
1177 continue;
1178 }
1179
1180 // Skip through the temporary-materialization expression.
1181 if (const MaterializeTemporaryExpr *MTE
1182 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1183 Init = MTE->GetTemporaryExpr();
1184 continue;
1185 }
1186
1187 // Skip derived-to-base and no-op casts.
1188 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1189 if ((CE->getCastKind() == CK_DerivedToBase ||
1190 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1191 CE->getCastKind() == CK_NoOp) &&
1192 Init->getType()->isRecordType()) {
1193 Init = CE->getSubExpr();
1194 continue;
1195 }
1196 }
1197
1198 // Skip member accesses into rvalues.
1199 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1200 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1201 Init = ME->getBase();
1202 continue;
1203 }
1204 }
1205
1206 break;
1207 }
1208
1209 return Init->getType();
1210}
1211
Marcin Swiderski5e415732010-09-30 23:05:00 +00001212/// addAutomaticObjDtors - Add to current block automatic objects destructors
1213/// for objects in range of local scope positions. Use S as trigger statement
1214/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001215void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001216 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001217 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001218 return;
1219
Marcin Swiderski5e415732010-09-30 23:05:00 +00001220 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001221 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001222
Chandler Carruthad747252011-09-13 06:09:01 +00001223 // We need to append the destructors in reverse order, but any one of them
1224 // may be a no-return destructor which changes the CFG. As a result, buffer
1225 // this sequence up and replay them in reverse order when appending onto the
1226 // CFGBlock(s).
1227 SmallVector<VarDecl*, 10> Decls;
1228 Decls.reserve(B.distance(E));
1229 for (LocalScope::const_iterator I = B; I != E; ++I)
1230 Decls.push_back(*I);
1231
1232 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1233 E = Decls.rend();
1234 I != E; ++I) {
1235 // If this destructor is marked as a no-return destructor, we need to
1236 // create a new block for the destructor which does not have as a successor
1237 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001238 QualType Ty = (*I)->getType();
1239 if (Ty->isReferenceType()) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001240 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001241 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001242 Ty = Context->getBaseElementType(Ty);
1243
Richard Trieu95a192a2015-05-28 00:14:02 +00001244 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001245 Block = createNoReturnBlock();
1246 else
Chandler Carruthad747252011-09-13 06:09:01 +00001247 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001248
1249 appendAutomaticObjDtor(Block, *I, S);
1250 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001251}
1252
Marcin Swiderski20b88732010-10-05 05:37:00 +00001253/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1254/// base and member objects in destructor.
1255void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1256 assert (BuildOpts.AddImplicitDtors
1257 && "Can be called only when dtors should be added");
1258 const CXXRecordDecl *RD = DD->getParent();
1259
1260 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001261 for (const auto &VI : RD->vbases()) {
1262 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001263 if (!CD->hasTrivialDestructor()) {
1264 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001265 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001266 }
1267 }
1268
1269 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001270 for (const auto &BI : RD->bases()) {
1271 if (!BI.isVirtual()) {
1272 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001273 if (!CD->hasTrivialDestructor()) {
1274 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001275 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001276 }
1277 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001278 }
1279
1280 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001281 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001282 // Check for constant size array. Set type to array element type.
1283 QualType QT = FI->getType();
1284 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1285 if (AT->getSize() == 0)
1286 continue;
1287 QT = AT->getElementType();
1288 }
1289
1290 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001291 if (!CD->hasTrivialDestructor()) {
1292 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001293 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001294 }
1295 }
1296}
1297
Marcin Swiderski5e415732010-09-30 23:05:00 +00001298/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1299/// way return valid LocalScope object.
1300LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
David Blaikiec1334cc2015-08-13 22:12:21 +00001301 if (Scope)
1302 return Scope;
1303 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1304 return new (alloc.Allocate<LocalScope>())
1305 LocalScope(BumpVectorContext(alloc), ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001306}
1307
1308/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Zhongxing Xu81714f22010-10-01 03:00:16 +00001309/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001310void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001311 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001312 return;
1313
Craig Topper25542942014-05-20 04:30:07 +00001314 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001315
1316 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001317 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001318 for (auto *BI : CS->body()) {
1319 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001320 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001321 Scope = addLocalScopeForDeclStmt(DS, Scope);
1322 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001323 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001324 }
1325
1326 // For any other statement scope will be implicit and as such will be
1327 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001328 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001329 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001330}
1331
1332/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1333/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001334LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001335 LocalScope* Scope) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001336 if (!BuildOpts.AddImplicitDtors)
1337 return Scope;
1338
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001339 for (auto *DI : DS->decls())
1340 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001341 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001342 return Scope;
1343}
1344
1345/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1346/// create add scope for automatic objects and temporary objects bound to
1347/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001348LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001349 LocalScope* Scope) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001350 if (!BuildOpts.AddImplicitDtors)
1351 return Scope;
1352
1353 // Check if variable is local.
1354 switch (VD->getStorageClass()) {
1355 case SC_None:
1356 case SC_Auto:
1357 case SC_Register:
1358 break;
1359 default: return Scope;
1360 }
1361
1362 // Check for const references bound to temporary. Set type to pointee.
1363 QualType QT = VD->getType();
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001364 if (QT.getTypePtr()->isReferenceType()) {
Richard Smith5a0ef782013-06-27 21:43:17 +00001365 // Attempt to determine whether this declaration lifetime-extends a
1366 // temporary.
1367 //
1368 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1369 // temporaries, and a single declaration can extend multiple temporaries.
1370 // We should look at the storage duration on each nested
1371 // MaterializeTemporaryExpr instead.
1372 const Expr *Init = VD->getInit();
1373 if (!Init)
1374 return Scope;
1375 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
1376 Init = EWC->getSubExpr();
1377 if (!isa<MaterializeTemporaryExpr>(Init))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001378 return Scope;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001379
Richard Smith5a0ef782013-06-27 21:43:17 +00001380 // Lifetime-extending a temporary.
1381 QT = getReferenceInitTemporaryType(*Context, Init);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001382 }
1383
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001384 // Check for constant size array. Set type to array element type.
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001385 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001386 if (AT->getSize() == 0)
1387 return Scope;
1388 QT = AT->getElementType();
1389 }
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001390
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001391 // Check if type is a C++ class with non-trivial destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001392 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
David Blaikie0f2ae782012-01-24 04:51:48 +00001393 if (!CD->hasTrivialDestructor()) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001394 // Add the variable to scope
1395 Scope = createOrReuseLocalScope(Scope);
1396 Scope->addVar(VD);
1397 ScopePos = Scope->begin();
1398 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001399 return Scope;
1400}
1401
1402/// addLocalScopeAndDtors - For given statement add local scope for it and
1403/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001404void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001405 if (!BuildOpts.AddImplicitDtors)
1406 return;
1407
1408 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001409 addLocalScopeForStmt(S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001410 addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
1411}
1412
Marcin Swiderski321a7072010-09-30 22:54:37 +00001413/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1414/// variables with automatic storage duration to CFGBlock's elements vector.
1415/// Elements will be prepended to physical beginning of the vector which
1416/// happens to be logical end. Use blocks terminator as statement that specifies
1417/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001418/// FIXME: This mechanism for adding automatic destructors doesn't handle
1419/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001420void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00001421 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Chandler Carruthad747252011-09-13 06:09:01 +00001422 BumpVectorContext &C = cfg->getBumpVectorContext();
1423 CFGBlock::iterator InsertPos
1424 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1425 for (LocalScope::const_iterator I = B; I != E; ++I)
1426 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1427 Blk->getTerminator());
Marcin Swiderski321a7072010-09-30 22:54:37 +00001428}
1429
Ted Kremenek93668002009-07-17 22:18:43 +00001430/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00001431/// blocks for ternary operators, &&, and ||. We also process "," and
1432/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001433CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001434 if (!S) {
1435 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00001436 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001437 }
Jordy Rose17347372011-06-10 08:49:37 +00001438
1439 if (Expr *E = dyn_cast<Expr>(S))
1440 S = E->IgnoreParens();
1441
Ted Kremenek93668002009-07-17 22:18:43 +00001442 switch (S->getStmtClass()) {
1443 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001444 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001445
1446 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001447 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001448
John McCallc07a0c72011-02-17 10:25:35 +00001449 case Stmt::BinaryConditionalOperatorClass:
1450 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1451
Ted Kremenek93668002009-07-17 22:18:43 +00001452 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001453 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001454
Ted Kremenek93668002009-07-17 22:18:43 +00001455 case Stmt::BlockExprClass:
Ted Kremeneke2499842012-04-12 20:03:44 +00001456 return VisitNoRecurse(cast<Expr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001457
Ted Kremenek93668002009-07-17 22:18:43 +00001458 case Stmt::BreakStmtClass:
1459 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001460
Ted Kremenek93668002009-07-17 22:18:43 +00001461 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00001462 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00001463 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001464 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001465 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001466
Ted Kremenek93668002009-07-17 22:18:43 +00001467 case Stmt::CaseStmtClass:
1468 return VisitCaseStmt(cast<CaseStmt>(S));
1469
1470 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001471 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001472
Ted Kremenek93668002009-07-17 22:18:43 +00001473 case Stmt::CompoundStmtClass:
1474 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001475
Ted Kremenek93668002009-07-17 22:18:43 +00001476 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001477 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001478
Ted Kremenek93668002009-07-17 22:18:43 +00001479 case Stmt::ContinueStmtClass:
1480 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001481
Ted Kremenekb27378c2010-01-19 20:40:33 +00001482 case Stmt::CXXCatchStmtClass:
1483 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1484
John McCall5d413782010-12-06 08:20:24 +00001485 case Stmt::ExprWithCleanupsClass:
1486 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00001487
Jordan Rosee5d53932012-08-23 18:10:53 +00001488 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00001489 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00001490 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1491 // called function's declaration, not by the caller. If we simply add
1492 // this expression to the CFG, we could end up with the same Expr
1493 // appearing multiple times.
1494 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00001495 //
1496 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1497 // expression to be used in the same function (through aggregate
1498 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00001499 return VisitStmt(S, asc);
1500
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001501 case Stmt::CXXBindTemporaryExprClass:
1502 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1503
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001504 case Stmt::CXXConstructExprClass:
1505 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1506
Jordan Rosec9176072014-01-13 17:59:19 +00001507 case Stmt::CXXNewExprClass:
1508 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1509
Jordan Rosed2f40792013-09-03 17:00:57 +00001510 case Stmt::CXXDeleteExprClass:
1511 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1512
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001513 case Stmt::CXXFunctionalCastExprClass:
1514 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1515
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001516 case Stmt::CXXTemporaryObjectExprClass:
1517 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1518
Ted Kremenekb27378c2010-01-19 20:40:33 +00001519 case Stmt::CXXThrowExprClass:
1520 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001521
Ted Kremenekb27378c2010-01-19 20:40:33 +00001522 case Stmt::CXXTryStmtClass:
1523 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001524
Richard Smith02e85f32011-04-14 22:09:26 +00001525 case Stmt::CXXForRangeStmtClass:
1526 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1527
Ted Kremenek93668002009-07-17 22:18:43 +00001528 case Stmt::DeclStmtClass:
1529 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001530
Ted Kremenek93668002009-07-17 22:18:43 +00001531 case Stmt::DefaultStmtClass:
1532 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001533
Ted Kremenek93668002009-07-17 22:18:43 +00001534 case Stmt::DoStmtClass:
1535 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001536
Ted Kremenek93668002009-07-17 22:18:43 +00001537 case Stmt::ForStmtClass:
1538 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001539
Ted Kremenek93668002009-07-17 22:18:43 +00001540 case Stmt::GotoStmtClass:
1541 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001542
Ted Kremenek93668002009-07-17 22:18:43 +00001543 case Stmt::IfStmtClass:
1544 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001545
Ted Kremenek8219b822010-12-16 07:46:53 +00001546 case Stmt::ImplicitCastExprClass:
1547 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001548
Ted Kremenek93668002009-07-17 22:18:43 +00001549 case Stmt::IndirectGotoStmtClass:
1550 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001551
Ted Kremenek93668002009-07-17 22:18:43 +00001552 case Stmt::LabelStmtClass:
1553 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001554
Ted Kremenekda76a942012-04-12 20:34:52 +00001555 case Stmt::LambdaExprClass:
1556 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1557
Ted Kremenek5868ec62010-04-11 17:02:10 +00001558 case Stmt::MemberExprClass:
1559 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1560
Ted Kremenek04268232011-11-05 00:10:15 +00001561 case Stmt::NullStmtClass:
1562 return Block;
1563
Ted Kremenek93668002009-07-17 22:18:43 +00001564 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00001565 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1566
Ted Kremenek5022f1d2012-03-06 23:40:47 +00001567 case Stmt::ObjCAutoreleasePoolStmtClass:
1568 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1569
Ted Kremenek93668002009-07-17 22:18:43 +00001570 case Stmt::ObjCAtSynchronizedStmtClass:
1571 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001572
Ted Kremenek93668002009-07-17 22:18:43 +00001573 case Stmt::ObjCAtThrowStmtClass:
1574 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001575
Ted Kremenek93668002009-07-17 22:18:43 +00001576 case Stmt::ObjCAtTryStmtClass:
1577 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001578
Ted Kremenek93668002009-07-17 22:18:43 +00001579 case Stmt::ObjCForCollectionStmtClass:
1580 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001581
Ted Kremenek04268232011-11-05 00:10:15 +00001582 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00001583 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00001584
John McCallfe96e0b2011-11-06 09:01:30 +00001585 case Stmt::PseudoObjectExprClass:
1586 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1587
Ted Kremenek93668002009-07-17 22:18:43 +00001588 case Stmt::ReturnStmtClass:
1589 return VisitReturnStmt(cast<ReturnStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001590
Peter Collingbournee190dee2011-03-11 19:24:49 +00001591 case Stmt::UnaryExprOrTypeTraitExprClass:
1592 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1593 asc);
Mike Stump11289f42009-09-09 15:08:12 +00001594
Ted Kremenek93668002009-07-17 22:18:43 +00001595 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001596 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001597
Ted Kremenek93668002009-07-17 22:18:43 +00001598 case Stmt::SwitchStmtClass:
1599 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001600
Zhanyong Wan6dace612010-11-22 08:45:56 +00001601 case Stmt::UnaryOperatorClass:
1602 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1603
Ted Kremenek93668002009-07-17 22:18:43 +00001604 case Stmt::WhileStmtClass:
1605 return VisitWhileStmt(cast<WhileStmt>(S));
1606 }
1607}
Mike Stump11289f42009-09-09 15:08:12 +00001608
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001609CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001610 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001611 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001612 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00001613 }
Mike Stump11289f42009-09-09 15:08:12 +00001614
Ted Kremenek93668002009-07-17 22:18:43 +00001615 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00001616}
Mike Stump31feda52009-07-17 01:31:16 +00001617
Ted Kremenek93668002009-07-17 22:18:43 +00001618/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00001619CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1620 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00001621
Ted Kremenek8ae67872013-02-05 22:00:19 +00001622 // Visit the children in their reverse order so that they appear in
1623 // left-to-right (natural) order in the CFG.
1624 reverse_children RChildren(S);
1625 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1626 I != E; ++I) {
1627 if (Stmt *Child = *I)
1628 if (CFGBlock *R = Visit(Child))
1629 B = R;
1630 }
1631 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00001632}
Mike Stump11289f42009-09-09 15:08:12 +00001633
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001634CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1635 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00001636 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00001637
Ted Kremenek7c58d352011-03-10 01:14:11 +00001638 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001639 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001640 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00001641 }
Ted Kremenek81e14852007-08-27 19:46:09 +00001642
Ted Kremenek9aae5132007-08-23 21:42:29 +00001643 return Block;
1644}
Mike Stump11289f42009-09-09 15:08:12 +00001645
Zhanyong Wan6dace612010-11-22 08:45:56 +00001646CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00001647 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001648 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00001649 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001650 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00001651 }
1652
Ted Kremenek8219b822010-12-16 07:46:53 +00001653 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00001654}
1655
Ted Kremeneka16436f2012-07-14 05:04:06 +00001656CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1657 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1658 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00001659
Ted Kremeneka16436f2012-07-14 05:04:06 +00001660 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001661 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00001662
Craig Topper25542942014-05-20 04:30:07 +00001663 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1664 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001665}
1666
1667std::pair<CFGBlock*, CFGBlock*>
1668CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1669 Stmt *Term,
1670 CFGBlock *TrueBlock,
1671 CFGBlock *FalseBlock) {
1672
1673 // Introspect the RHS. If it is a nested logical operation, we recursively
1674 // build the CFG using this function. Otherwise, resort to default
1675 // CFG construction behavior.
1676 Expr *RHS = B->getRHS()->IgnoreParens();
1677 CFGBlock *RHSBlock, *ExitBlock;
1678
1679 do {
1680 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1681 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001682 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00001683 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1684 break;
1685 }
1686
1687 // The RHS is not a nested logical operation. Don't push the terminator
1688 // down further, but instead visit RHS and construct the respective
1689 // pieces of the CFG, and link up the RHSBlock with the terminator
1690 // we have been provided.
1691 ExitBlock = RHSBlock = createBlock(false);
1692
1693 if (!Term) {
1694 assert(TrueBlock == FalseBlock);
1695 addSuccessor(RHSBlock, TrueBlock);
1696 }
1697 else {
1698 RHSBlock->setTerminator(Term);
1699 TryResult KnownVal = tryEvaluateBool(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001700 if (!KnownVal.isKnown())
1701 KnownVal = tryEvaluateBool(B);
Ted Kremenek782f0032014-03-07 02:25:53 +00001702 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1703 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00001704 }
1705
1706 Block = RHSBlock;
1707 RHSBlock = addStmt(RHS);
1708 }
1709 while (false);
1710
1711 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001712 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00001713
1714 // Generate the blocks for evaluating the LHS.
1715 Expr *LHS = B->getLHS()->IgnoreParens();
1716
1717 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1718 if (B_LHS->isLogicalOp()) {
1719 if (B->getOpcode() == BO_LOr)
1720 FalseBlock = RHSBlock;
1721 else
1722 TrueBlock = RHSBlock;
1723
1724 // For the LHS, treat 'B' as the terminator that we want to sink
1725 // into the nested branch. The RHS always gets the top-most
1726 // terminator.
1727 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1728 }
1729
1730 // Create the block evaluating the LHS.
1731 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00001732 CFGBlock *LHSBlock = createBlock(false);
1733 LHSBlock->setTerminator(B);
1734
Ted Kremeneka16436f2012-07-14 05:04:06 +00001735 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001736 CFGBlock *EntryLHSBlock = addStmt(LHS);
1737
1738 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001739 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001740
1741 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00001742 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001743
1744 // Now link the LHSBlock with RHSBlock.
1745 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00001746 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
1747 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00001748 } else {
1749 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00001750 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
1751 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00001752 }
1753
Ted Kremenekb50e7162012-07-14 05:04:10 +00001754 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001755}
1756
Ted Kremenekb50e7162012-07-14 05:04:10 +00001757
Ted Kremeneka16436f2012-07-14 05:04:06 +00001758CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1759 AddStmtChoice asc) {
1760 // && or ||
1761 if (B->isLogicalOp())
1762 return VisitLogicalOperator(B);
1763
Zhanyong Wan59f09c72010-11-22 19:32:14 +00001764 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00001765 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001766 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00001767 addStmt(B->getRHS());
1768 return addStmt(B->getLHS());
1769 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00001770
1771 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001772 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001773 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001774 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001775 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001776 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00001777 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001778 }
Mike Stump11289f42009-09-09 15:08:12 +00001779
Ted Kremenek7c58d352011-03-10 01:14:11 +00001780 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00001781 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001782 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00001783 }
1784
Zhongxing Xud95ccd52010-10-27 03:23:10 +00001785 CFGBlock *RBlock = Visit(B->getRHS());
1786 CFGBlock *LBlock = Visit(B->getLHS());
1787 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1788 // containing a DoStmt, and the LHS doesn't create a new block, then we should
1789 // return RBlock. Otherwise we'll incorrectly return NULL.
1790 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00001791}
1792
Ted Kremeneke2499842012-04-12 20:03:44 +00001793CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001794 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00001795 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001796 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00001797 }
1798 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00001799}
1800
Ted Kremenek93668002009-07-17 22:18:43 +00001801CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1802 // "break" is a control-flow statement. Thus we stop processing the current
1803 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001804 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001805 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001806
Ted Kremenek93668002009-07-17 22:18:43 +00001807 // Now create a new block that ends with the break statement.
1808 Block = createBlock(false);
1809 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00001810
Ted Kremenek93668002009-07-17 22:18:43 +00001811 // If there is no target for the break, then we are looking at an incomplete
1812 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001813 if (BreakJumpTarget.block) {
1814 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1815 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001816 } else
Ted Kremenek93668002009-07-17 22:18:43 +00001817 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00001818
1819
Ted Kremenek9aae5132007-08-23 21:42:29 +00001820 return Block;
1821}
Mike Stump11289f42009-09-09 15:08:12 +00001822
Sebastian Redl31ad7542011-03-13 17:09:40 +00001823static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00001824 QualType Ty = E->getType();
1825 if (Ty->isFunctionPointerType())
1826 Ty = Ty->getAs<PointerType>()->getPointeeType();
1827 else if (Ty->isBlockPointerType())
1828 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001829
Mike Stump04c68512010-01-21 15:20:48 +00001830 const FunctionType *FT = Ty->getAs<FunctionType>();
1831 if (FT) {
1832 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00001833 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smithf623c962012-04-17 00:58:00 +00001834 Proto->isNothrow(Ctx))
Mike Stump04c68512010-01-21 15:20:48 +00001835 return false;
1836 }
1837 return true;
1838}
1839
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001840CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00001841 // Compute the callee type.
1842 QualType calleeType = C->getCallee()->getType();
1843 if (calleeType == Context->BoundMemberTy) {
1844 QualType boundType = Expr::findBoundMemberType(C->getCallee());
1845
1846 // We should only get a null bound type if processing a dependent
1847 // CFG. Recover by assuming nothing.
1848 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00001849 }
Mike Stump8c5d7992009-07-25 21:26:53 +00001850
John McCallc67067f2011-05-11 07:19:11 +00001851 // If this is a call to a no-return function, this stops the block here.
1852 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1853
Mike Stump04c68512010-01-21 15:20:48 +00001854 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00001855
1856 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001857 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00001858 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00001859 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00001860 }
1861
Jordan Rose5374c072013-08-19 16:27:28 +00001862 // If this is a call to a builtin function, it might not actually evaluate
1863 // its arguments. Don't add them to the CFG if this is the case.
1864 bool OmitArguments = false;
1865
Mike Stump92244b02010-01-19 22:00:14 +00001866 if (FunctionDecl *FD = C->getDirectCallee()) {
Richard Smith10876ef2013-01-17 01:30:42 +00001867 if (FD->isNoReturn())
Mike Stump8c5d7992009-07-25 21:26:53 +00001868 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00001869 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00001870 AddEHEdge = false;
Jordan Rose5374c072013-08-19 16:27:28 +00001871 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
1872 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00001873 }
Mike Stump8c5d7992009-07-25 21:26:53 +00001874
Sebastian Redl31ad7542011-03-13 17:09:40 +00001875 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00001876 AddEHEdge = false;
1877
Jordan Rose5374c072013-08-19 16:27:28 +00001878 if (OmitArguments) {
1879 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
1880 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
1881 autoCreateBlock();
1882 appendStmt(Block, C);
1883 return Visit(C->getCallee());
1884 }
1885
1886 if (!NoReturn && !AddEHEdge) {
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001887 return VisitStmt(C, asc.withAlwaysAdd(true));
Jordan Rose5374c072013-08-19 16:27:28 +00001888 }
Mike Stump11289f42009-09-09 15:08:12 +00001889
Mike Stump92244b02010-01-19 22:00:14 +00001890 if (Block) {
1891 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001892 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001893 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00001894 }
Mike Stump11289f42009-09-09 15:08:12 +00001895
Chandler Carrutha70991b2011-09-13 09:13:49 +00001896 if (NoReturn)
1897 Block = createNoReturnBlock();
1898 else
1899 Block = createBlock();
1900
Ted Kremenek2866bab2011-03-10 01:14:08 +00001901 appendStmt(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00001902
Mike Stump04c68512010-01-21 15:20:48 +00001903 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00001904 // Add exceptional edges.
1905 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001906 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00001907 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001908 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00001909 }
Mike Stump11289f42009-09-09 15:08:12 +00001910
Mike Stump8c5d7992009-07-25 21:26:53 +00001911 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00001912}
Ted Kremenek9aae5132007-08-23 21:42:29 +00001913
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001914CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1915 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001916 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001917 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001918 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001919 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001920
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001921 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00001922 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001923 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001924 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001925 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001926 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001927
Ted Kremenek21822592009-07-17 18:20:32 +00001928 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001929 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001930 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001931 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001932 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001933
Ted Kremenek21822592009-07-17 18:20:32 +00001934 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00001935 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001936 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00001937 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
1938 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00001939 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00001940 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00001941}
Mike Stump11289f42009-09-09 15:08:12 +00001942
1943
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001944CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Marcin Swiderski667ffec2010-10-01 00:23:17 +00001945 addLocalScopeAndDtors(C);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001946 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00001947
1948 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1949 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00001950 // If we hit a segment of code just containing ';' (NullStmts), we can
1951 // get a null block back. In such cases, just use the LastBlock
1952 if (CFGBlock *newBlock = addStmt(*I))
1953 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00001954
Ted Kremenekce499c22009-08-27 23:16:26 +00001955 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001956 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001957 }
Mike Stump92244b02010-01-19 22:00:14 +00001958
Ted Kremenek93668002009-07-17 22:18:43 +00001959 return LastBlock;
1960}
Mike Stump11289f42009-09-09 15:08:12 +00001961
John McCallc07a0c72011-02-17 10:25:35 +00001962CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001963 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00001964 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00001965 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00001966
Ted Kremenek51d40b02009-07-17 18:15:54 +00001967 // Create the confluence block that will "merge" the results of the ternary
1968 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001969 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001970 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001971 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001972 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001973
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001974 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00001975
Ted Kremenek51d40b02009-07-17 18:15:54 +00001976 // Create a block for the LHS expression if there is an LHS expression. A
1977 // GCC extension allows LHS to be NULL, causing the condition to be the
1978 // value that is returned instead.
1979 // e.g: x ?: y is shorthand for: x ? x : y;
1980 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001981 Block = nullptr;
1982 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00001983 const Expr *trueExpr = C->getTrueExpr();
1984 if (trueExpr != opaqueValue) {
1985 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001986 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001987 return nullptr;
1988 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00001989 }
Ted Kremenekd8138012011-02-24 03:09:15 +00001990 else
1991 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00001992
Ted Kremenek51d40b02009-07-17 18:15:54 +00001993 // Create the block for the RHS expression.
1994 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001995 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001996 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001997 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001998
Richard Smithf676e452012-07-24 21:02:14 +00001999 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2000 if (BinaryOperator *Cond =
2001 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2002 if (Cond->isLogicalOp())
2003 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2004
Ted Kremenek51d40b02009-07-17 18:15:54 +00002005 // Create the block that will contain the condition.
2006 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00002007
Mike Stump773582d2009-07-23 23:25:26 +00002008 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002009 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00002010 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2011 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00002012 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00002013 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00002014
Ted Kremenekd8138012011-02-24 03:09:15 +00002015 if (opaqueValue) {
2016 // Run the condition expression if it's not trivially expressed in
2017 // terms of the opaque value (or if there is no opaque value).
2018 if (condExpr != opaqueValue)
2019 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00002020
Ted Kremenekd8138012011-02-24 03:09:15 +00002021 // Before that, run the common subexpression if there was one.
2022 // At least one of this or the above will be run.
2023 return addStmt(BCO->getCommon());
2024 }
2025
2026 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00002027}
2028
Ted Kremenek93668002009-07-17 22:18:43 +00002029CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00002030 // Check if the Decl is for an __label__. If so, elide it from the
2031 // CFG entirely.
2032 if (isa<LabelDecl>(*DS->decl_begin()))
2033 return Block;
2034
Ted Kremenek3a601142011-05-24 20:41:31 +00002035 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002036 if (DS->isSingleDecl())
2037 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00002038
Craig Topper25542942014-05-20 04:30:07 +00002039 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002040
Jordan Rose8c6c8a92012-07-20 18:50:48 +00002041 // Build an individual DeclStmt for each decl.
2042 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2043 E = DS->decl_rend();
2044 I != E; ++I) {
Ted Kremenek93668002009-07-17 22:18:43 +00002045 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
2046 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
2047 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
Mike Stump11289f42009-09-09 15:08:12 +00002048
Ted Kremenek93668002009-07-17 22:18:43 +00002049 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2050 // automatically freed with the CFG.
2051 DeclGroupRef DG(*I);
2052 Decl *D = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002053 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
Ted Kremenek93668002009-07-17 22:18:43 +00002054 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00002055 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00002056
Ted Kremenek93668002009-07-17 22:18:43 +00002057 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002058 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002059 }
Mike Stump11289f42009-09-09 15:08:12 +00002060
2061 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002062}
Mike Stump11289f42009-09-09 15:08:12 +00002063
Ted Kremenek93668002009-07-17 22:18:43 +00002064/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002065/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002066CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002067 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002068 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002069
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002070 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002071 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2072 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002073 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002074 }
Mike Stump11289f42009-09-09 15:08:12 +00002075
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002076 bool HasTemporaries = false;
2077
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002078 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002079 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002080
2081 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2082 // For static variables, we need to create a branch to track
2083 // whether or not they are initialized.
2084 if (Block) {
2085 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002086 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002087 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002088 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002089 }
2090 blockAfterStaticInit = Succ;
2091 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002092
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002093 // Destructors of temporaries in initialization expression should be called
2094 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002095 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002096 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002097 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002098
Jordan Rose6d671cc2012-09-05 22:55:23 +00002099 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002100 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002101 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002102 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2103 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002104 }
2105 }
2106
2107 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002108 appendStmt(Block, DS);
Ted Kremenek213d0532012-03-22 05:57:43 +00002109
2110 // Keep track of the last non-null block, as 'Block' can be nulled out
2111 // if the initializer expression is something like a 'while' in a
2112 // statement-expression.
2113 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002114
Ted Kremenek93668002009-07-17 22:18:43 +00002115 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002116 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002117 // For expression with temporaries go directly to subexpression to omit
2118 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002119 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2120 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2121 LastBlock = newBlock;
2122 }
2123 else {
2124 if (CFGBlock *newBlock = Visit(Init))
2125 LastBlock = newBlock;
2126 }
Ted Kremenek93668002009-07-17 22:18:43 +00002127 }
Mike Stump11289f42009-09-09 15:08:12 +00002128
Ted Kremenek93668002009-07-17 22:18:43 +00002129 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002130 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002131 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002132 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2133 LastBlock = newBlock;
2134 }
Mike Stump11289f42009-09-09 15:08:12 +00002135
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002136 // Remove variable from local scope.
2137 if (ScopePos && VD == *ScopePos)
2138 ++ScopePos;
2139
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002140 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002141 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002142 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002143 Block = createBlock(false);
2144 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002145 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002146 addSuccessor(Block, B);
2147 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002148 }
2149
2150 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002151}
2152
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002153CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002154 // We may see an if statement in the middle of a basic block, or it may be the
2155 // first statement we are processing. In either case, we create a new basic
2156 // block. First, we create the blocks for the then...else statements, and
2157 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002158 // middle of a block, we stop processing that block. That block is then the
2159 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002160
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002161 // Save local scope position because in case of condition variable ScopePos
2162 // won't be restored when traversing AST.
2163 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2164
2165 // Create local scope for possible condition variable.
2166 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002167 if (VarDecl *VD = I->getConditionVariable()) {
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002168 LocalScope::const_iterator BeginScopePos = ScopePos;
2169 addLocalScopeForVarDecl(VD);
2170 addAutomaticObjDtors(ScopePos, BeginScopePos, I);
2171 }
2172
Chris Lattner57540c52011-04-15 05:22:18 +00002173 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002174 // block.
2175 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002176 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002177 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002178 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002179 }
Mike Stump31feda52009-07-17 01:31:16 +00002180
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002181 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002182 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002183
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002184 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002185 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002186
Ted Kremenek9aae5132007-08-23 21:42:29 +00002187 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002188 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002189 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002190
2191 // If branch is not a compound statement create implicit scope
2192 // and add destructors.
2193 if (!isa<CompoundStmt>(Else))
2194 addLocalScopeAndDtors(Else);
2195
Ted Kremenek93668002009-07-17 22:18:43 +00002196 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002197
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002198 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2199 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002200 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002201 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002202 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002203 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002204 }
Mike Stump31feda52009-07-17 01:31:16 +00002205
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002206 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002207 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002208 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002209 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002210 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002211 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002212 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002213
2214 // If branch is not a compound statement create implicit scope
2215 // and add destructors.
2216 if (!isa<CompoundStmt>(Then))
2217 addLocalScopeAndDtors(Then);
2218
Ted Kremenek93668002009-07-17 22:18:43 +00002219 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002220
Ted Kremenek1b379512009-04-01 03:52:47 +00002221 if (!ThenBlock) {
2222 // We can reach here if the "then" body has all NullStmts.
2223 // Create an empty block so we can distinguish between true and false
2224 // branches in path-sensitive analyses.
2225 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002226 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002227 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002228 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002229 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002230 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002231 }
2232
Ted Kremenekb50e7162012-07-14 05:04:10 +00002233 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2234 // having these handle the actual control-flow jump. Note that
2235 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2236 // we resort to the old control-flow behavior. This special handling
2237 // removes infeasible paths from the control-flow graph by having the
2238 // control-flow transfer of '&&' or '||' go directly into the then/else
2239 // blocks directly.
2240 if (!I->getConditionVariable())
Richard Smithf676e452012-07-24 21:02:14 +00002241 if (BinaryOperator *Cond =
2242 dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002243 if (Cond->isLogicalOp())
2244 return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2245
Mike Stump31feda52009-07-17 01:31:16 +00002246 // Now create a new block containing the if statement.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002247 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002248
Ted Kremenek9aae5132007-08-23 21:42:29 +00002249 // Set the terminator of the new block to the If statement.
2250 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002251
Mike Stump773582d2009-07-23 23:25:26 +00002252 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002253 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00002254
Ted Kremenekf3898612014-02-27 00:24:03 +00002255 // Add the successors. If we know that specific branches are
2256 // unreachable, inform addSuccessor() of that knowledge.
2257 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2258 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump31feda52009-07-17 01:31:16 +00002259
2260 // Add the condition as the last statement in the new block. This may create
2261 // new blocks as the condition may contain control-flow. Any newly created
2262 // blocks will be pointed to be "Block".
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002263 CFGBlock *LastBlock = addStmt(I->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002264
Manuel Klimek75f34c12014-05-05 18:21:06 +00002265 // Finally, if the IfStmt contains a condition variable, add it and its
2266 // initializer to the CFG.
2267 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2268 autoCreateBlock();
2269 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002270 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002271
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002272 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002273}
Mike Stump31feda52009-07-17 01:31:16 +00002274
2275
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002276CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002277 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002278 //
Mike Stump31feda52009-07-17 01:31:16 +00002279 // NOTE: If a "return" appears in the middle of a block, this means that the
2280 // code afterwards is DEAD (unreachable). We still keep a basic block
2281 // for that code; a simple "mark-and-sweep" from the entry block will be
2282 // able to report such dead blocks.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002283
2284 // Create the new block.
2285 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002286
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002287 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
Pavel Labath921e7652013-09-06 08:12:48 +00002288
2289 // If the one of the destructors does not return, we already have the Exit
2290 // block as a successor.
2291 if (!Block->hasNoReturnElement())
2292 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002293
2294 // Add the return statement to the block. This may create new blocks if R
2295 // contains control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002296 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002297}
2298
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002299CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002300 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00002301 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002302 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002303
Ted Kremenek93668002009-07-17 22:18:43 +00002304 if (!LabelBlock) // This can happen when the body is empty, i.e.
2305 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00002306
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002307 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2308 "label already in map");
2309 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002310
2311 // Labels partition blocks, so this is the end of the basic block we were
2312 // processing (L is the block's label). Because this is label (and we have
2313 // already processed the substatement) there is no extra control-flow to worry
2314 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00002315 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002316 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002317 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002318
2319 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00002320 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002321
Ted Kremenek9aae5132007-08-23 21:42:29 +00002322 // This block is now the implicit successor of other blocks.
2323 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002324
Ted Kremenek9aae5132007-08-23 21:42:29 +00002325 return LabelBlock;
2326}
2327
Ted Kremenekda76a942012-04-12 20:34:52 +00002328CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2329 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2330 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2331 et = E->capture_init_end(); it != et; ++it) {
2332 if (Expr *Init = *it) {
2333 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00002334 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00002335 LastBlock = Tmp;
2336 }
2337 }
2338 return LastBlock;
2339}
2340
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002341CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00002342 // Goto is a control-flow statement. Thus we stop processing the current
2343 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00002344
Ted Kremenek9aae5132007-08-23 21:42:29 +00002345 Block = createBlock(false);
2346 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00002347
2348 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002349 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00002350
Ted Kremenek9aae5132007-08-23 21:42:29 +00002351 if (I == LabelMap.end())
2352 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002353 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2354 else {
2355 JumpTarget JT = I->second;
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002356 addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
2357 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002358 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002359
Mike Stump31feda52009-07-17 01:31:16 +00002360 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002361}
2362
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002363CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00002364 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002365
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002366 // Save local scope position because in case of condition variable ScopePos
2367 // won't be restored when traversing AST.
2368 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2369
2370 // Create local scope for init statement and possible condition variable.
2371 // Add destructor for init statement and condition variable.
2372 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002373 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002374 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002375 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2376
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002377 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002378 addLocalScopeForVarDecl(VD);
2379 LocalScope::const_iterator ContinueScopePos = ScopePos;
2380
2381 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
2382
Mike Stump014b3ea2009-07-21 01:12:51 +00002383 // "for" is a control-flow statement. Thus we stop processing the current
2384 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002385 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002386 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002387 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002388 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002389 } else
2390 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002391
Ted Kremenek304a9532010-05-21 20:30:15 +00002392 // Save the current value for the break targets.
2393 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002394 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002395 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00002396
Craig Topper25542942014-05-20 04:30:07 +00002397 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002398
Ted Kremenek9aae5132007-08-23 21:42:29 +00002399 // Now create the loop body.
2400 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002401 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002402
Ted Kremenekb50e7162012-07-14 05:04:10 +00002403 // Save the current values for Block, Succ, continue and break targets.
2404 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2405 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002406
Ted Kremenekb50e7162012-07-14 05:04:10 +00002407 // Create an empty block to represent the transition block for looping back
2408 // to the head of the loop. If we have increment code, it will
2409 // go in this block as well.
2410 Block = Succ = TransitionBlock = createBlock(false);
2411 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002412
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002413 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00002414 // Generate increment code in its own basic block. This is the target of
2415 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00002416 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00002417 }
Mike Stump31feda52009-07-17 01:31:16 +00002418
Ted Kremenek902393b2009-04-28 00:51:56 +00002419 // Finish up the increment (or empty) block if it hasn't been already.
2420 if (Block) {
2421 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002422 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002423 return nullptr;
2424 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00002425 }
Mike Stump31feda52009-07-17 01:31:16 +00002426
Ted Kremenekb50e7162012-07-14 05:04:10 +00002427 // The starting block for the loop increment is the block that should
2428 // represent the 'loop target' for looping back to the start of the loop.
2429 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2430 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002431
Ted Kremenekb50e7162012-07-14 05:04:10 +00002432 // Loop body should end with destructor of Condition variable (if any).
2433 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00002434
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002435 // If body is not a compound statement create implicit scope
2436 // and add destructors.
2437 if (!isa<CompoundStmt>(F->getBody()))
2438 addLocalScopeAndDtors(F->getBody());
2439
Mike Stump31feda52009-07-17 01:31:16 +00002440 // Now populate the body block, and in the process create new blocks as we
2441 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002442 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00002443
Ted Kremenekb50e7162012-07-14 05:04:10 +00002444 if (!BodyBlock) {
2445 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2446 // Use the continue jump target as the proxy for the body.
2447 BodyBlock = ContinueJumpTarget.block;
2448 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002449 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002450 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002451 }
Ted Kremenekb50e7162012-07-14 05:04:10 +00002452
2453 // Because of short-circuit evaluation, the condition of the loop can span
2454 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2455 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002456 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002457
Ted Kremenekb50e7162012-07-14 05:04:10 +00002458 do {
2459 Expr *C = F->getCond();
2460
2461 // Specially handle logical operators, which have a slightly
2462 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002463 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00002464 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002465 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002466 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002467 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2468 break;
2469 }
2470
2471 // The default case when not handling logical operators.
2472 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2473 ExitConditionBlock->setTerminator(F);
2474
2475 // See if this is a known constant.
2476 TryResult KnownVal(true);
2477
2478 if (C) {
2479 // Now add the actual condition to the condition block.
2480 // Because the condition itself may contain control-flow, new blocks may
2481 // be created. Thus we update "Succ" after adding the condition.
2482 Block = ExitConditionBlock;
2483 EntryConditionBlock = addStmt(C);
2484
2485 // If this block contains a condition variable, add both the condition
2486 // variable and initializer to the CFG.
2487 if (VarDecl *VD = F->getConditionVariable()) {
2488 if (Expr *Init = VD->getInit()) {
2489 autoCreateBlock();
2490 appendStmt(Block, F->getConditionVariableDeclStmt());
2491 EntryConditionBlock = addStmt(Init);
2492 assert(Block == EntryConditionBlock);
2493 }
2494 }
2495
2496 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002497 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002498
2499 KnownVal = tryEvaluateBool(C);
2500 }
2501
2502 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002503 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002504 // Link up the condition block with the code that follows the loop. (the
2505 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002506 addSuccessor(ExitConditionBlock,
2507 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002508
2509 } while (false);
2510
2511 // Link up the loop-back block to the entry condition block.
2512 addSuccessor(TransitionBlock, EntryConditionBlock);
2513
2514 // The condition block is the implicit successor for any code above the loop.
2515 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002516
Ted Kremenek9aae5132007-08-23 21:42:29 +00002517 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00002518 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002519 if (Stmt *I = F->getInit()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002520 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00002521 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002522 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002523
2524 // There is no loop initialization. We are thus basically a while loop.
2525 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00002526 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002527 Succ = EntryConditionBlock;
2528 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002529}
2530
Ted Kremenek5868ec62010-04-11 17:02:10 +00002531CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002532 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00002533 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002534 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002535 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002536 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00002537}
2538
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002539CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00002540 // Objective-C fast enumeration 'for' statements:
2541 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2542 //
2543 // for ( Type newVariable in collection_expression ) { statements }
2544 //
2545 // becomes:
2546 //
2547 // prologue:
2548 // 1. collection_expression
2549 // T. jump to loop_entry
2550 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002551 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00002552 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2553 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2554 // TB:
2555 // statements
2556 // T. jump to loop_entry
2557 // FB:
2558 // what comes after
2559 //
2560 // and
2561 //
2562 // Type existingItem;
2563 // for ( existingItem in expression ) { statements }
2564 //
2565 // becomes:
2566 //
Mike Stump31feda52009-07-17 01:31:16 +00002567 // the same with newVariable replaced with existingItem; the binding works
2568 // the same except that for one ObjCForCollectionStmt::getElement() returns
2569 // a DeclStmt and the other returns a DeclRefExpr.
Ted Kremenek9d56e642008-11-11 17:10:00 +00002570 //
Mike Stump31feda52009-07-17 01:31:16 +00002571
Craig Topper25542942014-05-20 04:30:07 +00002572 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002573
Ted Kremenek9d56e642008-11-11 17:10:00 +00002574 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002575 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002576 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00002577 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002578 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00002579 } else
2580 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002581
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002582 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002583 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002584
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002585 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002586 ExitConditionBlock->setTerminator(S);
2587
2588 // The last statement in the block should be the ObjCForCollectionStmt, which
2589 // performs the actual binding to 'element' and determines if there are any
2590 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00002591 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002592 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002593
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002594 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00002595 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00002596 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00002597 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2598 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00002599 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002600 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002601 return nullptr;
2602 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002603 }
Mike Stump31feda52009-07-17 01:31:16 +00002604
2605 // The condition block is the implicit successor for the loop body as well as
2606 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002607 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002608
Ted Kremenek9d56e642008-11-11 17:10:00 +00002609 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00002610 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002611 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00002612 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002613 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00002614 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002615
Anna Zaks56b49752013-06-22 00:23:20 +00002616 // Add an intermediate block between the BodyBlock and the
2617 // EntryConditionBlock to represent the "loop back" transition, for looping
2618 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00002619 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00002620 Succ = LoopBackBlock = createBlock();
2621 LoopBackBlock->setLoopTarget(S);
2622
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002623 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00002624 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002625
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002626 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002627
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002628 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00002629 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00002630 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002631 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002632 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002633 }
Mike Stump31feda52009-07-17 01:31:16 +00002634
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002635 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002636 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002637 }
Mike Stump31feda52009-07-17 01:31:16 +00002638
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002639 // Link up the condition block with the code that follows the loop.
2640 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002641 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002642
Ted Kremenek9d56e642008-11-11 17:10:00 +00002643 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002644 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00002645 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00002646}
2647
Ted Kremenek5022f1d2012-03-06 23:40:47 +00002648CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2649 // Inline the body.
2650 return addStmt(S->getSubStmt());
2651 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2652}
2653
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002654CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00002655 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00002656
Ted Kremenek49805452009-05-02 01:49:13 +00002657 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00002658 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00002659
Ted Kremenekb3c657b2009-05-05 23:11:51 +00002660 // The sync body starts its own basic block. This makes it a little easier
2661 // for diagnostic clients.
2662 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002663 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002664 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002665
Craig Topper25542942014-05-20 04:30:07 +00002666 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00002667 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00002668 }
Mike Stump31feda52009-07-17 01:31:16 +00002669
Ted Kremeneked12f1b2010-09-10 03:05:33 +00002670 // Add the @synchronized to the CFG.
2671 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002672 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00002673
Ted Kremenek49805452009-05-02 01:49:13 +00002674 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00002675 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00002676}
Mike Stump31feda52009-07-17 01:31:16 +00002677
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002678CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00002679 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00002680 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00002681}
Ted Kremenek9d56e642008-11-11 17:10:00 +00002682
John McCallfe96e0b2011-11-06 09:01:30 +00002683CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2684 autoCreateBlock();
2685
2686 // Add the PseudoObject as the last thing.
2687 appendStmt(Block, E);
2688
2689 CFGBlock *lastBlock = Block;
2690
2691 // Before that, evaluate all of the semantics in order. In
2692 // CFG-land, that means appending them in reverse order.
2693 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2694 Expr *Semantic = E->getSemanticExpr(--i);
2695
2696 // If the semantic is an opaque value, we're being asked to bind
2697 // it to its source expression.
2698 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2699 Semantic = OVE->getSourceExpr();
2700
2701 if (CFGBlock *B = Visit(Semantic))
2702 lastBlock = B;
2703 }
2704
2705 return lastBlock;
2706}
2707
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002708CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00002709 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002710
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002711 // Save local scope position because in case of condition variable ScopePos
2712 // won't be restored when traversing AST.
2713 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2714
2715 // Create local scope for possible condition variable.
2716 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002717 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002718 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002719 addLocalScopeForVarDecl(VD);
2720 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2721 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002722
Mike Stump014b3ea2009-07-21 01:12:51 +00002723 // "while" is a control-flow statement. Thus we stop processing the current
2724 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002725 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002726 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002727 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002728 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002729 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002730 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00002731 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00002732 }
Mike Stump31feda52009-07-17 01:31:16 +00002733
Craig Topper25542942014-05-20 04:30:07 +00002734 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002735
Ted Kremenek9aae5132007-08-23 21:42:29 +00002736 // Process the loop body.
2737 {
Ted Kremenek49936f72009-04-28 03:09:44 +00002738 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00002739
Ted Kremenekb50e7162012-07-14 05:04:10 +00002740 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002741 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2742 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00002743 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00002744
Mike Stump31feda52009-07-17 01:31:16 +00002745 // Create an empty block to represent the transition block for looping back
2746 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002747 Succ = TransitionBlock = createBlock(false);
2748 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002749 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002750
Ted Kremenek9aae5132007-08-23 21:42:29 +00002751 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002752 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002753
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002754 // Loop body should end with destructor of Condition variable (if any).
2755 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2756
2757 // If body is not a compound statement create implicit scope
2758 // and add destructors.
2759 if (!isa<CompoundStmt>(W->getBody()))
2760 addLocalScopeAndDtors(W->getBody());
2761
Ted Kremenek9aae5132007-08-23 21:42:29 +00002762 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002763 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002764
Ted Kremeneke9610502007-08-30 18:39:40 +00002765 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002766 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00002767 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002768 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002769 }
2770
2771 // Because of short-circuit evaluation, the condition of the loop can span
2772 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2773 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002774 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002775
2776 do {
2777 Expr *C = W->getCond();
2778
2779 // Specially handle logical operators, which have a slightly
2780 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002781 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002782 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002783 std::tie(EntryConditionBlock, ExitConditionBlock) =
2784 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002785 break;
2786 }
2787
2788 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00002789 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002790 ExitConditionBlock->setTerminator(W);
2791
2792 // Now add the actual condition to the condition block.
2793 // Because the condition itself may contain control-flow, new blocks may
2794 // be created. Thus we update "Succ" after adding the condition.
2795 Block = ExitConditionBlock;
2796 Block = EntryConditionBlock = addStmt(C);
2797
2798 // If this block contains a condition variable, add both the condition
2799 // variable and initializer to the CFG.
2800 if (VarDecl *VD = W->getConditionVariable()) {
2801 if (Expr *Init = VD->getInit()) {
2802 autoCreateBlock();
2803 appendStmt(Block, W->getConditionVariableDeclStmt());
2804 EntryConditionBlock = addStmt(Init);
2805 assert(Block == EntryConditionBlock);
2806 }
Ted Kremenek55957a82009-05-02 00:13:27 +00002807 }
Mike Stump31feda52009-07-17 01:31:16 +00002808
Ted Kremenekb50e7162012-07-14 05:04:10 +00002809 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002810 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002811
2812 // See if this is a known constant.
2813 const TryResult& KnownVal = tryEvaluateBool(C);
2814
Ted Kremenek30754282009-07-24 04:47:11 +00002815 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002816 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002817 // Link up the condition block with the code that follows the loop. (the
2818 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002819 addSuccessor(ExitConditionBlock,
2820 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00002821
Ted Kremenekb50e7162012-07-14 05:04:10 +00002822 } while(false);
2823
2824 // Link up the loop-back block to the entry condition block.
2825 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00002826
2827 // There can be no more statements in the condition block since we loop back
2828 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00002829 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002830
Ted Kremenek1ce53c42009-12-24 01:34:10 +00002831 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00002832 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00002833 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002834}
Mike Stump11289f42009-09-09 15:08:12 +00002835
2836
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002837CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00002838 // FIXME: For now we pretend that @catch and the code it contains does not
2839 // exit.
2840 return Block;
2841}
Mike Stump31feda52009-07-17 01:31:16 +00002842
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002843CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00002844 // FIXME: This isn't complete. We basically treat @throw like a return
2845 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00002846
Ted Kremenek0868eea2009-09-24 18:45:41 +00002847 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002848 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002849 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002850
Ted Kremenek93041ba2008-12-09 20:20:09 +00002851 // Create the new block.
2852 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002853
Ted Kremenek93041ba2008-12-09 20:20:09 +00002854 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002855 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002856
2857 // Add the statement to the block. This may create new blocks if S contains
2858 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002859 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00002860}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002861
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002862CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002863 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002864 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002865 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002866
2867 // Create the new block.
2868 Block = createBlock(false);
2869
Mike Stumpbbf5ba62010-01-19 02:20:09 +00002870 if (TryTerminatedBlock)
2871 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002872 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002873 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00002874 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002875 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002876
2877 // Add the statement to the block. This may create new blocks if S contains
2878 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002879 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002880}
2881
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002882CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00002883 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002884
Mike Stump8d50b6a2009-07-21 01:27:50 +00002885 // "do...while" is a control-flow statement. Thus we stop processing the
2886 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002887 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002888 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002889 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002890 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002891 } else
2892 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002893
2894 // Because of short-circuit evaluation, the condition of the loop can span
2895 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2896 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002897 CFGBlock *ExitConditionBlock = createBlock(false);
2898 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002899
Ted Kremenek81e14852007-08-27 19:46:09 +00002900 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002901 ExitConditionBlock->setTerminator(D);
2902
2903 // Now add the actual condition to the condition block. Because the condition
2904 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002905 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00002906 Block = ExitConditionBlock;
2907 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00002908 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002909 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002910 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002911 }
Ted Kremenek81e14852007-08-27 19:46:09 +00002912 }
Mike Stump31feda52009-07-17 01:31:16 +00002913
Ted Kremeneka1523a32008-02-27 07:20:00 +00002914 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00002915 Succ = EntryConditionBlock;
2916
Mike Stump773582d2009-07-23 23:25:26 +00002917 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002918 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00002919
Ted Kremenek9aae5132007-08-23 21:42:29 +00002920 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00002921 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002922 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002923 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002924
Ted Kremenek9aae5132007-08-23 21:42:29 +00002925 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002926 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2927 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2928 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002929
Ted Kremenek9aae5132007-08-23 21:42:29 +00002930 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002931 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002932
Ted Kremenek9aae5132007-08-23 21:42:29 +00002933 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002934 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002935
Ted Kremenek9aae5132007-08-23 21:42:29 +00002936 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00002937 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002938
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002939 // If body is not a compound statement create implicit scope
2940 // and add destructors.
2941 if (!isa<CompoundStmt>(D->getBody()))
2942 addLocalScopeAndDtors(D->getBody());
2943
Ted Kremenek9aae5132007-08-23 21:42:29 +00002944 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00002945 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002946
Ted Kremeneke9610502007-08-30 18:39:40 +00002947 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00002948 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00002949 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002950 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002951 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002952 }
Mike Stump31feda52009-07-17 01:31:16 +00002953
Ted Kremenek110974d2010-08-17 20:59:56 +00002954 if (!KnownVal.isFalse()) {
2955 // Add an intermediate block between the BodyBlock and the
2956 // ExitConditionBlock to represent the "loop back" transition. Create an
2957 // empty block to represent the transition block for looping back to the
2958 // head of the loop.
2959 // FIXME: Can we do this more efficiently without adding another block?
Craig Topper25542942014-05-20 04:30:07 +00002960 Block = nullptr;
Ted Kremenek110974d2010-08-17 20:59:56 +00002961 Succ = BodyBlock;
2962 CFGBlock *LoopBackBlock = createBlock();
2963 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00002964
Ted Kremenek110974d2010-08-17 20:59:56 +00002965 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002966 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00002967 }
2968 else
Craig Topper25542942014-05-20 04:30:07 +00002969 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002970 }
Mike Stump31feda52009-07-17 01:31:16 +00002971
Ted Kremenek30754282009-07-24 04:47:11 +00002972 // Link up the condition block with the code that follows the loop.
2973 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00002974 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00002975
2976 // There can be no more statements in the body block(s) since we loop back to
2977 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00002978 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002979
Ted Kremenek9aae5132007-08-23 21:42:29 +00002980 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00002981 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002982 return BodyBlock;
2983}
2984
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002985CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002986 // "continue" is a control-flow statement. Thus we stop processing the
2987 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002988 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002989 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002990
Ted Kremenek9aae5132007-08-23 21:42:29 +00002991 // Now create a new block that ends with the continue statement.
2992 Block = createBlock(false);
2993 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00002994
Ted Kremenek9aae5132007-08-23 21:42:29 +00002995 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00002996 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002997 if (ContinueJumpTarget.block) {
2998 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
2999 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003000 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00003001 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00003002
Ted Kremenek9aae5132007-08-23 21:42:29 +00003003 return Block;
3004}
Mike Stump11289f42009-09-09 15:08:12 +00003005
Peter Collingbournee190dee2011-03-11 19:24:49 +00003006CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3007 AddStmtChoice asc) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003008
Ted Kremenek7c58d352011-03-10 01:14:11 +00003009 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003010 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003011 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00003012 }
Mike Stump11289f42009-09-09 15:08:12 +00003013
Ted Kremenek93668002009-07-17 22:18:43 +00003014 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003015 CFGBlock *lastBlock = Block;
3016
Ted Kremenek93668002009-07-17 22:18:43 +00003017 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003018 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00003019 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003020 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00003021 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003022 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003023}
Mike Stump11289f42009-09-09 15:08:12 +00003024
Ted Kremenek93668002009-07-17 22:18:43 +00003025/// VisitStmtExpr - Utility method to handle (nested) statement
3026/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003027CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003028 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003029 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003030 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00003031 }
Ted Kremenek93668002009-07-17 22:18:43 +00003032 return VisitCompoundStmt(SE->getSubStmt());
3033}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003034
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003035CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00003036 // "switch" is a control-flow statement. Thus we stop processing the current
3037 // block.
Craig Topper25542942014-05-20 04:30:07 +00003038 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003039
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003040 // Save local scope position because in case of condition variable ScopePos
3041 // won't be restored when traversing AST.
3042 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3043
3044 // Create local scope for possible condition variable.
3045 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003046 if (VarDecl *VD = Terminator->getConditionVariable()) {
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003047 LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
3048 addLocalScopeForVarDecl(VD);
3049 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
3050 }
3051
Ted Kremenek9aae5132007-08-23 21:42:29 +00003052 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003053 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003054 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003055 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003056 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003057
3058 // Save the current "switch" context.
3059 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003060 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003061 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003062
Mike Stump31feda52009-07-17 01:31:16 +00003063 // Set the "default" case to be the block after the switch statement. If the
3064 // switch statement contains a "default:", this value will be overwritten with
3065 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003066 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003067
Ted Kremenek9aae5132007-08-23 21:42:29 +00003068 // Create a new block that will contain the switch statement.
3069 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003070
Ted Kremenek9aae5132007-08-23 21:42:29 +00003071 // Now process the switch body. The code after the switch is the implicit
3072 // successor.
3073 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003074 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003075
3076 // When visiting the body, the case statements should automatically get linked
3077 // up to the switch. We also don't keep a pointer to the body, since all
3078 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003079 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003080 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003081
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003082 // For pruning unreachable case statements, save the current state
3083 // for tracking the condition value.
3084 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3085 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003086
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003087 // Determine if the switch condition can be explicitly evaluated.
3088 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003089 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003090 bool b = tryEvaluate(Terminator->getCond(), result);
3091 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003092 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003093
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003094 // If body is not a compound statement create implicit scope
3095 // and add destructors.
3096 if (!isa<CompoundStmt>(Terminator->getBody()))
3097 addLocalScopeAndDtors(Terminator->getBody());
3098
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003099 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003100 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003101 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003102 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003103 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003104
Mike Stump31feda52009-07-17 01:31:16 +00003105 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003106 // following the switch body. Moreover, take into account if all the
3107 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003108 //
3109 // Note: We add a successor to a switch that is considered covered yet has no
3110 // case statements if the enumeration has no enumerators.
3111 bool SwitchAlwaysHasSuccessor = false;
3112 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3113 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3114 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003115 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3116 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003117
Ted Kremenek81e14852007-08-27 19:46:09 +00003118 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003119 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003120 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003121 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003122
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003123 // Finally, if the SwitchStmt contains a condition variable, add both the
3124 // SwitchStmt and the condition variable initialization to the CFG.
3125 if (VarDecl *VD = Terminator->getConditionVariable()) {
3126 if (Expr *Init = VD->getInit()) {
3127 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003128 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003129 LastBlock = addStmt(Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003130 }
3131 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003132
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003133 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003134}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003135
3136static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00003137 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003138 const CaseStmt *CS,
3139 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003140 if (!switchCond)
3141 return true;
3142
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003143 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00003144
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003145 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003146 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003147 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003148 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00003149 const llvm::APSInt &condInt = switchCond->Val.getInt();
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003150
3151 if (condInt == lhsInt) {
3152 addCase = true;
3153 switchExclusivelyCovered = true;
3154 }
Devin Coughlineb538ab2015-09-22 20:31:19 +00003155 else if (condInt > lhsInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003156 if (const Expr *RHS = CS->getRHS()) {
3157 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003158 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
Devin Coughlineb538ab2015-09-22 20:31:19 +00003159 if (V2 >= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003160 addCase = true;
3161 switchExclusivelyCovered = true;
3162 }
3163 }
3164 }
3165 }
3166 else
3167 addCase = true;
3168 }
3169 return addCase;
3170}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003171
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003172CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00003173 // CaseStmts are essentially labels, so they are the first statement in a
3174 // block.
Craig Topper25542942014-05-20 04:30:07 +00003175 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00003176
Ted Kremenek60fa6572010-08-04 23:54:30 +00003177 if (Stmt *Sub = CS->getSubStmt()) {
3178 // For deeply nested chains of CaseStmts, instead of doing a recursion
3179 // (which can blow out the stack), manually unroll and create blocks
3180 // along the way.
3181 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003182 CFGBlock *currentBlock = createBlock(false);
3183 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00003184
Ted Kremenek60fa6572010-08-04 23:54:30 +00003185 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003186 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003187 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003188 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003189
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003190 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003191 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003192 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00003193 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003194
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003195 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003196 CS = cast<CaseStmt>(Sub);
3197 Sub = CS->getSubStmt();
3198 }
3199
3200 addStmt(Sub);
3201 }
Mike Stump11289f42009-09-09 15:08:12 +00003202
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003203 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003204 if (!CaseBlock)
3205 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003206
3207 // Cases statements partition blocks, so this is the top of the basic block we
3208 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00003209 CaseBlock->setLabel(CS);
3210
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003211 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003212 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003213
3214 // Add this block to the list of successors for the block with the switch
3215 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00003216 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003217 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003218 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003219 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00003220
Ted Kremenek9aae5132007-08-23 21:42:29 +00003221 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003222 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003223
Ted Kremenek60fa6572010-08-04 23:54:30 +00003224 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003225 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003226 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003227 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00003228 // This block is now the implicit successor of other blocks.
3229 Succ = CaseBlock;
3230 }
Mike Stump31feda52009-07-17 01:31:16 +00003231
Ted Kremenek60fa6572010-08-04 23:54:30 +00003232 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003233}
Mike Stump31feda52009-07-17 01:31:16 +00003234
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003235CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00003236 if (Terminator->getSubStmt())
3237 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00003238
Ted Kremenek654c78f2008-02-13 22:05:39 +00003239 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003240
3241 if (!DefaultCaseBlock)
3242 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003243
3244 // Default statements partition blocks, so this is the top of the basic block
3245 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003246 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00003247
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003248 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003249 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00003250
Mike Stump31feda52009-07-17 01:31:16 +00003251 // Unlike case statements, we don't add the default block to the successors
3252 // for the switch statement immediately. This is done when we finish
3253 // processing the switch statement. This allows for the default case
3254 // (including a fall-through to the code after the switch statement) to always
3255 // be the last successor of a switch-terminated block.
3256
Ted Kremenek654c78f2008-02-13 22:05:39 +00003257 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003258 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003259
Ted Kremenek654c78f2008-02-13 22:05:39 +00003260 // This block is now the implicit successor of other blocks.
3261 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003262
3263 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00003264}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003265
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003266CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3267 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3268 // current block.
Craig Topper25542942014-05-20 04:30:07 +00003269 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003270
3271 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003272 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003273 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003274 TrySuccessor = Block;
3275 } else TrySuccessor = Succ;
3276
Mike Stump0bdba6c2010-01-20 01:15:34 +00003277 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003278
3279 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00003280 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003281 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00003282 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003283
Mike Stump0bdba6c2010-01-20 01:15:34 +00003284 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003285 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3286 // The code after the try is the implicit successor.
3287 Succ = TrySuccessor;
3288 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00003289 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00003290 HasCatchAll = true;
3291 }
Craig Topper25542942014-05-20 04:30:07 +00003292 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003293 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00003294 if (!CatchBlock)
3295 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003296 // Add this block to the list of successors for the block with the try
3297 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003298 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003299 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00003300 if (!HasCatchAll) {
3301 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003302 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00003303 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003304 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00003305 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003306
3307 // The code after the try is the implicit successor.
3308 Succ = TrySuccessor;
3309
Mike Stump845384a2010-01-20 01:30:58 +00003310 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00003311 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3312 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00003313
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003314 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003315 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003316 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003317}
3318
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003319CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003320 // CXXCatchStmt are treated like labels, so they are the first statement in a
3321 // block.
3322
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003323 // Save local scope position because in case of exception variable ScopePos
3324 // won't be restored when traversing AST.
3325 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3326
3327 // Create local scope for possible exception variable.
3328 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003329 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003330 LocalScope::const_iterator BeginScopePos = ScopePos;
3331 addLocalScopeForVarDecl(VD);
3332 addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
3333 }
3334
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003335 if (CS->getHandlerBlock())
3336 addStmt(CS->getHandlerBlock());
3337
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003338 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003339 if (!CatchBlock)
3340 CatchBlock = createBlock();
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003341
3342 // CXXCatchStmt is more than just a label. They have semantic meaning
3343 // as well, as they implicitly "initialize" the catch variable. Add
3344 // it to the CFG as a CFGElement so that the control-flow of these
3345 // semantics gets captured.
3346 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003347
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003348 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3349 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003350 CatchBlock->setLabel(CS);
3351
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003352 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003353 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003354 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003355
3356 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003357 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003358
3359 return CatchBlock;
3360}
3361
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003362CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00003363 // C++0x for-range statements are specified as [stmt.ranged]:
3364 //
3365 // {
3366 // auto && __range = range-init;
3367 // for ( auto __begin = begin-expr,
3368 // __end = end-expr;
3369 // __begin != __end;
3370 // ++__begin ) {
3371 // for-range-declaration = *__begin;
3372 // statement
3373 // }
3374 // }
3375
3376 // Save local scope position before the addition of the implicit variables.
3377 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3378
3379 // Create local scopes and destructors for range, begin and end variables.
3380 if (Stmt *Range = S->getRangeStmt())
3381 addLocalScopeForStmt(Range);
3382 if (Stmt *BeginEnd = S->getBeginEndStmt())
3383 addLocalScopeForStmt(BeginEnd);
3384 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
3385
3386 LocalScope::const_iterator ContinueScopePos = ScopePos;
3387
3388 // "for" is a control-flow statement. Thus we stop processing the current
3389 // block.
Craig Topper25542942014-05-20 04:30:07 +00003390 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003391 if (Block) {
3392 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003393 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003394 LoopSuccessor = Block;
3395 } else
3396 LoopSuccessor = Succ;
3397
3398 // Save the current value for the break targets.
3399 // All breaks should go to the code following the loop.
3400 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3401 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3402
3403 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003404 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00003405 ConditionBlock->setTerminator(S);
3406
3407 // Now add the actual condition to the condition block.
3408 if (Expr *C = S->getCond()) {
3409 Block = ConditionBlock;
3410 CFGBlock *BeginConditionBlock = addStmt(C);
3411 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003412 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003413 assert(BeginConditionBlock == ConditionBlock &&
3414 "condition block in for-range was unexpectedly complex");
3415 (void)BeginConditionBlock;
3416 }
3417
3418 // The condition block is the implicit successor for the loop body as well as
3419 // any code above the loop.
3420 Succ = ConditionBlock;
3421
3422 // See if this is a known constant.
3423 TryResult KnownVal(true);
3424
3425 if (S->getCond())
3426 KnownVal = tryEvaluateBool(S->getCond());
3427
3428 // Now create the loop body.
3429 {
3430 assert(S->getBody());
3431
3432 // Save the current values for Block, Succ, and continue targets.
3433 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3434 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3435
3436 // Generate increment code in its own basic block. This is the target of
3437 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00003438 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003439 Succ = addStmt(S->getInc());
3440 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3441
3442 // The starting block for the loop increment is the block that should
3443 // represent the 'loop target' for looping back to the start of the loop.
3444 ContinueJumpTarget.block->setLoopTarget(S);
3445
3446 // Finish up the increment block and prepare to start the loop body.
3447 assert(Block);
3448 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003449 return nullptr;
3450 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003451
3452 // Add implicit scope and dtors for loop variable.
3453 addLocalScopeAndDtors(S->getLoopVarStmt());
3454
3455 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003456 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00003457 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003458 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003459 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003460 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003461 return nullptr;
3462
Richard Smith02e85f32011-04-14 22:09:26 +00003463 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00003464 addSuccessor(ConditionBlock,
3465 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00003466 }
3467
3468 // Link up the condition block with the code that follows the loop (the
3469 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003470 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00003471
3472 // Add the initialization statements.
3473 Block = createBlock();
Richard Smith0c502d22011-04-18 15:49:25 +00003474 addStmt(S->getBeginEndStmt());
3475 return addStmt(S->getRangeStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003476}
3477
John McCall5d413782010-12-06 08:20:24 +00003478CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003479 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003480 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003481 // If adding implicit destructors visit the full expression for adding
3482 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003483 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00003484 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003485
3486 // Full expression has to be added as CFGStmt so it will be sequenced
3487 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003488 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003489 }
3490 return Visit(E->getSubExpr(), asc);
3491}
3492
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003493CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3494 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003495 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003496 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003497 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003498
3499 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003500 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003501 }
3502 return Visit(E->getSubExpr(), asc);
3503}
3504
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003505CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3506 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003507 autoCreateBlock();
Zhongxing Xuf0cb43f2012-01-11 02:39:07 +00003508 appendStmt(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003509
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003510 return VisitChildren(C);
3511}
3512
Jordan Rosec9176072014-01-13 17:59:19 +00003513CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3514 AddStmtChoice asc) {
3515
3516 autoCreateBlock();
3517 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00003518
Jordan Rosec9176072014-01-13 17:59:19 +00003519 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003520 Block = Visit(NE->getInitializer());
Jordan Rosec9176072014-01-13 17:59:19 +00003521 if (BuildOpts.AddCXXNewAllocator)
3522 appendNewAllocator(Block, NE);
3523 if (NE->isArray())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003524 Block = Visit(NE->getArraySize());
Jordan Rosec9176072014-01-13 17:59:19 +00003525 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3526 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00003527 Block = Visit(*I);
Jordan Rosec9176072014-01-13 17:59:19 +00003528 return Block;
3529}
Jordan Rosed2f40792013-09-03 17:00:57 +00003530
3531CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3532 AddStmtChoice asc) {
3533 autoCreateBlock();
3534 appendStmt(Block, DE);
3535 QualType DTy = DE->getDestroyedType();
3536 DTy = DTy.getNonReferenceType();
3537 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3538 if (RD) {
Matt Beaumont-Gay093f2402013-09-09 21:07:58 +00003539 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
Jordan Rosed2f40792013-09-03 17:00:57 +00003540 appendDeleteDtor(Block, RD, DE);
3541 }
3542
3543 return VisitChildren(DE);
3544}
3545
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003546CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3547 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003548 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003549 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003550 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003551 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003552 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003553 }
3554 return Visit(E->getSubExpr(), asc);
3555}
3556
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003557CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3558 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003559 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003560 appendStmt(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003561 return VisitChildren(C);
3562}
3563
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003564CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3565 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003566 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003567 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003568 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003569 }
Ted Kremenek8219b822010-12-16 07:46:53 +00003570 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003571}
3572
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003573CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00003574 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003575 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003576
Ted Kremenekeda180e22007-08-28 19:26:49 +00003577 if (!IBlock) {
3578 IBlock = createBlock(false);
3579 cfg->setIndirectGotoBlock(IBlock);
3580 }
Mike Stump31feda52009-07-17 01:31:16 +00003581
Ted Kremenekeda180e22007-08-28 19:26:49 +00003582 // IndirectGoto is a control-flow statement. Thus we stop processing the
3583 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003584 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003585 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00003586
Ted Kremenekeda180e22007-08-28 19:26:49 +00003587 Block = createBlock(false);
3588 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003589 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00003590 return addStmt(I->getTarget());
3591}
3592
Manuel Klimekb5616c92014-08-07 10:42:17 +00003593CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
3594 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003595 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3596
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003597tryAgain:
3598 if (!E) {
3599 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00003600 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003601 }
3602 switch (E->getStmtClass()) {
3603 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00003604 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003605
3606 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00003607 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
3608 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003609
3610 case Stmt::CXXBindTemporaryExprClass:
3611 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003612 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003613
John McCallc07a0c72011-02-17 10:25:35 +00003614 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003615 case Stmt::ConditionalOperatorClass:
3616 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003617 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003618
3619 case Stmt::ImplicitCastExprClass:
3620 // For implicit cast we want BindToTemporary to be passed further.
3621 E = cast<CastExpr>(E)->getSubExpr();
3622 goto tryAgain;
3623
Manuel Klimekb0042c42014-07-30 08:34:42 +00003624 case Stmt::CXXFunctionalCastExprClass:
3625 // For functional cast we want BindToTemporary to be passed further.
3626 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
3627 goto tryAgain;
3628
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003629 case Stmt::ParenExprClass:
3630 E = cast<ParenExpr>(E)->getSubExpr();
3631 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00003632
Manuel Klimekb0042c42014-07-30 08:34:42 +00003633 case Stmt::MaterializeTemporaryExprClass: {
3634 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
3635 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
3636 SmallVector<const Expr *, 2> CommaLHSs;
3637 SmallVector<SubobjectAdjustment, 2> Adjustments;
3638 // Find the expression whose lifetime needs to be extended.
3639 E = const_cast<Expr *>(
3640 cast<MaterializeTemporaryExpr>(E)
3641 ->GetTemporaryExpr()
3642 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
3643 // Visit the skipped comma operator left-hand sides for other temporaries.
3644 for (const Expr *CommaLHS : CommaLHSs) {
3645 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00003646 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00003647 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003648 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00003649 }
Richard Smith4137af22014-07-27 05:12:49 +00003650
3651 case Stmt::BlockExprClass:
3652 // Don't recurse into blocks; their subexpressions don't get evaluated
3653 // here.
3654 return Block;
3655
3656 case Stmt::LambdaExprClass: {
3657 // For lambda expressions, only recurse into the capture initializers,
3658 // and not the body.
3659 auto *LE = cast<LambdaExpr>(E);
3660 CFGBlock *B = Block;
3661 for (Expr *Init : LE->capture_inits()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003662 if (CFGBlock *R = VisitForTemporaryDtors(
3663 Init, /*BindToTemporary=*/false, Context))
Richard Smith4137af22014-07-27 05:12:49 +00003664 B = R;
3665 }
3666 return B;
3667 }
3668
3669 case Stmt::CXXDefaultArgExprClass:
3670 E = cast<CXXDefaultArgExpr>(E)->getExpr();
3671 goto tryAgain;
3672
3673 case Stmt::CXXDefaultInitExprClass:
3674 E = cast<CXXDefaultInitExpr>(E)->getExpr();
3675 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003676 }
3677}
3678
Manuel Klimekb5616c92014-08-07 10:42:17 +00003679CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
3680 TempDtorContext &Context) {
3681 if (isa<LambdaExpr>(E)) {
3682 // Do not visit the children of lambdas; they have their own CFGs.
3683 return Block;
3684 }
3685
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003686 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00003687 // order that they will appear in the CFG. Because the CFG is built
3688 // bottom-up, this means we visit them in their natural order, which
3689 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003690 CFGBlock *B = Block;
Benjamin Kramer642f1732015-07-02 21:03:14 +00003691 for (Stmt *Child : E->children())
3692 if (Child)
Manuel Klimekb5616c92014-08-07 10:42:17 +00003693 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00003694 B = R;
Benjamin Kramer642f1732015-07-02 21:03:14 +00003695
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003696 return B;
3697}
3698
Manuel Klimekb5616c92014-08-07 10:42:17 +00003699CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
3700 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003701 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003702 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00003703 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
3704 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
3705 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00003706
Manuel Klimekedf925b92014-08-07 18:44:19 +00003707 // We do not know at CFG-construction time whether the right-hand-side was
3708 // executed, thus we add a branch node that depends on the temporary
3709 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003710 TempDtorContext RHSContext(
3711 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00003712 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00003713 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00003714
Manuel Klimekb5616c92014-08-07 10:42:17 +00003715 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003716 }
3717
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003718 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003719 // For assignment operator (=) LHS expression is visited
3720 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003721 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3722 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003723 return LHSBlock ? LHSBlock : RHSBlock;
3724 }
3725
3726 // For any other binary operator RHS expression is visited before
3727 // LHS expression (order of children). For destructors visit them in reverse
3728 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003729 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3730 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003731 return RHSBlock ? RHSBlock : LHSBlock;
3732}
3733
3734CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003735 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003736 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003737 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00003738 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003739 // If lifetime of temporary is not prolonged (by assigning to constant
3740 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00003741
Chandler Carruthad747252011-09-13 06:09:01 +00003742 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00003743
Richard Trieu95a192a2015-05-28 00:14:02 +00003744 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003745 // If the destructor is marked as a no-return destructor, we need to
3746 // create a new block for the destructor which does not have as a
3747 // successor anything built thus far. Control won't flow out of this
3748 // block.
3749 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00003750 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00003751 } else if (Context.needsTempDtorBranch()) {
3752 // If we need to introduce a branch, we add a new block that we will hook
3753 // up to a decision block later.
3754 if (B) Succ = B;
3755 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00003756 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00003757 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00003758 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00003759 if (Context.needsTempDtorBranch()) {
3760 Context.setDecisionPoint(Succ, E);
3761 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003762 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003763
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003764 B = Block;
3765 }
3766 return B;
3767}
3768
Manuel Klimekb5616c92014-08-07 10:42:17 +00003769void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
3770 CFGBlock *FalseSucc) {
3771 if (!Context.TerminatorExpr) {
3772 // If no temporary was found, we do not need to insert a decision point.
3773 return;
3774 }
3775 assert(Context.TerminatorExpr);
3776 CFGBlock *Decision = createBlock(false);
3777 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
Manuel Klimekdeb02622014-08-08 07:37:13 +00003778 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00003779 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00003780 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00003781 Block = Decision;
3782}
3783
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003784CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003785 AbstractConditionalOperator *E, bool BindToTemporary,
3786 TempDtorContext &Context) {
3787 VisitForTemporaryDtors(E->getCond(), false, Context);
3788 CFGBlock *ConditionBlock = Block;
3789 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00003790 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00003791 TryResult NegatedVal = ConditionVal;
3792 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00003793
Manuel Klimekdeb02622014-08-08 07:37:13 +00003794 TempDtorContext TrueContext(
3795 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00003796 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003797 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003798
Manuel Klimekb5616c92014-08-07 10:42:17 +00003799 Block = ConditionBlock;
3800 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00003801 TempDtorContext FalseContext(
3802 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00003803 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003804
Manuel Klimekb5616c92014-08-07 10:42:17 +00003805 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00003806 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003807 } else if (TrueContext.TerminatorExpr) {
3808 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00003809 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003810 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00003811 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003812 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003813 return Block;
3814}
3815
Ted Kremenek04cca642007-08-23 21:26:19 +00003816} // end anonymous namespace
Ted Kremenek889073f2007-08-23 16:51:22 +00003817
Mike Stump31feda52009-07-17 01:31:16 +00003818/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
3819/// no successors or predecessors. If this is the first block created in the
3820/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003821CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00003822 bool first_block = begin() == end();
3823
3824 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003825 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00003826 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003827 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00003828
3829 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003830 if (first_block)
3831 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00003832
3833 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003834 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00003835}
3836
David Blaikiee90195c2014-08-29 18:53:26 +00003837/// buildCFG - Constructs a CFG from an AST.
3838std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
3839 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00003840 CFGBuilder Builder(C, BO);
3841 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00003842}
3843
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003844const CXXDestructorDecl *
3845CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003846 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003847 case CFGElement::Statement:
3848 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00003849 case CFGElement::NewAllocator:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003850 llvm_unreachable("getDestructorDecl should only be used with "
3851 "ImplicitDtors");
3852 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00003853 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003854 QualType ty = var->getType();
Ted Kremenek1676a042011-03-03 01:01:03 +00003855 ty = ty.getNonReferenceType();
Ted Kremeneke7d78882012-03-19 23:48:41 +00003856 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003857 ty = arrayType->getElementType();
3858 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003859 const RecordType *recordType = ty->getAs<RecordType>();
3860 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00003861 cast<CXXRecordDecl>(recordType->getDecl());
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003862 return classDecl->getDestructor();
3863 }
Jordan Rosed2f40792013-09-03 17:00:57 +00003864 case CFGElement::DeleteDtor: {
3865 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
3866 QualType DTy = DE->getDestroyedType();
3867 DTy = DTy.getNonReferenceType();
3868 const CXXRecordDecl *classDecl =
3869 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
3870 return classDecl->getDestructor();
3871 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003872 case CFGElement::TemporaryDtor: {
3873 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00003874 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003875 const CXXTemporary *temp = bindExpr->getTemporary();
3876 return temp->getDestructor();
3877 }
3878 case CFGElement::BaseDtor:
3879 case CFGElement::MemberDtor:
3880
3881 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00003882 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003883 }
Ted Kremenek1676a042011-03-03 01:01:03 +00003884 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003885}
3886
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003887bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00003888 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
3889 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003890 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00003891}
3892
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00003893//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003894// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00003895//===----------------------------------------------------------------------===//
3896
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003897CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Craig Topper25542942014-05-20 04:30:07 +00003898 : ReachableBlock(IsReachable ? B : nullptr),
3899 UnreachableBlock(!IsReachable ? B : nullptr,
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003900 B && IsReachable ? AB_Normal : AB_Unreachable) {}
3901
3902CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
3903 : ReachableBlock(B),
Craig Topper25542942014-05-20 04:30:07 +00003904 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003905 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
3906
3907void CFGBlock::addSuccessor(AdjacentBlock Succ,
3908 BumpVectorContext &C) {
3909 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00003910 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003911
3912 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00003913 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003914
3915 Succs.push_back(Succ, C);
3916}
3917
Ted Kremenekb0371852010-09-09 00:06:04 +00003918bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00003919 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003920
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003921 if (F.IgnoreNullPredecessors && !From)
3922 return true;
3923
3924 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003925 // If the 'To' has no label or is labeled but the label isn't a
3926 // CaseStmt then filter this edge.
3927 if (const SwitchStmt *S =
Ted Kremenek89794742011-03-07 22:04:39 +00003928 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003929 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00003930 const Stmt *L = To->getLabel();
3931 if (!L || !isa<CaseStmt>(L))
3932 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00003933 }
3934 }
3935 }
3936
3937 return false;
3938}
3939
3940//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00003941// CFG pretty printing
3942//===----------------------------------------------------------------------===//
3943
Ted Kremenek7e776b12007-08-22 18:22:34 +00003944namespace {
3945
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00003946class StmtPrinterHelper : public PrinterHelper {
Ted Kremenek96a7a592011-03-01 03:15:10 +00003947 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
3948 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003949 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003950 DeclMapTy DeclMap;
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003951 signed currentBlock;
Ted Kremenekd94854a2012-08-22 06:26:15 +00003952 unsigned currStmt;
Chris Lattnerc61089a2009-06-30 01:26:17 +00003953 const LangOptions &LangOpts;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003954public:
Ted Kremenekf8b50e92007-08-31 22:26:13 +00003955
Chris Lattnerc61089a2009-06-30 01:26:17 +00003956 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Ted Kremenekd94854a2012-08-22 06:26:15 +00003957 : currentBlock(0), currStmt(0), LangOpts(LO)
Ted Kremenek96a7a592011-03-01 03:15:10 +00003958 {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003959 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
3960 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003961 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003962 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00003963 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
3964 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003965 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00003966 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003967
Ted Kremenek96a7a592011-03-01 03:15:10 +00003968 switch (stmt->getStmtClass()) {
3969 case Stmt::DeclStmtClass:
3970 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
3971 break;
3972 case Stmt::IfStmtClass: {
3973 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
3974 if (var)
3975 DeclMap[var] = P;
3976 break;
3977 }
3978 case Stmt::ForStmtClass: {
3979 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
3980 if (var)
3981 DeclMap[var] = P;
3982 break;
3983 }
3984 case Stmt::WhileStmtClass: {
3985 const VarDecl *var =
3986 cast<WhileStmt>(stmt)->getConditionVariable();
3987 if (var)
3988 DeclMap[var] = P;
3989 break;
3990 }
3991 case Stmt::SwitchStmtClass: {
3992 const VarDecl *var =
3993 cast<SwitchStmt>(stmt)->getConditionVariable();
3994 if (var)
3995 DeclMap[var] = P;
3996 break;
3997 }
3998 case Stmt::CXXCatchStmtClass: {
3999 const VarDecl *var =
4000 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4001 if (var)
4002 DeclMap[var] = P;
4003 break;
4004 }
4005 default:
4006 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004007 }
4008 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004009 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00004010 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004011 }
Mike Stump31feda52009-07-17 01:31:16 +00004012
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00004013 ~StmtPrinterHelper() override {}
Mike Stump31feda52009-07-17 01:31:16 +00004014
Chris Lattnerc61089a2009-06-30 01:26:17 +00004015 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004016 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00004017 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00004018
Craig Topperb45acb82014-03-14 06:02:07 +00004019 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004020 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004021
4022 if (I == StmtMap.end())
4023 return false;
Mike Stump31feda52009-07-17 01:31:16 +00004024
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004025 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004026 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004027 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004028 }
Mike Stump31feda52009-07-17 01:31:16 +00004029
Ted Kremenek60983dc2010-01-19 20:52:05 +00004030 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004031 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004032 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004033
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004034 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004035 DeclMapTy::iterator I = DeclMap.find(D);
4036
4037 if (I == DeclMap.end())
4038 return false;
4039
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004040 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004041 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004042 return false;
4043 }
4044
4045 OS << "[B" << I->second.first << "." << I->second.second << "]";
4046 return true;
4047 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004048};
Chris Lattnerc61089a2009-06-30 01:26:17 +00004049} // end anonymous namespace
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004050
Chris Lattnerc61089a2009-06-30 01:26:17 +00004051
4052namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004053class CFGBlockTerminatorPrint
Ted Kremenek83ebcef2008-01-08 18:15:10 +00004054 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Mike Stump31feda52009-07-17 01:31:16 +00004055
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004056 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004057 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00004058 PrintingPolicy Policy;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004059public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004060 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00004061 const PrintingPolicy &Policy)
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00004062 : OS(os), Helper(helper), Policy(Policy) {
4063 this->Policy.IncludeNewlines = false;
4064 }
Mike Stump31feda52009-07-17 01:31:16 +00004065
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004066 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004067 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004068 if (Stmt *C = I->getCond())
4069 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004070 }
Mike Stump31feda52009-07-17 01:31:16 +00004071
Ted Kremenek9aae5132007-08-23 21:42:29 +00004072 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004073 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00004074 Terminator->printPretty(OS, Helper, Policy);
4075 }
4076
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00004077 void VisitDeclStmt(DeclStmt *DS) {
4078 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4079 OS << "static init " << VD->getName();
4080 }
4081
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004082 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004083 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004084 if (F->getInit())
4085 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004086 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004087 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004088 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004089 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00004090 if (F->getInc())
4091 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00004092 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00004093 }
Mike Stump31feda52009-07-17 01:31:16 +00004094
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004095 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004096 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004097 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004098 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004099 }
Mike Stump31feda52009-07-17 01:31:16 +00004100
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004101 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004102 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004103 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004104 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004105 }
Mike Stump31feda52009-07-17 01:31:16 +00004106
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004107 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00004108 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00004109 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004110 }
Mike Stump31feda52009-07-17 01:31:16 +00004111
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004112 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004113 OS << "try ...";
4114 }
4115
John McCallc07a0c72011-02-17 10:25:35 +00004116 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00004117 if (Stmt *Cond = C->getCond())
4118 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004119 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004120 }
Mike Stump31feda52009-07-17 01:31:16 +00004121
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004122 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00004123 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004124 if (Stmt *Cond = C->getCond())
4125 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00004126 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00004127 }
Mike Stump31feda52009-07-17 01:31:16 +00004128
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004129 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004130 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004131 if (Stmt *T = I->getTarget())
4132 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004133 }
Mike Stump31feda52009-07-17 01:31:16 +00004134
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004135 void VisitBinaryOperator(BinaryOperator* B) {
4136 if (!B->isLogicalOp()) {
4137 VisitExpr(B);
4138 return;
4139 }
Mike Stump31feda52009-07-17 01:31:16 +00004140
Richard Trieuddd01ce2014-06-09 22:53:25 +00004141 if (B->getLHS())
4142 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004143
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004144 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004145 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00004146 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004147 return;
John McCalle3027922010-08-25 11:45:40 +00004148 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00004149 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004150 return;
4151 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004152 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00004153 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004154 }
Mike Stump31feda52009-07-17 01:31:16 +00004155
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004156 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00004157 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004158 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00004159
4160public:
4161 void print(CFGTerminator T) {
4162 if (T.isTemporaryDtorsBranch())
4163 OS << "(Temp Dtor) ";
4164 Visit(T.getStmt());
4165 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00004166};
Chris Lattnerc61089a2009-06-30 01:26:17 +00004167} // end anonymous namespace
4168
Aaron Ballmanff924b02013-11-18 20:11:50 +00004169static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00004170 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00004171 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4172 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00004173 assert(S != nullptr && "Expecting non-null Stmt");
4174
Aaron Ballmanff924b02013-11-18 20:11:50 +00004175 // special printing for statement-expressions.
4176 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4177 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00004178
Benjamin Kramer5733e352015-07-18 17:09:36 +00004179 auto Children = Sub->children();
4180 if (Children.begin() != Children.end()) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00004181 OS << "({ ... ; ";
4182 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4183 OS << " })\n";
4184 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004185 }
4186 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00004187 // special printing for comma expressions.
4188 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4189 if (B->getOpcode() == BO_Comma) {
4190 OS << "... , ";
4191 Helper.handledStmt(B->getRHS(),OS);
4192 OS << '\n';
4193 return;
4194 }
4195 }
4196 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00004197
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004198 if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004199 OS << " (OperatorCall)";
Ted Kremenek0ffba932011-12-21 19:32:38 +00004200 }
4201 else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004202 OS << " (BindTemporary)";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004203 }
Ted Kremenek1a7648b2011-12-21 19:39:59 +00004204 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4205 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
4206 }
Ted Kremenek0ffba932011-12-21 19:32:38 +00004207 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
4208 OS << " (" << CE->getStmtClassName() << ", "
4209 << CE->getCastKindName()
4210 << ", " << CE->getType().getAsString()
4211 << ")";
4212 }
Mike Stump31feda52009-07-17 01:31:16 +00004213
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004214 // Expressions need a newline.
4215 if (isa<Expr>(S))
4216 OS << '\n';
Ted Kremenek0f5d8bc2010-08-31 18:47:37 +00004217
David Blaikie00be69a2013-02-23 00:29:34 +00004218 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
4219 const CXXCtorInitializer *I = IE->getInitializer();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004220 if (I->isBaseInitializer())
4221 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
Jordan Rose69d0aed2013-10-22 23:19:47 +00004222 else if (I->isDelegatingInitializer())
4223 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
Francois Pichetd583da02010-12-04 09:14:42 +00004224 else OS << I->getAnyMember()->getName();
Mike Stump31feda52009-07-17 01:31:16 +00004225
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004226 OS << "(";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004227 if (Expr *IE = I->getInit())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004228 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004229 OS << ")";
4230
4231 if (I->isBaseInitializer())
4232 OS << " (Base initializer)\n";
Jordan Rose69d0aed2013-10-22 23:19:47 +00004233 else if (I->isDelegatingInitializer())
4234 OS << " (Delegating initializer)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004235 else OS << " (Member initializer)\n";
4236
David Blaikie00be69a2013-02-23 00:29:34 +00004237 } else if (Optional<CFGAutomaticObjDtor> DE =
4238 E.getAs<CFGAutomaticObjDtor>()) {
4239 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00004240 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004241
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00004242 const Type* T = VD->getType().getTypePtr();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004243 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4244 T = RT->getPointeeType().getTypePtr();
Richard Smithf676e452012-07-24 21:02:14 +00004245 T = T->getBaseElementTypeUnsafe();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004246
4247 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4248 OS << " (Implicit destructor)\n";
Marcin Swiderski20b88732010-10-05 05:37:00 +00004249
Jordan Rosec9176072014-01-13 17:59:19 +00004250 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4251 OS << "CFGNewAllocator(";
4252 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4253 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4254 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00004255 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4256 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4257 if (!RD)
4258 return;
4259 CXXDeleteExpr *DelExpr =
4260 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00004261 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00004262 OS << "->~" << RD->getName().str() << "()";
4263 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004264 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4265 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004266 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004267 OS << " (Base object destructor)\n";
Marcin Swiderski20b88732010-10-05 05:37:00 +00004268
David Blaikie00be69a2013-02-23 00:29:34 +00004269 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4270 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00004271 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004272 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00004273 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004274 OS << " (Member object destructor)\n";
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004275
David Blaikie00be69a2013-02-23 00:29:34 +00004276 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4277 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00004278 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004279 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00004280 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004281 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004282}
Mike Stump31feda52009-07-17 01:31:16 +00004283
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004284static void print_block(raw_ostream &OS, const CFG* cfg,
4285 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00004286 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004287 bool ShowColors) {
Mike Stump31feda52009-07-17 01:31:16 +00004288
Aaron Ballmanff924b02013-11-18 20:11:50 +00004289 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00004290
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004291 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004292 if (ShowColors)
4293 OS.changeColor(raw_ostream::YELLOW, true);
4294
4295 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00004296
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004297 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004298 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004299 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004300 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004301 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004302 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00004303 else if (B.hasNoReturnElement())
4304 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004305 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00004306 OS << "]\n";
4307
4308 if (ShowColors)
4309 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00004310
Ted Kremenek71eca012007-08-29 23:20:49 +00004311 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004312 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004313
4314 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004315 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004316
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004317 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004318 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004319 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004320 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004321 if (C->getLHS())
4322 C->getLHS()->printPretty(OS, &Helper,
4323 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004324 if (C->getRHS()) {
4325 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004326 C->getRHS()->printPretty(OS, &Helper,
4327 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004328 }
Mike Stump92244b02010-01-19 22:00:14 +00004329 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004330 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00004331 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004332 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00004333 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004334 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00004335 0);
4336 else
4337 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004338 OS << ")";
4339
4340 } else
David Blaikie83d382b2011-09-23 05:06:16 +00004341 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00004342
Ted Kremenek71eca012007-08-29 23:20:49 +00004343 OS << ":\n";
4344 }
Mike Stump31feda52009-07-17 01:31:16 +00004345
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004346 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004347 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00004348
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004349 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4350 I != E ; ++I, ++j ) {
Mike Stump31feda52009-07-17 01:31:16 +00004351
Ted Kremenek71eca012007-08-29 23:20:49 +00004352 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004353 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004354 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004355
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004356 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00004357
Aaron Ballmanff924b02013-11-18 20:11:50 +00004358 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00004359
Ted Kremenek72be32a2011-12-22 23:33:52 +00004360 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004361 }
Mike Stump31feda52009-07-17 01:31:16 +00004362
Ted Kremenek71eca012007-08-29 23:20:49 +00004363 // Print the terminator of this block.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004364 if (B.getTerminator()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00004365 if (ShowColors)
4366 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00004367
Ted Kremenek72be32a2011-12-22 23:33:52 +00004368 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00004369
Aaron Ballmanff924b02013-11-18 20:11:50 +00004370 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00004371
Aaron Ballmanff924b02013-11-18 20:11:50 +00004372 PrintingPolicy PP(Helper.getLangOpts());
4373 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00004374 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004375 OS << '\n';
Ted Kremenek72be32a2011-12-22 23:33:52 +00004376
4377 if (ShowColors)
4378 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004379 }
Mike Stump31feda52009-07-17 01:31:16 +00004380
Ted Kremenek71eca012007-08-29 23:20:49 +00004381 if (print_edges) {
4382 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004383 if (!B.pred_empty()) {
4384 const raw_ostream::Colors Color = raw_ostream::BLUE;
4385 if (ShowColors)
4386 OS.changeColor(Color);
4387 OS << " Preds " ;
4388 if (ShowColors)
4389 OS.resetColor();
4390 OS << '(' << B.pred_size() << "):";
4391 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00004392
Ted Kremenek72be32a2011-12-22 23:33:52 +00004393 if (ShowColors)
4394 OS.changeColor(Color);
4395
4396 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4397 I != E; ++I, ++i) {
Mike Stump31feda52009-07-17 01:31:16 +00004398
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004399 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004400 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00004401
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004402 CFGBlock *B = *I;
4403 bool Reachable = true;
4404 if (!B) {
4405 Reachable = false;
4406 B = I->getPossiblyUnreachableBlock();
4407 }
4408
4409 OS << " B" << B->getBlockID();
4410 if (!Reachable)
4411 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00004412 }
4413
4414 if (ShowColors)
4415 OS.resetColor();
4416
4417 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00004418 }
Mike Stump31feda52009-07-17 01:31:16 +00004419
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004420 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004421 if (!B.succ_empty()) {
4422 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4423 if (ShowColors)
4424 OS.changeColor(Color);
4425 OS << " Succs ";
4426 if (ShowColors)
4427 OS.resetColor();
4428 OS << '(' << B.succ_size() << "):";
4429 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004430
Ted Kremenek72be32a2011-12-22 23:33:52 +00004431 if (ShowColors)
4432 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00004433
Ted Kremenek72be32a2011-12-22 23:33:52 +00004434 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4435 I != E; ++I, ++i) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004436
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004437 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004438 OS << "\n ";
4439
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004440 CFGBlock *B = *I;
4441
4442 bool Reachable = true;
4443 if (!B) {
4444 Reachable = false;
4445 B = I->getPossiblyUnreachableBlock();
4446 }
4447
4448 if (B) {
4449 OS << " B" << B->getBlockID();
4450 if (!Reachable)
4451 OS << "(Unreachable)";
4452 }
4453 else {
4454 OS << " NULL";
4455 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00004456 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004457
Ted Kremenek72be32a2011-12-22 23:33:52 +00004458 if (ShowColors)
4459 OS.resetColor();
4460 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004461 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004462 }
Mike Stump31feda52009-07-17 01:31:16 +00004463}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004464
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004465
4466/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004467void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4468 print(llvm::errs(), LO, ShowColors);
4469}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004470
4471/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004472void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004473 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00004474
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004475 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004476 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00004477
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004478 // Iterate through the CFGBlocks and print them one by one.
4479 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4480 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004481 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004482 continue;
Mike Stump31feda52009-07-17 01:31:16 +00004483
Aaron Ballmanff924b02013-11-18 20:11:50 +00004484 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004485 }
Mike Stump31feda52009-07-17 01:31:16 +00004486
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004487 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004488 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004489 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00004490 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00004491}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004492
4493/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004494void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4495 bool ShowColors) const {
4496 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00004497}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004498
Anna Zaksa6fea132014-06-13 23:47:38 +00004499void CFGBlock::dump() const {
4500 dump(getParent(), LangOptions(), false);
4501}
4502
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004503/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4504/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004505void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004506 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004507 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004508 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004509 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00004510}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004511
Ted Kremenek15647632008-01-30 23:02:42 +00004512/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004513void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00004514 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00004515 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00004516 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004517}
4518
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004519Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Marcin Swiderskia7d84a72010-10-29 05:21:47 +00004520 Stmt *Terminator = this->Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004521 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00004522 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004523
Craig Topper25542942014-05-20 04:30:07 +00004524 Expr *E = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004525
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004526 switch (Terminator->getStmtClass()) {
4527 default:
4528 break;
Mike Stump31feda52009-07-17 01:31:16 +00004529
Jordan Rosecf10ea82013-06-06 21:53:45 +00004530 case Stmt::CXXForRangeStmtClass:
4531 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4532 break;
4533
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004534 case Stmt::ForStmtClass:
4535 E = cast<ForStmt>(Terminator)->getCond();
4536 break;
Mike Stump31feda52009-07-17 01:31:16 +00004537
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004538 case Stmt::WhileStmtClass:
4539 E = cast<WhileStmt>(Terminator)->getCond();
4540 break;
Mike Stump31feda52009-07-17 01:31:16 +00004541
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004542 case Stmt::DoStmtClass:
4543 E = cast<DoStmt>(Terminator)->getCond();
4544 break;
Mike Stump31feda52009-07-17 01:31:16 +00004545
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004546 case Stmt::IfStmtClass:
4547 E = cast<IfStmt>(Terminator)->getCond();
4548 break;
Mike Stump31feda52009-07-17 01:31:16 +00004549
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004550 case Stmt::ChooseExprClass:
4551 E = cast<ChooseExpr>(Terminator)->getCond();
4552 break;
Mike Stump31feda52009-07-17 01:31:16 +00004553
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004554 case Stmt::IndirectGotoStmtClass:
4555 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4556 break;
Mike Stump31feda52009-07-17 01:31:16 +00004557
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004558 case Stmt::SwitchStmtClass:
4559 E = cast<SwitchStmt>(Terminator)->getCond();
4560 break;
Mike Stump31feda52009-07-17 01:31:16 +00004561
John McCallc07a0c72011-02-17 10:25:35 +00004562 case Stmt::BinaryConditionalOperatorClass:
4563 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4564 break;
4565
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004566 case Stmt::ConditionalOperatorClass:
4567 E = cast<ConditionalOperator>(Terminator)->getCond();
4568 break;
Mike Stump31feda52009-07-17 01:31:16 +00004569
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004570 case Stmt::BinaryOperatorClass: // '&&' and '||'
4571 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00004572 break;
Mike Stump31feda52009-07-17 01:31:16 +00004573
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00004574 case Stmt::ObjCForCollectionStmtClass:
Mike Stump31feda52009-07-17 01:31:16 +00004575 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004576 }
Mike Stump31feda52009-07-17 01:31:16 +00004577
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004578 if (!StripParens)
4579 return E;
4580
Craig Topper25542942014-05-20 04:30:07 +00004581 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004582}
4583
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004584//===----------------------------------------------------------------------===//
4585// CFG Graphviz Visualization
4586//===----------------------------------------------------------------------===//
4587
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004588
4589#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00004590static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004591#endif
4592
Chris Lattnerc61089a2009-06-30 01:26:17 +00004593void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004594#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00004595 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004596 GraphHelper = &H;
4597 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00004598 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004599#endif
4600}
4601
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004602namespace llvm {
4603template<>
4604struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Tobias Grosser9fc223a2009-11-30 14:16:05 +00004605
4606 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4607
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004608 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004609
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00004610#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004611 std::string OutSStr;
4612 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004613 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004614 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004615
4616 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4617
4618 // Process string output to make it nicer...
4619 for (unsigned i = 0; i != OutStr.length(); ++i)
4620 if (OutStr[i] == '\n') { // Left justify
4621 OutStr[i] = '\\';
4622 OutStr.insert(OutStr.begin()+i+1, 'l');
4623 }
Mike Stump31feda52009-07-17 01:31:16 +00004624
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004625 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00004626#else
4627 return "";
4628#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004629 }
4630};
4631} // end namespace llvm