blob: 49f35ef10f1afab595960133688d33a6f2778b28 [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
David Blaikie7d170102013-05-15 07:37:26 +0000159 LLVM_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
206/// BlockScopePosPair - Structure for specifying position in CFG during its
207/// build process. It consists of CFGBlock that specifies position in CFG graph
208/// and 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.
Ted Kremenekf9d82902011-03-10 01:14:05 +0000352 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 {
Manuel Klimekdeb02622014-08-08 07:37:13 +0000448 TempDtorContext() : KnownExecuted(true) {}
449
450 TempDtorContext(TryResult KnownExecuted)
451 : IsConditional(true), KnownExecuted(KnownExecuted) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000452
453 /// Returns whether we need to start a new branch for a temporary destructor
454 /// call. This is the case when the the temporary destructor is
455 /// conditionally executed, and it is the first one we encounter while
456 /// visiting a subexpression - other temporary destructors at the same level
457 /// will be added to the same block and are executed under the same
458 /// condition.
459 bool needsTempDtorBranch() const {
460 return IsConditional && !TerminatorExpr;
461 }
462
463 /// Remember the successor S of a temporary destructor decision branch for
464 /// the corresponding CXXBindTemporaryExpr E.
465 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
466 Succ = S;
467 TerminatorExpr = E;
468 }
469
Manuel Klimekdeb02622014-08-08 07:37:13 +0000470 const bool IsConditional = false;
471 const TryResult KnownExecuted;
472 CFGBlock *Succ = nullptr;
473 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000474 };
475
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000476 // Visitors to walk an AST and generate destructors of temporaries in
477 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000478 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
479 TempDtorContext &Context);
480 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
481 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
482 TempDtorContext &Context);
483 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
484 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
485 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
486 AbstractConditionalOperator *E, bool BindToTemporary,
487 TempDtorContext &Context);
488 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
489 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000490
Ted Kremenek6065ef62008-04-28 18:00:46 +0000491 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000492 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000493 badCFG = true;
494 return Block;
495 }
Mike Stump31feda52009-07-17 01:31:16 +0000496
Ted Kremenek93668002009-07-17 22:18:43 +0000497 void autoCreateBlock() { if (!Block) Block = createBlock(); }
498 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000499 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000500
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000501 CFGBlock *addStmt(Stmt *S) {
502 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000503 }
Alexis Hunt1d792652011-01-08 20:30:50 +0000504 CFGBlock *addInitializer(CXXCtorInitializer *I);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000505 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000506 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000507 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000508
Marcin Swiderski5e415732010-09-30 23:05:00 +0000509 // Local scopes creation.
510 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
511
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000512 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000513 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
514 LocalScope* Scope = nullptr);
515 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000516
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000517 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000518
519 // Interface to CFGBlock - adding CFGElements.
Ted Kremenek37881932011-04-04 23:29:12 +0000520 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000521 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000522 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000523
Jordy Rose17347372011-06-10 08:49:37 +0000524 // All block-level expressions should have already been IgnoreParens()ed.
525 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000526 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000527 }
Alexis Hunt1d792652011-01-08 20:30:50 +0000528 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000529 B->appendInitializer(I, cfg->getBumpVectorContext());
530 }
Jordan Rosec9176072014-01-13 17:59:19 +0000531 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
532 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
533 }
Marcin Swiderski20b88732010-10-05 05:37:00 +0000534 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
535 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
536 }
537 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
538 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
539 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000540 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
541 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
542 }
Chandler Carruthad747252011-09-13 06:09:01 +0000543 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
544 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
545 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000546
Jordan Rosed2f40792013-09-03 17:00:57 +0000547 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
548 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
549 }
550
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000551 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000552 LocalScope::const_iterator B, LocalScope::const_iterator E);
553
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000554 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
555 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
556 cfg->getBumpVectorContext());
557 }
558
559 /// Add a reachable successor to a block, with the alternate variant that is
560 /// unreachable.
561 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
562 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
563 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000564 }
Mike Stump11289f42009-09-09 15:08:12 +0000565
Richard Trieuf935b562014-04-05 05:17:01 +0000566 /// \brief Find a relational comparison with an expression evaluating to a
567 /// boolean and a constant other than 0 and 1.
568 /// e.g. if ((x < y) == 10)
569 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
570 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
571 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
572
573 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
574 const Expr *BoolExpr = RHSExpr;
575 bool IntFirst = true;
576 if (!IntLiteral) {
577 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
578 BoolExpr = LHSExpr;
579 IntFirst = false;
580 }
581
582 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
583 return TryResult();
584
585 llvm::APInt IntValue = IntLiteral->getValue();
586 if ((IntValue == 1) || (IntValue == 0))
587 return TryResult();
588
589 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
590 !IntValue.isNegative();
591
592 BinaryOperatorKind Bok = B->getOpcode();
593 if (Bok == BO_GT || Bok == BO_GE) {
594 // Always true for 10 > bool and bool > -1
595 // Always false for -1 > bool and bool > 10
596 return TryResult(IntFirst == IntLarger);
597 } else {
598 // Always true for -1 < bool and bool < 10
599 // Always false for 10 < bool and bool < -1
600 return TryResult(IntFirst != IntLarger);
601 }
602 }
603
Jordan Rose7afd71e2014-05-20 17:31:11 +0000604 /// Find an incorrect equality comparison. Either with an expression
605 /// evaluating to a boolean and a constant other than 0 and 1.
606 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
607 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000608 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
609 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
610 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
611
612 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
613 const Expr *BoolExpr = RHSExpr;
614
615 if (!IntLiteral) {
616 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
617 BoolExpr = LHSExpr;
618 }
619
Jordan Rose7afd71e2014-05-20 17:31:11 +0000620 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000621 return TryResult();
622
Jordan Rose7afd71e2014-05-20 17:31:11 +0000623 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
624 if (BitOp && (BitOp->getOpcode() == BO_And ||
625 BitOp->getOpcode() == BO_Or)) {
626 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
627 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
628
629 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
630
631 if (!IntLiteral2)
632 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
633
634 if (!IntLiteral2)
635 return TryResult();
636
637 llvm::APInt L1 = IntLiteral->getValue();
638 llvm::APInt L2 = IntLiteral2->getValue();
639 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
640 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
641 if (BuildOpts.Observer)
642 BuildOpts.Observer->compareBitwiseEquality(B,
643 B->getOpcode() != BO_EQ);
644 TryResult(B->getOpcode() != BO_EQ);
645 }
646 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
647 llvm::APInt IntValue = IntLiteral->getValue();
648 if ((IntValue == 1) || (IntValue == 0)) {
649 return TryResult();
650 }
651 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000652 }
653
Jordan Rose7afd71e2014-05-20 17:31:11 +0000654 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000655 }
656
657 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
658 const llvm::APSInt &Value1,
659 const llvm::APSInt &Value2) {
660 assert(Value1.isSigned() == Value2.isSigned());
661 switch (Relation) {
662 default:
663 return TryResult();
664 case BO_EQ:
665 return TryResult(Value1 == Value2);
666 case BO_NE:
667 return TryResult(Value1 != Value2);
668 case BO_LT:
669 return TryResult(Value1 < Value2);
670 case BO_LE:
671 return TryResult(Value1 <= Value2);
672 case BO_GT:
673 return TryResult(Value1 > Value2);
674 case BO_GE:
675 return TryResult(Value1 >= Value2);
676 }
677 }
678
679 /// \brief Find a pair of comparison expressions with or without parentheses
680 /// with a shared variable and constants and a logical operator between them
681 /// that always evaluates to either true or false.
682 /// e.g. if (x != 3 || x != 4)
683 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
684 assert(B->isLogicalOp());
685 const BinaryOperator *LHS =
686 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
687 const BinaryOperator *RHS =
688 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
689 if (!LHS || !RHS)
690 return TryResult();
691
692 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
693 return TryResult();
694
695 BinaryOperatorKind BO1 = LHS->getOpcode();
696 const DeclRefExpr *Decl1 =
697 dyn_cast<DeclRefExpr>(LHS->getLHS()->IgnoreParenImpCasts());
698 const IntegerLiteral *Literal1 =
699 dyn_cast<IntegerLiteral>(LHS->getRHS()->IgnoreParens());
700 if (!Decl1 && !Literal1) {
701 if (BO1 == BO_GT)
702 BO1 = BO_LT;
703 else if (BO1 == BO_GE)
704 BO1 = BO_LE;
705 else if (BO1 == BO_LT)
706 BO1 = BO_GT;
707 else if (BO1 == BO_LE)
708 BO1 = BO_GE;
709 Decl1 = dyn_cast<DeclRefExpr>(LHS->getRHS()->IgnoreParenImpCasts());
710 Literal1 = dyn_cast<IntegerLiteral>(LHS->getLHS()->IgnoreParens());
711 }
712
713 if (!Decl1 || !Literal1)
714 return TryResult();
715
716 BinaryOperatorKind BO2 = RHS->getOpcode();
717 const DeclRefExpr *Decl2 =
718 dyn_cast<DeclRefExpr>(RHS->getLHS()->IgnoreParenImpCasts());
719 const IntegerLiteral *Literal2 =
720 dyn_cast<IntegerLiteral>(RHS->getRHS()->IgnoreParens());
721 if (!Decl2 && !Literal2) {
722 if (BO2 == BO_GT)
723 BO2 = BO_LT;
724 else if (BO2 == BO_GE)
725 BO2 = BO_LE;
726 else if (BO2 == BO_LT)
727 BO2 = BO_GT;
728 else if (BO2 == BO_LE)
729 BO2 = BO_GE;
730 Decl2 = dyn_cast<DeclRefExpr>(RHS->getRHS()->IgnoreParenImpCasts());
731 Literal2 = dyn_cast<IntegerLiteral>(RHS->getLHS()->IgnoreParens());
732 }
733
734 if (!Decl2 || !Literal2)
735 return TryResult();
736
737 // Check that it is the same variable on both sides.
738 if (Decl1->getDecl() != Decl2->getDecl())
739 return TryResult();
740
741 llvm::APSInt L1, L2;
742
743 if (!Literal1->EvaluateAsInt(L1, *Context) ||
744 !Literal2->EvaluateAsInt(L2, *Context))
745 return TryResult();
746
747 // Can't compare signed with unsigned or with different bit width.
748 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
749 return TryResult();
750
751 // Values that will be used to determine if result of logical
752 // operator is always true/false
753 const llvm::APSInt Values[] = {
754 // Value less than both Value1 and Value2
755 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
756 // L1
757 L1,
758 // Value between Value1 and Value2
759 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
760 L1.isUnsigned()),
761 // L2
762 L2,
763 // Value greater than both Value1 and Value2
764 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
765 };
766
767 // Check whether expression is always true/false by evaluating the following
768 // * variable x is less than the smallest literal.
769 // * variable x is equal to the smallest literal.
770 // * Variable x is between smallest and largest literal.
771 // * Variable x is equal to the largest literal.
772 // * Variable x is greater than largest literal.
773 bool AlwaysTrue = true, AlwaysFalse = true;
774 for (unsigned int ValueIndex = 0;
775 ValueIndex < sizeof(Values) / sizeof(Values[0]);
776 ++ValueIndex) {
777 llvm::APSInt Value = Values[ValueIndex];
778 TryResult Res1, Res2;
779 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
780 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
781
782 if (!Res1.isKnown() || !Res2.isKnown())
783 return TryResult();
784
785 if (B->getOpcode() == BO_LAnd) {
786 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
787 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
788 } else {
789 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
790 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
791 }
792 }
793
794 if (AlwaysTrue || AlwaysFalse) {
795 if (BuildOpts.Observer)
796 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
797 return TryResult(AlwaysTrue);
798 }
799 return TryResult();
800 }
801
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000802 /// Try and evaluate an expression to an integer constant.
803 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
804 if (!BuildOpts.PruneTriviallyFalseEdges)
805 return false;
806 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +0000807 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +0000808 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000809 }
Mike Stump11289f42009-09-09 15:08:12 +0000810
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000811 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +0000812 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000813 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +0000814 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000815 S->isTypeDependent() || S->isValueDependent())
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000816 return TryResult();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000817
818 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
819 if (Bop->isLogicalOp()) {
820 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000821 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
822 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000823 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +0000824
825 // Retrieve result at first, or the map might be updated.
826 TryResult Result = evaluateAsBooleanConditionNoCache(S);
827 CachedBoolEvals[S] = Result; // update or insert
828 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000829 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000830 else {
831 switch (Bop->getOpcode()) {
832 default: break;
833 // For 'x & 0' and 'x * 0', we can determine that
834 // the value is always false.
835 case BO_Mul:
836 case BO_And: {
837 // If either operand is zero, we know the value
838 // must be false.
839 llvm::APSInt IntVal;
840 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
841 if (IntVal.getBoolValue() == false) {
842 return TryResult(false);
843 }
844 }
845 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
846 if (IntVal.getBoolValue() == false) {
847 return TryResult(false);
848 }
849 }
850 }
851 break;
852 }
853 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000854 }
855
856 return evaluateAsBooleanConditionNoCache(S);
857 }
858
859 /// \brief Evaluate as boolean \param E without using the cache.
860 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
861 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
862 if (Bop->isLogicalOp()) {
863 TryResult LHS = tryEvaluateBool(Bop->getLHS());
864 if (LHS.isKnown()) {
865 // We were able to evaluate the LHS, see if we can get away with not
866 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
867 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
868 return LHS.isTrue();
869
870 TryResult RHS = tryEvaluateBool(Bop->getRHS());
871 if (RHS.isKnown()) {
872 if (Bop->getOpcode() == BO_LOr)
873 return LHS.isTrue() || RHS.isTrue();
874 else
875 return LHS.isTrue() && RHS.isTrue();
876 }
877 } else {
878 TryResult RHS = tryEvaluateBool(Bop->getRHS());
879 if (RHS.isKnown()) {
880 // We can't evaluate the LHS; however, sometimes the result
881 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
882 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
883 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +0000884 } else {
885 TryResult BopRes = checkIncorrectLogicOperator(Bop);
886 if (BopRes.isKnown())
887 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000888 }
889 }
890
891 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000892 } else if (Bop->isEqualityOp()) {
893 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
894 if (BopRes.isKnown())
895 return BopRes.isTrue();
896 } else if (Bop->isRelationalOp()) {
897 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
898 if (BopRes.isKnown())
899 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000900 }
901 }
902
903 bool Result;
904 if (E->EvaluateAsBooleanCondition(Result, *Context))
905 return Result;
906
907 return TryResult();
Mike Stump773582d2009-07-23 23:25:26 +0000908 }
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000909
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000910};
Mike Stump31feda52009-07-17 01:31:16 +0000911
Ted Kremeneka099c592011-03-10 03:50:34 +0000912inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
913 const Stmt *stmt) const {
914 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
915}
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000916
Ted Kremeneka099c592011-03-10 03:50:34 +0000917bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000918 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
919
Ted Kremeneka099c592011-03-10 03:50:34 +0000920 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +0000921 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000922
923 if (lastLookup == stmt) {
924 if (cachedEntry) {
925 assert(cachedEntry->first == stmt);
926 return true;
927 }
Ted Kremenek8b46c002011-07-19 14:18:43 +0000928 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000929 }
Ted Kremeneka099c592011-03-10 03:50:34 +0000930
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000931 lastLookup = stmt;
932
933 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +0000934 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
935
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000936 if (!fb) {
937 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +0000938 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +0000939 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000940 }
Ted Kremeneka099c592011-03-10 03:50:34 +0000941
942 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000943 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +0000944 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +0000945 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000946 }
947
Ted Kremeneka099c592011-03-10 03:50:34 +0000948 cachedEntry = &*itr;
949 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +0000950}
951
Douglas Gregor4619e432008-12-05 23:32:09 +0000952// FIXME: Add support for dependent-sized array types in C++?
953// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +0000954static const VariableArrayType *FindVA(const Type *t) {
955 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
956 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +0000957 if (vat->getSizeExpr())
958 return vat;
Mike Stump31feda52009-07-17 01:31:16 +0000959
Ted Kremenekd86d39c2008-09-26 22:58:57 +0000960 t = vt->getElementType().getTypePtr();
961 }
Mike Stump31feda52009-07-17 01:31:16 +0000962
Craig Topper25542942014-05-20 04:30:07 +0000963 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +0000964}
Mike Stump31feda52009-07-17 01:31:16 +0000965
966/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
967/// arbitrary statement. Examples include a single expression or a function
968/// body (compound statement). The ownership of the returned CFG is
969/// transferred to the caller. If CFG construction fails, this method returns
970/// NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000971CFG* CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +0000972 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +0000973 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +0000974 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +0000975
Mike Stump31feda52009-07-17 01:31:16 +0000976 // Create an empty block that will serve as the exit block for the CFG. Since
977 // this is the first block added to the CFG, it will be implicitly registered
978 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +0000979 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000980 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +0000981 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +0000982
Marcin Swiderski20b88732010-10-05 05:37:00 +0000983 if (BuildOpts.AddImplicitDtors)
984 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
985 addImplicitDtorsForDestructor(DD);
986
Ted Kremenek9aae5132007-08-23 21:42:29 +0000987 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +0000988 CFGBlock *B = addStmt(Statement);
989
990 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +0000991 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +0000992
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000993 // For C++ constructor add initializers to CFG.
994 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
995 for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
996 E = CD->init_rend(); I != E; ++I) {
997 B = addInitializer(*I);
998 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +0000999 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001000 }
1001 }
1002
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001003 if (B)
1004 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001005
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001006 // Backpatch the gotos whose label -> block mappings we didn't know when we
1007 // encountered them.
1008 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1009 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001010
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001011 CFGBlock *B = I->block;
Rafael Espindola210de572013-03-27 15:37:54 +00001012 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001013 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00001014
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001015 // If there is no target for the goto, then we are looking at an
1016 // incomplete AST. Handle this by not registering a successor.
1017 if (LI == LabelMap.end()) continue;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001018
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001019 JumpTarget JT = LI->second;
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001020 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1021 JT.scopePosition);
1022 addSuccessor(B, JT.block);
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001023 }
1024
1025 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001026 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001027 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1028 E = AddressTakenLabels.end(); I != E; ++I ) {
1029
1030 // Lookup the target block.
1031 LabelMapTy::iterator LI = LabelMap.find(*I);
1032
1033 // If there is no target block that contains label, then we are looking
1034 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001035 if (LI == LabelMap.end()) continue;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001036
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001037 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001038 }
Mike Stump31feda52009-07-17 01:31:16 +00001039
Mike Stump31feda52009-07-17 01:31:16 +00001040 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001041 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001042
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001043 return cfg.release();
Ted Kremenek9aae5132007-08-23 21:42:29 +00001044}
Mike Stump31feda52009-07-17 01:31:16 +00001045
Ted Kremenek9aae5132007-08-23 21:42:29 +00001046/// createBlock - Used to lazily create blocks that are connected
1047/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001048CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1049 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001050 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001051 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001052 return B;
1053}
Mike Stump31feda52009-07-17 01:31:16 +00001054
Chandler Carrutha70991b2011-09-13 09:13:49 +00001055/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1056/// CFG. It is *not* connected to the current (global) successor, and instead
1057/// directly tied to the exit block in order to be reachable.
1058CFGBlock *CFGBuilder::createNoReturnBlock() {
1059 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001060 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001061 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001062 return B;
1063}
1064
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001065/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001066CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001067 if (!BuildOpts.AddInitializers)
1068 return Block;
1069
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001070 bool HasTemporaries = false;
1071
1072 // Destructors of temporaries in initialization expression should be called
1073 // after initialization finishes.
1074 Expr *Init = I->getInit();
1075 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001076 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001077
Jordan Rose6d671cc2012-09-05 22:55:23 +00001078 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001079 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001080 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001081 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1082 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001083 }
1084 }
1085
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001086 autoCreateBlock();
1087 appendInitializer(Block, I);
1088
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001089 if (Init) {
Ted Kremenek8219b822010-12-16 07:46:53 +00001090 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001091 // For expression with temporaries go directly to subexpression to omit
1092 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001093 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1094 }
1095 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001096 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001097
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001098 return Block;
1099}
1100
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001101/// \brief Retrieve the type of the temporary object whose lifetime was
1102/// extended by a local reference with the given initializer.
1103static QualType getReferenceInitTemporaryType(ASTContext &Context,
1104 const Expr *Init) {
1105 while (true) {
1106 // Skip parentheses.
1107 Init = Init->IgnoreParens();
1108
1109 // Skip through cleanups.
1110 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1111 Init = EWC->getSubExpr();
1112 continue;
1113 }
1114
1115 // Skip through the temporary-materialization expression.
1116 if (const MaterializeTemporaryExpr *MTE
1117 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1118 Init = MTE->GetTemporaryExpr();
1119 continue;
1120 }
1121
1122 // Skip derived-to-base and no-op casts.
1123 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1124 if ((CE->getCastKind() == CK_DerivedToBase ||
1125 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1126 CE->getCastKind() == CK_NoOp) &&
1127 Init->getType()->isRecordType()) {
1128 Init = CE->getSubExpr();
1129 continue;
1130 }
1131 }
1132
1133 // Skip member accesses into rvalues.
1134 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1135 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1136 Init = ME->getBase();
1137 continue;
1138 }
1139 }
1140
1141 break;
1142 }
1143
1144 return Init->getType();
1145}
1146
Marcin Swiderski5e415732010-09-30 23:05:00 +00001147/// addAutomaticObjDtors - Add to current block automatic objects destructors
1148/// for objects in range of local scope positions. Use S as trigger statement
1149/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001150void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001151 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001152 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001153 return;
1154
Marcin Swiderski5e415732010-09-30 23:05:00 +00001155 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001156 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001157
Chandler Carruthad747252011-09-13 06:09:01 +00001158 // We need to append the destructors in reverse order, but any one of them
1159 // may be a no-return destructor which changes the CFG. As a result, buffer
1160 // this sequence up and replay them in reverse order when appending onto the
1161 // CFGBlock(s).
1162 SmallVector<VarDecl*, 10> Decls;
1163 Decls.reserve(B.distance(E));
1164 for (LocalScope::const_iterator I = B; I != E; ++I)
1165 Decls.push_back(*I);
1166
1167 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1168 E = Decls.rend();
1169 I != E; ++I) {
1170 // If this destructor is marked as a no-return destructor, we need to
1171 // create a new block for the destructor which does not have as a successor
1172 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001173 QualType Ty = (*I)->getType();
1174 if (Ty->isReferenceType()) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001175 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001176 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001177 Ty = Context->getBaseElementType(Ty);
1178
Chandler Carruthad747252011-09-13 06:09:01 +00001179 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
Richard Smith10876ef2013-01-17 01:30:42 +00001180 if (Dtor->isNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001181 Block = createNoReturnBlock();
1182 else
Chandler Carruthad747252011-09-13 06:09:01 +00001183 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001184
1185 appendAutomaticObjDtor(Block, *I, S);
1186 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001187}
1188
Marcin Swiderski20b88732010-10-05 05:37:00 +00001189/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1190/// base and member objects in destructor.
1191void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1192 assert (BuildOpts.AddImplicitDtors
1193 && "Can be called only when dtors should be added");
1194 const CXXRecordDecl *RD = DD->getParent();
1195
1196 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001197 for (const auto &VI : RD->vbases()) {
1198 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001199 if (!CD->hasTrivialDestructor()) {
1200 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001201 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001202 }
1203 }
1204
1205 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001206 for (const auto &BI : RD->bases()) {
1207 if (!BI.isVirtual()) {
1208 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001209 if (!CD->hasTrivialDestructor()) {
1210 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001211 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001212 }
1213 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001214 }
1215
1216 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001217 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001218 // Check for constant size array. Set type to array element type.
1219 QualType QT = FI->getType();
1220 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1221 if (AT->getSize() == 0)
1222 continue;
1223 QT = AT->getElementType();
1224 }
1225
1226 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001227 if (!CD->hasTrivialDestructor()) {
1228 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001229 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001230 }
1231 }
1232}
1233
Marcin Swiderski5e415732010-09-30 23:05:00 +00001234/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1235/// way return valid LocalScope object.
1236LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
1237 if (!Scope) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +00001238 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1239 Scope = alloc.Allocate<LocalScope>();
1240 BumpVectorContext ctx(alloc);
1241 new (Scope) LocalScope(ctx, ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001242 }
1243 return Scope;
1244}
1245
1246/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Zhongxing Xu81714f22010-10-01 03:00:16 +00001247/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001248void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001249 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001250 return;
1251
Craig Topper25542942014-05-20 04:30:07 +00001252 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001253
1254 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001255 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001256 for (auto *BI : CS->body()) {
1257 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001258 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001259 Scope = addLocalScopeForDeclStmt(DS, Scope);
1260 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001261 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001262 }
1263
1264 // For any other statement scope will be implicit and as such will be
1265 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001266 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001267 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001268}
1269
1270/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1271/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001272LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001273 LocalScope* Scope) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001274 if (!BuildOpts.AddImplicitDtors)
1275 return Scope;
1276
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001277 for (auto *DI : DS->decls())
1278 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001279 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001280 return Scope;
1281}
1282
1283/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1284/// create add scope for automatic objects and temporary objects bound to
1285/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001286LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001287 LocalScope* Scope) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001288 if (!BuildOpts.AddImplicitDtors)
1289 return Scope;
1290
1291 // Check if variable is local.
1292 switch (VD->getStorageClass()) {
1293 case SC_None:
1294 case SC_Auto:
1295 case SC_Register:
1296 break;
1297 default: return Scope;
1298 }
1299
1300 // Check for const references bound to temporary. Set type to pointee.
1301 QualType QT = VD->getType();
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001302 if (QT.getTypePtr()->isReferenceType()) {
Richard Smith5a0ef782013-06-27 21:43:17 +00001303 // Attempt to determine whether this declaration lifetime-extends a
1304 // temporary.
1305 //
1306 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1307 // temporaries, and a single declaration can extend multiple temporaries.
1308 // We should look at the storage duration on each nested
1309 // MaterializeTemporaryExpr instead.
1310 const Expr *Init = VD->getInit();
1311 if (!Init)
1312 return Scope;
1313 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
1314 Init = EWC->getSubExpr();
1315 if (!isa<MaterializeTemporaryExpr>(Init))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001316 return Scope;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001317
Richard Smith5a0ef782013-06-27 21:43:17 +00001318 // Lifetime-extending a temporary.
1319 QT = getReferenceInitTemporaryType(*Context, Init);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001320 }
1321
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001322 // Check for constant size array. Set type to array element type.
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001323 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001324 if (AT->getSize() == 0)
1325 return Scope;
1326 QT = AT->getElementType();
1327 }
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001328
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001329 // Check if type is a C++ class with non-trivial destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001330 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
David Blaikie0f2ae782012-01-24 04:51:48 +00001331 if (!CD->hasTrivialDestructor()) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001332 // Add the variable to scope
1333 Scope = createOrReuseLocalScope(Scope);
1334 Scope->addVar(VD);
1335 ScopePos = Scope->begin();
1336 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001337 return Scope;
1338}
1339
1340/// addLocalScopeAndDtors - For given statement add local scope for it and
1341/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001342void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001343 if (!BuildOpts.AddImplicitDtors)
1344 return;
1345
1346 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001347 addLocalScopeForStmt(S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001348 addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
1349}
1350
Marcin Swiderski321a7072010-09-30 22:54:37 +00001351/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1352/// variables with automatic storage duration to CFGBlock's elements vector.
1353/// Elements will be prepended to physical beginning of the vector which
1354/// happens to be logical end. Use blocks terminator as statement that specifies
1355/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001356/// FIXME: This mechanism for adding automatic destructors doesn't handle
1357/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001358void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00001359 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Chandler Carruthad747252011-09-13 06:09:01 +00001360 BumpVectorContext &C = cfg->getBumpVectorContext();
1361 CFGBlock::iterator InsertPos
1362 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1363 for (LocalScope::const_iterator I = B; I != E; ++I)
1364 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1365 Blk->getTerminator());
Marcin Swiderski321a7072010-09-30 22:54:37 +00001366}
1367
Ted Kremenek93668002009-07-17 22:18:43 +00001368/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00001369/// blocks for ternary operators, &&, and ||. We also process "," and
1370/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001371CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001372 if (!S) {
1373 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00001374 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001375 }
Jordy Rose17347372011-06-10 08:49:37 +00001376
1377 if (Expr *E = dyn_cast<Expr>(S))
1378 S = E->IgnoreParens();
1379
Ted Kremenek93668002009-07-17 22:18:43 +00001380 switch (S->getStmtClass()) {
1381 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001382 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001383
1384 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001385 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001386
John McCallc07a0c72011-02-17 10:25:35 +00001387 case Stmt::BinaryConditionalOperatorClass:
1388 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1389
Ted Kremenek93668002009-07-17 22:18:43 +00001390 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001391 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Ted Kremenek93668002009-07-17 22:18:43 +00001393 case Stmt::BlockExprClass:
Ted Kremeneke2499842012-04-12 20:03:44 +00001394 return VisitNoRecurse(cast<Expr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001395
Ted Kremenek93668002009-07-17 22:18:43 +00001396 case Stmt::BreakStmtClass:
1397 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001398
Ted Kremenek93668002009-07-17 22:18:43 +00001399 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00001400 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00001401 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001402 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001403 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001404
Ted Kremenek93668002009-07-17 22:18:43 +00001405 case Stmt::CaseStmtClass:
1406 return VisitCaseStmt(cast<CaseStmt>(S));
1407
1408 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001409 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001410
Ted Kremenek93668002009-07-17 22:18:43 +00001411 case Stmt::CompoundStmtClass:
1412 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001413
Ted Kremenek93668002009-07-17 22:18:43 +00001414 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001415 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001416
Ted Kremenek93668002009-07-17 22:18:43 +00001417 case Stmt::ContinueStmtClass:
1418 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001419
Ted Kremenekb27378c2010-01-19 20:40:33 +00001420 case Stmt::CXXCatchStmtClass:
1421 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1422
John McCall5d413782010-12-06 08:20:24 +00001423 case Stmt::ExprWithCleanupsClass:
1424 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00001425
Jordan Rosee5d53932012-08-23 18:10:53 +00001426 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00001427 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00001428 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1429 // called function's declaration, not by the caller. If we simply add
1430 // this expression to the CFG, we could end up with the same Expr
1431 // appearing multiple times.
1432 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00001433 //
1434 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1435 // expression to be used in the same function (through aggregate
1436 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00001437 return VisitStmt(S, asc);
1438
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001439 case Stmt::CXXBindTemporaryExprClass:
1440 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1441
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001442 case Stmt::CXXConstructExprClass:
1443 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1444
Jordan Rosec9176072014-01-13 17:59:19 +00001445 case Stmt::CXXNewExprClass:
1446 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1447
Jordan Rosed2f40792013-09-03 17:00:57 +00001448 case Stmt::CXXDeleteExprClass:
1449 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1450
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001451 case Stmt::CXXFunctionalCastExprClass:
1452 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1453
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001454 case Stmt::CXXTemporaryObjectExprClass:
1455 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1456
Ted Kremenekb27378c2010-01-19 20:40:33 +00001457 case Stmt::CXXThrowExprClass:
1458 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001459
Ted Kremenekb27378c2010-01-19 20:40:33 +00001460 case Stmt::CXXTryStmtClass:
1461 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001462
Richard Smith02e85f32011-04-14 22:09:26 +00001463 case Stmt::CXXForRangeStmtClass:
1464 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1465
Ted Kremenek93668002009-07-17 22:18:43 +00001466 case Stmt::DeclStmtClass:
1467 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001468
Ted Kremenek93668002009-07-17 22:18:43 +00001469 case Stmt::DefaultStmtClass:
1470 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001471
Ted Kremenek93668002009-07-17 22:18:43 +00001472 case Stmt::DoStmtClass:
1473 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001474
Ted Kremenek93668002009-07-17 22:18:43 +00001475 case Stmt::ForStmtClass:
1476 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001477
Ted Kremenek93668002009-07-17 22:18:43 +00001478 case Stmt::GotoStmtClass:
1479 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001480
Ted Kremenek93668002009-07-17 22:18:43 +00001481 case Stmt::IfStmtClass:
1482 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001483
Ted Kremenek8219b822010-12-16 07:46:53 +00001484 case Stmt::ImplicitCastExprClass:
1485 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001486
Ted Kremenek93668002009-07-17 22:18:43 +00001487 case Stmt::IndirectGotoStmtClass:
1488 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001489
Ted Kremenek93668002009-07-17 22:18:43 +00001490 case Stmt::LabelStmtClass:
1491 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001492
Ted Kremenekda76a942012-04-12 20:34:52 +00001493 case Stmt::LambdaExprClass:
1494 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1495
Ted Kremenek5868ec62010-04-11 17:02:10 +00001496 case Stmt::MemberExprClass:
1497 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1498
Ted Kremenek04268232011-11-05 00:10:15 +00001499 case Stmt::NullStmtClass:
1500 return Block;
1501
Ted Kremenek93668002009-07-17 22:18:43 +00001502 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00001503 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1504
Ted Kremenek5022f1d2012-03-06 23:40:47 +00001505 case Stmt::ObjCAutoreleasePoolStmtClass:
1506 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1507
Ted Kremenek93668002009-07-17 22:18:43 +00001508 case Stmt::ObjCAtSynchronizedStmtClass:
1509 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001510
Ted Kremenek93668002009-07-17 22:18:43 +00001511 case Stmt::ObjCAtThrowStmtClass:
1512 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001513
Ted Kremenek93668002009-07-17 22:18:43 +00001514 case Stmt::ObjCAtTryStmtClass:
1515 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001516
Ted Kremenek93668002009-07-17 22:18:43 +00001517 case Stmt::ObjCForCollectionStmtClass:
1518 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001519
Ted Kremenek04268232011-11-05 00:10:15 +00001520 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00001521 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00001522
John McCallfe96e0b2011-11-06 09:01:30 +00001523 case Stmt::PseudoObjectExprClass:
1524 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1525
Ted Kremenek93668002009-07-17 22:18:43 +00001526 case Stmt::ReturnStmtClass:
1527 return VisitReturnStmt(cast<ReturnStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001528
Peter Collingbournee190dee2011-03-11 19:24:49 +00001529 case Stmt::UnaryExprOrTypeTraitExprClass:
1530 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1531 asc);
Mike Stump11289f42009-09-09 15:08:12 +00001532
Ted Kremenek93668002009-07-17 22:18:43 +00001533 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001534 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001535
Ted Kremenek93668002009-07-17 22:18:43 +00001536 case Stmt::SwitchStmtClass:
1537 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001538
Zhanyong Wan6dace612010-11-22 08:45:56 +00001539 case Stmt::UnaryOperatorClass:
1540 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1541
Ted Kremenek93668002009-07-17 22:18:43 +00001542 case Stmt::WhileStmtClass:
1543 return VisitWhileStmt(cast<WhileStmt>(S));
1544 }
1545}
Mike Stump11289f42009-09-09 15:08:12 +00001546
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001547CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001548 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001549 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001550 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00001551 }
Mike Stump11289f42009-09-09 15:08:12 +00001552
Ted Kremenek93668002009-07-17 22:18:43 +00001553 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00001554}
Mike Stump31feda52009-07-17 01:31:16 +00001555
Ted Kremenek93668002009-07-17 22:18:43 +00001556/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00001557CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1558 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00001559
Ted Kremenek8ae67872013-02-05 22:00:19 +00001560 // Visit the children in their reverse order so that they appear in
1561 // left-to-right (natural) order in the CFG.
1562 reverse_children RChildren(S);
1563 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1564 I != E; ++I) {
1565 if (Stmt *Child = *I)
1566 if (CFGBlock *R = Visit(Child))
1567 B = R;
1568 }
1569 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00001570}
Mike Stump11289f42009-09-09 15:08:12 +00001571
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001572CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1573 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00001574 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00001575
Ted Kremenek7c58d352011-03-10 01:14:11 +00001576 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001577 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001578 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00001579 }
Ted Kremenek81e14852007-08-27 19:46:09 +00001580
Ted Kremenek9aae5132007-08-23 21:42:29 +00001581 return Block;
1582}
Mike Stump11289f42009-09-09 15:08:12 +00001583
Zhanyong Wan6dace612010-11-22 08:45:56 +00001584CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00001585 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001586 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00001587 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001588 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00001589 }
1590
Ted Kremenek8219b822010-12-16 07:46:53 +00001591 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00001592}
1593
Ted Kremeneka16436f2012-07-14 05:04:06 +00001594CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1595 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1596 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00001597
Ted Kremeneka16436f2012-07-14 05:04:06 +00001598 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001599 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00001600
Craig Topper25542942014-05-20 04:30:07 +00001601 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1602 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001603}
1604
1605std::pair<CFGBlock*, CFGBlock*>
1606CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1607 Stmt *Term,
1608 CFGBlock *TrueBlock,
1609 CFGBlock *FalseBlock) {
1610
1611 // Introspect the RHS. If it is a nested logical operation, we recursively
1612 // build the CFG using this function. Otherwise, resort to default
1613 // CFG construction behavior.
1614 Expr *RHS = B->getRHS()->IgnoreParens();
1615 CFGBlock *RHSBlock, *ExitBlock;
1616
1617 do {
1618 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1619 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001620 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00001621 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1622 break;
1623 }
1624
1625 // The RHS is not a nested logical operation. Don't push the terminator
1626 // down further, but instead visit RHS and construct the respective
1627 // pieces of the CFG, and link up the RHSBlock with the terminator
1628 // we have been provided.
1629 ExitBlock = RHSBlock = createBlock(false);
1630
1631 if (!Term) {
1632 assert(TrueBlock == FalseBlock);
1633 addSuccessor(RHSBlock, TrueBlock);
1634 }
1635 else {
1636 RHSBlock->setTerminator(Term);
1637 TryResult KnownVal = tryEvaluateBool(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001638 if (!KnownVal.isKnown())
1639 KnownVal = tryEvaluateBool(B);
Ted Kremenek782f0032014-03-07 02:25:53 +00001640 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1641 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00001642 }
1643
1644 Block = RHSBlock;
1645 RHSBlock = addStmt(RHS);
1646 }
1647 while (false);
1648
1649 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001650 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00001651
1652 // Generate the blocks for evaluating the LHS.
1653 Expr *LHS = B->getLHS()->IgnoreParens();
1654
1655 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1656 if (B_LHS->isLogicalOp()) {
1657 if (B->getOpcode() == BO_LOr)
1658 FalseBlock = RHSBlock;
1659 else
1660 TrueBlock = RHSBlock;
1661
1662 // For the LHS, treat 'B' as the terminator that we want to sink
1663 // into the nested branch. The RHS always gets the top-most
1664 // terminator.
1665 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1666 }
1667
1668 // Create the block evaluating the LHS.
1669 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00001670 CFGBlock *LHSBlock = createBlock(false);
1671 LHSBlock->setTerminator(B);
1672
Ted Kremeneka16436f2012-07-14 05:04:06 +00001673 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001674 CFGBlock *EntryLHSBlock = addStmt(LHS);
1675
1676 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001677 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001678
1679 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00001680 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001681
1682 // Now link the LHSBlock with RHSBlock.
1683 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00001684 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
1685 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00001686 } else {
1687 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00001688 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
1689 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00001690 }
1691
Ted Kremenekb50e7162012-07-14 05:04:10 +00001692 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001693}
1694
Ted Kremenekb50e7162012-07-14 05:04:10 +00001695
Ted Kremeneka16436f2012-07-14 05:04:06 +00001696CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1697 AddStmtChoice asc) {
1698 // && or ||
1699 if (B->isLogicalOp())
1700 return VisitLogicalOperator(B);
1701
Zhanyong Wan59f09c72010-11-22 19:32:14 +00001702 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00001703 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001704 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00001705 addStmt(B->getRHS());
1706 return addStmt(B->getLHS());
1707 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00001708
1709 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001710 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001711 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001712 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001713 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001714 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00001715 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001716 }
Mike Stump11289f42009-09-09 15:08:12 +00001717
Ted Kremenek7c58d352011-03-10 01:14:11 +00001718 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00001719 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001720 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00001721 }
1722
Zhongxing Xud95ccd52010-10-27 03:23:10 +00001723 CFGBlock *RBlock = Visit(B->getRHS());
1724 CFGBlock *LBlock = Visit(B->getLHS());
1725 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1726 // containing a DoStmt, and the LHS doesn't create a new block, then we should
1727 // return RBlock. Otherwise we'll incorrectly return NULL.
1728 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00001729}
1730
Ted Kremeneke2499842012-04-12 20:03:44 +00001731CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001732 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00001733 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001734 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00001735 }
1736 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00001737}
1738
Ted Kremenek93668002009-07-17 22:18:43 +00001739CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1740 // "break" is a control-flow statement. Thus we stop processing the current
1741 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001742 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001743 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001744
Ted Kremenek93668002009-07-17 22:18:43 +00001745 // Now create a new block that ends with the break statement.
1746 Block = createBlock(false);
1747 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00001748
Ted Kremenek93668002009-07-17 22:18:43 +00001749 // If there is no target for the break, then we are looking at an incomplete
1750 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001751 if (BreakJumpTarget.block) {
1752 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1753 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001754 } else
Ted Kremenek93668002009-07-17 22:18:43 +00001755 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00001756
1757
Ted Kremenek9aae5132007-08-23 21:42:29 +00001758 return Block;
1759}
Mike Stump11289f42009-09-09 15:08:12 +00001760
Sebastian Redl31ad7542011-03-13 17:09:40 +00001761static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00001762 QualType Ty = E->getType();
1763 if (Ty->isFunctionPointerType())
1764 Ty = Ty->getAs<PointerType>()->getPointeeType();
1765 else if (Ty->isBlockPointerType())
1766 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001767
Mike Stump04c68512010-01-21 15:20:48 +00001768 const FunctionType *FT = Ty->getAs<FunctionType>();
1769 if (FT) {
1770 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00001771 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smithf623c962012-04-17 00:58:00 +00001772 Proto->isNothrow(Ctx))
Mike Stump04c68512010-01-21 15:20:48 +00001773 return false;
1774 }
1775 return true;
1776}
1777
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001778CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00001779 // Compute the callee type.
1780 QualType calleeType = C->getCallee()->getType();
1781 if (calleeType == Context->BoundMemberTy) {
1782 QualType boundType = Expr::findBoundMemberType(C->getCallee());
1783
1784 // We should only get a null bound type if processing a dependent
1785 // CFG. Recover by assuming nothing.
1786 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00001787 }
Mike Stump8c5d7992009-07-25 21:26:53 +00001788
John McCallc67067f2011-05-11 07:19:11 +00001789 // If this is a call to a no-return function, this stops the block here.
1790 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1791
Mike Stump04c68512010-01-21 15:20:48 +00001792 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00001793
1794 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001795 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00001796 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00001797 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00001798 }
1799
Jordan Rose5374c072013-08-19 16:27:28 +00001800 // If this is a call to a builtin function, it might not actually evaluate
1801 // its arguments. Don't add them to the CFG if this is the case.
1802 bool OmitArguments = false;
1803
Mike Stump92244b02010-01-19 22:00:14 +00001804 if (FunctionDecl *FD = C->getDirectCallee()) {
Richard Smith10876ef2013-01-17 01:30:42 +00001805 if (FD->isNoReturn())
Mike Stump8c5d7992009-07-25 21:26:53 +00001806 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00001807 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00001808 AddEHEdge = false;
Jordan Rose5374c072013-08-19 16:27:28 +00001809 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
1810 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00001811 }
Mike Stump8c5d7992009-07-25 21:26:53 +00001812
Sebastian Redl31ad7542011-03-13 17:09:40 +00001813 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00001814 AddEHEdge = false;
1815
Jordan Rose5374c072013-08-19 16:27:28 +00001816 if (OmitArguments) {
1817 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
1818 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
1819 autoCreateBlock();
1820 appendStmt(Block, C);
1821 return Visit(C->getCallee());
1822 }
1823
1824 if (!NoReturn && !AddEHEdge) {
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001825 return VisitStmt(C, asc.withAlwaysAdd(true));
Jordan Rose5374c072013-08-19 16:27:28 +00001826 }
Mike Stump11289f42009-09-09 15:08:12 +00001827
Mike Stump92244b02010-01-19 22:00:14 +00001828 if (Block) {
1829 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001830 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001831 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00001832 }
Mike Stump11289f42009-09-09 15:08:12 +00001833
Chandler Carrutha70991b2011-09-13 09:13:49 +00001834 if (NoReturn)
1835 Block = createNoReturnBlock();
1836 else
1837 Block = createBlock();
1838
Ted Kremenek2866bab2011-03-10 01:14:08 +00001839 appendStmt(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00001840
Mike Stump04c68512010-01-21 15:20:48 +00001841 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00001842 // Add exceptional edges.
1843 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001844 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00001845 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001846 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00001847 }
Mike Stump11289f42009-09-09 15:08:12 +00001848
Mike Stump8c5d7992009-07-25 21:26:53 +00001849 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00001850}
Ted Kremenek9aae5132007-08-23 21:42:29 +00001851
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001852CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1853 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001854 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001855 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001856 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001857 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001858
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001859 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00001860 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001861 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001862 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001863 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001864 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001865
Ted Kremenek21822592009-07-17 18:20:32 +00001866 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001867 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001868 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001869 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001870 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001871
Ted Kremenek21822592009-07-17 18:20:32 +00001872 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00001873 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001874 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00001875 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
1876 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00001877 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00001878 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00001879}
Mike Stump11289f42009-09-09 15:08:12 +00001880
1881
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001882CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Marcin Swiderski667ffec2010-10-01 00:23:17 +00001883 addLocalScopeAndDtors(C);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001884 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00001885
1886 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1887 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00001888 // If we hit a segment of code just containing ';' (NullStmts), we can
1889 // get a null block back. In such cases, just use the LastBlock
1890 if (CFGBlock *newBlock = addStmt(*I))
1891 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00001892
Ted Kremenekce499c22009-08-27 23:16:26 +00001893 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001894 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001895 }
Mike Stump92244b02010-01-19 22:00:14 +00001896
Ted Kremenek93668002009-07-17 22:18:43 +00001897 return LastBlock;
1898}
Mike Stump11289f42009-09-09 15:08:12 +00001899
John McCallc07a0c72011-02-17 10:25:35 +00001900CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001901 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00001902 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00001903 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00001904
Ted Kremenek51d40b02009-07-17 18:15:54 +00001905 // Create the confluence block that will "merge" the results of the ternary
1906 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001907 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001908 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001909 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001910 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001911
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001912 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00001913
Ted Kremenek51d40b02009-07-17 18:15:54 +00001914 // Create a block for the LHS expression if there is an LHS expression. A
1915 // GCC extension allows LHS to be NULL, causing the condition to be the
1916 // value that is returned instead.
1917 // e.g: x ?: y is shorthand for: x ? x : y;
1918 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001919 Block = nullptr;
1920 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00001921 const Expr *trueExpr = C->getTrueExpr();
1922 if (trueExpr != opaqueValue) {
1923 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001924 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001925 return nullptr;
1926 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00001927 }
Ted Kremenekd8138012011-02-24 03:09:15 +00001928 else
1929 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00001930
Ted Kremenek51d40b02009-07-17 18:15:54 +00001931 // Create the block for the RHS expression.
1932 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001933 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001934 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001935 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001936
Richard Smithf676e452012-07-24 21:02:14 +00001937 // If the condition is a logical '&&' or '||', build a more accurate CFG.
1938 if (BinaryOperator *Cond =
1939 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
1940 if (Cond->isLogicalOp())
1941 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
1942
Ted Kremenek51d40b02009-07-17 18:15:54 +00001943 // Create the block that will contain the condition.
1944 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00001945
Mike Stump773582d2009-07-23 23:25:26 +00001946 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001947 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00001948 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
1949 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00001950 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00001951 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00001952
Ted Kremenekd8138012011-02-24 03:09:15 +00001953 if (opaqueValue) {
1954 // Run the condition expression if it's not trivially expressed in
1955 // terms of the opaque value (or if there is no opaque value).
1956 if (condExpr != opaqueValue)
1957 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00001958
Ted Kremenekd8138012011-02-24 03:09:15 +00001959 // Before that, run the common subexpression if there was one.
1960 // At least one of this or the above will be run.
1961 return addStmt(BCO->getCommon());
1962 }
1963
1964 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00001965}
1966
Ted Kremenek93668002009-07-17 22:18:43 +00001967CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00001968 // Check if the Decl is for an __label__. If so, elide it from the
1969 // CFG entirely.
1970 if (isa<LabelDecl>(*DS->decl_begin()))
1971 return Block;
1972
Ted Kremenek3a601142011-05-24 20:41:31 +00001973 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001974 if (DS->isSingleDecl())
1975 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00001976
Craig Topper25542942014-05-20 04:30:07 +00001977 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001978
Jordan Rose8c6c8a92012-07-20 18:50:48 +00001979 // Build an individual DeclStmt for each decl.
1980 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
1981 E = DS->decl_rend();
1982 I != E; ++I) {
Ted Kremenek93668002009-07-17 22:18:43 +00001983 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
1984 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
1985 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
Mike Stump11289f42009-09-09 15:08:12 +00001986
Ted Kremenek93668002009-07-17 22:18:43 +00001987 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
1988 // automatically freed with the CFG.
1989 DeclGroupRef DG(*I);
1990 Decl *D = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001991 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
Ted Kremenek93668002009-07-17 22:18:43 +00001992 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00001993 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00001994
Ted Kremenek93668002009-07-17 22:18:43 +00001995 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001996 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00001997 }
Mike Stump11289f42009-09-09 15:08:12 +00001998
1999 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002000}
Mike Stump11289f42009-09-09 15:08:12 +00002001
Ted Kremenek93668002009-07-17 22:18:43 +00002002/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002003/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002004CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002005 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002006 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002007
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002008 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002009 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2010 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002011 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002012 }
Mike Stump11289f42009-09-09 15:08:12 +00002013
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002014 bool HasTemporaries = false;
2015
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002016 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002017 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002018
2019 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2020 // For static variables, we need to create a branch to track
2021 // whether or not they are initialized.
2022 if (Block) {
2023 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002024 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002025 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002026 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002027 }
2028 blockAfterStaticInit = Succ;
2029 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002030
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002031 // Destructors of temporaries in initialization expression should be called
2032 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002033 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002034 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002035 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002036
Jordan Rose6d671cc2012-09-05 22:55:23 +00002037 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002038 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002039 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002040 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2041 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002042 }
2043 }
2044
2045 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002046 appendStmt(Block, DS);
Ted Kremenek213d0532012-03-22 05:57:43 +00002047
2048 // Keep track of the last non-null block, as 'Block' can be nulled out
2049 // if the initializer expression is something like a 'while' in a
2050 // statement-expression.
2051 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002052
Ted Kremenek93668002009-07-17 22:18:43 +00002053 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002054 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002055 // For expression with temporaries go directly to subexpression to omit
2056 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002057 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2058 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2059 LastBlock = newBlock;
2060 }
2061 else {
2062 if (CFGBlock *newBlock = Visit(Init))
2063 LastBlock = newBlock;
2064 }
Ted Kremenek93668002009-07-17 22:18:43 +00002065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066
Ted Kremenek93668002009-07-17 22:18:43 +00002067 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002068 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002069 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002070 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2071 LastBlock = newBlock;
2072 }
Mike Stump11289f42009-09-09 15:08:12 +00002073
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002074 // Remove variable from local scope.
2075 if (ScopePos && VD == *ScopePos)
2076 ++ScopePos;
2077
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002078 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002079 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002080 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002081 Block = createBlock(false);
2082 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002083 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002084 addSuccessor(Block, B);
2085 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002086 }
2087
2088 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002089}
2090
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002091CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002092 // We may see an if statement in the middle of a basic block, or it may be the
2093 // first statement we are processing. In either case, we create a new basic
2094 // block. First, we create the blocks for the then...else statements, and
2095 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002096 // middle of a block, we stop processing that block. That block is then the
2097 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002098
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002099 // Save local scope position because in case of condition variable ScopePos
2100 // won't be restored when traversing AST.
2101 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2102
2103 // Create local scope for possible condition variable.
2104 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002105 if (VarDecl *VD = I->getConditionVariable()) {
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002106 LocalScope::const_iterator BeginScopePos = ScopePos;
2107 addLocalScopeForVarDecl(VD);
2108 addAutomaticObjDtors(ScopePos, BeginScopePos, I);
2109 }
2110
Chris Lattner57540c52011-04-15 05:22:18 +00002111 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002112 // block.
2113 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002114 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002115 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002116 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002117 }
Mike Stump31feda52009-07-17 01:31:16 +00002118
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002119 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002120 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002121
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002122 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002123 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002124
Ted Kremenek9aae5132007-08-23 21:42:29 +00002125 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002126 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002127 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002128
2129 // If branch is not a compound statement create implicit scope
2130 // and add destructors.
2131 if (!isa<CompoundStmt>(Else))
2132 addLocalScopeAndDtors(Else);
2133
Ted Kremenek93668002009-07-17 22:18:43 +00002134 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002135
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002136 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2137 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002138 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002139 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002140 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002141 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002142 }
Mike Stump31feda52009-07-17 01:31:16 +00002143
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002144 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002145 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002146 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002147 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002148 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002149 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002150 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002151
2152 // If branch is not a compound statement create implicit scope
2153 // and add destructors.
2154 if (!isa<CompoundStmt>(Then))
2155 addLocalScopeAndDtors(Then);
2156
Ted Kremenek93668002009-07-17 22:18:43 +00002157 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002158
Ted Kremenek1b379512009-04-01 03:52:47 +00002159 if (!ThenBlock) {
2160 // We can reach here if the "then" body has all NullStmts.
2161 // Create an empty block so we can distinguish between true and false
2162 // branches in path-sensitive analyses.
2163 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002164 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002165 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002166 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002167 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002168 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002169 }
2170
Ted Kremenekb50e7162012-07-14 05:04:10 +00002171 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2172 // having these handle the actual control-flow jump. Note that
2173 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2174 // we resort to the old control-flow behavior. This special handling
2175 // removes infeasible paths from the control-flow graph by having the
2176 // control-flow transfer of '&&' or '||' go directly into the then/else
2177 // blocks directly.
2178 if (!I->getConditionVariable())
Richard Smithf676e452012-07-24 21:02:14 +00002179 if (BinaryOperator *Cond =
2180 dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002181 if (Cond->isLogicalOp())
2182 return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2183
Mike Stump31feda52009-07-17 01:31:16 +00002184 // Now create a new block containing the if statement.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002185 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002186
Ted Kremenek9aae5132007-08-23 21:42:29 +00002187 // Set the terminator of the new block to the If statement.
2188 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002189
Mike Stump773582d2009-07-23 23:25:26 +00002190 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002191 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00002192
Ted Kremenekf3898612014-02-27 00:24:03 +00002193 // Add the successors. If we know that specific branches are
2194 // unreachable, inform addSuccessor() of that knowledge.
2195 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2196 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump31feda52009-07-17 01:31:16 +00002197
2198 // Add the condition as the last statement in the new block. This may create
2199 // new blocks as the condition may contain control-flow. Any newly created
2200 // blocks will be pointed to be "Block".
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002201 CFGBlock *LastBlock = addStmt(I->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002202
Manuel Klimek75f34c12014-05-05 18:21:06 +00002203 // Finally, if the IfStmt contains a condition variable, add it and its
2204 // initializer to the CFG.
2205 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2206 autoCreateBlock();
2207 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002208 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002209
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002210 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002211}
Mike Stump31feda52009-07-17 01:31:16 +00002212
2213
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002214CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002215 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002216 //
Mike Stump31feda52009-07-17 01:31:16 +00002217 // NOTE: If a "return" appears in the middle of a block, this means that the
2218 // code afterwards is DEAD (unreachable). We still keep a basic block
2219 // for that code; a simple "mark-and-sweep" from the entry block will be
2220 // able to report such dead blocks.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002221
2222 // Create the new block.
2223 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002224
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002225 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
Pavel Labath921e7652013-09-06 08:12:48 +00002226
2227 // If the one of the destructors does not return, we already have the Exit
2228 // block as a successor.
2229 if (!Block->hasNoReturnElement())
2230 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002231
2232 // Add the return statement to the block. This may create new blocks if R
2233 // contains control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002234 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002235}
2236
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002237CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002238 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00002239 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002240 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002241
Ted Kremenek93668002009-07-17 22:18:43 +00002242 if (!LabelBlock) // This can happen when the body is empty, i.e.
2243 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00002244
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002245 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2246 "label already in map");
2247 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002248
2249 // Labels partition blocks, so this is the end of the basic block we were
2250 // processing (L is the block's label). Because this is label (and we have
2251 // already processed the substatement) there is no extra control-flow to worry
2252 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00002253 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002254 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002255 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002256
2257 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00002258 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002259
Ted Kremenek9aae5132007-08-23 21:42:29 +00002260 // This block is now the implicit successor of other blocks.
2261 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002262
Ted Kremenek9aae5132007-08-23 21:42:29 +00002263 return LabelBlock;
2264}
2265
Ted Kremenekda76a942012-04-12 20:34:52 +00002266CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2267 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2268 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2269 et = E->capture_init_end(); it != et; ++it) {
2270 if (Expr *Init = *it) {
2271 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00002272 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00002273 LastBlock = Tmp;
2274 }
2275 }
2276 return LastBlock;
2277}
2278
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002279CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00002280 // Goto is a control-flow statement. Thus we stop processing the current
2281 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00002282
Ted Kremenek9aae5132007-08-23 21:42:29 +00002283 Block = createBlock(false);
2284 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00002285
2286 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002287 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00002288
Ted Kremenek9aae5132007-08-23 21:42:29 +00002289 if (I == LabelMap.end())
2290 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002291 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2292 else {
2293 JumpTarget JT = I->second;
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002294 addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
2295 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002296 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002297
Mike Stump31feda52009-07-17 01:31:16 +00002298 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002299}
2300
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002301CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00002302 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002303
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002304 // Save local scope position because in case of condition variable ScopePos
2305 // won't be restored when traversing AST.
2306 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2307
2308 // Create local scope for init statement and possible condition variable.
2309 // Add destructor for init statement and condition variable.
2310 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002311 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002312 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002313 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2314
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002315 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002316 addLocalScopeForVarDecl(VD);
2317 LocalScope::const_iterator ContinueScopePos = ScopePos;
2318
2319 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
2320
Mike Stump014b3ea2009-07-21 01:12:51 +00002321 // "for" is a control-flow statement. Thus we stop processing the current
2322 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002323 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002324 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002325 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002326 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002327 } else
2328 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002329
Ted Kremenek304a9532010-05-21 20:30:15 +00002330 // Save the current value for the break targets.
2331 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002332 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002333 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00002334
Craig Topper25542942014-05-20 04:30:07 +00002335 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002336
Ted Kremenek9aae5132007-08-23 21:42:29 +00002337 // Now create the loop body.
2338 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002339 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002340
Ted Kremenekb50e7162012-07-14 05:04:10 +00002341 // Save the current values for Block, Succ, continue and break targets.
2342 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2343 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002344
Ted Kremenekb50e7162012-07-14 05:04:10 +00002345 // Create an empty block to represent the transition block for looping back
2346 // to the head of the loop. If we have increment code, it will
2347 // go in this block as well.
2348 Block = Succ = TransitionBlock = createBlock(false);
2349 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002350
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002351 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00002352 // Generate increment code in its own basic block. This is the target of
2353 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00002354 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00002355 }
Mike Stump31feda52009-07-17 01:31:16 +00002356
Ted Kremenek902393b2009-04-28 00:51:56 +00002357 // Finish up the increment (or empty) block if it hasn't been already.
2358 if (Block) {
2359 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002360 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002361 return nullptr;
2362 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00002363 }
Mike Stump31feda52009-07-17 01:31:16 +00002364
Ted Kremenekb50e7162012-07-14 05:04:10 +00002365 // The starting block for the loop increment is the block that should
2366 // represent the 'loop target' for looping back to the start of the loop.
2367 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2368 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002369
Ted Kremenekb50e7162012-07-14 05:04:10 +00002370 // Loop body should end with destructor of Condition variable (if any).
2371 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00002372
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002373 // If body is not a compound statement create implicit scope
2374 // and add destructors.
2375 if (!isa<CompoundStmt>(F->getBody()))
2376 addLocalScopeAndDtors(F->getBody());
2377
Mike Stump31feda52009-07-17 01:31:16 +00002378 // Now populate the body block, and in the process create new blocks as we
2379 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002380 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00002381
Ted Kremenekb50e7162012-07-14 05:04:10 +00002382 if (!BodyBlock) {
2383 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2384 // Use the continue jump target as the proxy for the body.
2385 BodyBlock = ContinueJumpTarget.block;
2386 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002387 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002388 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002389 }
Ted Kremenekb50e7162012-07-14 05:04:10 +00002390
2391 // Because of short-circuit evaluation, the condition of the loop can span
2392 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2393 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002394 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002395
Ted Kremenekb50e7162012-07-14 05:04:10 +00002396 do {
2397 Expr *C = F->getCond();
2398
2399 // Specially handle logical operators, which have a slightly
2400 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002401 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00002402 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002403 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002404 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002405 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2406 break;
2407 }
2408
2409 // The default case when not handling logical operators.
2410 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2411 ExitConditionBlock->setTerminator(F);
2412
2413 // See if this is a known constant.
2414 TryResult KnownVal(true);
2415
2416 if (C) {
2417 // Now add the actual condition to the condition block.
2418 // Because the condition itself may contain control-flow, new blocks may
2419 // be created. Thus we update "Succ" after adding the condition.
2420 Block = ExitConditionBlock;
2421 EntryConditionBlock = addStmt(C);
2422
2423 // If this block contains a condition variable, add both the condition
2424 // variable and initializer to the CFG.
2425 if (VarDecl *VD = F->getConditionVariable()) {
2426 if (Expr *Init = VD->getInit()) {
2427 autoCreateBlock();
2428 appendStmt(Block, F->getConditionVariableDeclStmt());
2429 EntryConditionBlock = addStmt(Init);
2430 assert(Block == EntryConditionBlock);
2431 }
2432 }
2433
2434 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002435 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002436
2437 KnownVal = tryEvaluateBool(C);
2438 }
2439
2440 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002441 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002442 // Link up the condition block with the code that follows the loop. (the
2443 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002444 addSuccessor(ExitConditionBlock,
2445 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002446
2447 } while (false);
2448
2449 // Link up the loop-back block to the entry condition block.
2450 addSuccessor(TransitionBlock, EntryConditionBlock);
2451
2452 // The condition block is the implicit successor for any code above the loop.
2453 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002454
Ted Kremenek9aae5132007-08-23 21:42:29 +00002455 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00002456 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002457 if (Stmt *I = F->getInit()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002458 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00002459 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002460 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002461
2462 // There is no loop initialization. We are thus basically a while loop.
2463 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00002464 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002465 Succ = EntryConditionBlock;
2466 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002467}
2468
Ted Kremenek5868ec62010-04-11 17:02:10 +00002469CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002470 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00002471 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002472 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002473 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002474 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00002475}
2476
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002477CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00002478 // Objective-C fast enumeration 'for' statements:
2479 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2480 //
2481 // for ( Type newVariable in collection_expression ) { statements }
2482 //
2483 // becomes:
2484 //
2485 // prologue:
2486 // 1. collection_expression
2487 // T. jump to loop_entry
2488 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002489 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00002490 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2491 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2492 // TB:
2493 // statements
2494 // T. jump to loop_entry
2495 // FB:
2496 // what comes after
2497 //
2498 // and
2499 //
2500 // Type existingItem;
2501 // for ( existingItem in expression ) { statements }
2502 //
2503 // becomes:
2504 //
Mike Stump31feda52009-07-17 01:31:16 +00002505 // the same with newVariable replaced with existingItem; the binding works
2506 // the same except that for one ObjCForCollectionStmt::getElement() returns
2507 // a DeclStmt and the other returns a DeclRefExpr.
Ted Kremenek9d56e642008-11-11 17:10:00 +00002508 //
Mike Stump31feda52009-07-17 01:31:16 +00002509
Craig Topper25542942014-05-20 04:30:07 +00002510 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002511
Ted Kremenek9d56e642008-11-11 17:10:00 +00002512 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002513 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002514 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00002515 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002516 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00002517 } else
2518 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002519
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002520 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002521 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002522
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002523 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002524 ExitConditionBlock->setTerminator(S);
2525
2526 // The last statement in the block should be the ObjCForCollectionStmt, which
2527 // performs the actual binding to 'element' and determines if there are any
2528 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00002529 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002530 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002531
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002532 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00002533 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00002534 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00002535 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2536 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00002537 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002538 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002539 return nullptr;
2540 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002541 }
Mike Stump31feda52009-07-17 01:31:16 +00002542
2543 // The condition block is the implicit successor for the loop body as well as
2544 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002545 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002546
Ted Kremenek9d56e642008-11-11 17:10:00 +00002547 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00002548 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002549 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00002550 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002551 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00002552 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002553
Anna Zaks56b49752013-06-22 00:23:20 +00002554 // Add an intermediate block between the BodyBlock and the
2555 // EntryConditionBlock to represent the "loop back" transition, for looping
2556 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00002557 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00002558 Succ = LoopBackBlock = createBlock();
2559 LoopBackBlock->setLoopTarget(S);
2560
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002561 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00002562 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002563
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002564 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002565
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002566 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00002567 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00002568 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002569 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002570 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002571 }
Mike Stump31feda52009-07-17 01:31:16 +00002572
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002573 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002574 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002575 }
Mike Stump31feda52009-07-17 01:31:16 +00002576
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002577 // Link up the condition block with the code that follows the loop.
2578 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002579 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002580
Ted Kremenek9d56e642008-11-11 17:10:00 +00002581 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002582 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00002583 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00002584}
2585
Ted Kremenek5022f1d2012-03-06 23:40:47 +00002586CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2587 // Inline the body.
2588 return addStmt(S->getSubStmt());
2589 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2590}
2591
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002592CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00002593 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00002594
Ted Kremenek49805452009-05-02 01:49:13 +00002595 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00002596 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00002597
Ted Kremenekb3c657b2009-05-05 23:11:51 +00002598 // The sync body starts its own basic block. This makes it a little easier
2599 // for diagnostic clients.
2600 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002601 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002602 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002603
Craig Topper25542942014-05-20 04:30:07 +00002604 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00002605 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00002606 }
Mike Stump31feda52009-07-17 01:31:16 +00002607
Ted Kremeneked12f1b2010-09-10 03:05:33 +00002608 // Add the @synchronized to the CFG.
2609 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002610 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00002611
Ted Kremenek49805452009-05-02 01:49:13 +00002612 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00002613 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00002614}
Mike Stump31feda52009-07-17 01:31:16 +00002615
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002616CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00002617 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00002618 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00002619}
Ted Kremenek9d56e642008-11-11 17:10:00 +00002620
John McCallfe96e0b2011-11-06 09:01:30 +00002621CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2622 autoCreateBlock();
2623
2624 // Add the PseudoObject as the last thing.
2625 appendStmt(Block, E);
2626
2627 CFGBlock *lastBlock = Block;
2628
2629 // Before that, evaluate all of the semantics in order. In
2630 // CFG-land, that means appending them in reverse order.
2631 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2632 Expr *Semantic = E->getSemanticExpr(--i);
2633
2634 // If the semantic is an opaque value, we're being asked to bind
2635 // it to its source expression.
2636 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2637 Semantic = OVE->getSourceExpr();
2638
2639 if (CFGBlock *B = Visit(Semantic))
2640 lastBlock = B;
2641 }
2642
2643 return lastBlock;
2644}
2645
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002646CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00002647 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002648
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002649 // Save local scope position because in case of condition variable ScopePos
2650 // won't be restored when traversing AST.
2651 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2652
2653 // Create local scope for possible condition variable.
2654 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002655 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002656 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002657 addLocalScopeForVarDecl(VD);
2658 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2659 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002660
Mike Stump014b3ea2009-07-21 01:12:51 +00002661 // "while" is a control-flow statement. Thus we stop processing the current
2662 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002663 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002664 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002665 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002666 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002667 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002668 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00002669 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00002670 }
Mike Stump31feda52009-07-17 01:31:16 +00002671
Craig Topper25542942014-05-20 04:30:07 +00002672 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002673
Ted Kremenek9aae5132007-08-23 21:42:29 +00002674 // Process the loop body.
2675 {
Ted Kremenek49936f72009-04-28 03:09:44 +00002676 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00002677
Ted Kremenekb50e7162012-07-14 05:04:10 +00002678 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002679 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2680 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00002681 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00002682
Mike Stump31feda52009-07-17 01:31:16 +00002683 // Create an empty block to represent the transition block for looping back
2684 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002685 Succ = TransitionBlock = createBlock(false);
2686 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002687 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002688
Ted Kremenek9aae5132007-08-23 21:42:29 +00002689 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002690 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002691
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002692 // Loop body should end with destructor of Condition variable (if any).
2693 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2694
2695 // If body is not a compound statement create implicit scope
2696 // and add destructors.
2697 if (!isa<CompoundStmt>(W->getBody()))
2698 addLocalScopeAndDtors(W->getBody());
2699
Ted Kremenek9aae5132007-08-23 21:42:29 +00002700 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002701 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002702
Ted Kremeneke9610502007-08-30 18:39:40 +00002703 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002704 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00002705 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002706 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002707 }
2708
2709 // Because of short-circuit evaluation, the condition of the loop can span
2710 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2711 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002712 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002713
2714 do {
2715 Expr *C = W->getCond();
2716
2717 // Specially handle logical operators, which have a slightly
2718 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002719 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002720 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002721 std::tie(EntryConditionBlock, ExitConditionBlock) =
2722 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002723 break;
2724 }
2725
2726 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00002727 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002728 ExitConditionBlock->setTerminator(W);
2729
2730 // Now add the actual condition to the condition block.
2731 // Because the condition itself may contain control-flow, new blocks may
2732 // be created. Thus we update "Succ" after adding the condition.
2733 Block = ExitConditionBlock;
2734 Block = EntryConditionBlock = addStmt(C);
2735
2736 // If this block contains a condition variable, add both the condition
2737 // variable and initializer to the CFG.
2738 if (VarDecl *VD = W->getConditionVariable()) {
2739 if (Expr *Init = VD->getInit()) {
2740 autoCreateBlock();
2741 appendStmt(Block, W->getConditionVariableDeclStmt());
2742 EntryConditionBlock = addStmt(Init);
2743 assert(Block == EntryConditionBlock);
2744 }
Ted Kremenek55957a82009-05-02 00:13:27 +00002745 }
Mike Stump31feda52009-07-17 01:31:16 +00002746
Ted Kremenekb50e7162012-07-14 05:04:10 +00002747 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002748 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002749
2750 // See if this is a known constant.
2751 const TryResult& KnownVal = tryEvaluateBool(C);
2752
Ted Kremenek30754282009-07-24 04:47:11 +00002753 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002754 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002755 // Link up the condition block with the code that follows the loop. (the
2756 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002757 addSuccessor(ExitConditionBlock,
2758 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00002759
Ted Kremenekb50e7162012-07-14 05:04:10 +00002760 } while(false);
2761
2762 // Link up the loop-back block to the entry condition block.
2763 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00002764
2765 // There can be no more statements in the condition block since we loop back
2766 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00002767 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002768
Ted Kremenek1ce53c42009-12-24 01:34:10 +00002769 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00002770 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00002771 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002772}
Mike Stump11289f42009-09-09 15:08:12 +00002773
2774
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002775CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00002776 // FIXME: For now we pretend that @catch and the code it contains does not
2777 // exit.
2778 return Block;
2779}
Mike Stump31feda52009-07-17 01:31:16 +00002780
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002781CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00002782 // FIXME: This isn't complete. We basically treat @throw like a return
2783 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00002784
Ted Kremenek0868eea2009-09-24 18:45:41 +00002785 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002786 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002787 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002788
Ted Kremenek93041ba2008-12-09 20:20:09 +00002789 // Create the new block.
2790 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002791
Ted Kremenek93041ba2008-12-09 20:20:09 +00002792 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002793 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002794
2795 // Add the statement to the block. This may create new blocks if S contains
2796 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002797 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00002798}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002799
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002800CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002801 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002802 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002803 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002804
2805 // Create the new block.
2806 Block = createBlock(false);
2807
Mike Stumpbbf5ba62010-01-19 02:20:09 +00002808 if (TryTerminatedBlock)
2809 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002810 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002811 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00002812 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002813 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002814
2815 // Add the statement to the block. This may create new blocks if S contains
2816 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002817 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002818}
2819
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002820CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00002821 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002822
Mike Stump8d50b6a2009-07-21 01:27:50 +00002823 // "do...while" is a control-flow statement. Thus we stop processing the
2824 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002825 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002826 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002827 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002828 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002829 } else
2830 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002831
2832 // Because of short-circuit evaluation, the condition of the loop can span
2833 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2834 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002835 CFGBlock *ExitConditionBlock = createBlock(false);
2836 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002837
Ted Kremenek81e14852007-08-27 19:46:09 +00002838 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002839 ExitConditionBlock->setTerminator(D);
2840
2841 // Now add the actual condition to the condition block. Because the condition
2842 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002843 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00002844 Block = ExitConditionBlock;
2845 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00002846 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002847 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002848 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002849 }
Ted Kremenek81e14852007-08-27 19:46:09 +00002850 }
Mike Stump31feda52009-07-17 01:31:16 +00002851
Ted Kremeneka1523a32008-02-27 07:20:00 +00002852 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00002853 Succ = EntryConditionBlock;
2854
Mike Stump773582d2009-07-23 23:25:26 +00002855 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002856 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00002857
Ted Kremenek9aae5132007-08-23 21:42:29 +00002858 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00002859 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002860 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002861 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002862
Ted Kremenek9aae5132007-08-23 21:42:29 +00002863 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002864 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2865 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2866 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002867
Ted Kremenek9aae5132007-08-23 21:42:29 +00002868 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002869 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002870
Ted Kremenek9aae5132007-08-23 21:42:29 +00002871 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002872 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002873
Ted Kremenek9aae5132007-08-23 21:42:29 +00002874 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00002875 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002876
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002877 // If body is not a compound statement create implicit scope
2878 // and add destructors.
2879 if (!isa<CompoundStmt>(D->getBody()))
2880 addLocalScopeAndDtors(D->getBody());
2881
Ted Kremenek9aae5132007-08-23 21:42:29 +00002882 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00002883 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002884
Ted Kremeneke9610502007-08-30 18:39:40 +00002885 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00002886 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00002887 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002888 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002889 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002890 }
Mike Stump31feda52009-07-17 01:31:16 +00002891
Ted Kremenek110974d2010-08-17 20:59:56 +00002892 if (!KnownVal.isFalse()) {
2893 // Add an intermediate block between the BodyBlock and the
2894 // ExitConditionBlock to represent the "loop back" transition. Create an
2895 // empty block to represent the transition block for looping back to the
2896 // head of the loop.
2897 // FIXME: Can we do this more efficiently without adding another block?
Craig Topper25542942014-05-20 04:30:07 +00002898 Block = nullptr;
Ted Kremenek110974d2010-08-17 20:59:56 +00002899 Succ = BodyBlock;
2900 CFGBlock *LoopBackBlock = createBlock();
2901 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00002902
Ted Kremenek110974d2010-08-17 20:59:56 +00002903 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002904 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00002905 }
2906 else
Craig Topper25542942014-05-20 04:30:07 +00002907 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002908 }
Mike Stump31feda52009-07-17 01:31:16 +00002909
Ted Kremenek30754282009-07-24 04:47:11 +00002910 // Link up the condition block with the code that follows the loop.
2911 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00002912 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00002913
2914 // There can be no more statements in the body block(s) since we loop back to
2915 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00002916 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002917
Ted Kremenek9aae5132007-08-23 21:42:29 +00002918 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00002919 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002920 return BodyBlock;
2921}
2922
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002923CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002924 // "continue" is a control-flow statement. Thus we stop processing the
2925 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002926 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002927 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002928
Ted Kremenek9aae5132007-08-23 21:42:29 +00002929 // Now create a new block that ends with the continue statement.
2930 Block = createBlock(false);
2931 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00002932
Ted Kremenek9aae5132007-08-23 21:42:29 +00002933 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00002934 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002935 if (ContinueJumpTarget.block) {
2936 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
2937 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002938 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00002939 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00002940
Ted Kremenek9aae5132007-08-23 21:42:29 +00002941 return Block;
2942}
Mike Stump11289f42009-09-09 15:08:12 +00002943
Peter Collingbournee190dee2011-03-11 19:24:49 +00002944CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
2945 AddStmtChoice asc) {
Ted Kremenek0747de62009-07-18 00:47:21 +00002946
Ted Kremenek7c58d352011-03-10 01:14:11 +00002947 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00002948 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002949 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00002950 }
Mike Stump11289f42009-09-09 15:08:12 +00002951
Ted Kremenek93668002009-07-17 22:18:43 +00002952 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00002953 CFGBlock *lastBlock = Block;
2954
Ted Kremenek93668002009-07-17 22:18:43 +00002955 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00002956 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002957 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00002958 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00002959 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00002960 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002961}
Mike Stump11289f42009-09-09 15:08:12 +00002962
Ted Kremenek93668002009-07-17 22:18:43 +00002963/// VisitStmtExpr - Utility method to handle (nested) statement
2964/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002965CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002966 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00002967 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002968 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00002969 }
Ted Kremenek93668002009-07-17 22:18:43 +00002970 return VisitCompoundStmt(SE->getSubStmt());
2971}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002972
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002973CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00002974 // "switch" is a control-flow statement. Thus we stop processing the current
2975 // block.
Craig Topper25542942014-05-20 04:30:07 +00002976 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002977
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00002978 // Save local scope position because in case of condition variable ScopePos
2979 // won't be restored when traversing AST.
2980 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2981
2982 // Create local scope for possible condition variable.
2983 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002984 if (VarDecl *VD = Terminator->getConditionVariable()) {
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00002985 LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
2986 addLocalScopeForVarDecl(VD);
2987 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
2988 }
2989
Ted Kremenek9aae5132007-08-23 21:42:29 +00002990 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002991 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002992 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002993 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002994 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002995
2996 // Save the current "switch" context.
2997 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00002998 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002999 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003000
Mike Stump31feda52009-07-17 01:31:16 +00003001 // Set the "default" case to be the block after the switch statement. If the
3002 // switch statement contains a "default:", this value will be overwritten with
3003 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003004 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003005
Ted Kremenek9aae5132007-08-23 21:42:29 +00003006 // Create a new block that will contain the switch statement.
3007 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003008
Ted Kremenek9aae5132007-08-23 21:42:29 +00003009 // Now process the switch body. The code after the switch is the implicit
3010 // successor.
3011 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003012 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003013
3014 // When visiting the body, the case statements should automatically get linked
3015 // up to the switch. We also don't keep a pointer to the body, since all
3016 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003017 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003018 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003019
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003020 // For pruning unreachable case statements, save the current state
3021 // for tracking the condition value.
3022 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3023 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003024
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003025 // Determine if the switch condition can be explicitly evaluated.
3026 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003027 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003028 bool b = tryEvaluate(Terminator->getCond(), result);
3029 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003030 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003031
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003032 // If body is not a compound statement create implicit scope
3033 // and add destructors.
3034 if (!isa<CompoundStmt>(Terminator->getBody()))
3035 addLocalScopeAndDtors(Terminator->getBody());
3036
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003037 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003038 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003039 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003040 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003041 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003042
Mike Stump31feda52009-07-17 01:31:16 +00003043 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003044 // following the switch body. Moreover, take into account if all the
3045 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003046 //
3047 // Note: We add a successor to a switch that is considered covered yet has no
3048 // case statements if the enumeration has no enumerators.
3049 bool SwitchAlwaysHasSuccessor = false;
3050 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3051 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3052 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003053 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3054 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003055
Ted Kremenek81e14852007-08-27 19:46:09 +00003056 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003057 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003058 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003059 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003060
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003061 // Finally, if the SwitchStmt contains a condition variable, add both the
3062 // SwitchStmt and the condition variable initialization to the CFG.
3063 if (VarDecl *VD = Terminator->getConditionVariable()) {
3064 if (Expr *Init = VD->getInit()) {
3065 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003066 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003067 LastBlock = addStmt(Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003068 }
3069 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003070
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003071 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003072}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003073
3074static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00003075 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003076 const CaseStmt *CS,
3077 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003078 if (!switchCond)
3079 return true;
3080
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003081 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00003082
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003083 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003084 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003085 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003086 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00003087 const llvm::APSInt &condInt = switchCond->Val.getInt();
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003088
3089 if (condInt == lhsInt) {
3090 addCase = true;
3091 switchExclusivelyCovered = true;
3092 }
3093 else if (condInt < lhsInt) {
3094 if (const Expr *RHS = CS->getRHS()) {
3095 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003096 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
3097 if (V2 <= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003098 addCase = true;
3099 switchExclusivelyCovered = true;
3100 }
3101 }
3102 }
3103 }
3104 else
3105 addCase = true;
3106 }
3107 return addCase;
3108}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003109
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003110CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00003111 // CaseStmts are essentially labels, so they are the first statement in a
3112 // block.
Craig Topper25542942014-05-20 04:30:07 +00003113 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00003114
Ted Kremenek60fa6572010-08-04 23:54:30 +00003115 if (Stmt *Sub = CS->getSubStmt()) {
3116 // For deeply nested chains of CaseStmts, instead of doing a recursion
3117 // (which can blow out the stack), manually unroll and create blocks
3118 // along the way.
3119 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003120 CFGBlock *currentBlock = createBlock(false);
3121 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00003122
Ted Kremenek60fa6572010-08-04 23:54:30 +00003123 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003124 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003125 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003126 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003127
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003128 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003129 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003130 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00003131 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003132
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003133 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003134 CS = cast<CaseStmt>(Sub);
3135 Sub = CS->getSubStmt();
3136 }
3137
3138 addStmt(Sub);
3139 }
Mike Stump11289f42009-09-09 15:08:12 +00003140
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003141 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003142 if (!CaseBlock)
3143 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003144
3145 // Cases statements partition blocks, so this is the top of the basic block we
3146 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00003147 CaseBlock->setLabel(CS);
3148
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003149 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003150 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003151
3152 // Add this block to the list of successors for the block with the switch
3153 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00003154 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003155 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003156 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003157 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00003158
Ted Kremenek9aae5132007-08-23 21:42:29 +00003159 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003160 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003161
Ted Kremenek60fa6572010-08-04 23:54:30 +00003162 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003163 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003164 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003165 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00003166 // This block is now the implicit successor of other blocks.
3167 Succ = CaseBlock;
3168 }
Mike Stump31feda52009-07-17 01:31:16 +00003169
Ted Kremenek60fa6572010-08-04 23:54:30 +00003170 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003171}
Mike Stump31feda52009-07-17 01:31:16 +00003172
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003173CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00003174 if (Terminator->getSubStmt())
3175 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00003176
Ted Kremenek654c78f2008-02-13 22:05:39 +00003177 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003178
3179 if (!DefaultCaseBlock)
3180 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003181
3182 // Default statements partition blocks, so this is the top of the basic block
3183 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003184 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00003185
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003186 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003187 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00003188
Mike Stump31feda52009-07-17 01:31:16 +00003189 // Unlike case statements, we don't add the default block to the successors
3190 // for the switch statement immediately. This is done when we finish
3191 // processing the switch statement. This allows for the default case
3192 // (including a fall-through to the code after the switch statement) to always
3193 // be the last successor of a switch-terminated block.
3194
Ted Kremenek654c78f2008-02-13 22:05:39 +00003195 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003196 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003197
Ted Kremenek654c78f2008-02-13 22:05:39 +00003198 // This block is now the implicit successor of other blocks.
3199 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003200
3201 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00003202}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003203
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003204CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3205 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3206 // current block.
Craig Topper25542942014-05-20 04:30:07 +00003207 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003208
3209 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003210 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003211 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003212 TrySuccessor = Block;
3213 } else TrySuccessor = Succ;
3214
Mike Stump0bdba6c2010-01-20 01:15:34 +00003215 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003216
3217 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00003218 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003219 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00003220 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003221
Mike Stump0bdba6c2010-01-20 01:15:34 +00003222 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003223 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3224 // The code after the try is the implicit successor.
3225 Succ = TrySuccessor;
3226 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00003227 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00003228 HasCatchAll = true;
3229 }
Craig Topper25542942014-05-20 04:30:07 +00003230 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003231 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00003232 if (!CatchBlock)
3233 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003234 // Add this block to the list of successors for the block with the try
3235 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003236 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003237 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00003238 if (!HasCatchAll) {
3239 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003240 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00003241 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003242 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00003243 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003244
3245 // The code after the try is the implicit successor.
3246 Succ = TrySuccessor;
3247
Mike Stump845384a2010-01-20 01:30:58 +00003248 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00003249 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3250 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00003251
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003252 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003253 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003254 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003255}
3256
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003257CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003258 // CXXCatchStmt are treated like labels, so they are the first statement in a
3259 // block.
3260
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003261 // Save local scope position because in case of exception variable ScopePos
3262 // won't be restored when traversing AST.
3263 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3264
3265 // Create local scope for possible exception variable.
3266 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003267 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003268 LocalScope::const_iterator BeginScopePos = ScopePos;
3269 addLocalScopeForVarDecl(VD);
3270 addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
3271 }
3272
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003273 if (CS->getHandlerBlock())
3274 addStmt(CS->getHandlerBlock());
3275
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003276 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003277 if (!CatchBlock)
3278 CatchBlock = createBlock();
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003279
3280 // CXXCatchStmt is more than just a label. They have semantic meaning
3281 // as well, as they implicitly "initialize" the catch variable. Add
3282 // it to the CFG as a CFGElement so that the control-flow of these
3283 // semantics gets captured.
3284 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003285
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003286 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3287 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003288 CatchBlock->setLabel(CS);
3289
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003290 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003291 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003292 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003293
3294 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003295 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003296
3297 return CatchBlock;
3298}
3299
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003300CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00003301 // C++0x for-range statements are specified as [stmt.ranged]:
3302 //
3303 // {
3304 // auto && __range = range-init;
3305 // for ( auto __begin = begin-expr,
3306 // __end = end-expr;
3307 // __begin != __end;
3308 // ++__begin ) {
3309 // for-range-declaration = *__begin;
3310 // statement
3311 // }
3312 // }
3313
3314 // Save local scope position before the addition of the implicit variables.
3315 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3316
3317 // Create local scopes and destructors for range, begin and end variables.
3318 if (Stmt *Range = S->getRangeStmt())
3319 addLocalScopeForStmt(Range);
3320 if (Stmt *BeginEnd = S->getBeginEndStmt())
3321 addLocalScopeForStmt(BeginEnd);
3322 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
3323
3324 LocalScope::const_iterator ContinueScopePos = ScopePos;
3325
3326 // "for" is a control-flow statement. Thus we stop processing the current
3327 // block.
Craig Topper25542942014-05-20 04:30:07 +00003328 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003329 if (Block) {
3330 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003331 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003332 LoopSuccessor = Block;
3333 } else
3334 LoopSuccessor = Succ;
3335
3336 // Save the current value for the break targets.
3337 // All breaks should go to the code following the loop.
3338 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3339 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3340
3341 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003342 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00003343 ConditionBlock->setTerminator(S);
3344
3345 // Now add the actual condition to the condition block.
3346 if (Expr *C = S->getCond()) {
3347 Block = ConditionBlock;
3348 CFGBlock *BeginConditionBlock = addStmt(C);
3349 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003350 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003351 assert(BeginConditionBlock == ConditionBlock &&
3352 "condition block in for-range was unexpectedly complex");
3353 (void)BeginConditionBlock;
3354 }
3355
3356 // The condition block is the implicit successor for the loop body as well as
3357 // any code above the loop.
3358 Succ = ConditionBlock;
3359
3360 // See if this is a known constant.
3361 TryResult KnownVal(true);
3362
3363 if (S->getCond())
3364 KnownVal = tryEvaluateBool(S->getCond());
3365
3366 // Now create the loop body.
3367 {
3368 assert(S->getBody());
3369
3370 // Save the current values for Block, Succ, and continue targets.
3371 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3372 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3373
3374 // Generate increment code in its own basic block. This is the target of
3375 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00003376 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003377 Succ = addStmt(S->getInc());
3378 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3379
3380 // The starting block for the loop increment is the block that should
3381 // represent the 'loop target' for looping back to the start of the loop.
3382 ContinueJumpTarget.block->setLoopTarget(S);
3383
3384 // Finish up the increment block and prepare to start the loop body.
3385 assert(Block);
3386 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003387 return nullptr;
3388 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003389
3390 // Add implicit scope and dtors for loop variable.
3391 addLocalScopeAndDtors(S->getLoopVarStmt());
3392
3393 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003394 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00003395 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003396 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003397 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003398 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003399 return nullptr;
3400
Richard Smith02e85f32011-04-14 22:09:26 +00003401 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00003402 addSuccessor(ConditionBlock,
3403 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00003404 }
3405
3406 // Link up the condition block with the code that follows the loop (the
3407 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003408 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00003409
3410 // Add the initialization statements.
3411 Block = createBlock();
Richard Smith0c502d22011-04-18 15:49:25 +00003412 addStmt(S->getBeginEndStmt());
3413 return addStmt(S->getRangeStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003414}
3415
John McCall5d413782010-12-06 08:20:24 +00003416CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003417 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003418 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003419 // If adding implicit destructors visit the full expression for adding
3420 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003421 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00003422 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003423
3424 // Full expression has to be added as CFGStmt so it will be sequenced
3425 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003426 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003427 }
3428 return Visit(E->getSubExpr(), asc);
3429}
3430
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003431CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3432 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003433 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003434 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003435 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003436
3437 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003438 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003439 }
3440 return Visit(E->getSubExpr(), asc);
3441}
3442
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003443CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3444 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003445 autoCreateBlock();
Zhongxing Xuf0cb43f2012-01-11 02:39:07 +00003446 appendStmt(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003447
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003448 return VisitChildren(C);
3449}
3450
Jordan Rosec9176072014-01-13 17:59:19 +00003451CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3452 AddStmtChoice asc) {
3453
3454 autoCreateBlock();
3455 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00003456
Jordan Rosec9176072014-01-13 17:59:19 +00003457 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003458 Block = Visit(NE->getInitializer());
Jordan Rosec9176072014-01-13 17:59:19 +00003459 if (BuildOpts.AddCXXNewAllocator)
3460 appendNewAllocator(Block, NE);
3461 if (NE->isArray())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003462 Block = Visit(NE->getArraySize());
Jordan Rosec9176072014-01-13 17:59:19 +00003463 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3464 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00003465 Block = Visit(*I);
Jordan Rosec9176072014-01-13 17:59:19 +00003466 return Block;
3467}
Jordan Rosed2f40792013-09-03 17:00:57 +00003468
3469CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3470 AddStmtChoice asc) {
3471 autoCreateBlock();
3472 appendStmt(Block, DE);
3473 QualType DTy = DE->getDestroyedType();
3474 DTy = DTy.getNonReferenceType();
3475 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3476 if (RD) {
Matt Beaumont-Gay093f2402013-09-09 21:07:58 +00003477 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
Jordan Rosed2f40792013-09-03 17:00:57 +00003478 appendDeleteDtor(Block, RD, DE);
3479 }
3480
3481 return VisitChildren(DE);
3482}
3483
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003484CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3485 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003486 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003487 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003488 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003489 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003490 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003491 }
3492 return Visit(E->getSubExpr(), asc);
3493}
3494
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003495CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3496 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003497 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003498 appendStmt(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003499 return VisitChildren(C);
3500}
3501
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003502CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3503 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003504 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003505 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003506 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003507 }
Ted Kremenek8219b822010-12-16 07:46:53 +00003508 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003509}
3510
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003511CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00003512 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003513 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003514
Ted Kremenekeda180e22007-08-28 19:26:49 +00003515 if (!IBlock) {
3516 IBlock = createBlock(false);
3517 cfg->setIndirectGotoBlock(IBlock);
3518 }
Mike Stump31feda52009-07-17 01:31:16 +00003519
Ted Kremenekeda180e22007-08-28 19:26:49 +00003520 // IndirectGoto is a control-flow statement. Thus we stop processing the
3521 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003522 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003523 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00003524
Ted Kremenekeda180e22007-08-28 19:26:49 +00003525 Block = createBlock(false);
3526 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003527 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00003528 return addStmt(I->getTarget());
3529}
3530
Manuel Klimekb5616c92014-08-07 10:42:17 +00003531CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
3532 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003533 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3534
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003535tryAgain:
3536 if (!E) {
3537 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00003538 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003539 }
3540 switch (E->getStmtClass()) {
3541 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00003542 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003543
3544 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00003545 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
3546 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003547
3548 case Stmt::CXXBindTemporaryExprClass:
3549 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003550 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003551
John McCallc07a0c72011-02-17 10:25:35 +00003552 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003553 case Stmt::ConditionalOperatorClass:
3554 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003555 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003556
3557 case Stmt::ImplicitCastExprClass:
3558 // For implicit cast we want BindToTemporary to be passed further.
3559 E = cast<CastExpr>(E)->getSubExpr();
3560 goto tryAgain;
3561
Manuel Klimekb0042c42014-07-30 08:34:42 +00003562 case Stmt::CXXFunctionalCastExprClass:
3563 // For functional cast we want BindToTemporary to be passed further.
3564 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
3565 goto tryAgain;
3566
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003567 case Stmt::ParenExprClass:
3568 E = cast<ParenExpr>(E)->getSubExpr();
3569 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00003570
Manuel Klimekb0042c42014-07-30 08:34:42 +00003571 case Stmt::MaterializeTemporaryExprClass: {
3572 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
3573 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
3574 SmallVector<const Expr *, 2> CommaLHSs;
3575 SmallVector<SubobjectAdjustment, 2> Adjustments;
3576 // Find the expression whose lifetime needs to be extended.
3577 E = const_cast<Expr *>(
3578 cast<MaterializeTemporaryExpr>(E)
3579 ->GetTemporaryExpr()
3580 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
3581 // Visit the skipped comma operator left-hand sides for other temporaries.
3582 for (const Expr *CommaLHS : CommaLHSs) {
3583 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00003584 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00003585 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003586 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00003587 }
Richard Smith4137af22014-07-27 05:12:49 +00003588
3589 case Stmt::BlockExprClass:
3590 // Don't recurse into blocks; their subexpressions don't get evaluated
3591 // here.
3592 return Block;
3593
3594 case Stmt::LambdaExprClass: {
3595 // For lambda expressions, only recurse into the capture initializers,
3596 // and not the body.
3597 auto *LE = cast<LambdaExpr>(E);
3598 CFGBlock *B = Block;
3599 for (Expr *Init : LE->capture_inits()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003600 if (CFGBlock *R = VisitForTemporaryDtors(
3601 Init, /*BindToTemporary=*/false, Context))
Richard Smith4137af22014-07-27 05:12:49 +00003602 B = R;
3603 }
3604 return B;
3605 }
3606
3607 case Stmt::CXXDefaultArgExprClass:
3608 E = cast<CXXDefaultArgExpr>(E)->getExpr();
3609 goto tryAgain;
3610
3611 case Stmt::CXXDefaultInitExprClass:
3612 E = cast<CXXDefaultInitExpr>(E)->getExpr();
3613 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003614 }
3615}
3616
Manuel Klimekb5616c92014-08-07 10:42:17 +00003617CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
3618 TempDtorContext &Context) {
3619 if (isa<LambdaExpr>(E)) {
3620 // Do not visit the children of lambdas; they have their own CFGs.
3621 return Block;
3622 }
3623
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003624 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00003625 // order that they will appear in the CFG. Because the CFG is built
3626 // bottom-up, this means we visit them in their natural order, which
3627 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003628 CFGBlock *B = Block;
Ted Kremenek8ae67872013-02-05 22:00:19 +00003629 for (Stmt::child_range I = E->children(); I; ++I) {
3630 if (Stmt *Child = *I)
Manuel Klimekb5616c92014-08-07 10:42:17 +00003631 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00003632 B = R;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003633 }
3634 return B;
3635}
3636
Manuel Klimekb5616c92014-08-07 10:42:17 +00003637CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
3638 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003639 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003640 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00003641 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
3642 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
3643 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00003644
Manuel Klimekedf925b92014-08-07 18:44:19 +00003645 // We do not know at CFG-construction time whether the right-hand-side was
3646 // executed, thus we add a branch node that depends on the temporary
3647 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003648 TempDtorContext RHSContext(
3649 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00003650 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00003651 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00003652
Manuel Klimekb5616c92014-08-07 10:42:17 +00003653 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003654 }
3655
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003656 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003657 // For assignment operator (=) LHS expression is visited
3658 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003659 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3660 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003661 return LHSBlock ? LHSBlock : RHSBlock;
3662 }
3663
3664 // For any other binary operator RHS expression is visited before
3665 // LHS expression (order of children). For destructors visit them in reverse
3666 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003667 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3668 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003669 return RHSBlock ? RHSBlock : LHSBlock;
3670}
3671
3672CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003673 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003674 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003675 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00003676 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003677 // If lifetime of temporary is not prolonged (by assigning to constant
3678 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00003679
Chandler Carruthad747252011-09-13 06:09:01 +00003680 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00003681
Ted Kremenekff909f92014-03-08 02:22:25 +00003682 if (Dtor->isNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003683 // If the destructor is marked as a no-return destructor, we need to
3684 // create a new block for the destructor which does not have as a
3685 // successor anything built thus far. Control won't flow out of this
3686 // block.
3687 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00003688 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00003689 } else if (Context.needsTempDtorBranch()) {
3690 // If we need to introduce a branch, we add a new block that we will hook
3691 // up to a decision block later.
3692 if (B) Succ = B;
3693 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00003694 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00003695 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00003696 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00003697 if (Context.needsTempDtorBranch()) {
3698 Context.setDecisionPoint(Succ, E);
3699 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003700 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003701
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003702 B = Block;
3703 }
3704 return B;
3705}
3706
Manuel Klimekb5616c92014-08-07 10:42:17 +00003707void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
3708 CFGBlock *FalseSucc) {
3709 if (!Context.TerminatorExpr) {
3710 // If no temporary was found, we do not need to insert a decision point.
3711 return;
3712 }
3713 assert(Context.TerminatorExpr);
3714 CFGBlock *Decision = createBlock(false);
3715 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
Manuel Klimekdeb02622014-08-08 07:37:13 +00003716 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00003717 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00003718 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00003719 Block = Decision;
3720}
3721
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003722CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003723 AbstractConditionalOperator *E, bool BindToTemporary,
3724 TempDtorContext &Context) {
3725 VisitForTemporaryDtors(E->getCond(), false, Context);
3726 CFGBlock *ConditionBlock = Block;
3727 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00003728 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00003729 TryResult NegatedVal = ConditionVal;
3730 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00003731
Manuel Klimekdeb02622014-08-08 07:37:13 +00003732 TempDtorContext TrueContext(
3733 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00003734 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003735 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003736
Manuel Klimekb5616c92014-08-07 10:42:17 +00003737 Block = ConditionBlock;
3738 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00003739 TempDtorContext FalseContext(
3740 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00003741 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003742
Manuel Klimekb5616c92014-08-07 10:42:17 +00003743 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00003744 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003745 } else if (TrueContext.TerminatorExpr) {
3746 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00003747 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003748 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00003749 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003750 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003751 return Block;
3752}
3753
Ted Kremenek04cca642007-08-23 21:26:19 +00003754} // end anonymous namespace
Ted Kremenek889073f2007-08-23 16:51:22 +00003755
Mike Stump31feda52009-07-17 01:31:16 +00003756/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
3757/// no successors or predecessors. If this is the first block created in the
3758/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003759CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00003760 bool first_block = begin() == end();
3761
3762 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003763 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00003764 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003765 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00003766
3767 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003768 if (first_block)
3769 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00003770
3771 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003772 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00003773}
3774
Ted Kremenek889073f2007-08-23 16:51:22 +00003775/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
3776/// CFG is returned to the caller.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003777CFG* CFG::buildCFG(const Decl *D, Stmt *Statement, ASTContext *C,
Ted Kremenekf9d82902011-03-10 01:14:05 +00003778 const BuildOptions &BO) {
3779 CFGBuilder Builder(C, BO);
3780 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00003781}
3782
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003783const CXXDestructorDecl *
3784CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003785 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003786 case CFGElement::Statement:
3787 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00003788 case CFGElement::NewAllocator:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003789 llvm_unreachable("getDestructorDecl should only be used with "
3790 "ImplicitDtors");
3791 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00003792 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003793 QualType ty = var->getType();
Ted Kremenek1676a042011-03-03 01:01:03 +00003794 ty = ty.getNonReferenceType();
Ted Kremeneke7d78882012-03-19 23:48:41 +00003795 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003796 ty = arrayType->getElementType();
3797 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003798 const RecordType *recordType = ty->getAs<RecordType>();
3799 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00003800 cast<CXXRecordDecl>(recordType->getDecl());
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003801 return classDecl->getDestructor();
3802 }
Jordan Rosed2f40792013-09-03 17:00:57 +00003803 case CFGElement::DeleteDtor: {
3804 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
3805 QualType DTy = DE->getDestroyedType();
3806 DTy = DTy.getNonReferenceType();
3807 const CXXRecordDecl *classDecl =
3808 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
3809 return classDecl->getDestructor();
3810 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003811 case CFGElement::TemporaryDtor: {
3812 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00003813 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003814 const CXXTemporary *temp = bindExpr->getTemporary();
3815 return temp->getDestructor();
3816 }
3817 case CFGElement::BaseDtor:
3818 case CFGElement::MemberDtor:
3819
3820 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00003821 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003822 }
Ted Kremenek1676a042011-03-03 01:01:03 +00003823 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003824}
3825
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003826bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00003827 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
3828 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003829 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00003830}
3831
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00003832//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003833// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00003834//===----------------------------------------------------------------------===//
3835
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003836CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Craig Topper25542942014-05-20 04:30:07 +00003837 : ReachableBlock(IsReachable ? B : nullptr),
3838 UnreachableBlock(!IsReachable ? B : nullptr,
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003839 B && IsReachable ? AB_Normal : AB_Unreachable) {}
3840
3841CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
3842 : ReachableBlock(B),
Craig Topper25542942014-05-20 04:30:07 +00003843 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003844 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
3845
3846void CFGBlock::addSuccessor(AdjacentBlock Succ,
3847 BumpVectorContext &C) {
3848 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00003849 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003850
3851 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00003852 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003853
3854 Succs.push_back(Succ, C);
3855}
3856
Ted Kremenekb0371852010-09-09 00:06:04 +00003857bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00003858 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003859
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003860 if (F.IgnoreNullPredecessors && !From)
3861 return true;
3862
3863 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003864 // If the 'To' has no label or is labeled but the label isn't a
3865 // CaseStmt then filter this edge.
3866 if (const SwitchStmt *S =
Ted Kremenek89794742011-03-07 22:04:39 +00003867 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003868 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00003869 const Stmt *L = To->getLabel();
3870 if (!L || !isa<CaseStmt>(L))
3871 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00003872 }
3873 }
3874 }
3875
3876 return false;
3877}
3878
3879//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00003880// CFG pretty printing
3881//===----------------------------------------------------------------------===//
3882
Ted Kremenek7e776b12007-08-22 18:22:34 +00003883namespace {
3884
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00003885class StmtPrinterHelper : public PrinterHelper {
Ted Kremenek96a7a592011-03-01 03:15:10 +00003886 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
3887 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003888 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003889 DeclMapTy DeclMap;
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003890 signed currentBlock;
Ted Kremenekd94854a2012-08-22 06:26:15 +00003891 unsigned currStmt;
Chris Lattnerc61089a2009-06-30 01:26:17 +00003892 const LangOptions &LangOpts;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003893public:
Ted Kremenekf8b50e92007-08-31 22:26:13 +00003894
Chris Lattnerc61089a2009-06-30 01:26:17 +00003895 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Ted Kremenekd94854a2012-08-22 06:26:15 +00003896 : currentBlock(0), currStmt(0), LangOpts(LO)
Ted Kremenek96a7a592011-03-01 03:15:10 +00003897 {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003898 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
3899 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003900 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003901 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00003902 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
3903 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003904 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00003905 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003906
Ted Kremenek96a7a592011-03-01 03:15:10 +00003907 switch (stmt->getStmtClass()) {
3908 case Stmt::DeclStmtClass:
3909 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
3910 break;
3911 case Stmt::IfStmtClass: {
3912 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
3913 if (var)
3914 DeclMap[var] = P;
3915 break;
3916 }
3917 case Stmt::ForStmtClass: {
3918 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
3919 if (var)
3920 DeclMap[var] = P;
3921 break;
3922 }
3923 case Stmt::WhileStmtClass: {
3924 const VarDecl *var =
3925 cast<WhileStmt>(stmt)->getConditionVariable();
3926 if (var)
3927 DeclMap[var] = P;
3928 break;
3929 }
3930 case Stmt::SwitchStmtClass: {
3931 const VarDecl *var =
3932 cast<SwitchStmt>(stmt)->getConditionVariable();
3933 if (var)
3934 DeclMap[var] = P;
3935 break;
3936 }
3937 case Stmt::CXXCatchStmtClass: {
3938 const VarDecl *var =
3939 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
3940 if (var)
3941 DeclMap[var] = P;
3942 break;
3943 }
3944 default:
3945 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003946 }
3947 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003948 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00003949 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003950 }
Ted Kremenek96a7a592011-03-01 03:15:10 +00003951
Mike Stump31feda52009-07-17 01:31:16 +00003952
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003953 virtual ~StmtPrinterHelper() {}
Mike Stump31feda52009-07-17 01:31:16 +00003954
Chris Lattnerc61089a2009-06-30 01:26:17 +00003955 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003956 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00003957 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00003958
Craig Topperb45acb82014-03-14 06:02:07 +00003959 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003960 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003961
3962 if (I == StmtMap.end())
3963 return false;
Mike Stump31feda52009-07-17 01:31:16 +00003964
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003965 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00003966 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003967 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00003968 }
Mike Stump31feda52009-07-17 01:31:16 +00003969
Ted Kremenek60983dc2010-01-19 20:52:05 +00003970 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00003971 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003972 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003973
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003974 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003975 DeclMapTy::iterator I = DeclMap.find(D);
3976
3977 if (I == DeclMap.end())
3978 return false;
3979
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003980 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00003981 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003982 return false;
3983 }
3984
3985 OS << "[B" << I->second.first << "." << I->second.second << "]";
3986 return true;
3987 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003988};
Chris Lattnerc61089a2009-06-30 01:26:17 +00003989} // end anonymous namespace
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003990
Chris Lattnerc61089a2009-06-30 01:26:17 +00003991
3992namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00003993class CFGBlockTerminatorPrint
Ted Kremenek83ebcef2008-01-08 18:15:10 +00003994 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Mike Stump31feda52009-07-17 01:31:16 +00003995
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003996 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003997 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00003998 PrintingPolicy Policy;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003999public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004000 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00004001 const PrintingPolicy &Policy)
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00004002 : OS(os), Helper(helper), Policy(Policy) {
4003 this->Policy.IncludeNewlines = false;
4004 }
Mike Stump31feda52009-07-17 01:31:16 +00004005
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004006 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004007 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004008 if (Stmt *C = I->getCond())
4009 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004010 }
Mike Stump31feda52009-07-17 01:31:16 +00004011
Ted Kremenek9aae5132007-08-23 21:42:29 +00004012 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004013 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00004014 Terminator->printPretty(OS, Helper, Policy);
4015 }
4016
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00004017 void VisitDeclStmt(DeclStmt *DS) {
4018 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4019 OS << "static init " << VD->getName();
4020 }
4021
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004022 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004023 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004024 if (F->getInit())
4025 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004026 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004027 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004028 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004029 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00004030 if (F->getInc())
4031 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00004032 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00004033 }
Mike Stump31feda52009-07-17 01:31:16 +00004034
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004035 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004036 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004037 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004038 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004039 }
Mike Stump31feda52009-07-17 01:31:16 +00004040
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004041 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004042 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004043 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004044 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004045 }
Mike Stump31feda52009-07-17 01:31:16 +00004046
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004047 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00004048 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00004049 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004050 }
Mike Stump31feda52009-07-17 01:31:16 +00004051
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004052 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004053 OS << "try ...";
4054 }
4055
John McCallc07a0c72011-02-17 10:25:35 +00004056 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00004057 if (Stmt *Cond = C->getCond())
4058 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004059 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004060 }
Mike Stump31feda52009-07-17 01:31:16 +00004061
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004062 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00004063 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004064 if (Stmt *Cond = C->getCond())
4065 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00004066 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00004067 }
Mike Stump31feda52009-07-17 01:31:16 +00004068
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004069 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004070 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004071 if (Stmt *T = I->getTarget())
4072 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004073 }
Mike Stump31feda52009-07-17 01:31:16 +00004074
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004075 void VisitBinaryOperator(BinaryOperator* B) {
4076 if (!B->isLogicalOp()) {
4077 VisitExpr(B);
4078 return;
4079 }
Mike Stump31feda52009-07-17 01:31:16 +00004080
Richard Trieuddd01ce2014-06-09 22:53:25 +00004081 if (B->getLHS())
4082 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004083
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004084 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004085 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00004086 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004087 return;
John McCalle3027922010-08-25 11:45:40 +00004088 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00004089 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004090 return;
4091 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004092 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00004093 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004094 }
Mike Stump31feda52009-07-17 01:31:16 +00004095
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004096 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00004097 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004098 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00004099
4100public:
4101 void print(CFGTerminator T) {
4102 if (T.isTemporaryDtorsBranch())
4103 OS << "(Temp Dtor) ";
4104 Visit(T.getStmt());
4105 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00004106};
Chris Lattnerc61089a2009-06-30 01:26:17 +00004107} // end anonymous namespace
4108
Aaron Ballmanff924b02013-11-18 20:11:50 +00004109static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00004110 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00004111 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4112 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00004113 assert(S != nullptr && "Expecting non-null Stmt");
4114
Aaron Ballmanff924b02013-11-18 20:11:50 +00004115 // special printing for statement-expressions.
4116 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4117 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00004118
Aaron Ballmanff924b02013-11-18 20:11:50 +00004119 if (Sub->children()) {
4120 OS << "({ ... ; ";
4121 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4122 OS << " })\n";
4123 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004124 }
4125 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00004126 // special printing for comma expressions.
4127 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4128 if (B->getOpcode() == BO_Comma) {
4129 OS << "... , ";
4130 Helper.handledStmt(B->getRHS(),OS);
4131 OS << '\n';
4132 return;
4133 }
4134 }
4135 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00004136
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004137 if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004138 OS << " (OperatorCall)";
Ted Kremenek0ffba932011-12-21 19:32:38 +00004139 }
4140 else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004141 OS << " (BindTemporary)";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004142 }
Ted Kremenek1a7648b2011-12-21 19:39:59 +00004143 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4144 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
4145 }
Ted Kremenek0ffba932011-12-21 19:32:38 +00004146 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
4147 OS << " (" << CE->getStmtClassName() << ", "
4148 << CE->getCastKindName()
4149 << ", " << CE->getType().getAsString()
4150 << ")";
4151 }
Mike Stump31feda52009-07-17 01:31:16 +00004152
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004153 // Expressions need a newline.
4154 if (isa<Expr>(S))
4155 OS << '\n';
Ted Kremenek0f5d8bc2010-08-31 18:47:37 +00004156
David Blaikie00be69a2013-02-23 00:29:34 +00004157 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
4158 const CXXCtorInitializer *I = IE->getInitializer();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004159 if (I->isBaseInitializer())
4160 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
Jordan Rose69d0aed2013-10-22 23:19:47 +00004161 else if (I->isDelegatingInitializer())
4162 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
Francois Pichetd583da02010-12-04 09:14:42 +00004163 else OS << I->getAnyMember()->getName();
Mike Stump31feda52009-07-17 01:31:16 +00004164
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004165 OS << "(";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004166 if (Expr *IE = I->getInit())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004167 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004168 OS << ")";
4169
4170 if (I->isBaseInitializer())
4171 OS << " (Base initializer)\n";
Jordan Rose69d0aed2013-10-22 23:19:47 +00004172 else if (I->isDelegatingInitializer())
4173 OS << " (Delegating initializer)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004174 else OS << " (Member initializer)\n";
4175
David Blaikie00be69a2013-02-23 00:29:34 +00004176 } else if (Optional<CFGAutomaticObjDtor> DE =
4177 E.getAs<CFGAutomaticObjDtor>()) {
4178 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00004179 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004180
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00004181 const Type* T = VD->getType().getTypePtr();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004182 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4183 T = RT->getPointeeType().getTypePtr();
Richard Smithf676e452012-07-24 21:02:14 +00004184 T = T->getBaseElementTypeUnsafe();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004185
4186 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4187 OS << " (Implicit destructor)\n";
Marcin Swiderski20b88732010-10-05 05:37:00 +00004188
Jordan Rosec9176072014-01-13 17:59:19 +00004189 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4190 OS << "CFGNewAllocator(";
4191 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4192 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4193 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00004194 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4195 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4196 if (!RD)
4197 return;
4198 CXXDeleteExpr *DelExpr =
4199 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00004200 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00004201 OS << "->~" << RD->getName().str() << "()";
4202 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004203 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4204 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004205 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004206 OS << " (Base object destructor)\n";
Marcin Swiderski20b88732010-10-05 05:37:00 +00004207
David Blaikie00be69a2013-02-23 00:29:34 +00004208 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4209 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00004210 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004211 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00004212 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004213 OS << " (Member object destructor)\n";
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004214
David Blaikie00be69a2013-02-23 00:29:34 +00004215 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4216 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00004217 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004218 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00004219 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004220 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004221}
Mike Stump31feda52009-07-17 01:31:16 +00004222
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004223static void print_block(raw_ostream &OS, const CFG* cfg,
4224 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00004225 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004226 bool ShowColors) {
Mike Stump31feda52009-07-17 01:31:16 +00004227
Aaron Ballmanff924b02013-11-18 20:11:50 +00004228 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00004229
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004230 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004231 if (ShowColors)
4232 OS.changeColor(raw_ostream::YELLOW, true);
4233
4234 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00004235
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004236 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004237 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004238 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004239 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004240 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004241 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00004242 else if (B.hasNoReturnElement())
4243 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004244 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00004245 OS << "]\n";
4246
4247 if (ShowColors)
4248 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00004249
Ted Kremenek71eca012007-08-29 23:20:49 +00004250 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004251 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004252
4253 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004254 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004255
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004256 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004257 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004258 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004259 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004260 if (C->getLHS())
4261 C->getLHS()->printPretty(OS, &Helper,
4262 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004263 if (C->getRHS()) {
4264 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004265 C->getRHS()->printPretty(OS, &Helper,
4266 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004267 }
Mike Stump92244b02010-01-19 22:00:14 +00004268 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004269 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00004270 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004271 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00004272 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004273 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00004274 0);
4275 else
4276 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004277 OS << ")";
4278
4279 } else
David Blaikie83d382b2011-09-23 05:06:16 +00004280 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00004281
Ted Kremenek71eca012007-08-29 23:20:49 +00004282 OS << ":\n";
4283 }
Mike Stump31feda52009-07-17 01:31:16 +00004284
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004285 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004286 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00004287
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004288 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4289 I != E ; ++I, ++j ) {
Mike Stump31feda52009-07-17 01:31:16 +00004290
Ted Kremenek71eca012007-08-29 23:20:49 +00004291 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004292 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004293 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004294
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004295 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00004296
Aaron Ballmanff924b02013-11-18 20:11:50 +00004297 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00004298
Ted Kremenek72be32a2011-12-22 23:33:52 +00004299 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004300 }
Mike Stump31feda52009-07-17 01:31:16 +00004301
Ted Kremenek71eca012007-08-29 23:20:49 +00004302 // Print the terminator of this block.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004303 if (B.getTerminator()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00004304 if (ShowColors)
4305 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00004306
Ted Kremenek72be32a2011-12-22 23:33:52 +00004307 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00004308
Aaron Ballmanff924b02013-11-18 20:11:50 +00004309 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00004310
Aaron Ballmanff924b02013-11-18 20:11:50 +00004311 PrintingPolicy PP(Helper.getLangOpts());
4312 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00004313 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004314 OS << '\n';
Ted Kremenek72be32a2011-12-22 23:33:52 +00004315
4316 if (ShowColors)
4317 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004318 }
Mike Stump31feda52009-07-17 01:31:16 +00004319
Ted Kremenek71eca012007-08-29 23:20:49 +00004320 if (print_edges) {
4321 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004322 if (!B.pred_empty()) {
4323 const raw_ostream::Colors Color = raw_ostream::BLUE;
4324 if (ShowColors)
4325 OS.changeColor(Color);
4326 OS << " Preds " ;
4327 if (ShowColors)
4328 OS.resetColor();
4329 OS << '(' << B.pred_size() << "):";
4330 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00004331
Ted Kremenek72be32a2011-12-22 23:33:52 +00004332 if (ShowColors)
4333 OS.changeColor(Color);
4334
4335 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4336 I != E; ++I, ++i) {
Mike Stump31feda52009-07-17 01:31:16 +00004337
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004338 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004339 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00004340
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004341 CFGBlock *B = *I;
4342 bool Reachable = true;
4343 if (!B) {
4344 Reachable = false;
4345 B = I->getPossiblyUnreachableBlock();
4346 }
4347
4348 OS << " B" << B->getBlockID();
4349 if (!Reachable)
4350 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00004351 }
4352
4353 if (ShowColors)
4354 OS.resetColor();
4355
4356 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00004357 }
Mike Stump31feda52009-07-17 01:31:16 +00004358
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004359 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004360 if (!B.succ_empty()) {
4361 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4362 if (ShowColors)
4363 OS.changeColor(Color);
4364 OS << " Succs ";
4365 if (ShowColors)
4366 OS.resetColor();
4367 OS << '(' << B.succ_size() << "):";
4368 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004369
Ted Kremenek72be32a2011-12-22 23:33:52 +00004370 if (ShowColors)
4371 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00004372
Ted Kremenek72be32a2011-12-22 23:33:52 +00004373 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4374 I != E; ++I, ++i) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004375
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004376 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004377 OS << "\n ";
4378
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004379 CFGBlock *B = *I;
4380
4381 bool Reachable = true;
4382 if (!B) {
4383 Reachable = false;
4384 B = I->getPossiblyUnreachableBlock();
4385 }
4386
4387 if (B) {
4388 OS << " B" << B->getBlockID();
4389 if (!Reachable)
4390 OS << "(Unreachable)";
4391 }
4392 else {
4393 OS << " NULL";
4394 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00004395 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004396
Ted Kremenek72be32a2011-12-22 23:33:52 +00004397 if (ShowColors)
4398 OS.resetColor();
4399 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004400 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004401 }
Mike Stump31feda52009-07-17 01:31:16 +00004402}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004403
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004404
4405/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004406void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4407 print(llvm::errs(), LO, ShowColors);
4408}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004409
4410/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004411void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004412 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00004413
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004414 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004415 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00004416
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004417 // Iterate through the CFGBlocks and print them one by one.
4418 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4419 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004420 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004421 continue;
Mike Stump31feda52009-07-17 01:31:16 +00004422
Aaron Ballmanff924b02013-11-18 20:11:50 +00004423 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004424 }
Mike Stump31feda52009-07-17 01:31:16 +00004425
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004426 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004427 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004428 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00004429 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00004430}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004431
4432/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004433void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4434 bool ShowColors) const {
4435 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00004436}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004437
Anna Zaksa6fea132014-06-13 23:47:38 +00004438void CFGBlock::dump() const {
4439 dump(getParent(), LangOptions(), false);
4440}
4441
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004442/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4443/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004444void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004445 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004446 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004447 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004448 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00004449}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004450
Ted Kremenek15647632008-01-30 23:02:42 +00004451/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004452void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00004453 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00004454 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00004455 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004456}
4457
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004458Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Marcin Swiderskia7d84a72010-10-29 05:21:47 +00004459 Stmt *Terminator = this->Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004460 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00004461 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004462
Craig Topper25542942014-05-20 04:30:07 +00004463 Expr *E = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004464
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004465 switch (Terminator->getStmtClass()) {
4466 default:
4467 break;
Mike Stump31feda52009-07-17 01:31:16 +00004468
Jordan Rosecf10ea82013-06-06 21:53:45 +00004469 case Stmt::CXXForRangeStmtClass:
4470 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4471 break;
4472
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004473 case Stmt::ForStmtClass:
4474 E = cast<ForStmt>(Terminator)->getCond();
4475 break;
Mike Stump31feda52009-07-17 01:31:16 +00004476
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004477 case Stmt::WhileStmtClass:
4478 E = cast<WhileStmt>(Terminator)->getCond();
4479 break;
Mike Stump31feda52009-07-17 01:31:16 +00004480
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004481 case Stmt::DoStmtClass:
4482 E = cast<DoStmt>(Terminator)->getCond();
4483 break;
Mike Stump31feda52009-07-17 01:31:16 +00004484
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004485 case Stmt::IfStmtClass:
4486 E = cast<IfStmt>(Terminator)->getCond();
4487 break;
Mike Stump31feda52009-07-17 01:31:16 +00004488
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004489 case Stmt::ChooseExprClass:
4490 E = cast<ChooseExpr>(Terminator)->getCond();
4491 break;
Mike Stump31feda52009-07-17 01:31:16 +00004492
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004493 case Stmt::IndirectGotoStmtClass:
4494 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4495 break;
Mike Stump31feda52009-07-17 01:31:16 +00004496
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004497 case Stmt::SwitchStmtClass:
4498 E = cast<SwitchStmt>(Terminator)->getCond();
4499 break;
Mike Stump31feda52009-07-17 01:31:16 +00004500
John McCallc07a0c72011-02-17 10:25:35 +00004501 case Stmt::BinaryConditionalOperatorClass:
4502 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4503 break;
4504
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004505 case Stmt::ConditionalOperatorClass:
4506 E = cast<ConditionalOperator>(Terminator)->getCond();
4507 break;
Mike Stump31feda52009-07-17 01:31:16 +00004508
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004509 case Stmt::BinaryOperatorClass: // '&&' and '||'
4510 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00004511 break;
Mike Stump31feda52009-07-17 01:31:16 +00004512
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00004513 case Stmt::ObjCForCollectionStmtClass:
Mike Stump31feda52009-07-17 01:31:16 +00004514 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004515 }
Mike Stump31feda52009-07-17 01:31:16 +00004516
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004517 if (!StripParens)
4518 return E;
4519
Craig Topper25542942014-05-20 04:30:07 +00004520 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004521}
4522
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004523//===----------------------------------------------------------------------===//
4524// CFG Graphviz Visualization
4525//===----------------------------------------------------------------------===//
4526
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004527
4528#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00004529static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004530#endif
4531
Chris Lattnerc61089a2009-06-30 01:26:17 +00004532void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004533#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00004534 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004535 GraphHelper = &H;
4536 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00004537 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004538#endif
4539}
4540
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004541namespace llvm {
4542template<>
4543struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Tobias Grosser9fc223a2009-11-30 14:16:05 +00004544
4545 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4546
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004547 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004548
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00004549#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004550 std::string OutSStr;
4551 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004552 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004553 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004554
4555 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4556
4557 // Process string output to make it nicer...
4558 for (unsigned i = 0; i != OutStr.length(); ++i)
4559 if (OutStr[i] == '\n') { // Left justify
4560 OutStr[i] = '\\';
4561 OutStr.insert(OutStr.begin()+i+1, 'l');
4562 }
Mike Stump31feda52009-07-17 01:31:16 +00004563
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004564 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00004565#else
4566 return "";
4567#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004568 }
4569};
4570} // end namespace llvm