blob: 2744c5fbe72d7db083dd18e2e2f9a25020119165 [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
Ted Kremenek7c58d352011-03-10 01:14:11 +000042class CFGBuilder;
43
Zhanyong Wanb5d11c12010-11-24 03:28:53 +000044/// The CFG builder uses a recursive algorithm to build the CFG. When
45/// we process an expression, sometimes we know that we must add the
46/// subexpressions as block-level expressions. For example:
47///
48/// exp1 || exp2
49///
50/// When processing the '||' expression, we know that exp1 and exp2
51/// need to be added as block-level expressions, even though they
52/// might not normally need to be. AddStmtChoice records this
53/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
54/// the builder has an option not to add a subexpression as a
55/// block-level expression.
56///
Ted Kremenek4cad5fc2009-12-16 03:18:58 +000057class AddStmtChoice {
58public:
Ted Kremenek8219b822010-12-16 07:46:53 +000059 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +000060
Zhanyong Wanb5d11c12010-11-24 03:28:53 +000061 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +000062
Ted Kremenek7c58d352011-03-10 01:14:11 +000063 bool alwaysAdd(CFGBuilder &builder,
64 const Stmt *stmt) const;
Zhanyong Wanb5d11c12010-11-24 03:28:53 +000065
66 /// Return a copy of this object, except with the 'always-add' bit
67 /// set as specified.
68 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
Ted Kremenek7c58d352011-03-10 01:14:11 +000069 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +000070 }
71
Ted Kremenek4cad5fc2009-12-16 03:18:58 +000072private:
Zhanyong Wanb5d11c12010-11-24 03:28:53 +000073 Kind kind;
Ted Kremenek4cad5fc2009-12-16 03:18:58 +000074};
Mike Stump31feda52009-07-17 01:31:16 +000075
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +000076/// LocalScope - Node in tree of local scopes created for C++ implicit
77/// destructor calls generation. It contains list of automatic variables
78/// declared in the scope and link to position in previous scope this scope
79/// began in.
80///
81/// The process of creating local scopes is as follows:
82/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
83/// - Before processing statements in scope (e.g. CompoundStmt) create
84/// LocalScope object using CFGBuilder::ScopePos as link to previous scope
85/// and set CFGBuilder::ScopePos to the end of new scope,
Marcin Swiderskie9862ce2010-09-30 22:42:32 +000086/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +000087/// at this VarDecl,
88/// - For every normal (without jump) end of scope add to CFGBlock destructors
89/// for objects in the current scope,
90/// - For every jump add to CFGBlock destructors for objects
91/// between CFGBuilder::ScopePos and local scope position saved for jump
92/// target. Thanks to C++ restrictions on goto jumps we can be sure that
93/// jump target position will be on the path to root from CFGBuilder::ScopePos
94/// (adding any variable that doesn't need constructor to be called to
95/// LocalScope can break this assumption),
96///
97class LocalScope {
98public:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +000099 typedef BumpVector<VarDecl*> AutomaticVarsTy;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000100
101 /// const_iterator - Iterates local scope backwards and jumps to previous
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000102 /// scope on reaching the beginning of currently iterated scope.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000103 class const_iterator {
104 const LocalScope* Scope;
105
106 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
107 /// Invalid iterator (with null Scope) has VarIter equal to 0.
108 unsigned VarIter;
109
110 public:
111 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
112 /// Incrementing invalid iterator is allowed and will result in invalid
113 /// iterator.
114 const_iterator()
Craig Topper25542942014-05-20 04:30:07 +0000115 : Scope(nullptr), VarIter(0) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000116
117 /// Create valid iterator. In case when S.Prev is an invalid iterator and
118 /// I is equal to 0, this will create invalid iterator.
119 const_iterator(const LocalScope& S, unsigned I)
120 : Scope(&S), VarIter(I) {
121 // Iterator to "end" of scope is not allowed. Handle it by going up
122 // in scopes tree possibly up to invalid iterator in the root.
123 if (VarIter == 0 && Scope)
124 *this = Scope->Prev;
125 }
126
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000127 VarDecl *const* operator->() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000128 assert (Scope && "Dereferencing invalid iterator is not allowed");
129 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
130 return &Scope->Vars[VarIter - 1];
131 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000132 VarDecl *operator*() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000133 return *this->operator->();
134 }
135
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000136 const_iterator &operator++() {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000137 if (!Scope)
138 return *this;
139
140 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
141 --VarIter;
142 if (VarIter == 0)
143 *this = Scope->Prev;
144 return *this;
145 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000146 const_iterator operator++(int) {
147 const_iterator P = *this;
148 ++*this;
149 return P;
150 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000151
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000152 bool operator==(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000153 return Scope == rhs.Scope && VarIter == rhs.VarIter;
154 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000155 bool operator!=(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000156 return !(*this == rhs);
157 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000158
Aaron Ballman67347662015-02-15 22:00:28 +0000159 explicit operator bool() const {
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000160 return *this != const_iterator();
161 }
162
163 int distance(const_iterator L);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000164 };
165
166 friend class const_iterator;
167
168private:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000169 BumpVectorContext ctx;
170
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000171 /// Automatic variables in order of declaration.
172 AutomaticVarsTy Vars;
173 /// Iterator to variable in previous scope that was declared just before
174 /// begin of this scope.
175 const_iterator Prev;
176
177public:
178 /// Constructs empty scope linked to previous scope in specified place.
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000179 LocalScope(BumpVectorContext &ctx, const_iterator P)
180 : ctx(ctx), Vars(ctx, 4), Prev(P) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000181
182 /// Begin of scope in direction of CFG building (backwards).
183 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000184
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000185 void addVar(VarDecl *VD) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000186 Vars.push_back(VD, ctx);
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000187 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000188};
189
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000190/// distance - Calculates distance from this to L. L must be reachable from this
191/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
192/// number of scopes between this and L.
193int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
194 int D = 0;
195 const_iterator F = *this;
196 while (F.Scope != L.Scope) {
Ted Kremenek50aa2d42011-08-12 14:41:23 +0000197 assert (F != const_iterator()
198 && "L iterator is not reachable from F iterator.");
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000199 D += F.VarIter;
200 F = F.Scope->Prev;
201 }
202 D += F.VarIter - L.VarIter;
203 return D;
204}
205
Jonathan Roelofs99bdd982015-05-19 18:51:56 +0000206/// Structure for specifying position in CFG during its build process. It
207/// consists of CFGBlock that specifies position in CFG and
208/// LocalScope::const_iterator that specifies position in LocalScope graph.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000209struct BlockScopePosPair {
Craig Topper25542942014-05-20 04:30:07 +0000210 BlockScopePosPair() : block(nullptr) {}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000211 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000212 : block(b), scopePosition(scopePos) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000213
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000214 CFGBlock *block;
215 LocalScope::const_iterator scopePosition;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000216};
217
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000218/// TryResult - a class representing a variant over the values
219/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
220/// and is used by the CFGBuilder to decide if a branch condition
221/// can be decided up front during CFG construction.
222class TryResult {
223 int X;
224public:
225 TryResult(bool b) : X(b ? 1 : 0) {}
226 TryResult() : X(-1) {}
227
228 bool isTrue() const { return X == 1; }
229 bool isFalse() const { return X == 0; }
230 bool isKnown() const { return X >= 0; }
231 void negate() {
232 assert(isKnown());
233 X ^= 0x1;
234 }
235};
236
Manuel Klimekdeb02622014-08-08 07:37:13 +0000237TryResult bothKnownTrue(TryResult R1, TryResult R2) {
238 if (!R1.isKnown() || !R2.isKnown())
239 return TryResult();
240 return TryResult(R1.isTrue() && R2.isTrue());
241}
242
Ted Kremenek8ae67872013-02-05 22:00:19 +0000243class reverse_children {
244 llvm::SmallVector<Stmt *, 12> childrenBuf;
245 ArrayRef<Stmt*> children;
246public:
247 reverse_children(Stmt *S);
248
249 typedef ArrayRef<Stmt*>::reverse_iterator iterator;
250 iterator begin() const { return children.rbegin(); }
251 iterator end() const { return children.rend(); }
252};
253
254
255reverse_children::reverse_children(Stmt *S) {
256 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
257 children = CE->getRawSubExprs();
258 return;
259 }
260 switch (S->getStmtClass()) {
Ted Kremenek7d86b9c2013-02-05 22:03:14 +0000261 // Note: Fill in this switch with more cases we want to optimize.
Ted Kremenek8ae67872013-02-05 22:00:19 +0000262 case Stmt::InitListExprClass: {
263 InitListExpr *IE = cast<InitListExpr>(S);
264 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
265 IE->getNumInits());
266 return;
267 }
268 default:
269 break;
270 }
271
272 // Default case for all other statements.
273 for (Stmt::child_range I = S->children(); I; ++I) {
274 childrenBuf.push_back(*I);
275 }
276
277 // This needs to be done *after* childrenBuf has been populated.
278 children = childrenBuf;
279}
280
Ted Kremenekbe9b33b2008-08-04 22:51:42 +0000281/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000282/// The builder is stateful: an instance of the builder should be used to only
283/// construct a single CFG.
284///
285/// Example usage:
286///
287/// CFGBuilder builder;
288/// CFG* cfg = builder.BuildAST(stmt1);
289///
Mike Stump31feda52009-07-17 01:31:16 +0000290/// CFG construction is done via a recursive walk of an AST. We actually parse
291/// the AST in reverse order so that the successor of a basic block is
292/// constructed prior to its predecessor. This allows us to nicely capture
293/// implicit fall-throughs without extra basic blocks.
Ted Kremenek1b8ac852007-08-21 22:06:14 +0000294///
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000295class CFGBuilder {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000296 typedef BlockScopePosPair JumpTarget;
297 typedef BlockScopePosPair JumpSource;
298
Mike Stump0d76d072009-07-20 23:24:15 +0000299 ASTContext *Context;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000300 std::unique_ptr<CFG> cfg;
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000301
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000302 CFGBlock *Block;
303 CFGBlock *Succ;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000304 JumpTarget ContinueJumpTarget;
305 JumpTarget BreakJumpTarget;
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000306 CFGBlock *SwitchTerminatedBlock;
307 CFGBlock *DefaultCaseBlock;
308 CFGBlock *TryTerminatedBlock;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000309
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000310 // Current position in local scope.
311 LocalScope::const_iterator ScopePos;
312
313 // LabelMap records the mapping from Label expressions to their jump targets.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000314 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
Ted Kremenek8a632182007-08-21 23:26:17 +0000315 LabelMapTy LabelMap;
Mike Stump31feda52009-07-17 01:31:16 +0000316
317 // A list of blocks that end with a "goto" that must be backpatched to their
318 // resolved targets upon completion of CFG construction.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000319 typedef std::vector<JumpSource> BackpatchBlocksTy;
Ted Kremenek8a632182007-08-21 23:26:17 +0000320 BackpatchBlocksTy BackpatchBlocks;
Mike Stump31feda52009-07-17 01:31:16 +0000321
Ted Kremenekeda180e22007-08-28 19:26:49 +0000322 // A list of labels whose address has been taken (for indirect gotos).
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000323 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
Ted Kremenekeda180e22007-08-28 19:26:49 +0000324 LabelSetTy AddressTakenLabels;
Mike Stump31feda52009-07-17 01:31:16 +0000325
Zhongxing Xud38fb842010-09-16 03:28:18 +0000326 bool badCFG;
Ted Kremenekf9d82902011-03-10 01:14:05 +0000327 const CFG::BuildOptions &BuildOpts;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000328
329 // State to track for building switch statements.
330 bool switchExclusivelyCovered;
Ted Kremenekbe528712011-03-04 01:03:41 +0000331 Expr::EvalResult *switchCond;
Ted Kremeneka099c592011-03-10 03:50:34 +0000332
333 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000334 const Stmt *lastLookup;
Zhongxing Xud38fb842010-09-16 03:28:18 +0000335
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000336 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
337 // during construction of branches for chained logical operators.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000338 typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
339 CachedBoolEvalsTy CachedBoolEvals;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000340
Mike Stump31feda52009-07-17 01:31:16 +0000341public:
Ted Kremenekf9d82902011-03-10 01:14:05 +0000342 explicit CFGBuilder(ASTContext *astContext,
343 const CFG::BuildOptions &buildOpts)
344 : Context(astContext), cfg(new CFG()), // crew a new CFG
Craig Topper25542942014-05-20 04:30:07 +0000345 Block(nullptr), Succ(nullptr),
346 SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr),
347 TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts),
348 switchExclusivelyCovered(false), switchCond(nullptr),
349 cachedEntry(nullptr), lastLookup(nullptr) {}
Mike Stump31feda52009-07-17 01:31:16 +0000350
Ted Kremenek9aae5132007-08-23 21:42:29 +0000351 // buildCFG - Used by external clients to construct the CFG.
David Blaikiee90195c2014-08-29 18:53:26 +0000352 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
Mike Stump31feda52009-07-17 01:31:16 +0000353
Ted Kremeneka099c592011-03-10 03:50:34 +0000354 bool alwaysAdd(const Stmt *stmt);
355
Ted Kremenek93668002009-07-17 22:18:43 +0000356private:
357 // Visitors to walk an AST and construct the CFG.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000358 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
359 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000360 CFGBlock *VisitBreakStmt(BreakStmt *B);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000361 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000362 CFGBlock *VisitCaseStmt(CaseStmt *C);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000363 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000364 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
John McCallc07a0c72011-02-17 10:25:35 +0000365 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
366 AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000367 CFGBlock *VisitContinueStmt(ContinueStmt *C);
Ted Kremenek6f400242012-07-14 05:04:01 +0000368 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
369 AddStmtChoice asc);
370 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
371 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
Jordan Rosec9176072014-01-13 17:59:19 +0000372 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
Jordan Rosed2f40792013-09-03 17:00:57 +0000373 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000374 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
375 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
376 AddStmtChoice asc);
377 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
378 AddStmtChoice asc);
379 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
380 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000381 CFGBlock *VisitDeclStmt(DeclStmt *DS);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000382 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
Ted Kremenek21822592009-07-17 18:20:32 +0000383 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
384 CFGBlock *VisitDoStmt(DoStmt *D);
Ted Kremenek6f400242012-07-14 05:04:01 +0000385 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000386 CFGBlock *VisitForStmt(ForStmt *F);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000387 CFGBlock *VisitGotoStmt(GotoStmt *G);
Ted Kremenek93668002009-07-17 22:18:43 +0000388 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000389 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000390 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
391 CFGBlock *VisitLabelStmt(LabelStmt *L);
Ted Kremenek6f400242012-07-14 05:04:01 +0000392 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000393 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000394 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
395 Stmt *Term,
396 CFGBlock *TrueBlock,
397 CFGBlock *FalseBlock);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000398 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000399 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
400 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
401 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
402 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000403 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000404 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
John McCallfe96e0b2011-11-06 09:01:30 +0000405 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Ted Kremenek6f400242012-07-14 05:04:01 +0000406 CFGBlock *VisitReturnStmt(ReturnStmt *R);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000407 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000408 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000409 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
410 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000411 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000412 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000413
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000414 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
415 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000416 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000417 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000418
Manuel Klimekb5616c92014-08-07 10:42:17 +0000419 /// When creating the CFG for temporary destructors, we want to mirror the
420 /// branch structure of the corresponding constructor calls.
421 /// Thus, while visiting a statement for temporary destructors, we keep a
422 /// context to keep track of the following information:
423 /// - whether a subexpression is executed unconditionally
424 /// - if a subexpression is executed conditionally, the first
425 /// CXXBindTemporaryExpr we encounter in that subexpression (which
426 /// corresponds to the last temporary destructor we have to call for this
427 /// subexpression) and the CFG block at that point (which will become the
428 /// successor block when inserting the decision point).
429 ///
430 /// That way, we can build the branch structure for temporary destructors as
431 /// follows:
432 /// 1. If a subexpression is executed unconditionally, we add the temporary
433 /// destructor calls to the current block.
434 /// 2. If a subexpression is executed conditionally, when we encounter a
435 /// CXXBindTemporaryExpr:
436 /// a) If it is the first temporary destructor call in the subexpression,
437 /// we remember the CXXBindTemporaryExpr and the current block in the
438 /// TempDtorContext; we start a new block, and insert the temporary
439 /// destructor call.
440 /// b) Otherwise, add the temporary destructor call to the current block.
441 /// 3. When we finished visiting a conditionally executed subexpression,
442 /// and we found at least one temporary constructor during the visitation
443 /// (2.a has executed), we insert a decision block that uses the
444 /// CXXBindTemporaryExpr as terminator, and branches to the current block
445 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
446 /// branches to the stored successor.
447 struct TempDtorContext {
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000448 TempDtorContext()
449 : IsConditional(false), KnownExecuted(true), Succ(nullptr),
450 TerminatorExpr(nullptr) {}
Manuel Klimekdeb02622014-08-08 07:37:13 +0000451
452 TempDtorContext(TryResult KnownExecuted)
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000453 : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr),
454 TerminatorExpr(nullptr) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000455
456 /// Returns whether we need to start a new branch for a temporary destructor
457 /// call. This is the case when the the temporary destructor is
458 /// conditionally executed, and it is the first one we encounter while
459 /// visiting a subexpression - other temporary destructors at the same level
460 /// will be added to the same block and are executed under the same
461 /// condition.
462 bool needsTempDtorBranch() const {
463 return IsConditional && !TerminatorExpr;
464 }
465
466 /// Remember the successor S of a temporary destructor decision branch for
467 /// the corresponding CXXBindTemporaryExpr E.
468 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
469 Succ = S;
470 TerminatorExpr = E;
471 }
472
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000473 const bool IsConditional;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000474 const TryResult KnownExecuted;
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000475 CFGBlock *Succ;
476 CXXBindTemporaryExpr *TerminatorExpr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000477 };
478
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000479 // Visitors to walk an AST and generate destructors of temporaries in
480 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000481 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
482 TempDtorContext &Context);
483 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
484 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
485 TempDtorContext &Context);
486 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
487 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
488 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
489 AbstractConditionalOperator *E, bool BindToTemporary,
490 TempDtorContext &Context);
491 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
492 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000493
Ted Kremenek6065ef62008-04-28 18:00:46 +0000494 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000495 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000496 badCFG = true;
497 return Block;
498 }
Mike Stump31feda52009-07-17 01:31:16 +0000499
Ted Kremenek93668002009-07-17 22:18:43 +0000500 void autoCreateBlock() { if (!Block) Block = createBlock(); }
501 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000502 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000503
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000504 CFGBlock *addStmt(Stmt *S) {
505 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000506 }
Alexis Hunt1d792652011-01-08 20:30:50 +0000507 CFGBlock *addInitializer(CXXCtorInitializer *I);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000508 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000509 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000510 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000511
Marcin Swiderski5e415732010-09-30 23:05:00 +0000512 // Local scopes creation.
513 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
514
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000515 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000516 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
517 LocalScope* Scope = nullptr);
518 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000519
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000520 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000521
522 // Interface to CFGBlock - adding CFGElements.
Ted Kremenek37881932011-04-04 23:29:12 +0000523 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000524 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000525 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000526
Jordy Rose17347372011-06-10 08:49:37 +0000527 // All block-level expressions should have already been IgnoreParens()ed.
528 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000529 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000530 }
Alexis Hunt1d792652011-01-08 20:30:50 +0000531 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000532 B->appendInitializer(I, cfg->getBumpVectorContext());
533 }
Jordan Rosec9176072014-01-13 17:59:19 +0000534 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
535 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
536 }
Marcin Swiderski20b88732010-10-05 05:37:00 +0000537 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
538 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
539 }
540 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
541 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
542 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000543 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
544 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
545 }
Chandler Carruthad747252011-09-13 06:09:01 +0000546 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
547 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
548 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000549
Jordan Rosed2f40792013-09-03 17:00:57 +0000550 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
551 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
552 }
553
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000554 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000555 LocalScope::const_iterator B, LocalScope::const_iterator E);
556
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000557 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
558 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
559 cfg->getBumpVectorContext());
560 }
561
562 /// Add a reachable successor to a block, with the alternate variant that is
563 /// unreachable.
564 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
565 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
566 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000567 }
Mike Stump11289f42009-09-09 15:08:12 +0000568
Richard Trieuf935b562014-04-05 05:17:01 +0000569 /// \brief Find a relational comparison with an expression evaluating to a
570 /// boolean and a constant other than 0 and 1.
571 /// e.g. if ((x < y) == 10)
572 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
573 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
574 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
575
576 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
577 const Expr *BoolExpr = RHSExpr;
578 bool IntFirst = true;
579 if (!IntLiteral) {
580 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
581 BoolExpr = LHSExpr;
582 IntFirst = false;
583 }
584
585 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
586 return TryResult();
587
588 llvm::APInt IntValue = IntLiteral->getValue();
589 if ((IntValue == 1) || (IntValue == 0))
590 return TryResult();
591
592 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
593 !IntValue.isNegative();
594
595 BinaryOperatorKind Bok = B->getOpcode();
596 if (Bok == BO_GT || Bok == BO_GE) {
597 // Always true for 10 > bool and bool > -1
598 // Always false for -1 > bool and bool > 10
599 return TryResult(IntFirst == IntLarger);
600 } else {
601 // Always true for -1 < bool and bool < 10
602 // Always false for 10 < bool and bool < -1
603 return TryResult(IntFirst != IntLarger);
604 }
605 }
606
Jordan Rose7afd71e2014-05-20 17:31:11 +0000607 /// Find an incorrect equality comparison. Either with an expression
608 /// evaluating to a boolean and a constant other than 0 and 1.
609 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
610 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000611 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
612 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
613 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
614
615 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
616 const Expr *BoolExpr = RHSExpr;
617
618 if (!IntLiteral) {
619 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
620 BoolExpr = LHSExpr;
621 }
622
Jordan Rose7afd71e2014-05-20 17:31:11 +0000623 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000624 return TryResult();
625
Jordan Rose7afd71e2014-05-20 17:31:11 +0000626 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
627 if (BitOp && (BitOp->getOpcode() == BO_And ||
628 BitOp->getOpcode() == BO_Or)) {
629 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
630 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
631
632 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
633
634 if (!IntLiteral2)
635 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
636
637 if (!IntLiteral2)
638 return TryResult();
639
640 llvm::APInt L1 = IntLiteral->getValue();
641 llvm::APInt L2 = IntLiteral2->getValue();
642 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
643 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
644 if (BuildOpts.Observer)
645 BuildOpts.Observer->compareBitwiseEquality(B,
646 B->getOpcode() != BO_EQ);
647 TryResult(B->getOpcode() != BO_EQ);
648 }
649 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
650 llvm::APInt IntValue = IntLiteral->getValue();
651 if ((IntValue == 1) || (IntValue == 0)) {
652 return TryResult();
653 }
654 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000655 }
656
Jordan Rose7afd71e2014-05-20 17:31:11 +0000657 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000658 }
659
660 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
661 const llvm::APSInt &Value1,
662 const llvm::APSInt &Value2) {
663 assert(Value1.isSigned() == Value2.isSigned());
664 switch (Relation) {
665 default:
666 return TryResult();
667 case BO_EQ:
668 return TryResult(Value1 == Value2);
669 case BO_NE:
670 return TryResult(Value1 != Value2);
671 case BO_LT:
672 return TryResult(Value1 < Value2);
673 case BO_LE:
674 return TryResult(Value1 <= Value2);
675 case BO_GT:
676 return TryResult(Value1 > Value2);
677 case BO_GE:
678 return TryResult(Value1 >= Value2);
679 }
680 }
681
682 /// \brief Find a pair of comparison expressions with or without parentheses
683 /// with a shared variable and constants and a logical operator between them
684 /// that always evaluates to either true or false.
685 /// e.g. if (x != 3 || x != 4)
686 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
687 assert(B->isLogicalOp());
688 const BinaryOperator *LHS =
689 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
690 const BinaryOperator *RHS =
691 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
692 if (!LHS || !RHS)
693 return TryResult();
694
695 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
696 return TryResult();
697
698 BinaryOperatorKind BO1 = LHS->getOpcode();
699 const DeclRefExpr *Decl1 =
700 dyn_cast<DeclRefExpr>(LHS->getLHS()->IgnoreParenImpCasts());
701 const IntegerLiteral *Literal1 =
702 dyn_cast<IntegerLiteral>(LHS->getRHS()->IgnoreParens());
703 if (!Decl1 && !Literal1) {
704 if (BO1 == BO_GT)
705 BO1 = BO_LT;
706 else if (BO1 == BO_GE)
707 BO1 = BO_LE;
708 else if (BO1 == BO_LT)
709 BO1 = BO_GT;
710 else if (BO1 == BO_LE)
711 BO1 = BO_GE;
712 Decl1 = dyn_cast<DeclRefExpr>(LHS->getRHS()->IgnoreParenImpCasts());
713 Literal1 = dyn_cast<IntegerLiteral>(LHS->getLHS()->IgnoreParens());
714 }
715
716 if (!Decl1 || !Literal1)
717 return TryResult();
718
719 BinaryOperatorKind BO2 = RHS->getOpcode();
720 const DeclRefExpr *Decl2 =
721 dyn_cast<DeclRefExpr>(RHS->getLHS()->IgnoreParenImpCasts());
722 const IntegerLiteral *Literal2 =
723 dyn_cast<IntegerLiteral>(RHS->getRHS()->IgnoreParens());
724 if (!Decl2 && !Literal2) {
725 if (BO2 == BO_GT)
726 BO2 = BO_LT;
727 else if (BO2 == BO_GE)
728 BO2 = BO_LE;
729 else if (BO2 == BO_LT)
730 BO2 = BO_GT;
731 else if (BO2 == BO_LE)
732 BO2 = BO_GE;
733 Decl2 = dyn_cast<DeclRefExpr>(RHS->getRHS()->IgnoreParenImpCasts());
734 Literal2 = dyn_cast<IntegerLiteral>(RHS->getLHS()->IgnoreParens());
735 }
736
737 if (!Decl2 || !Literal2)
738 return TryResult();
739
740 // Check that it is the same variable on both sides.
741 if (Decl1->getDecl() != Decl2->getDecl())
742 return TryResult();
743
744 llvm::APSInt L1, L2;
745
746 if (!Literal1->EvaluateAsInt(L1, *Context) ||
747 !Literal2->EvaluateAsInt(L2, *Context))
748 return TryResult();
749
750 // Can't compare signed with unsigned or with different bit width.
751 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
752 return TryResult();
753
754 // Values that will be used to determine if result of logical
755 // operator is always true/false
756 const llvm::APSInt Values[] = {
757 // Value less than both Value1 and Value2
758 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
759 // L1
760 L1,
761 // Value between Value1 and Value2
762 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
763 L1.isUnsigned()),
764 // L2
765 L2,
766 // Value greater than both Value1 and Value2
767 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
768 };
769
770 // Check whether expression is always true/false by evaluating the following
771 // * variable x is less than the smallest literal.
772 // * variable x is equal to the smallest literal.
773 // * Variable x is between smallest and largest literal.
774 // * Variable x is equal to the largest literal.
775 // * Variable x is greater than largest literal.
776 bool AlwaysTrue = true, AlwaysFalse = true;
777 for (unsigned int ValueIndex = 0;
778 ValueIndex < sizeof(Values) / sizeof(Values[0]);
779 ++ValueIndex) {
780 llvm::APSInt Value = Values[ValueIndex];
781 TryResult Res1, Res2;
782 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
783 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
784
785 if (!Res1.isKnown() || !Res2.isKnown())
786 return TryResult();
787
788 if (B->getOpcode() == BO_LAnd) {
789 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
790 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
791 } else {
792 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
793 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
794 }
795 }
796
797 if (AlwaysTrue || AlwaysFalse) {
798 if (BuildOpts.Observer)
799 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
800 return TryResult(AlwaysTrue);
801 }
802 return TryResult();
803 }
804
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000805 /// Try and evaluate an expression to an integer constant.
806 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
807 if (!BuildOpts.PruneTriviallyFalseEdges)
808 return false;
809 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +0000810 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +0000811 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000812 }
Mike Stump11289f42009-09-09 15:08:12 +0000813
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000814 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +0000815 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000816 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +0000817 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000818 S->isTypeDependent() || S->isValueDependent())
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000819 return TryResult();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000820
821 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
822 if (Bop->isLogicalOp()) {
823 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000824 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
825 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000826 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +0000827
828 // Retrieve result at first, or the map might be updated.
829 TryResult Result = evaluateAsBooleanConditionNoCache(S);
830 CachedBoolEvals[S] = Result; // update or insert
831 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000832 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000833 else {
834 switch (Bop->getOpcode()) {
835 default: break;
836 // For 'x & 0' and 'x * 0', we can determine that
837 // the value is always false.
838 case BO_Mul:
839 case BO_And: {
840 // If either operand is zero, we know the value
841 // must be false.
842 llvm::APSInt IntVal;
843 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +0000844 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000845 return TryResult(false);
846 }
847 }
848 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +0000849 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000850 return TryResult(false);
851 }
852 }
853 }
854 break;
855 }
856 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000857 }
858
859 return evaluateAsBooleanConditionNoCache(S);
860 }
861
862 /// \brief Evaluate as boolean \param E without using the cache.
863 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
864 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
865 if (Bop->isLogicalOp()) {
866 TryResult LHS = tryEvaluateBool(Bop->getLHS());
867 if (LHS.isKnown()) {
868 // We were able to evaluate the LHS, see if we can get away with not
869 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
870 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
871 return LHS.isTrue();
872
873 TryResult RHS = tryEvaluateBool(Bop->getRHS());
874 if (RHS.isKnown()) {
875 if (Bop->getOpcode() == BO_LOr)
876 return LHS.isTrue() || RHS.isTrue();
877 else
878 return LHS.isTrue() && RHS.isTrue();
879 }
880 } else {
881 TryResult RHS = tryEvaluateBool(Bop->getRHS());
882 if (RHS.isKnown()) {
883 // We can't evaluate the LHS; however, sometimes the result
884 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
885 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
886 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +0000887 } else {
888 TryResult BopRes = checkIncorrectLogicOperator(Bop);
889 if (BopRes.isKnown())
890 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000891 }
892 }
893
894 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000895 } else if (Bop->isEqualityOp()) {
896 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
897 if (BopRes.isKnown())
898 return BopRes.isTrue();
899 } else if (Bop->isRelationalOp()) {
900 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
901 if (BopRes.isKnown())
902 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000903 }
904 }
905
906 bool Result;
907 if (E->EvaluateAsBooleanCondition(Result, *Context))
908 return Result;
909
910 return TryResult();
Mike Stump773582d2009-07-23 23:25:26 +0000911 }
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000912
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000913};
Mike Stump31feda52009-07-17 01:31:16 +0000914
Ted Kremeneka099c592011-03-10 03:50:34 +0000915inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
916 const Stmt *stmt) const {
917 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
918}
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000919
Ted Kremeneka099c592011-03-10 03:50:34 +0000920bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000921 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
922
Ted Kremeneka099c592011-03-10 03:50:34 +0000923 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +0000924 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000925
926 if (lastLookup == stmt) {
927 if (cachedEntry) {
928 assert(cachedEntry->first == stmt);
929 return true;
930 }
Ted Kremenek8b46c002011-07-19 14:18:43 +0000931 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000932 }
Ted Kremeneka099c592011-03-10 03:50:34 +0000933
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000934 lastLookup = stmt;
935
936 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +0000937 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
938
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000939 if (!fb) {
940 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +0000941 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +0000942 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000943 }
Ted Kremeneka099c592011-03-10 03:50:34 +0000944
945 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000946 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +0000947 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +0000948 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000949 }
950
Ted Kremeneka099c592011-03-10 03:50:34 +0000951 cachedEntry = &*itr;
952 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +0000953}
954
Douglas Gregor4619e432008-12-05 23:32:09 +0000955// FIXME: Add support for dependent-sized array types in C++?
956// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +0000957static const VariableArrayType *FindVA(const Type *t) {
958 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
959 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +0000960 if (vat->getSizeExpr())
961 return vat;
Mike Stump31feda52009-07-17 01:31:16 +0000962
Ted Kremenekd86d39c2008-09-26 22:58:57 +0000963 t = vt->getElementType().getTypePtr();
964 }
Mike Stump31feda52009-07-17 01:31:16 +0000965
Craig Topper25542942014-05-20 04:30:07 +0000966 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +0000967}
Mike Stump31feda52009-07-17 01:31:16 +0000968
969/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
970/// arbitrary statement. Examples include a single expression or a function
971/// body (compound statement). The ownership of the returned CFG is
972/// transferred to the caller. If CFG construction fails, this method returns
973/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +0000974std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +0000975 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +0000976 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +0000977 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +0000978
Mike Stump31feda52009-07-17 01:31:16 +0000979 // Create an empty block that will serve as the exit block for the CFG. Since
980 // this is the first block added to the CFG, it will be implicitly registered
981 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +0000982 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000983 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +0000984 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +0000985
Marcin Swiderski20b88732010-10-05 05:37:00 +0000986 if (BuildOpts.AddImplicitDtors)
987 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
988 addImplicitDtorsForDestructor(DD);
989
Ted Kremenek9aae5132007-08-23 21:42:29 +0000990 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +0000991 CFGBlock *B = addStmt(Statement);
992
993 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +0000994 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +0000995
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000996 // For C++ constructor add initializers to CFG.
997 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
998 for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
999 E = CD->init_rend(); I != E; ++I) {
1000 B = addInitializer(*I);
1001 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001002 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001003 }
1004 }
1005
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001006 if (B)
1007 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001008
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001009 // Backpatch the gotos whose label -> block mappings we didn't know when we
1010 // encountered them.
1011 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1012 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001013
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001014 CFGBlock *B = I->block;
Rafael Espindola210de572013-03-27 15:37:54 +00001015 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001016 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00001017
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001018 // If there is no target for the goto, then we are looking at an
1019 // incomplete AST. Handle this by not registering a successor.
1020 if (LI == LabelMap.end()) continue;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001021
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001022 JumpTarget JT = LI->second;
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001023 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1024 JT.scopePosition);
1025 addSuccessor(B, JT.block);
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001026 }
1027
1028 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001029 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001030 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1031 E = AddressTakenLabels.end(); I != E; ++I ) {
1032
1033 // Lookup the target block.
1034 LabelMapTy::iterator LI = LabelMap.find(*I);
1035
1036 // If there is no target block that contains label, then we are looking
1037 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001038 if (LI == LabelMap.end()) continue;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001039
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001040 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001041 }
Mike Stump31feda52009-07-17 01:31:16 +00001042
Mike Stump31feda52009-07-17 01:31:16 +00001043 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001044 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001045
David Blaikiee90195c2014-08-29 18:53:26 +00001046 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001047}
Mike Stump31feda52009-07-17 01:31:16 +00001048
Ted Kremenek9aae5132007-08-23 21:42:29 +00001049/// createBlock - Used to lazily create blocks that are connected
1050/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001051CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1052 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001053 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001054 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001055 return B;
1056}
Mike Stump31feda52009-07-17 01:31:16 +00001057
Chandler Carrutha70991b2011-09-13 09:13:49 +00001058/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1059/// CFG. It is *not* connected to the current (global) successor, and instead
1060/// directly tied to the exit block in order to be reachable.
1061CFGBlock *CFGBuilder::createNoReturnBlock() {
1062 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001063 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001064 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001065 return B;
1066}
1067
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001068/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001069CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001070 if (!BuildOpts.AddInitializers)
1071 return Block;
1072
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001073 bool HasTemporaries = false;
1074
1075 // Destructors of temporaries in initialization expression should be called
1076 // after initialization finishes.
1077 Expr *Init = I->getInit();
1078 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001079 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001080
Jordan Rose6d671cc2012-09-05 22:55:23 +00001081 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001082 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001083 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001084 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1085 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001086 }
1087 }
1088
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001089 autoCreateBlock();
1090 appendInitializer(Block, I);
1091
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001092 if (Init) {
Ted Kremenek8219b822010-12-16 07:46:53 +00001093 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001094 // For expression with temporaries go directly to subexpression to omit
1095 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001096 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1097 }
1098 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001099 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001100
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001101 return Block;
1102}
1103
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001104/// \brief Retrieve the type of the temporary object whose lifetime was
1105/// extended by a local reference with the given initializer.
1106static QualType getReferenceInitTemporaryType(ASTContext &Context,
1107 const Expr *Init) {
1108 while (true) {
1109 // Skip parentheses.
1110 Init = Init->IgnoreParens();
1111
1112 // Skip through cleanups.
1113 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1114 Init = EWC->getSubExpr();
1115 continue;
1116 }
1117
1118 // Skip through the temporary-materialization expression.
1119 if (const MaterializeTemporaryExpr *MTE
1120 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1121 Init = MTE->GetTemporaryExpr();
1122 continue;
1123 }
1124
1125 // Skip derived-to-base and no-op casts.
1126 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1127 if ((CE->getCastKind() == CK_DerivedToBase ||
1128 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1129 CE->getCastKind() == CK_NoOp) &&
1130 Init->getType()->isRecordType()) {
1131 Init = CE->getSubExpr();
1132 continue;
1133 }
1134 }
1135
1136 // Skip member accesses into rvalues.
1137 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1138 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1139 Init = ME->getBase();
1140 continue;
1141 }
1142 }
1143
1144 break;
1145 }
1146
1147 return Init->getType();
1148}
1149
Marcin Swiderski5e415732010-09-30 23:05:00 +00001150/// addAutomaticObjDtors - Add to current block automatic objects destructors
1151/// for objects in range of local scope positions. Use S as trigger statement
1152/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001153void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001154 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001155 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001156 return;
1157
Marcin Swiderski5e415732010-09-30 23:05:00 +00001158 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001159 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001160
Chandler Carruthad747252011-09-13 06:09:01 +00001161 // We need to append the destructors in reverse order, but any one of them
1162 // may be a no-return destructor which changes the CFG. As a result, buffer
1163 // this sequence up and replay them in reverse order when appending onto the
1164 // CFGBlock(s).
1165 SmallVector<VarDecl*, 10> Decls;
1166 Decls.reserve(B.distance(E));
1167 for (LocalScope::const_iterator I = B; I != E; ++I)
1168 Decls.push_back(*I);
1169
1170 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1171 E = Decls.rend();
1172 I != E; ++I) {
1173 // If this destructor is marked as a no-return destructor, we need to
1174 // create a new block for the destructor which does not have as a successor
1175 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001176 QualType Ty = (*I)->getType();
1177 if (Ty->isReferenceType()) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001178 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001179 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001180 Ty = Context->getBaseElementType(Ty);
1181
Chandler Carruthad747252011-09-13 06:09:01 +00001182 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
Richard Smith10876ef2013-01-17 01:30:42 +00001183 if (Dtor->isNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001184 Block = createNoReturnBlock();
1185 else
Chandler Carruthad747252011-09-13 06:09:01 +00001186 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001187
1188 appendAutomaticObjDtor(Block, *I, S);
1189 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001190}
1191
Marcin Swiderski20b88732010-10-05 05:37:00 +00001192/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1193/// base and member objects in destructor.
1194void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1195 assert (BuildOpts.AddImplicitDtors
1196 && "Can be called only when dtors should be added");
1197 const CXXRecordDecl *RD = DD->getParent();
1198
1199 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001200 for (const auto &VI : RD->vbases()) {
1201 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001202 if (!CD->hasTrivialDestructor()) {
1203 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001204 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001205 }
1206 }
1207
1208 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001209 for (const auto &BI : RD->bases()) {
1210 if (!BI.isVirtual()) {
1211 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001212 if (!CD->hasTrivialDestructor()) {
1213 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001214 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001215 }
1216 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001217 }
1218
1219 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001220 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001221 // Check for constant size array. Set type to array element type.
1222 QualType QT = FI->getType();
1223 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1224 if (AT->getSize() == 0)
1225 continue;
1226 QT = AT->getElementType();
1227 }
1228
1229 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001230 if (!CD->hasTrivialDestructor()) {
1231 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001232 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001233 }
1234 }
1235}
1236
Marcin Swiderski5e415732010-09-30 23:05:00 +00001237/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1238/// way return valid LocalScope object.
1239LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
1240 if (!Scope) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +00001241 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1242 Scope = alloc.Allocate<LocalScope>();
1243 BumpVectorContext ctx(alloc);
1244 new (Scope) LocalScope(ctx, ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001245 }
1246 return Scope;
1247}
1248
1249/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Zhongxing Xu81714f22010-10-01 03:00:16 +00001250/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001251void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001252 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001253 return;
1254
Craig Topper25542942014-05-20 04:30:07 +00001255 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001256
1257 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001258 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001259 for (auto *BI : CS->body()) {
1260 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001261 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001262 Scope = addLocalScopeForDeclStmt(DS, Scope);
1263 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001264 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001265 }
1266
1267 // For any other statement scope will be implicit and as such will be
1268 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001269 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001270 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001271}
1272
1273/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1274/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001275LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001276 LocalScope* Scope) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001277 if (!BuildOpts.AddImplicitDtors)
1278 return Scope;
1279
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001280 for (auto *DI : DS->decls())
1281 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001282 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001283 return Scope;
1284}
1285
1286/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1287/// create add scope for automatic objects and temporary objects bound to
1288/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001289LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001290 LocalScope* Scope) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001291 if (!BuildOpts.AddImplicitDtors)
1292 return Scope;
1293
1294 // Check if variable is local.
1295 switch (VD->getStorageClass()) {
1296 case SC_None:
1297 case SC_Auto:
1298 case SC_Register:
1299 break;
1300 default: return Scope;
1301 }
1302
1303 // Check for const references bound to temporary. Set type to pointee.
1304 QualType QT = VD->getType();
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001305 if (QT.getTypePtr()->isReferenceType()) {
Richard Smith5a0ef782013-06-27 21:43:17 +00001306 // Attempt to determine whether this declaration lifetime-extends a
1307 // temporary.
1308 //
1309 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1310 // temporaries, and a single declaration can extend multiple temporaries.
1311 // We should look at the storage duration on each nested
1312 // MaterializeTemporaryExpr instead.
1313 const Expr *Init = VD->getInit();
1314 if (!Init)
1315 return Scope;
1316 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
1317 Init = EWC->getSubExpr();
1318 if (!isa<MaterializeTemporaryExpr>(Init))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001319 return Scope;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001320
Richard Smith5a0ef782013-06-27 21:43:17 +00001321 // Lifetime-extending a temporary.
1322 QT = getReferenceInitTemporaryType(*Context, Init);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001323 }
1324
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001325 // Check for constant size array. Set type to array element type.
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001326 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001327 if (AT->getSize() == 0)
1328 return Scope;
1329 QT = AT->getElementType();
1330 }
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001331
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001332 // Check if type is a C++ class with non-trivial destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001333 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
David Blaikie0f2ae782012-01-24 04:51:48 +00001334 if (!CD->hasTrivialDestructor()) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001335 // Add the variable to scope
1336 Scope = createOrReuseLocalScope(Scope);
1337 Scope->addVar(VD);
1338 ScopePos = Scope->begin();
1339 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001340 return Scope;
1341}
1342
1343/// addLocalScopeAndDtors - For given statement add local scope for it and
1344/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001345void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001346 if (!BuildOpts.AddImplicitDtors)
1347 return;
1348
1349 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001350 addLocalScopeForStmt(S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001351 addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
1352}
1353
Marcin Swiderski321a7072010-09-30 22:54:37 +00001354/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1355/// variables with automatic storage duration to CFGBlock's elements vector.
1356/// Elements will be prepended to physical beginning of the vector which
1357/// happens to be logical end. Use blocks terminator as statement that specifies
1358/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001359/// FIXME: This mechanism for adding automatic destructors doesn't handle
1360/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001361void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00001362 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Chandler Carruthad747252011-09-13 06:09:01 +00001363 BumpVectorContext &C = cfg->getBumpVectorContext();
1364 CFGBlock::iterator InsertPos
1365 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1366 for (LocalScope::const_iterator I = B; I != E; ++I)
1367 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1368 Blk->getTerminator());
Marcin Swiderski321a7072010-09-30 22:54:37 +00001369}
1370
Ted Kremenek93668002009-07-17 22:18:43 +00001371/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00001372/// blocks for ternary operators, &&, and ||. We also process "," and
1373/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001374CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001375 if (!S) {
1376 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00001377 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001378 }
Jordy Rose17347372011-06-10 08:49:37 +00001379
1380 if (Expr *E = dyn_cast<Expr>(S))
1381 S = E->IgnoreParens();
1382
Ted Kremenek93668002009-07-17 22:18:43 +00001383 switch (S->getStmtClass()) {
1384 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001385 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001386
1387 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001388 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001389
John McCallc07a0c72011-02-17 10:25:35 +00001390 case Stmt::BinaryConditionalOperatorClass:
1391 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1392
Ted Kremenek93668002009-07-17 22:18:43 +00001393 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001394 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001395
Ted Kremenek93668002009-07-17 22:18:43 +00001396 case Stmt::BlockExprClass:
Ted Kremeneke2499842012-04-12 20:03:44 +00001397 return VisitNoRecurse(cast<Expr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001398
Ted Kremenek93668002009-07-17 22:18:43 +00001399 case Stmt::BreakStmtClass:
1400 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001401
Ted Kremenek93668002009-07-17 22:18:43 +00001402 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00001403 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00001404 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001405 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001406 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001407
Ted Kremenek93668002009-07-17 22:18:43 +00001408 case Stmt::CaseStmtClass:
1409 return VisitCaseStmt(cast<CaseStmt>(S));
1410
1411 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001412 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001413
Ted Kremenek93668002009-07-17 22:18:43 +00001414 case Stmt::CompoundStmtClass:
1415 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001416
Ted Kremenek93668002009-07-17 22:18:43 +00001417 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001418 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001419
Ted Kremenek93668002009-07-17 22:18:43 +00001420 case Stmt::ContinueStmtClass:
1421 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001422
Ted Kremenekb27378c2010-01-19 20:40:33 +00001423 case Stmt::CXXCatchStmtClass:
1424 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1425
John McCall5d413782010-12-06 08:20:24 +00001426 case Stmt::ExprWithCleanupsClass:
1427 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00001428
Jordan Rosee5d53932012-08-23 18:10:53 +00001429 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00001430 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00001431 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1432 // called function's declaration, not by the caller. If we simply add
1433 // this expression to the CFG, we could end up with the same Expr
1434 // appearing multiple times.
1435 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00001436 //
1437 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1438 // expression to be used in the same function (through aggregate
1439 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00001440 return VisitStmt(S, asc);
1441
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001442 case Stmt::CXXBindTemporaryExprClass:
1443 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1444
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001445 case Stmt::CXXConstructExprClass:
1446 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1447
Jordan Rosec9176072014-01-13 17:59:19 +00001448 case Stmt::CXXNewExprClass:
1449 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1450
Jordan Rosed2f40792013-09-03 17:00:57 +00001451 case Stmt::CXXDeleteExprClass:
1452 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1453
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001454 case Stmt::CXXFunctionalCastExprClass:
1455 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1456
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001457 case Stmt::CXXTemporaryObjectExprClass:
1458 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1459
Ted Kremenekb27378c2010-01-19 20:40:33 +00001460 case Stmt::CXXThrowExprClass:
1461 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001462
Ted Kremenekb27378c2010-01-19 20:40:33 +00001463 case Stmt::CXXTryStmtClass:
1464 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001465
Richard Smith02e85f32011-04-14 22:09:26 +00001466 case Stmt::CXXForRangeStmtClass:
1467 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1468
Ted Kremenek93668002009-07-17 22:18:43 +00001469 case Stmt::DeclStmtClass:
1470 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001471
Ted Kremenek93668002009-07-17 22:18:43 +00001472 case Stmt::DefaultStmtClass:
1473 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001474
Ted Kremenek93668002009-07-17 22:18:43 +00001475 case Stmt::DoStmtClass:
1476 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001477
Ted Kremenek93668002009-07-17 22:18:43 +00001478 case Stmt::ForStmtClass:
1479 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001480
Ted Kremenek93668002009-07-17 22:18:43 +00001481 case Stmt::GotoStmtClass:
1482 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001483
Ted Kremenek93668002009-07-17 22:18:43 +00001484 case Stmt::IfStmtClass:
1485 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001486
Ted Kremenek8219b822010-12-16 07:46:53 +00001487 case Stmt::ImplicitCastExprClass:
1488 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001489
Ted Kremenek93668002009-07-17 22:18:43 +00001490 case Stmt::IndirectGotoStmtClass:
1491 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001492
Ted Kremenek93668002009-07-17 22:18:43 +00001493 case Stmt::LabelStmtClass:
1494 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001495
Ted Kremenekda76a942012-04-12 20:34:52 +00001496 case Stmt::LambdaExprClass:
1497 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1498
Ted Kremenek5868ec62010-04-11 17:02:10 +00001499 case Stmt::MemberExprClass:
1500 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1501
Ted Kremenek04268232011-11-05 00:10:15 +00001502 case Stmt::NullStmtClass:
1503 return Block;
1504
Ted Kremenek93668002009-07-17 22:18:43 +00001505 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00001506 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1507
Ted Kremenek5022f1d2012-03-06 23:40:47 +00001508 case Stmt::ObjCAutoreleasePoolStmtClass:
1509 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1510
Ted Kremenek93668002009-07-17 22:18:43 +00001511 case Stmt::ObjCAtSynchronizedStmtClass:
1512 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001513
Ted Kremenek93668002009-07-17 22:18:43 +00001514 case Stmt::ObjCAtThrowStmtClass:
1515 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001516
Ted Kremenek93668002009-07-17 22:18:43 +00001517 case Stmt::ObjCAtTryStmtClass:
1518 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001519
Ted Kremenek93668002009-07-17 22:18:43 +00001520 case Stmt::ObjCForCollectionStmtClass:
1521 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001522
Ted Kremenek04268232011-11-05 00:10:15 +00001523 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00001524 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00001525
John McCallfe96e0b2011-11-06 09:01:30 +00001526 case Stmt::PseudoObjectExprClass:
1527 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1528
Ted Kremenek93668002009-07-17 22:18:43 +00001529 case Stmt::ReturnStmtClass:
1530 return VisitReturnStmt(cast<ReturnStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001531
Peter Collingbournee190dee2011-03-11 19:24:49 +00001532 case Stmt::UnaryExprOrTypeTraitExprClass:
1533 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1534 asc);
Mike Stump11289f42009-09-09 15:08:12 +00001535
Ted Kremenek93668002009-07-17 22:18:43 +00001536 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001537 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001538
Ted Kremenek93668002009-07-17 22:18:43 +00001539 case Stmt::SwitchStmtClass:
1540 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001541
Zhanyong Wan6dace612010-11-22 08:45:56 +00001542 case Stmt::UnaryOperatorClass:
1543 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1544
Ted Kremenek93668002009-07-17 22:18:43 +00001545 case Stmt::WhileStmtClass:
1546 return VisitWhileStmt(cast<WhileStmt>(S));
1547 }
1548}
Mike Stump11289f42009-09-09 15:08:12 +00001549
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001550CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001551 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001552 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001553 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00001554 }
Mike Stump11289f42009-09-09 15:08:12 +00001555
Ted Kremenek93668002009-07-17 22:18:43 +00001556 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00001557}
Mike Stump31feda52009-07-17 01:31:16 +00001558
Ted Kremenek93668002009-07-17 22:18:43 +00001559/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00001560CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1561 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00001562
Ted Kremenek8ae67872013-02-05 22:00:19 +00001563 // Visit the children in their reverse order so that they appear in
1564 // left-to-right (natural) order in the CFG.
1565 reverse_children RChildren(S);
1566 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1567 I != E; ++I) {
1568 if (Stmt *Child = *I)
1569 if (CFGBlock *R = Visit(Child))
1570 B = R;
1571 }
1572 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00001573}
Mike Stump11289f42009-09-09 15:08:12 +00001574
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001575CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1576 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00001577 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00001578
Ted Kremenek7c58d352011-03-10 01:14:11 +00001579 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001580 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001581 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00001582 }
Ted Kremenek81e14852007-08-27 19:46:09 +00001583
Ted Kremenek9aae5132007-08-23 21:42:29 +00001584 return Block;
1585}
Mike Stump11289f42009-09-09 15:08:12 +00001586
Zhanyong Wan6dace612010-11-22 08:45:56 +00001587CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00001588 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001589 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00001590 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001591 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00001592 }
1593
Ted Kremenek8219b822010-12-16 07:46:53 +00001594 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00001595}
1596
Ted Kremeneka16436f2012-07-14 05:04:06 +00001597CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1598 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1599 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00001600
Ted Kremeneka16436f2012-07-14 05:04:06 +00001601 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001602 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00001603
Craig Topper25542942014-05-20 04:30:07 +00001604 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1605 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001606}
1607
1608std::pair<CFGBlock*, CFGBlock*>
1609CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1610 Stmt *Term,
1611 CFGBlock *TrueBlock,
1612 CFGBlock *FalseBlock) {
1613
1614 // Introspect the RHS. If it is a nested logical operation, we recursively
1615 // build the CFG using this function. Otherwise, resort to default
1616 // CFG construction behavior.
1617 Expr *RHS = B->getRHS()->IgnoreParens();
1618 CFGBlock *RHSBlock, *ExitBlock;
1619
1620 do {
1621 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1622 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001623 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00001624 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1625 break;
1626 }
1627
1628 // The RHS is not a nested logical operation. Don't push the terminator
1629 // down further, but instead visit RHS and construct the respective
1630 // pieces of the CFG, and link up the RHSBlock with the terminator
1631 // we have been provided.
1632 ExitBlock = RHSBlock = createBlock(false);
1633
1634 if (!Term) {
1635 assert(TrueBlock == FalseBlock);
1636 addSuccessor(RHSBlock, TrueBlock);
1637 }
1638 else {
1639 RHSBlock->setTerminator(Term);
1640 TryResult KnownVal = tryEvaluateBool(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001641 if (!KnownVal.isKnown())
1642 KnownVal = tryEvaluateBool(B);
Ted Kremenek782f0032014-03-07 02:25:53 +00001643 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1644 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00001645 }
1646
1647 Block = RHSBlock;
1648 RHSBlock = addStmt(RHS);
1649 }
1650 while (false);
1651
1652 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001653 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00001654
1655 // Generate the blocks for evaluating the LHS.
1656 Expr *LHS = B->getLHS()->IgnoreParens();
1657
1658 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1659 if (B_LHS->isLogicalOp()) {
1660 if (B->getOpcode() == BO_LOr)
1661 FalseBlock = RHSBlock;
1662 else
1663 TrueBlock = RHSBlock;
1664
1665 // For the LHS, treat 'B' as the terminator that we want to sink
1666 // into the nested branch. The RHS always gets the top-most
1667 // terminator.
1668 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1669 }
1670
1671 // Create the block evaluating the LHS.
1672 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00001673 CFGBlock *LHSBlock = createBlock(false);
1674 LHSBlock->setTerminator(B);
1675
Ted Kremeneka16436f2012-07-14 05:04:06 +00001676 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001677 CFGBlock *EntryLHSBlock = addStmt(LHS);
1678
1679 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001680 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001681
1682 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00001683 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001684
1685 // Now link the LHSBlock with RHSBlock.
1686 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00001687 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
1688 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00001689 } else {
1690 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00001691 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
1692 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00001693 }
1694
Ted Kremenekb50e7162012-07-14 05:04:10 +00001695 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001696}
1697
Ted Kremenekb50e7162012-07-14 05:04:10 +00001698
Ted Kremeneka16436f2012-07-14 05:04:06 +00001699CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1700 AddStmtChoice asc) {
1701 // && or ||
1702 if (B->isLogicalOp())
1703 return VisitLogicalOperator(B);
1704
Zhanyong Wan59f09c72010-11-22 19:32:14 +00001705 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00001706 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001707 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00001708 addStmt(B->getRHS());
1709 return addStmt(B->getLHS());
1710 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00001711
1712 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001713 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001714 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001715 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001716 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001717 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00001718 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001719 }
Mike Stump11289f42009-09-09 15:08:12 +00001720
Ted Kremenek7c58d352011-03-10 01:14:11 +00001721 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00001722 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001723 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00001724 }
1725
Zhongxing Xud95ccd52010-10-27 03:23:10 +00001726 CFGBlock *RBlock = Visit(B->getRHS());
1727 CFGBlock *LBlock = Visit(B->getLHS());
1728 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1729 // containing a DoStmt, and the LHS doesn't create a new block, then we should
1730 // return RBlock. Otherwise we'll incorrectly return NULL.
1731 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00001732}
1733
Ted Kremeneke2499842012-04-12 20:03:44 +00001734CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001735 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00001736 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001737 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00001738 }
1739 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00001740}
1741
Ted Kremenek93668002009-07-17 22:18:43 +00001742CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1743 // "break" is a control-flow statement. Thus we stop processing the current
1744 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001745 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001746 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001747
Ted Kremenek93668002009-07-17 22:18:43 +00001748 // Now create a new block that ends with the break statement.
1749 Block = createBlock(false);
1750 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00001751
Ted Kremenek93668002009-07-17 22:18:43 +00001752 // If there is no target for the break, then we are looking at an incomplete
1753 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001754 if (BreakJumpTarget.block) {
1755 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1756 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001757 } else
Ted Kremenek93668002009-07-17 22:18:43 +00001758 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00001759
1760
Ted Kremenek9aae5132007-08-23 21:42:29 +00001761 return Block;
1762}
Mike Stump11289f42009-09-09 15:08:12 +00001763
Sebastian Redl31ad7542011-03-13 17:09:40 +00001764static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00001765 QualType Ty = E->getType();
1766 if (Ty->isFunctionPointerType())
1767 Ty = Ty->getAs<PointerType>()->getPointeeType();
1768 else if (Ty->isBlockPointerType())
1769 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001770
Mike Stump04c68512010-01-21 15:20:48 +00001771 const FunctionType *FT = Ty->getAs<FunctionType>();
1772 if (FT) {
1773 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00001774 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smithf623c962012-04-17 00:58:00 +00001775 Proto->isNothrow(Ctx))
Mike Stump04c68512010-01-21 15:20:48 +00001776 return false;
1777 }
1778 return true;
1779}
1780
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001781CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00001782 // Compute the callee type.
1783 QualType calleeType = C->getCallee()->getType();
1784 if (calleeType == Context->BoundMemberTy) {
1785 QualType boundType = Expr::findBoundMemberType(C->getCallee());
1786
1787 // We should only get a null bound type if processing a dependent
1788 // CFG. Recover by assuming nothing.
1789 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00001790 }
Mike Stump8c5d7992009-07-25 21:26:53 +00001791
John McCallc67067f2011-05-11 07:19:11 +00001792 // If this is a call to a no-return function, this stops the block here.
1793 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1794
Mike Stump04c68512010-01-21 15:20:48 +00001795 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00001796
1797 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001798 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00001799 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00001800 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00001801 }
1802
Jordan Rose5374c072013-08-19 16:27:28 +00001803 // If this is a call to a builtin function, it might not actually evaluate
1804 // its arguments. Don't add them to the CFG if this is the case.
1805 bool OmitArguments = false;
1806
Mike Stump92244b02010-01-19 22:00:14 +00001807 if (FunctionDecl *FD = C->getDirectCallee()) {
Richard Smith10876ef2013-01-17 01:30:42 +00001808 if (FD->isNoReturn())
Mike Stump8c5d7992009-07-25 21:26:53 +00001809 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00001810 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00001811 AddEHEdge = false;
Jordan Rose5374c072013-08-19 16:27:28 +00001812 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
1813 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00001814 }
Mike Stump8c5d7992009-07-25 21:26:53 +00001815
Sebastian Redl31ad7542011-03-13 17:09:40 +00001816 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00001817 AddEHEdge = false;
1818
Jordan Rose5374c072013-08-19 16:27:28 +00001819 if (OmitArguments) {
1820 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
1821 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
1822 autoCreateBlock();
1823 appendStmt(Block, C);
1824 return Visit(C->getCallee());
1825 }
1826
1827 if (!NoReturn && !AddEHEdge) {
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001828 return VisitStmt(C, asc.withAlwaysAdd(true));
Jordan Rose5374c072013-08-19 16:27:28 +00001829 }
Mike Stump11289f42009-09-09 15:08:12 +00001830
Mike Stump92244b02010-01-19 22:00:14 +00001831 if (Block) {
1832 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001833 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001834 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00001835 }
Mike Stump11289f42009-09-09 15:08:12 +00001836
Chandler Carrutha70991b2011-09-13 09:13:49 +00001837 if (NoReturn)
1838 Block = createNoReturnBlock();
1839 else
1840 Block = createBlock();
1841
Ted Kremenek2866bab2011-03-10 01:14:08 +00001842 appendStmt(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00001843
Mike Stump04c68512010-01-21 15:20:48 +00001844 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00001845 // Add exceptional edges.
1846 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001847 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00001848 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001849 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00001850 }
Mike Stump11289f42009-09-09 15:08:12 +00001851
Mike Stump8c5d7992009-07-25 21:26:53 +00001852 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00001853}
Ted Kremenek9aae5132007-08-23 21:42:29 +00001854
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001855CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1856 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001857 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001858 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001859 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001860 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001861
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001862 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00001863 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001864 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001865 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001866 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001867 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001868
Ted Kremenek21822592009-07-17 18:20:32 +00001869 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001870 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001871 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001872 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001873 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001874
Ted Kremenek21822592009-07-17 18:20:32 +00001875 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00001876 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001877 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00001878 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
1879 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00001880 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00001881 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00001882}
Mike Stump11289f42009-09-09 15:08:12 +00001883
1884
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001885CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Marcin Swiderski667ffec2010-10-01 00:23:17 +00001886 addLocalScopeAndDtors(C);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001887 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00001888
1889 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1890 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00001891 // If we hit a segment of code just containing ';' (NullStmts), we can
1892 // get a null block back. In such cases, just use the LastBlock
1893 if (CFGBlock *newBlock = addStmt(*I))
1894 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00001895
Ted Kremenekce499c22009-08-27 23:16:26 +00001896 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001897 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001898 }
Mike Stump92244b02010-01-19 22:00:14 +00001899
Ted Kremenek93668002009-07-17 22:18:43 +00001900 return LastBlock;
1901}
Mike Stump11289f42009-09-09 15:08:12 +00001902
John McCallc07a0c72011-02-17 10:25:35 +00001903CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001904 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00001905 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00001906 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00001907
Ted Kremenek51d40b02009-07-17 18:15:54 +00001908 // Create the confluence block that will "merge" the results of the ternary
1909 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001910 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001911 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001912 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001913 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001914
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001915 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00001916
Ted Kremenek51d40b02009-07-17 18:15:54 +00001917 // Create a block for the LHS expression if there is an LHS expression. A
1918 // GCC extension allows LHS to be NULL, causing the condition to be the
1919 // value that is returned instead.
1920 // e.g: x ?: y is shorthand for: x ? x : y;
1921 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001922 Block = nullptr;
1923 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00001924 const Expr *trueExpr = C->getTrueExpr();
1925 if (trueExpr != opaqueValue) {
1926 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001927 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001928 return nullptr;
1929 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00001930 }
Ted Kremenekd8138012011-02-24 03:09:15 +00001931 else
1932 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00001933
Ted Kremenek51d40b02009-07-17 18:15:54 +00001934 // Create the block for the RHS expression.
1935 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001936 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001937 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001938 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001939
Richard Smithf676e452012-07-24 21:02:14 +00001940 // If the condition is a logical '&&' or '||', build a more accurate CFG.
1941 if (BinaryOperator *Cond =
1942 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
1943 if (Cond->isLogicalOp())
1944 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
1945
Ted Kremenek51d40b02009-07-17 18:15:54 +00001946 // Create the block that will contain the condition.
1947 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00001948
Mike Stump773582d2009-07-23 23:25:26 +00001949 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001950 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00001951 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
1952 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00001953 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00001954 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00001955
Ted Kremenekd8138012011-02-24 03:09:15 +00001956 if (opaqueValue) {
1957 // Run the condition expression if it's not trivially expressed in
1958 // terms of the opaque value (or if there is no opaque value).
1959 if (condExpr != opaqueValue)
1960 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00001961
Ted Kremenekd8138012011-02-24 03:09:15 +00001962 // Before that, run the common subexpression if there was one.
1963 // At least one of this or the above will be run.
1964 return addStmt(BCO->getCommon());
1965 }
1966
1967 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00001968}
1969
Ted Kremenek93668002009-07-17 22:18:43 +00001970CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00001971 // Check if the Decl is for an __label__. If so, elide it from the
1972 // CFG entirely.
1973 if (isa<LabelDecl>(*DS->decl_begin()))
1974 return Block;
1975
Ted Kremenek3a601142011-05-24 20:41:31 +00001976 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001977 if (DS->isSingleDecl())
1978 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00001979
Craig Topper25542942014-05-20 04:30:07 +00001980 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001981
Jordan Rose8c6c8a92012-07-20 18:50:48 +00001982 // Build an individual DeclStmt for each decl.
1983 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
1984 E = DS->decl_rend();
1985 I != E; ++I) {
Ted Kremenek93668002009-07-17 22:18:43 +00001986 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
1987 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
1988 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
Mike Stump11289f42009-09-09 15:08:12 +00001989
Ted Kremenek93668002009-07-17 22:18:43 +00001990 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
1991 // automatically freed with the CFG.
1992 DeclGroupRef DG(*I);
1993 Decl *D = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001994 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
Ted Kremenek93668002009-07-17 22:18:43 +00001995 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00001996 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00001997
Ted Kremenek93668002009-07-17 22:18:43 +00001998 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001999 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002000 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
2002 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002003}
Mike Stump11289f42009-09-09 15:08:12 +00002004
Ted Kremenek93668002009-07-17 22:18:43 +00002005/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002006/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002007CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002008 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002009 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002010
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002011 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002012 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2013 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002014 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002015 }
Mike Stump11289f42009-09-09 15:08:12 +00002016
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002017 bool HasTemporaries = false;
2018
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002019 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002020 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002021
2022 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2023 // For static variables, we need to create a branch to track
2024 // whether or not they are initialized.
2025 if (Block) {
2026 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002027 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002028 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002029 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002030 }
2031 blockAfterStaticInit = Succ;
2032 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002033
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002034 // Destructors of temporaries in initialization expression should be called
2035 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002036 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002037 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002038 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002039
Jordan Rose6d671cc2012-09-05 22:55:23 +00002040 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002041 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002042 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002043 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2044 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002045 }
2046 }
2047
2048 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002049 appendStmt(Block, DS);
Ted Kremenek213d0532012-03-22 05:57:43 +00002050
2051 // Keep track of the last non-null block, as 'Block' can be nulled out
2052 // if the initializer expression is something like a 'while' in a
2053 // statement-expression.
2054 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002055
Ted Kremenek93668002009-07-17 22:18:43 +00002056 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002057 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002058 // For expression with temporaries go directly to subexpression to omit
2059 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002060 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2061 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2062 LastBlock = newBlock;
2063 }
2064 else {
2065 if (CFGBlock *newBlock = Visit(Init))
2066 LastBlock = newBlock;
2067 }
Ted Kremenek93668002009-07-17 22:18:43 +00002068 }
Mike Stump11289f42009-09-09 15:08:12 +00002069
Ted Kremenek93668002009-07-17 22:18:43 +00002070 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002071 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002072 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002073 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2074 LastBlock = newBlock;
2075 }
Mike Stump11289f42009-09-09 15:08:12 +00002076
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002077 // Remove variable from local scope.
2078 if (ScopePos && VD == *ScopePos)
2079 ++ScopePos;
2080
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002081 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002082 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002083 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002084 Block = createBlock(false);
2085 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002086 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002087 addSuccessor(Block, B);
2088 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002089 }
2090
2091 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002092}
2093
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002094CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002095 // We may see an if statement in the middle of a basic block, or it may be the
2096 // first statement we are processing. In either case, we create a new basic
2097 // block. First, we create the blocks for the then...else statements, and
2098 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002099 // middle of a block, we stop processing that block. That block is then the
2100 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002101
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002102 // Save local scope position because in case of condition variable ScopePos
2103 // won't be restored when traversing AST.
2104 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2105
2106 // Create local scope for possible condition variable.
2107 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002108 if (VarDecl *VD = I->getConditionVariable()) {
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002109 LocalScope::const_iterator BeginScopePos = ScopePos;
2110 addLocalScopeForVarDecl(VD);
2111 addAutomaticObjDtors(ScopePos, BeginScopePos, I);
2112 }
2113
Chris Lattner57540c52011-04-15 05:22:18 +00002114 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002115 // block.
2116 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002117 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002118 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002119 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002120 }
Mike Stump31feda52009-07-17 01:31:16 +00002121
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002122 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002123 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002124
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002125 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002126 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002127
Ted Kremenek9aae5132007-08-23 21:42:29 +00002128 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002129 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002130 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002131
2132 // If branch is not a compound statement create implicit scope
2133 // and add destructors.
2134 if (!isa<CompoundStmt>(Else))
2135 addLocalScopeAndDtors(Else);
2136
Ted Kremenek93668002009-07-17 22:18:43 +00002137 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002138
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002139 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2140 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002141 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002142 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002143 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002144 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002145 }
Mike Stump31feda52009-07-17 01:31:16 +00002146
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002147 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002148 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002149 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002150 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002151 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002152 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002153 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002154
2155 // If branch is not a compound statement create implicit scope
2156 // and add destructors.
2157 if (!isa<CompoundStmt>(Then))
2158 addLocalScopeAndDtors(Then);
2159
Ted Kremenek93668002009-07-17 22:18:43 +00002160 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002161
Ted Kremenek1b379512009-04-01 03:52:47 +00002162 if (!ThenBlock) {
2163 // We can reach here if the "then" body has all NullStmts.
2164 // Create an empty block so we can distinguish between true and false
2165 // branches in path-sensitive analyses.
2166 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002167 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002168 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002169 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002170 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002171 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002172 }
2173
Ted Kremenekb50e7162012-07-14 05:04:10 +00002174 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2175 // having these handle the actual control-flow jump. Note that
2176 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2177 // we resort to the old control-flow behavior. This special handling
2178 // removes infeasible paths from the control-flow graph by having the
2179 // control-flow transfer of '&&' or '||' go directly into the then/else
2180 // blocks directly.
2181 if (!I->getConditionVariable())
Richard Smithf676e452012-07-24 21:02:14 +00002182 if (BinaryOperator *Cond =
2183 dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002184 if (Cond->isLogicalOp())
2185 return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2186
Mike Stump31feda52009-07-17 01:31:16 +00002187 // Now create a new block containing the if statement.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002188 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002189
Ted Kremenek9aae5132007-08-23 21:42:29 +00002190 // Set the terminator of the new block to the If statement.
2191 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002192
Mike Stump773582d2009-07-23 23:25:26 +00002193 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002194 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00002195
Ted Kremenekf3898612014-02-27 00:24:03 +00002196 // Add the successors. If we know that specific branches are
2197 // unreachable, inform addSuccessor() of that knowledge.
2198 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2199 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump31feda52009-07-17 01:31:16 +00002200
2201 // Add the condition as the last statement in the new block. This may create
2202 // new blocks as the condition may contain control-flow. Any newly created
2203 // blocks will be pointed to be "Block".
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002204 CFGBlock *LastBlock = addStmt(I->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002205
Manuel Klimek75f34c12014-05-05 18:21:06 +00002206 // Finally, if the IfStmt contains a condition variable, add it and its
2207 // initializer to the CFG.
2208 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2209 autoCreateBlock();
2210 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002211 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002212
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002213 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002214}
Mike Stump31feda52009-07-17 01:31:16 +00002215
2216
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002217CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002218 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002219 //
Mike Stump31feda52009-07-17 01:31:16 +00002220 // NOTE: If a "return" appears in the middle of a block, this means that the
2221 // code afterwards is DEAD (unreachable). We still keep a basic block
2222 // for that code; a simple "mark-and-sweep" from the entry block will be
2223 // able to report such dead blocks.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002224
2225 // Create the new block.
2226 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002227
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002228 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
Pavel Labath921e7652013-09-06 08:12:48 +00002229
2230 // If the one of the destructors does not return, we already have the Exit
2231 // block as a successor.
2232 if (!Block->hasNoReturnElement())
2233 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002234
2235 // Add the return statement to the block. This may create new blocks if R
2236 // contains control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002237 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002238}
2239
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002240CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002241 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00002242 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002243 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002244
Ted Kremenek93668002009-07-17 22:18:43 +00002245 if (!LabelBlock) // This can happen when the body is empty, i.e.
2246 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00002247
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002248 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2249 "label already in map");
2250 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002251
2252 // Labels partition blocks, so this is the end of the basic block we were
2253 // processing (L is the block's label). Because this is label (and we have
2254 // already processed the substatement) there is no extra control-flow to worry
2255 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00002256 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002257 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002258 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002259
2260 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00002261 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002262
Ted Kremenek9aae5132007-08-23 21:42:29 +00002263 // This block is now the implicit successor of other blocks.
2264 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002265
Ted Kremenek9aae5132007-08-23 21:42:29 +00002266 return LabelBlock;
2267}
2268
Ted Kremenekda76a942012-04-12 20:34:52 +00002269CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2270 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2271 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2272 et = E->capture_init_end(); it != et; ++it) {
2273 if (Expr *Init = *it) {
2274 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00002275 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00002276 LastBlock = Tmp;
2277 }
2278 }
2279 return LastBlock;
2280}
2281
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002282CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00002283 // Goto is a control-flow statement. Thus we stop processing the current
2284 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00002285
Ted Kremenek9aae5132007-08-23 21:42:29 +00002286 Block = createBlock(false);
2287 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00002288
2289 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002290 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00002291
Ted Kremenek9aae5132007-08-23 21:42:29 +00002292 if (I == LabelMap.end())
2293 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002294 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2295 else {
2296 JumpTarget JT = I->second;
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002297 addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
2298 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002299 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002300
Mike Stump31feda52009-07-17 01:31:16 +00002301 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002302}
2303
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002304CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00002305 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002306
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002307 // Save local scope position because in case of condition variable ScopePos
2308 // won't be restored when traversing AST.
2309 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2310
2311 // Create local scope for init statement and possible condition variable.
2312 // Add destructor for init statement and condition variable.
2313 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002314 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002315 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002316 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2317
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002318 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002319 addLocalScopeForVarDecl(VD);
2320 LocalScope::const_iterator ContinueScopePos = ScopePos;
2321
2322 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
2323
Mike Stump014b3ea2009-07-21 01:12:51 +00002324 // "for" is a control-flow statement. Thus we stop processing the current
2325 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002326 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002327 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002328 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002329 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002330 } else
2331 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002332
Ted Kremenek304a9532010-05-21 20:30:15 +00002333 // Save the current value for the break targets.
2334 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002335 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002336 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00002337
Craig Topper25542942014-05-20 04:30:07 +00002338 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002339
Ted Kremenek9aae5132007-08-23 21:42:29 +00002340 // Now create the loop body.
2341 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002342 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002343
Ted Kremenekb50e7162012-07-14 05:04:10 +00002344 // Save the current values for Block, Succ, continue and break targets.
2345 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2346 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002347
Ted Kremenekb50e7162012-07-14 05:04:10 +00002348 // Create an empty block to represent the transition block for looping back
2349 // to the head of the loop. If we have increment code, it will
2350 // go in this block as well.
2351 Block = Succ = TransitionBlock = createBlock(false);
2352 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002353
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002354 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00002355 // Generate increment code in its own basic block. This is the target of
2356 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00002357 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00002358 }
Mike Stump31feda52009-07-17 01:31:16 +00002359
Ted Kremenek902393b2009-04-28 00:51:56 +00002360 // Finish up the increment (or empty) block if it hasn't been already.
2361 if (Block) {
2362 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002363 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002364 return nullptr;
2365 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00002366 }
Mike Stump31feda52009-07-17 01:31:16 +00002367
Ted Kremenekb50e7162012-07-14 05:04:10 +00002368 // The starting block for the loop increment is the block that should
2369 // represent the 'loop target' for looping back to the start of the loop.
2370 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2371 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002372
Ted Kremenekb50e7162012-07-14 05:04:10 +00002373 // Loop body should end with destructor of Condition variable (if any).
2374 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00002375
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002376 // If body is not a compound statement create implicit scope
2377 // and add destructors.
2378 if (!isa<CompoundStmt>(F->getBody()))
2379 addLocalScopeAndDtors(F->getBody());
2380
Mike Stump31feda52009-07-17 01:31:16 +00002381 // Now populate the body block, and in the process create new blocks as we
2382 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002383 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00002384
Ted Kremenekb50e7162012-07-14 05:04:10 +00002385 if (!BodyBlock) {
2386 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2387 // Use the continue jump target as the proxy for the body.
2388 BodyBlock = ContinueJumpTarget.block;
2389 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002390 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002391 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002392 }
Ted Kremenekb50e7162012-07-14 05:04:10 +00002393
2394 // Because of short-circuit evaluation, the condition of the loop can span
2395 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2396 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002397 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002398
Ted Kremenekb50e7162012-07-14 05:04:10 +00002399 do {
2400 Expr *C = F->getCond();
2401
2402 // Specially handle logical operators, which have a slightly
2403 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002404 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00002405 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002406 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002407 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002408 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2409 break;
2410 }
2411
2412 // The default case when not handling logical operators.
2413 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2414 ExitConditionBlock->setTerminator(F);
2415
2416 // See if this is a known constant.
2417 TryResult KnownVal(true);
2418
2419 if (C) {
2420 // Now add the actual condition to the condition block.
2421 // Because the condition itself may contain control-flow, new blocks may
2422 // be created. Thus we update "Succ" after adding the condition.
2423 Block = ExitConditionBlock;
2424 EntryConditionBlock = addStmt(C);
2425
2426 // If this block contains a condition variable, add both the condition
2427 // variable and initializer to the CFG.
2428 if (VarDecl *VD = F->getConditionVariable()) {
2429 if (Expr *Init = VD->getInit()) {
2430 autoCreateBlock();
2431 appendStmt(Block, F->getConditionVariableDeclStmt());
2432 EntryConditionBlock = addStmt(Init);
2433 assert(Block == EntryConditionBlock);
2434 }
2435 }
2436
2437 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002438 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002439
2440 KnownVal = tryEvaluateBool(C);
2441 }
2442
2443 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002444 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002445 // Link up the condition block with the code that follows the loop. (the
2446 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002447 addSuccessor(ExitConditionBlock,
2448 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002449
2450 } while (false);
2451
2452 // Link up the loop-back block to the entry condition block.
2453 addSuccessor(TransitionBlock, EntryConditionBlock);
2454
2455 // The condition block is the implicit successor for any code above the loop.
2456 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002457
Ted Kremenek9aae5132007-08-23 21:42:29 +00002458 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00002459 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002460 if (Stmt *I = F->getInit()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002461 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00002462 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002463 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002464
2465 // There is no loop initialization. We are thus basically a while loop.
2466 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00002467 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002468 Succ = EntryConditionBlock;
2469 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002470}
2471
Ted Kremenek5868ec62010-04-11 17:02:10 +00002472CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002473 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00002474 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002475 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002476 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002477 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00002478}
2479
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002480CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00002481 // Objective-C fast enumeration 'for' statements:
2482 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2483 //
2484 // for ( Type newVariable in collection_expression ) { statements }
2485 //
2486 // becomes:
2487 //
2488 // prologue:
2489 // 1. collection_expression
2490 // T. jump to loop_entry
2491 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002492 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00002493 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2494 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2495 // TB:
2496 // statements
2497 // T. jump to loop_entry
2498 // FB:
2499 // what comes after
2500 //
2501 // and
2502 //
2503 // Type existingItem;
2504 // for ( existingItem in expression ) { statements }
2505 //
2506 // becomes:
2507 //
Mike Stump31feda52009-07-17 01:31:16 +00002508 // the same with newVariable replaced with existingItem; the binding works
2509 // the same except that for one ObjCForCollectionStmt::getElement() returns
2510 // a DeclStmt and the other returns a DeclRefExpr.
Ted Kremenek9d56e642008-11-11 17:10:00 +00002511 //
Mike Stump31feda52009-07-17 01:31:16 +00002512
Craig Topper25542942014-05-20 04:30:07 +00002513 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002514
Ted Kremenek9d56e642008-11-11 17:10:00 +00002515 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002516 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002517 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00002518 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002519 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00002520 } else
2521 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002522
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002523 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002524 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002525
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002526 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002527 ExitConditionBlock->setTerminator(S);
2528
2529 // The last statement in the block should be the ObjCForCollectionStmt, which
2530 // performs the actual binding to 'element' and determines if there are any
2531 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00002532 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002533 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002534
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002535 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00002536 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00002537 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00002538 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2539 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00002540 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002541 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002542 return nullptr;
2543 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002544 }
Mike Stump31feda52009-07-17 01:31:16 +00002545
2546 // The condition block is the implicit successor for the loop body as well as
2547 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002548 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002549
Ted Kremenek9d56e642008-11-11 17:10:00 +00002550 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00002551 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002552 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00002553 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002554 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00002555 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002556
Anna Zaks56b49752013-06-22 00:23:20 +00002557 // Add an intermediate block between the BodyBlock and the
2558 // EntryConditionBlock to represent the "loop back" transition, for looping
2559 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00002560 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00002561 Succ = LoopBackBlock = createBlock();
2562 LoopBackBlock->setLoopTarget(S);
2563
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002564 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00002565 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002566
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002567 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002568
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002569 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00002570 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00002571 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002572 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002573 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002574 }
Mike Stump31feda52009-07-17 01:31:16 +00002575
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002576 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002577 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002578 }
Mike Stump31feda52009-07-17 01:31:16 +00002579
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002580 // Link up the condition block with the code that follows the loop.
2581 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002582 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002583
Ted Kremenek9d56e642008-11-11 17:10:00 +00002584 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002585 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00002586 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00002587}
2588
Ted Kremenek5022f1d2012-03-06 23:40:47 +00002589CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2590 // Inline the body.
2591 return addStmt(S->getSubStmt());
2592 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2593}
2594
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002595CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00002596 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00002597
Ted Kremenek49805452009-05-02 01:49:13 +00002598 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00002599 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00002600
Ted Kremenekb3c657b2009-05-05 23:11:51 +00002601 // The sync body starts its own basic block. This makes it a little easier
2602 // for diagnostic clients.
2603 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002604 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002605 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002606
Craig Topper25542942014-05-20 04:30:07 +00002607 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00002608 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00002609 }
Mike Stump31feda52009-07-17 01:31:16 +00002610
Ted Kremeneked12f1b2010-09-10 03:05:33 +00002611 // Add the @synchronized to the CFG.
2612 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002613 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00002614
Ted Kremenek49805452009-05-02 01:49:13 +00002615 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00002616 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00002617}
Mike Stump31feda52009-07-17 01:31:16 +00002618
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002619CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00002620 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00002621 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00002622}
Ted Kremenek9d56e642008-11-11 17:10:00 +00002623
John McCallfe96e0b2011-11-06 09:01:30 +00002624CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2625 autoCreateBlock();
2626
2627 // Add the PseudoObject as the last thing.
2628 appendStmt(Block, E);
2629
2630 CFGBlock *lastBlock = Block;
2631
2632 // Before that, evaluate all of the semantics in order. In
2633 // CFG-land, that means appending them in reverse order.
2634 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2635 Expr *Semantic = E->getSemanticExpr(--i);
2636
2637 // If the semantic is an opaque value, we're being asked to bind
2638 // it to its source expression.
2639 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2640 Semantic = OVE->getSourceExpr();
2641
2642 if (CFGBlock *B = Visit(Semantic))
2643 lastBlock = B;
2644 }
2645
2646 return lastBlock;
2647}
2648
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002649CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00002650 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002651
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002652 // Save local scope position because in case of condition variable ScopePos
2653 // won't be restored when traversing AST.
2654 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2655
2656 // Create local scope for possible condition variable.
2657 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002658 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002659 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002660 addLocalScopeForVarDecl(VD);
2661 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2662 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002663
Mike Stump014b3ea2009-07-21 01:12:51 +00002664 // "while" is a control-flow statement. Thus we stop processing the current
2665 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002666 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002667 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002668 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002669 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002670 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002671 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00002672 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00002673 }
Mike Stump31feda52009-07-17 01:31:16 +00002674
Craig Topper25542942014-05-20 04:30:07 +00002675 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002676
Ted Kremenek9aae5132007-08-23 21:42:29 +00002677 // Process the loop body.
2678 {
Ted Kremenek49936f72009-04-28 03:09:44 +00002679 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00002680
Ted Kremenekb50e7162012-07-14 05:04:10 +00002681 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002682 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2683 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00002684 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00002685
Mike Stump31feda52009-07-17 01:31:16 +00002686 // Create an empty block to represent the transition block for looping back
2687 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002688 Succ = TransitionBlock = createBlock(false);
2689 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002690 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002691
Ted Kremenek9aae5132007-08-23 21:42:29 +00002692 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002693 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002694
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002695 // Loop body should end with destructor of Condition variable (if any).
2696 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2697
2698 // If body is not a compound statement create implicit scope
2699 // and add destructors.
2700 if (!isa<CompoundStmt>(W->getBody()))
2701 addLocalScopeAndDtors(W->getBody());
2702
Ted Kremenek9aae5132007-08-23 21:42:29 +00002703 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002704 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002705
Ted Kremeneke9610502007-08-30 18:39:40 +00002706 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002707 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00002708 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002709 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002710 }
2711
2712 // Because of short-circuit evaluation, the condition of the loop can span
2713 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2714 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002715 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002716
2717 do {
2718 Expr *C = W->getCond();
2719
2720 // Specially handle logical operators, which have a slightly
2721 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002722 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002723 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002724 std::tie(EntryConditionBlock, ExitConditionBlock) =
2725 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002726 break;
2727 }
2728
2729 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00002730 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002731 ExitConditionBlock->setTerminator(W);
2732
2733 // Now add the actual condition to the condition block.
2734 // Because the condition itself may contain control-flow, new blocks may
2735 // be created. Thus we update "Succ" after adding the condition.
2736 Block = ExitConditionBlock;
2737 Block = EntryConditionBlock = addStmt(C);
2738
2739 // If this block contains a condition variable, add both the condition
2740 // variable and initializer to the CFG.
2741 if (VarDecl *VD = W->getConditionVariable()) {
2742 if (Expr *Init = VD->getInit()) {
2743 autoCreateBlock();
2744 appendStmt(Block, W->getConditionVariableDeclStmt());
2745 EntryConditionBlock = addStmt(Init);
2746 assert(Block == EntryConditionBlock);
2747 }
Ted Kremenek55957a82009-05-02 00:13:27 +00002748 }
Mike Stump31feda52009-07-17 01:31:16 +00002749
Ted Kremenekb50e7162012-07-14 05:04:10 +00002750 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002751 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002752
2753 // See if this is a known constant.
2754 const TryResult& KnownVal = tryEvaluateBool(C);
2755
Ted Kremenek30754282009-07-24 04:47:11 +00002756 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002757 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002758 // Link up the condition block with the code that follows the loop. (the
2759 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002760 addSuccessor(ExitConditionBlock,
2761 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00002762
Ted Kremenekb50e7162012-07-14 05:04:10 +00002763 } while(false);
2764
2765 // Link up the loop-back block to the entry condition block.
2766 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00002767
2768 // There can be no more statements in the condition block since we loop back
2769 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00002770 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002771
Ted Kremenek1ce53c42009-12-24 01:34:10 +00002772 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00002773 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00002774 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002775}
Mike Stump11289f42009-09-09 15:08:12 +00002776
2777
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002778CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00002779 // FIXME: For now we pretend that @catch and the code it contains does not
2780 // exit.
2781 return Block;
2782}
Mike Stump31feda52009-07-17 01:31:16 +00002783
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002784CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00002785 // FIXME: This isn't complete. We basically treat @throw like a return
2786 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00002787
Ted Kremenek0868eea2009-09-24 18:45:41 +00002788 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002789 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002790 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002791
Ted Kremenek93041ba2008-12-09 20:20:09 +00002792 // Create the new block.
2793 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002794
Ted Kremenek93041ba2008-12-09 20:20:09 +00002795 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002796 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002797
2798 // Add the statement to the block. This may create new blocks if S contains
2799 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002800 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00002801}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002802
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002803CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002804 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002805 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002806 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002807
2808 // Create the new block.
2809 Block = createBlock(false);
2810
Mike Stumpbbf5ba62010-01-19 02:20:09 +00002811 if (TryTerminatedBlock)
2812 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002813 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002814 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00002815 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002816 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002817
2818 // Add the statement to the block. This may create new blocks if S contains
2819 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002820 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002821}
2822
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002823CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00002824 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002825
Mike Stump8d50b6a2009-07-21 01:27:50 +00002826 // "do...while" is a control-flow statement. Thus we stop processing the
2827 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002828 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002829 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002830 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002831 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002832 } else
2833 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002834
2835 // Because of short-circuit evaluation, the condition of the loop can span
2836 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2837 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002838 CFGBlock *ExitConditionBlock = createBlock(false);
2839 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002840
Ted Kremenek81e14852007-08-27 19:46:09 +00002841 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002842 ExitConditionBlock->setTerminator(D);
2843
2844 // Now add the actual condition to the condition block. Because the condition
2845 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002846 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00002847 Block = ExitConditionBlock;
2848 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00002849 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002850 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002851 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002852 }
Ted Kremenek81e14852007-08-27 19:46:09 +00002853 }
Mike Stump31feda52009-07-17 01:31:16 +00002854
Ted Kremeneka1523a32008-02-27 07:20:00 +00002855 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00002856 Succ = EntryConditionBlock;
2857
Mike Stump773582d2009-07-23 23:25:26 +00002858 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002859 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00002860
Ted Kremenek9aae5132007-08-23 21:42:29 +00002861 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00002862 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002863 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002864 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002865
Ted Kremenek9aae5132007-08-23 21:42:29 +00002866 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002867 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2868 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2869 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002870
Ted Kremenek9aae5132007-08-23 21:42:29 +00002871 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002872 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002873
Ted Kremenek9aae5132007-08-23 21:42:29 +00002874 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002875 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002876
Ted Kremenek9aae5132007-08-23 21:42:29 +00002877 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00002878 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002879
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002880 // If body is not a compound statement create implicit scope
2881 // and add destructors.
2882 if (!isa<CompoundStmt>(D->getBody()))
2883 addLocalScopeAndDtors(D->getBody());
2884
Ted Kremenek9aae5132007-08-23 21:42:29 +00002885 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00002886 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002887
Ted Kremeneke9610502007-08-30 18:39:40 +00002888 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00002889 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00002890 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002891 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002892 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002893 }
Mike Stump31feda52009-07-17 01:31:16 +00002894
Ted Kremenek110974d2010-08-17 20:59:56 +00002895 if (!KnownVal.isFalse()) {
2896 // Add an intermediate block between the BodyBlock and the
2897 // ExitConditionBlock to represent the "loop back" transition. Create an
2898 // empty block to represent the transition block for looping back to the
2899 // head of the loop.
2900 // FIXME: Can we do this more efficiently without adding another block?
Craig Topper25542942014-05-20 04:30:07 +00002901 Block = nullptr;
Ted Kremenek110974d2010-08-17 20:59:56 +00002902 Succ = BodyBlock;
2903 CFGBlock *LoopBackBlock = createBlock();
2904 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00002905
Ted Kremenek110974d2010-08-17 20:59:56 +00002906 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002907 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00002908 }
2909 else
Craig Topper25542942014-05-20 04:30:07 +00002910 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002911 }
Mike Stump31feda52009-07-17 01:31:16 +00002912
Ted Kremenek30754282009-07-24 04:47:11 +00002913 // Link up the condition block with the code that follows the loop.
2914 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00002915 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00002916
2917 // There can be no more statements in the body block(s) since we loop back to
2918 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00002919 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002920
Ted Kremenek9aae5132007-08-23 21:42:29 +00002921 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00002922 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002923 return BodyBlock;
2924}
2925
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002926CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002927 // "continue" is a control-flow statement. Thus we stop processing the
2928 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002929 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002930 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002931
Ted Kremenek9aae5132007-08-23 21:42:29 +00002932 // Now create a new block that ends with the continue statement.
2933 Block = createBlock(false);
2934 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00002935
Ted Kremenek9aae5132007-08-23 21:42:29 +00002936 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00002937 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002938 if (ContinueJumpTarget.block) {
2939 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
2940 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002941 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00002942 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00002943
Ted Kremenek9aae5132007-08-23 21:42:29 +00002944 return Block;
2945}
Mike Stump11289f42009-09-09 15:08:12 +00002946
Peter Collingbournee190dee2011-03-11 19:24:49 +00002947CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
2948 AddStmtChoice asc) {
Ted Kremenek0747de62009-07-18 00:47:21 +00002949
Ted Kremenek7c58d352011-03-10 01:14:11 +00002950 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00002951 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002952 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00002953 }
Mike Stump11289f42009-09-09 15:08:12 +00002954
Ted Kremenek93668002009-07-17 22:18:43 +00002955 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00002956 CFGBlock *lastBlock = Block;
2957
Ted Kremenek93668002009-07-17 22:18:43 +00002958 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00002959 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002960 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00002961 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00002962 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00002963 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002964}
Mike Stump11289f42009-09-09 15:08:12 +00002965
Ted Kremenek93668002009-07-17 22:18:43 +00002966/// VisitStmtExpr - Utility method to handle (nested) statement
2967/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002968CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002969 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00002970 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002971 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00002972 }
Ted Kremenek93668002009-07-17 22:18:43 +00002973 return VisitCompoundStmt(SE->getSubStmt());
2974}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002975
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002976CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00002977 // "switch" is a control-flow statement. Thus we stop processing the current
2978 // block.
Craig Topper25542942014-05-20 04:30:07 +00002979 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002980
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00002981 // Save local scope position because in case of condition variable ScopePos
2982 // won't be restored when traversing AST.
2983 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2984
2985 // Create local scope for possible condition variable.
2986 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002987 if (VarDecl *VD = Terminator->getConditionVariable()) {
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00002988 LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
2989 addLocalScopeForVarDecl(VD);
2990 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
2991 }
2992
Ted Kremenek9aae5132007-08-23 21:42:29 +00002993 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002994 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002995 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002996 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002997 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002998
2999 // Save the current "switch" context.
3000 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003001 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003002 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003003
Mike Stump31feda52009-07-17 01:31:16 +00003004 // Set the "default" case to be the block after the switch statement. If the
3005 // switch statement contains a "default:", this value will be overwritten with
3006 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003007 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003008
Ted Kremenek9aae5132007-08-23 21:42:29 +00003009 // Create a new block that will contain the switch statement.
3010 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003011
Ted Kremenek9aae5132007-08-23 21:42:29 +00003012 // Now process the switch body. The code after the switch is the implicit
3013 // successor.
3014 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003015 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003016
3017 // When visiting the body, the case statements should automatically get linked
3018 // up to the switch. We also don't keep a pointer to the body, since all
3019 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003020 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003021 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003022
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003023 // For pruning unreachable case statements, save the current state
3024 // for tracking the condition value.
3025 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3026 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003027
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003028 // Determine if the switch condition can be explicitly evaluated.
3029 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003030 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003031 bool b = tryEvaluate(Terminator->getCond(), result);
3032 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003033 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003034
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003035 // If body is not a compound statement create implicit scope
3036 // and add destructors.
3037 if (!isa<CompoundStmt>(Terminator->getBody()))
3038 addLocalScopeAndDtors(Terminator->getBody());
3039
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003040 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003041 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003042 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003043 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003044 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003045
Mike Stump31feda52009-07-17 01:31:16 +00003046 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003047 // following the switch body. Moreover, take into account if all the
3048 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003049 //
3050 // Note: We add a successor to a switch that is considered covered yet has no
3051 // case statements if the enumeration has no enumerators.
3052 bool SwitchAlwaysHasSuccessor = false;
3053 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3054 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3055 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003056 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3057 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003058
Ted Kremenek81e14852007-08-27 19:46:09 +00003059 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003060 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003061 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003062 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003063
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003064 // Finally, if the SwitchStmt contains a condition variable, add both the
3065 // SwitchStmt and the condition variable initialization to the CFG.
3066 if (VarDecl *VD = Terminator->getConditionVariable()) {
3067 if (Expr *Init = VD->getInit()) {
3068 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003069 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003070 LastBlock = addStmt(Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003071 }
3072 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003073
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003074 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003075}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003076
3077static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00003078 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003079 const CaseStmt *CS,
3080 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003081 if (!switchCond)
3082 return true;
3083
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003084 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00003085
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003086 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003087 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003088 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003089 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00003090 const llvm::APSInt &condInt = switchCond->Val.getInt();
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003091
3092 if (condInt == lhsInt) {
3093 addCase = true;
3094 switchExclusivelyCovered = true;
3095 }
3096 else if (condInt < lhsInt) {
3097 if (const Expr *RHS = CS->getRHS()) {
3098 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003099 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
3100 if (V2 <= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003101 addCase = true;
3102 switchExclusivelyCovered = true;
3103 }
3104 }
3105 }
3106 }
3107 else
3108 addCase = true;
3109 }
3110 return addCase;
3111}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003112
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003113CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00003114 // CaseStmts are essentially labels, so they are the first statement in a
3115 // block.
Craig Topper25542942014-05-20 04:30:07 +00003116 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00003117
Ted Kremenek60fa6572010-08-04 23:54:30 +00003118 if (Stmt *Sub = CS->getSubStmt()) {
3119 // For deeply nested chains of CaseStmts, instead of doing a recursion
3120 // (which can blow out the stack), manually unroll and create blocks
3121 // along the way.
3122 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003123 CFGBlock *currentBlock = createBlock(false);
3124 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00003125
Ted Kremenek60fa6572010-08-04 23:54:30 +00003126 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003127 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003128 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003129 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003130
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003131 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003132 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003133 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00003134 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003135
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003136 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003137 CS = cast<CaseStmt>(Sub);
3138 Sub = CS->getSubStmt();
3139 }
3140
3141 addStmt(Sub);
3142 }
Mike Stump11289f42009-09-09 15:08:12 +00003143
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003144 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003145 if (!CaseBlock)
3146 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003147
3148 // Cases statements partition blocks, so this is the top of the basic block we
3149 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00003150 CaseBlock->setLabel(CS);
3151
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003152 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003153 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003154
3155 // Add this block to the list of successors for the block with the switch
3156 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00003157 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003158 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003159 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003160 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00003161
Ted Kremenek9aae5132007-08-23 21:42:29 +00003162 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003163 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003164
Ted Kremenek60fa6572010-08-04 23:54:30 +00003165 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003166 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003167 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003168 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00003169 // This block is now the implicit successor of other blocks.
3170 Succ = CaseBlock;
3171 }
Mike Stump31feda52009-07-17 01:31:16 +00003172
Ted Kremenek60fa6572010-08-04 23:54:30 +00003173 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003174}
Mike Stump31feda52009-07-17 01:31:16 +00003175
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003176CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00003177 if (Terminator->getSubStmt())
3178 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00003179
Ted Kremenek654c78f2008-02-13 22:05:39 +00003180 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003181
3182 if (!DefaultCaseBlock)
3183 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003184
3185 // Default statements partition blocks, so this is the top of the basic block
3186 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003187 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00003188
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003189 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003190 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00003191
Mike Stump31feda52009-07-17 01:31:16 +00003192 // Unlike case statements, we don't add the default block to the successors
3193 // for the switch statement immediately. This is done when we finish
3194 // processing the switch statement. This allows for the default case
3195 // (including a fall-through to the code after the switch statement) to always
3196 // be the last successor of a switch-terminated block.
3197
Ted Kremenek654c78f2008-02-13 22:05:39 +00003198 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003199 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003200
Ted Kremenek654c78f2008-02-13 22:05:39 +00003201 // This block is now the implicit successor of other blocks.
3202 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003203
3204 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00003205}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003206
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003207CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3208 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3209 // current block.
Craig Topper25542942014-05-20 04:30:07 +00003210 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003211
3212 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003213 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003214 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003215 TrySuccessor = Block;
3216 } else TrySuccessor = Succ;
3217
Mike Stump0bdba6c2010-01-20 01:15:34 +00003218 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003219
3220 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00003221 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003222 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00003223 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003224
Mike Stump0bdba6c2010-01-20 01:15:34 +00003225 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003226 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3227 // The code after the try is the implicit successor.
3228 Succ = TrySuccessor;
3229 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00003230 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00003231 HasCatchAll = true;
3232 }
Craig Topper25542942014-05-20 04:30:07 +00003233 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003234 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00003235 if (!CatchBlock)
3236 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003237 // Add this block to the list of successors for the block with the try
3238 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003239 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003240 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00003241 if (!HasCatchAll) {
3242 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003243 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00003244 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003245 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00003246 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003247
3248 // The code after the try is the implicit successor.
3249 Succ = TrySuccessor;
3250
Mike Stump845384a2010-01-20 01:30:58 +00003251 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00003252 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3253 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00003254
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003255 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003256 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003257 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003258}
3259
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003260CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003261 // CXXCatchStmt are treated like labels, so they are the first statement in a
3262 // block.
3263
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003264 // Save local scope position because in case of exception variable ScopePos
3265 // won't be restored when traversing AST.
3266 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3267
3268 // Create local scope for possible exception variable.
3269 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003270 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003271 LocalScope::const_iterator BeginScopePos = ScopePos;
3272 addLocalScopeForVarDecl(VD);
3273 addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
3274 }
3275
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003276 if (CS->getHandlerBlock())
3277 addStmt(CS->getHandlerBlock());
3278
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003279 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003280 if (!CatchBlock)
3281 CatchBlock = createBlock();
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003282
3283 // CXXCatchStmt is more than just a label. They have semantic meaning
3284 // as well, as they implicitly "initialize" the catch variable. Add
3285 // it to the CFG as a CFGElement so that the control-flow of these
3286 // semantics gets captured.
3287 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003288
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003289 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3290 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003291 CatchBlock->setLabel(CS);
3292
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003293 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003294 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003295 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003296
3297 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003298 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003299
3300 return CatchBlock;
3301}
3302
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003303CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00003304 // C++0x for-range statements are specified as [stmt.ranged]:
3305 //
3306 // {
3307 // auto && __range = range-init;
3308 // for ( auto __begin = begin-expr,
3309 // __end = end-expr;
3310 // __begin != __end;
3311 // ++__begin ) {
3312 // for-range-declaration = *__begin;
3313 // statement
3314 // }
3315 // }
3316
3317 // Save local scope position before the addition of the implicit variables.
3318 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3319
3320 // Create local scopes and destructors for range, begin and end variables.
3321 if (Stmt *Range = S->getRangeStmt())
3322 addLocalScopeForStmt(Range);
3323 if (Stmt *BeginEnd = S->getBeginEndStmt())
3324 addLocalScopeForStmt(BeginEnd);
3325 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
3326
3327 LocalScope::const_iterator ContinueScopePos = ScopePos;
3328
3329 // "for" is a control-flow statement. Thus we stop processing the current
3330 // block.
Craig Topper25542942014-05-20 04:30:07 +00003331 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003332 if (Block) {
3333 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003334 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003335 LoopSuccessor = Block;
3336 } else
3337 LoopSuccessor = Succ;
3338
3339 // Save the current value for the break targets.
3340 // All breaks should go to the code following the loop.
3341 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3342 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3343
3344 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003345 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00003346 ConditionBlock->setTerminator(S);
3347
3348 // Now add the actual condition to the condition block.
3349 if (Expr *C = S->getCond()) {
3350 Block = ConditionBlock;
3351 CFGBlock *BeginConditionBlock = addStmt(C);
3352 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003353 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003354 assert(BeginConditionBlock == ConditionBlock &&
3355 "condition block in for-range was unexpectedly complex");
3356 (void)BeginConditionBlock;
3357 }
3358
3359 // The condition block is the implicit successor for the loop body as well as
3360 // any code above the loop.
3361 Succ = ConditionBlock;
3362
3363 // See if this is a known constant.
3364 TryResult KnownVal(true);
3365
3366 if (S->getCond())
3367 KnownVal = tryEvaluateBool(S->getCond());
3368
3369 // Now create the loop body.
3370 {
3371 assert(S->getBody());
3372
3373 // Save the current values for Block, Succ, and continue targets.
3374 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3375 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3376
3377 // Generate increment code in its own basic block. This is the target of
3378 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00003379 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003380 Succ = addStmt(S->getInc());
3381 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3382
3383 // The starting block for the loop increment is the block that should
3384 // represent the 'loop target' for looping back to the start of the loop.
3385 ContinueJumpTarget.block->setLoopTarget(S);
3386
3387 // Finish up the increment block and prepare to start the loop body.
3388 assert(Block);
3389 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003390 return nullptr;
3391 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003392
3393 // Add implicit scope and dtors for loop variable.
3394 addLocalScopeAndDtors(S->getLoopVarStmt());
3395
3396 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003397 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00003398 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003399 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003400 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003401 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003402 return nullptr;
3403
Richard Smith02e85f32011-04-14 22:09:26 +00003404 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00003405 addSuccessor(ConditionBlock,
3406 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00003407 }
3408
3409 // Link up the condition block with the code that follows the loop (the
3410 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003411 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00003412
3413 // Add the initialization statements.
3414 Block = createBlock();
Richard Smith0c502d22011-04-18 15:49:25 +00003415 addStmt(S->getBeginEndStmt());
3416 return addStmt(S->getRangeStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003417}
3418
John McCall5d413782010-12-06 08:20:24 +00003419CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003420 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003421 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003422 // If adding implicit destructors visit the full expression for adding
3423 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003424 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00003425 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003426
3427 // Full expression has to be added as CFGStmt so it will be sequenced
3428 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003429 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003430 }
3431 return Visit(E->getSubExpr(), asc);
3432}
3433
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003434CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3435 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003436 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003437 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003438 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003439
3440 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003441 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003442 }
3443 return Visit(E->getSubExpr(), asc);
3444}
3445
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003446CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3447 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003448 autoCreateBlock();
Zhongxing Xuf0cb43f2012-01-11 02:39:07 +00003449 appendStmt(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003450
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003451 return VisitChildren(C);
3452}
3453
Jordan Rosec9176072014-01-13 17:59:19 +00003454CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3455 AddStmtChoice asc) {
3456
3457 autoCreateBlock();
3458 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00003459
Jordan Rosec9176072014-01-13 17:59:19 +00003460 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003461 Block = Visit(NE->getInitializer());
Jordan Rosec9176072014-01-13 17:59:19 +00003462 if (BuildOpts.AddCXXNewAllocator)
3463 appendNewAllocator(Block, NE);
3464 if (NE->isArray())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003465 Block = Visit(NE->getArraySize());
Jordan Rosec9176072014-01-13 17:59:19 +00003466 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3467 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00003468 Block = Visit(*I);
Jordan Rosec9176072014-01-13 17:59:19 +00003469 return Block;
3470}
Jordan Rosed2f40792013-09-03 17:00:57 +00003471
3472CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3473 AddStmtChoice asc) {
3474 autoCreateBlock();
3475 appendStmt(Block, DE);
3476 QualType DTy = DE->getDestroyedType();
3477 DTy = DTy.getNonReferenceType();
3478 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3479 if (RD) {
Matt Beaumont-Gay093f2402013-09-09 21:07:58 +00003480 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
Jordan Rosed2f40792013-09-03 17:00:57 +00003481 appendDeleteDtor(Block, RD, DE);
3482 }
3483
3484 return VisitChildren(DE);
3485}
3486
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003487CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3488 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003489 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003490 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003491 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003492 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003493 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003494 }
3495 return Visit(E->getSubExpr(), asc);
3496}
3497
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003498CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3499 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003500 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003501 appendStmt(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003502 return VisitChildren(C);
3503}
3504
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003505CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3506 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003507 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003508 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003509 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003510 }
Ted Kremenek8219b822010-12-16 07:46:53 +00003511 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003512}
3513
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003514CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00003515 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003516 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003517
Ted Kremenekeda180e22007-08-28 19:26:49 +00003518 if (!IBlock) {
3519 IBlock = createBlock(false);
3520 cfg->setIndirectGotoBlock(IBlock);
3521 }
Mike Stump31feda52009-07-17 01:31:16 +00003522
Ted Kremenekeda180e22007-08-28 19:26:49 +00003523 // IndirectGoto is a control-flow statement. Thus we stop processing the
3524 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003525 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003526 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00003527
Ted Kremenekeda180e22007-08-28 19:26:49 +00003528 Block = createBlock(false);
3529 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003530 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00003531 return addStmt(I->getTarget());
3532}
3533
Manuel Klimekb5616c92014-08-07 10:42:17 +00003534CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
3535 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003536 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3537
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003538tryAgain:
3539 if (!E) {
3540 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00003541 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003542 }
3543 switch (E->getStmtClass()) {
3544 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00003545 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003546
3547 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00003548 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
3549 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003550
3551 case Stmt::CXXBindTemporaryExprClass:
3552 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003553 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003554
John McCallc07a0c72011-02-17 10:25:35 +00003555 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003556 case Stmt::ConditionalOperatorClass:
3557 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003558 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003559
3560 case Stmt::ImplicitCastExprClass:
3561 // For implicit cast we want BindToTemporary to be passed further.
3562 E = cast<CastExpr>(E)->getSubExpr();
3563 goto tryAgain;
3564
Manuel Klimekb0042c42014-07-30 08:34:42 +00003565 case Stmt::CXXFunctionalCastExprClass:
3566 // For functional cast we want BindToTemporary to be passed further.
3567 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
3568 goto tryAgain;
3569
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003570 case Stmt::ParenExprClass:
3571 E = cast<ParenExpr>(E)->getSubExpr();
3572 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00003573
Manuel Klimekb0042c42014-07-30 08:34:42 +00003574 case Stmt::MaterializeTemporaryExprClass: {
3575 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
3576 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
3577 SmallVector<const Expr *, 2> CommaLHSs;
3578 SmallVector<SubobjectAdjustment, 2> Adjustments;
3579 // Find the expression whose lifetime needs to be extended.
3580 E = const_cast<Expr *>(
3581 cast<MaterializeTemporaryExpr>(E)
3582 ->GetTemporaryExpr()
3583 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
3584 // Visit the skipped comma operator left-hand sides for other temporaries.
3585 for (const Expr *CommaLHS : CommaLHSs) {
3586 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00003587 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00003588 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003589 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00003590 }
Richard Smith4137af22014-07-27 05:12:49 +00003591
3592 case Stmt::BlockExprClass:
3593 // Don't recurse into blocks; their subexpressions don't get evaluated
3594 // here.
3595 return Block;
3596
3597 case Stmt::LambdaExprClass: {
3598 // For lambda expressions, only recurse into the capture initializers,
3599 // and not the body.
3600 auto *LE = cast<LambdaExpr>(E);
3601 CFGBlock *B = Block;
3602 for (Expr *Init : LE->capture_inits()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003603 if (CFGBlock *R = VisitForTemporaryDtors(
3604 Init, /*BindToTemporary=*/false, Context))
Richard Smith4137af22014-07-27 05:12:49 +00003605 B = R;
3606 }
3607 return B;
3608 }
3609
3610 case Stmt::CXXDefaultArgExprClass:
3611 E = cast<CXXDefaultArgExpr>(E)->getExpr();
3612 goto tryAgain;
3613
3614 case Stmt::CXXDefaultInitExprClass:
3615 E = cast<CXXDefaultInitExpr>(E)->getExpr();
3616 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003617 }
3618}
3619
Manuel Klimekb5616c92014-08-07 10:42:17 +00003620CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
3621 TempDtorContext &Context) {
3622 if (isa<LambdaExpr>(E)) {
3623 // Do not visit the children of lambdas; they have their own CFGs.
3624 return Block;
3625 }
3626
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003627 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00003628 // order that they will appear in the CFG. Because the CFG is built
3629 // bottom-up, this means we visit them in their natural order, which
3630 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003631 CFGBlock *B = Block;
Ted Kremenek8ae67872013-02-05 22:00:19 +00003632 for (Stmt::child_range I = E->children(); I; ++I) {
3633 if (Stmt *Child = *I)
Manuel Klimekb5616c92014-08-07 10:42:17 +00003634 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00003635 B = R;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003636 }
3637 return B;
3638}
3639
Manuel Klimekb5616c92014-08-07 10:42:17 +00003640CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
3641 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003642 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003643 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00003644 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
3645 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
3646 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00003647
Manuel Klimekedf925b92014-08-07 18:44:19 +00003648 // We do not know at CFG-construction time whether the right-hand-side was
3649 // executed, thus we add a branch node that depends on the temporary
3650 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003651 TempDtorContext RHSContext(
3652 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00003653 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00003654 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00003655
Manuel Klimekb5616c92014-08-07 10:42:17 +00003656 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003657 }
3658
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003659 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003660 // For assignment operator (=) LHS expression is visited
3661 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003662 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3663 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003664 return LHSBlock ? LHSBlock : RHSBlock;
3665 }
3666
3667 // For any other binary operator RHS expression is visited before
3668 // LHS expression (order of children). For destructors visit them in reverse
3669 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003670 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3671 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003672 return RHSBlock ? RHSBlock : LHSBlock;
3673}
3674
3675CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003676 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003677 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003678 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00003679 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003680 // If lifetime of temporary is not prolonged (by assigning to constant
3681 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00003682
Chandler Carruthad747252011-09-13 06:09:01 +00003683 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00003684
Ted Kremenekff909f92014-03-08 02:22:25 +00003685 if (Dtor->isNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003686 // If the destructor is marked as a no-return destructor, we need to
3687 // create a new block for the destructor which does not have as a
3688 // successor anything built thus far. Control won't flow out of this
3689 // block.
3690 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00003691 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00003692 } else if (Context.needsTempDtorBranch()) {
3693 // If we need to introduce a branch, we add a new block that we will hook
3694 // up to a decision block later.
3695 if (B) Succ = B;
3696 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00003697 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00003698 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00003699 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00003700 if (Context.needsTempDtorBranch()) {
3701 Context.setDecisionPoint(Succ, E);
3702 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003703 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003704
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003705 B = Block;
3706 }
3707 return B;
3708}
3709
Manuel Klimekb5616c92014-08-07 10:42:17 +00003710void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
3711 CFGBlock *FalseSucc) {
3712 if (!Context.TerminatorExpr) {
3713 // If no temporary was found, we do not need to insert a decision point.
3714 return;
3715 }
3716 assert(Context.TerminatorExpr);
3717 CFGBlock *Decision = createBlock(false);
3718 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
Manuel Klimekdeb02622014-08-08 07:37:13 +00003719 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00003720 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00003721 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00003722 Block = Decision;
3723}
3724
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003725CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003726 AbstractConditionalOperator *E, bool BindToTemporary,
3727 TempDtorContext &Context) {
3728 VisitForTemporaryDtors(E->getCond(), false, Context);
3729 CFGBlock *ConditionBlock = Block;
3730 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00003731 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00003732 TryResult NegatedVal = ConditionVal;
3733 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00003734
Manuel Klimekdeb02622014-08-08 07:37:13 +00003735 TempDtorContext TrueContext(
3736 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00003737 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003738 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003739
Manuel Klimekb5616c92014-08-07 10:42:17 +00003740 Block = ConditionBlock;
3741 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00003742 TempDtorContext FalseContext(
3743 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00003744 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003745
Manuel Klimekb5616c92014-08-07 10:42:17 +00003746 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00003747 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003748 } else if (TrueContext.TerminatorExpr) {
3749 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00003750 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003751 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00003752 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003753 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003754 return Block;
3755}
3756
Ted Kremenek04cca642007-08-23 21:26:19 +00003757} // end anonymous namespace
Ted Kremenek889073f2007-08-23 16:51:22 +00003758
Mike Stump31feda52009-07-17 01:31:16 +00003759/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
3760/// no successors or predecessors. If this is the first block created in the
3761/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003762CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00003763 bool first_block = begin() == end();
3764
3765 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003766 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00003767 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003768 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00003769
3770 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003771 if (first_block)
3772 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00003773
3774 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003775 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00003776}
3777
David Blaikiee90195c2014-08-29 18:53:26 +00003778/// buildCFG - Constructs a CFG from an AST.
3779std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
3780 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00003781 CFGBuilder Builder(C, BO);
3782 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00003783}
3784
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003785const CXXDestructorDecl *
3786CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003787 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003788 case CFGElement::Statement:
3789 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00003790 case CFGElement::NewAllocator:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003791 llvm_unreachable("getDestructorDecl should only be used with "
3792 "ImplicitDtors");
3793 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00003794 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003795 QualType ty = var->getType();
Ted Kremenek1676a042011-03-03 01:01:03 +00003796 ty = ty.getNonReferenceType();
Ted Kremeneke7d78882012-03-19 23:48:41 +00003797 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003798 ty = arrayType->getElementType();
3799 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003800 const RecordType *recordType = ty->getAs<RecordType>();
3801 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00003802 cast<CXXRecordDecl>(recordType->getDecl());
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003803 return classDecl->getDestructor();
3804 }
Jordan Rosed2f40792013-09-03 17:00:57 +00003805 case CFGElement::DeleteDtor: {
3806 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
3807 QualType DTy = DE->getDestroyedType();
3808 DTy = DTy.getNonReferenceType();
3809 const CXXRecordDecl *classDecl =
3810 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
3811 return classDecl->getDestructor();
3812 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003813 case CFGElement::TemporaryDtor: {
3814 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00003815 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003816 const CXXTemporary *temp = bindExpr->getTemporary();
3817 return temp->getDestructor();
3818 }
3819 case CFGElement::BaseDtor:
3820 case CFGElement::MemberDtor:
3821
3822 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00003823 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003824 }
Ted Kremenek1676a042011-03-03 01:01:03 +00003825 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003826}
3827
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003828bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00003829 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
3830 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003831 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00003832}
3833
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00003834//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003835// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00003836//===----------------------------------------------------------------------===//
3837
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003838CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Craig Topper25542942014-05-20 04:30:07 +00003839 : ReachableBlock(IsReachable ? B : nullptr),
3840 UnreachableBlock(!IsReachable ? B : nullptr,
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003841 B && IsReachable ? AB_Normal : AB_Unreachable) {}
3842
3843CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
3844 : ReachableBlock(B),
Craig Topper25542942014-05-20 04:30:07 +00003845 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003846 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
3847
3848void CFGBlock::addSuccessor(AdjacentBlock Succ,
3849 BumpVectorContext &C) {
3850 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00003851 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003852
3853 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00003854 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003855
3856 Succs.push_back(Succ, C);
3857}
3858
Ted Kremenekb0371852010-09-09 00:06:04 +00003859bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00003860 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003861
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003862 if (F.IgnoreNullPredecessors && !From)
3863 return true;
3864
3865 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003866 // If the 'To' has no label or is labeled but the label isn't a
3867 // CaseStmt then filter this edge.
3868 if (const SwitchStmt *S =
Ted Kremenek89794742011-03-07 22:04:39 +00003869 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003870 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00003871 const Stmt *L = To->getLabel();
3872 if (!L || !isa<CaseStmt>(L))
3873 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00003874 }
3875 }
3876 }
3877
3878 return false;
3879}
3880
3881//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00003882// CFG pretty printing
3883//===----------------------------------------------------------------------===//
3884
Ted Kremenek7e776b12007-08-22 18:22:34 +00003885namespace {
3886
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00003887class StmtPrinterHelper : public PrinterHelper {
Ted Kremenek96a7a592011-03-01 03:15:10 +00003888 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
3889 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003890 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003891 DeclMapTy DeclMap;
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003892 signed currentBlock;
Ted Kremenekd94854a2012-08-22 06:26:15 +00003893 unsigned currStmt;
Chris Lattnerc61089a2009-06-30 01:26:17 +00003894 const LangOptions &LangOpts;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003895public:
Ted Kremenekf8b50e92007-08-31 22:26:13 +00003896
Chris Lattnerc61089a2009-06-30 01:26:17 +00003897 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Ted Kremenekd94854a2012-08-22 06:26:15 +00003898 : currentBlock(0), currStmt(0), LangOpts(LO)
Ted Kremenek96a7a592011-03-01 03:15:10 +00003899 {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003900 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
3901 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003902 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003903 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00003904 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
3905 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003906 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00003907 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003908
Ted Kremenek96a7a592011-03-01 03:15:10 +00003909 switch (stmt->getStmtClass()) {
3910 case Stmt::DeclStmtClass:
3911 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
3912 break;
3913 case Stmt::IfStmtClass: {
3914 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
3915 if (var)
3916 DeclMap[var] = P;
3917 break;
3918 }
3919 case Stmt::ForStmtClass: {
3920 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
3921 if (var)
3922 DeclMap[var] = P;
3923 break;
3924 }
3925 case Stmt::WhileStmtClass: {
3926 const VarDecl *var =
3927 cast<WhileStmt>(stmt)->getConditionVariable();
3928 if (var)
3929 DeclMap[var] = P;
3930 break;
3931 }
3932 case Stmt::SwitchStmtClass: {
3933 const VarDecl *var =
3934 cast<SwitchStmt>(stmt)->getConditionVariable();
3935 if (var)
3936 DeclMap[var] = P;
3937 break;
3938 }
3939 case Stmt::CXXCatchStmtClass: {
3940 const VarDecl *var =
3941 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
3942 if (var)
3943 DeclMap[var] = P;
3944 break;
3945 }
3946 default:
3947 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003948 }
3949 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003950 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00003951 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003952 }
Mike Stump31feda52009-07-17 01:31:16 +00003953
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003954 ~StmtPrinterHelper() override {}
Mike Stump31feda52009-07-17 01:31:16 +00003955
Chris Lattnerc61089a2009-06-30 01:26:17 +00003956 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003957 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00003958 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00003959
Craig Topperb45acb82014-03-14 06:02:07 +00003960 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003961 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003962
3963 if (I == StmtMap.end())
3964 return false;
Mike Stump31feda52009-07-17 01:31:16 +00003965
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003966 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00003967 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003968 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00003969 }
Mike Stump31feda52009-07-17 01:31:16 +00003970
Ted Kremenek60983dc2010-01-19 20:52:05 +00003971 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00003972 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003973 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003974
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003975 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003976 DeclMapTy::iterator I = DeclMap.find(D);
3977
3978 if (I == DeclMap.end())
3979 return false;
3980
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003981 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00003982 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003983 return false;
3984 }
3985
3986 OS << "[B" << I->second.first << "." << I->second.second << "]";
3987 return true;
3988 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003989};
Chris Lattnerc61089a2009-06-30 01:26:17 +00003990} // end anonymous namespace
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003991
Chris Lattnerc61089a2009-06-30 01:26:17 +00003992
3993namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00003994class CFGBlockTerminatorPrint
Ted Kremenek83ebcef2008-01-08 18:15:10 +00003995 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Mike Stump31feda52009-07-17 01:31:16 +00003996
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003997 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003998 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00003999 PrintingPolicy Policy;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004000public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004001 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00004002 const PrintingPolicy &Policy)
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00004003 : OS(os), Helper(helper), Policy(Policy) {
4004 this->Policy.IncludeNewlines = false;
4005 }
Mike Stump31feda52009-07-17 01:31:16 +00004006
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004007 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004008 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004009 if (Stmt *C = I->getCond())
4010 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004011 }
Mike Stump31feda52009-07-17 01:31:16 +00004012
Ted Kremenek9aae5132007-08-23 21:42:29 +00004013 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004014 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00004015 Terminator->printPretty(OS, Helper, Policy);
4016 }
4017
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00004018 void VisitDeclStmt(DeclStmt *DS) {
4019 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4020 OS << "static init " << VD->getName();
4021 }
4022
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004023 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004024 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004025 if (F->getInit())
4026 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004027 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004028 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004029 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004030 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00004031 if (F->getInc())
4032 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00004033 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00004034 }
Mike Stump31feda52009-07-17 01:31:16 +00004035
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004036 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004037 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004038 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004039 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004040 }
Mike Stump31feda52009-07-17 01:31:16 +00004041
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004042 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004043 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004044 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004045 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004046 }
Mike Stump31feda52009-07-17 01:31:16 +00004047
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004048 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00004049 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00004050 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004051 }
Mike Stump31feda52009-07-17 01:31:16 +00004052
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004053 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004054 OS << "try ...";
4055 }
4056
John McCallc07a0c72011-02-17 10:25:35 +00004057 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00004058 if (Stmt *Cond = C->getCond())
4059 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004060 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004061 }
Mike Stump31feda52009-07-17 01:31:16 +00004062
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004063 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00004064 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004065 if (Stmt *Cond = C->getCond())
4066 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00004067 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00004068 }
Mike Stump31feda52009-07-17 01:31:16 +00004069
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004070 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004071 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004072 if (Stmt *T = I->getTarget())
4073 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004074 }
Mike Stump31feda52009-07-17 01:31:16 +00004075
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004076 void VisitBinaryOperator(BinaryOperator* B) {
4077 if (!B->isLogicalOp()) {
4078 VisitExpr(B);
4079 return;
4080 }
Mike Stump31feda52009-07-17 01:31:16 +00004081
Richard Trieuddd01ce2014-06-09 22:53:25 +00004082 if (B->getLHS())
4083 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004084
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004085 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004086 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00004087 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004088 return;
John McCalle3027922010-08-25 11:45:40 +00004089 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00004090 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004091 return;
4092 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004093 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00004094 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004095 }
Mike Stump31feda52009-07-17 01:31:16 +00004096
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004097 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00004098 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004099 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00004100
4101public:
4102 void print(CFGTerminator T) {
4103 if (T.isTemporaryDtorsBranch())
4104 OS << "(Temp Dtor) ";
4105 Visit(T.getStmt());
4106 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00004107};
Chris Lattnerc61089a2009-06-30 01:26:17 +00004108} // end anonymous namespace
4109
Aaron Ballmanff924b02013-11-18 20:11:50 +00004110static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00004111 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00004112 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4113 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00004114 assert(S != nullptr && "Expecting non-null Stmt");
4115
Aaron Ballmanff924b02013-11-18 20:11:50 +00004116 // special printing for statement-expressions.
4117 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4118 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00004119
Aaron Ballmanff924b02013-11-18 20:11:50 +00004120 if (Sub->children()) {
4121 OS << "({ ... ; ";
4122 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4123 OS << " })\n";
4124 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004125 }
4126 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00004127 // special printing for comma expressions.
4128 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4129 if (B->getOpcode() == BO_Comma) {
4130 OS << "... , ";
4131 Helper.handledStmt(B->getRHS(),OS);
4132 OS << '\n';
4133 return;
4134 }
4135 }
4136 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00004137
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004138 if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004139 OS << " (OperatorCall)";
Ted Kremenek0ffba932011-12-21 19:32:38 +00004140 }
4141 else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004142 OS << " (BindTemporary)";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004143 }
Ted Kremenek1a7648b2011-12-21 19:39:59 +00004144 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4145 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
4146 }
Ted Kremenek0ffba932011-12-21 19:32:38 +00004147 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
4148 OS << " (" << CE->getStmtClassName() << ", "
4149 << CE->getCastKindName()
4150 << ", " << CE->getType().getAsString()
4151 << ")";
4152 }
Mike Stump31feda52009-07-17 01:31:16 +00004153
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004154 // Expressions need a newline.
4155 if (isa<Expr>(S))
4156 OS << '\n';
Ted Kremenek0f5d8bc2010-08-31 18:47:37 +00004157
David Blaikie00be69a2013-02-23 00:29:34 +00004158 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
4159 const CXXCtorInitializer *I = IE->getInitializer();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004160 if (I->isBaseInitializer())
4161 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
Jordan Rose69d0aed2013-10-22 23:19:47 +00004162 else if (I->isDelegatingInitializer())
4163 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
Francois Pichetd583da02010-12-04 09:14:42 +00004164 else OS << I->getAnyMember()->getName();
Mike Stump31feda52009-07-17 01:31:16 +00004165
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004166 OS << "(";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004167 if (Expr *IE = I->getInit())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004168 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004169 OS << ")";
4170
4171 if (I->isBaseInitializer())
4172 OS << " (Base initializer)\n";
Jordan Rose69d0aed2013-10-22 23:19:47 +00004173 else if (I->isDelegatingInitializer())
4174 OS << " (Delegating initializer)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004175 else OS << " (Member initializer)\n";
4176
David Blaikie00be69a2013-02-23 00:29:34 +00004177 } else if (Optional<CFGAutomaticObjDtor> DE =
4178 E.getAs<CFGAutomaticObjDtor>()) {
4179 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00004180 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004181
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00004182 const Type* T = VD->getType().getTypePtr();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004183 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4184 T = RT->getPointeeType().getTypePtr();
Richard Smithf676e452012-07-24 21:02:14 +00004185 T = T->getBaseElementTypeUnsafe();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004186
4187 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4188 OS << " (Implicit destructor)\n";
Marcin Swiderski20b88732010-10-05 05:37:00 +00004189
Jordan Rosec9176072014-01-13 17:59:19 +00004190 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4191 OS << "CFGNewAllocator(";
4192 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4193 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4194 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00004195 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4196 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4197 if (!RD)
4198 return;
4199 CXXDeleteExpr *DelExpr =
4200 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00004201 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00004202 OS << "->~" << RD->getName().str() << "()";
4203 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004204 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4205 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004206 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004207 OS << " (Base object destructor)\n";
Marcin Swiderski20b88732010-10-05 05:37:00 +00004208
David Blaikie00be69a2013-02-23 00:29:34 +00004209 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4210 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00004211 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004212 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00004213 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004214 OS << " (Member object destructor)\n";
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004215
David Blaikie00be69a2013-02-23 00:29:34 +00004216 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4217 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00004218 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004219 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00004220 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004221 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004222}
Mike Stump31feda52009-07-17 01:31:16 +00004223
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004224static void print_block(raw_ostream &OS, const CFG* cfg,
4225 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00004226 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004227 bool ShowColors) {
Mike Stump31feda52009-07-17 01:31:16 +00004228
Aaron Ballmanff924b02013-11-18 20:11:50 +00004229 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00004230
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004231 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004232 if (ShowColors)
4233 OS.changeColor(raw_ostream::YELLOW, true);
4234
4235 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00004236
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004237 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004238 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004239 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004240 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004241 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004242 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00004243 else if (B.hasNoReturnElement())
4244 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004245 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00004246 OS << "]\n";
4247
4248 if (ShowColors)
4249 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00004250
Ted Kremenek71eca012007-08-29 23:20:49 +00004251 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004252 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004253
4254 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004255 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004256
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004257 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004258 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004259 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004260 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004261 if (C->getLHS())
4262 C->getLHS()->printPretty(OS, &Helper,
4263 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004264 if (C->getRHS()) {
4265 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004266 C->getRHS()->printPretty(OS, &Helper,
4267 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004268 }
Mike Stump92244b02010-01-19 22:00:14 +00004269 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004270 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00004271 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004272 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00004273 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004274 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00004275 0);
4276 else
4277 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004278 OS << ")";
4279
4280 } else
David Blaikie83d382b2011-09-23 05:06:16 +00004281 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00004282
Ted Kremenek71eca012007-08-29 23:20:49 +00004283 OS << ":\n";
4284 }
Mike Stump31feda52009-07-17 01:31:16 +00004285
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004286 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004287 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00004288
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004289 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4290 I != E ; ++I, ++j ) {
Mike Stump31feda52009-07-17 01:31:16 +00004291
Ted Kremenek71eca012007-08-29 23:20:49 +00004292 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004293 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004294 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004295
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004296 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00004297
Aaron Ballmanff924b02013-11-18 20:11:50 +00004298 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00004299
Ted Kremenek72be32a2011-12-22 23:33:52 +00004300 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004301 }
Mike Stump31feda52009-07-17 01:31:16 +00004302
Ted Kremenek71eca012007-08-29 23:20:49 +00004303 // Print the terminator of this block.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004304 if (B.getTerminator()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00004305 if (ShowColors)
4306 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00004307
Ted Kremenek72be32a2011-12-22 23:33:52 +00004308 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00004309
Aaron Ballmanff924b02013-11-18 20:11:50 +00004310 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00004311
Aaron Ballmanff924b02013-11-18 20:11:50 +00004312 PrintingPolicy PP(Helper.getLangOpts());
4313 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00004314 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004315 OS << '\n';
Ted Kremenek72be32a2011-12-22 23:33:52 +00004316
4317 if (ShowColors)
4318 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004319 }
Mike Stump31feda52009-07-17 01:31:16 +00004320
Ted Kremenek71eca012007-08-29 23:20:49 +00004321 if (print_edges) {
4322 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004323 if (!B.pred_empty()) {
4324 const raw_ostream::Colors Color = raw_ostream::BLUE;
4325 if (ShowColors)
4326 OS.changeColor(Color);
4327 OS << " Preds " ;
4328 if (ShowColors)
4329 OS.resetColor();
4330 OS << '(' << B.pred_size() << "):";
4331 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00004332
Ted Kremenek72be32a2011-12-22 23:33:52 +00004333 if (ShowColors)
4334 OS.changeColor(Color);
4335
4336 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4337 I != E; ++I, ++i) {
Mike Stump31feda52009-07-17 01:31:16 +00004338
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004339 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004340 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00004341
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004342 CFGBlock *B = *I;
4343 bool Reachable = true;
4344 if (!B) {
4345 Reachable = false;
4346 B = I->getPossiblyUnreachableBlock();
4347 }
4348
4349 OS << " B" << B->getBlockID();
4350 if (!Reachable)
4351 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00004352 }
4353
4354 if (ShowColors)
4355 OS.resetColor();
4356
4357 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00004358 }
Mike Stump31feda52009-07-17 01:31:16 +00004359
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004360 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004361 if (!B.succ_empty()) {
4362 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4363 if (ShowColors)
4364 OS.changeColor(Color);
4365 OS << " Succs ";
4366 if (ShowColors)
4367 OS.resetColor();
4368 OS << '(' << B.succ_size() << "):";
4369 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004370
Ted Kremenek72be32a2011-12-22 23:33:52 +00004371 if (ShowColors)
4372 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00004373
Ted Kremenek72be32a2011-12-22 23:33:52 +00004374 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4375 I != E; ++I, ++i) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004376
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004377 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004378 OS << "\n ";
4379
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004380 CFGBlock *B = *I;
4381
4382 bool Reachable = true;
4383 if (!B) {
4384 Reachable = false;
4385 B = I->getPossiblyUnreachableBlock();
4386 }
4387
4388 if (B) {
4389 OS << " B" << B->getBlockID();
4390 if (!Reachable)
4391 OS << "(Unreachable)";
4392 }
4393 else {
4394 OS << " NULL";
4395 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00004396 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004397
Ted Kremenek72be32a2011-12-22 23:33:52 +00004398 if (ShowColors)
4399 OS.resetColor();
4400 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004401 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004402 }
Mike Stump31feda52009-07-17 01:31:16 +00004403}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004404
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004405
4406/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004407void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4408 print(llvm::errs(), LO, ShowColors);
4409}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004410
4411/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004412void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004413 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00004414
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004415 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004416 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00004417
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004418 // Iterate through the CFGBlocks and print them one by one.
4419 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4420 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004421 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004422 continue;
Mike Stump31feda52009-07-17 01:31:16 +00004423
Aaron Ballmanff924b02013-11-18 20:11:50 +00004424 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004425 }
Mike Stump31feda52009-07-17 01:31:16 +00004426
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004427 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004428 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004429 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00004430 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00004431}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004432
4433/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004434void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4435 bool ShowColors) const {
4436 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00004437}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004438
Anna Zaksa6fea132014-06-13 23:47:38 +00004439void CFGBlock::dump() const {
4440 dump(getParent(), LangOptions(), false);
4441}
4442
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004443/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4444/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004445void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004446 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004447 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004448 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004449 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00004450}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004451
Ted Kremenek15647632008-01-30 23:02:42 +00004452/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004453void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00004454 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00004455 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00004456 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004457}
4458
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004459Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Marcin Swiderskia7d84a72010-10-29 05:21:47 +00004460 Stmt *Terminator = this->Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004461 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00004462 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004463
Craig Topper25542942014-05-20 04:30:07 +00004464 Expr *E = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004465
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004466 switch (Terminator->getStmtClass()) {
4467 default:
4468 break;
Mike Stump31feda52009-07-17 01:31:16 +00004469
Jordan Rosecf10ea82013-06-06 21:53:45 +00004470 case Stmt::CXXForRangeStmtClass:
4471 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4472 break;
4473
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004474 case Stmt::ForStmtClass:
4475 E = cast<ForStmt>(Terminator)->getCond();
4476 break;
Mike Stump31feda52009-07-17 01:31:16 +00004477
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004478 case Stmt::WhileStmtClass:
4479 E = cast<WhileStmt>(Terminator)->getCond();
4480 break;
Mike Stump31feda52009-07-17 01:31:16 +00004481
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004482 case Stmt::DoStmtClass:
4483 E = cast<DoStmt>(Terminator)->getCond();
4484 break;
Mike Stump31feda52009-07-17 01:31:16 +00004485
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004486 case Stmt::IfStmtClass:
4487 E = cast<IfStmt>(Terminator)->getCond();
4488 break;
Mike Stump31feda52009-07-17 01:31:16 +00004489
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004490 case Stmt::ChooseExprClass:
4491 E = cast<ChooseExpr>(Terminator)->getCond();
4492 break;
Mike Stump31feda52009-07-17 01:31:16 +00004493
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004494 case Stmt::IndirectGotoStmtClass:
4495 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4496 break;
Mike Stump31feda52009-07-17 01:31:16 +00004497
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004498 case Stmt::SwitchStmtClass:
4499 E = cast<SwitchStmt>(Terminator)->getCond();
4500 break;
Mike Stump31feda52009-07-17 01:31:16 +00004501
John McCallc07a0c72011-02-17 10:25:35 +00004502 case Stmt::BinaryConditionalOperatorClass:
4503 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4504 break;
4505
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004506 case Stmt::ConditionalOperatorClass:
4507 E = cast<ConditionalOperator>(Terminator)->getCond();
4508 break;
Mike Stump31feda52009-07-17 01:31:16 +00004509
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004510 case Stmt::BinaryOperatorClass: // '&&' and '||'
4511 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00004512 break;
Mike Stump31feda52009-07-17 01:31:16 +00004513
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00004514 case Stmt::ObjCForCollectionStmtClass:
Mike Stump31feda52009-07-17 01:31:16 +00004515 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004516 }
Mike Stump31feda52009-07-17 01:31:16 +00004517
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004518 if (!StripParens)
4519 return E;
4520
Craig Topper25542942014-05-20 04:30:07 +00004521 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004522}
4523
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004524//===----------------------------------------------------------------------===//
4525// CFG Graphviz Visualization
4526//===----------------------------------------------------------------------===//
4527
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004528
4529#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00004530static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004531#endif
4532
Chris Lattnerc61089a2009-06-30 01:26:17 +00004533void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004534#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00004535 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004536 GraphHelper = &H;
4537 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00004538 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004539#endif
4540}
4541
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004542namespace llvm {
4543template<>
4544struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Tobias Grosser9fc223a2009-11-30 14:16:05 +00004545
4546 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4547
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004548 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004549
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00004550#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004551 std::string OutSStr;
4552 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004553 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004554 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004555
4556 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4557
4558 // Process string output to make it nicer...
4559 for (unsigned i = 0; i != OutStr.length(); ++i)
4560 if (OutStr[i] == '\n') { // Left justify
4561 OutStr[i] = '\\';
4562 OutStr.insert(OutStr.begin()+i+1, 'l');
4563 }
Mike Stump31feda52009-07-17 01:31:16 +00004564
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004565 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00004566#else
4567 return "";
4568#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004569 }
4570};
4571} // end namespace llvm