blob: f6970de783e6a2931a0d1331a616cb4de1983d53 [file] [log] [blame]
Tom Caredb2fa8a2010-07-06 21:43:29 +00001//==- IdempotentOperationChecker.cpp - Idempotent Operations ----*- C++ -*-==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a set of path-sensitive checks for idempotent and/or
11// tautological operations. Each potential operation is checked along all paths
12// to see if every path results in a pointless operation.
13// +-------------------------------------------+
14// |Table of idempotent/tautological operations|
15// +-------------------------------------------+
16//+--------------------------------------------------------------------------+
17//|Operator | x op x | x op 1 | 1 op x | x op 0 | 0 op x | x op ~0 | ~0 op x |
18//+--------------------------------------------------------------------------+
19// +, += | | | | x | x | |
20// -, -= | | | | x | -x | |
21// *, *= | | x | x | 0 | 0 | |
22// /, /= | 1 | x | | N/A | 0 | |
23// &, &= | x | | | 0 | 0 | x | x
24// |, |= | x | | | x | x | ~0 | ~0
25// ^, ^= | 0 | | | x | x | |
26// <<, <<= | | | | x | 0 | |
27// >>, >>= | | | | x | 0 | |
28// || | 1 | 1 | 1 | x | x | 1 | 1
29// && | 1 | x | x | 0 | 0 | x | x
30// = | x | | | | | |
31// == | 1 | | | | | |
32// >= | 1 | | | | | |
33// <= | 1 | | | | | |
34// > | 0 | | | | | |
35// < | 0 | | | | | |
36// != | 0 | | | | | |
37//===----------------------------------------------------------------------===//
38//
Tom Carea7a8a452010-08-12 22:45:47 +000039// Things TODO:
Tom Caredb2fa8a2010-07-06 21:43:29 +000040// - Improved error messages
41// - Handle mixed assumptions (which assumptions can belong together?)
42// - Finer grained false positive control (levels)
Tom Carea7a8a452010-08-12 22:45:47 +000043// - Handling ~0 values
Tom Caredb2fa8a2010-07-06 21:43:29 +000044
Tom Care1fafd1d2010-08-06 22:23:07 +000045#include "GRExprEngineExperimentalChecks.h"
Tom Carea7a8a452010-08-12 22:45:47 +000046#include "clang/Analysis/CFGStmtMap.h"
Tom Caredb34ab72010-08-23 19:51:57 +000047#include "clang/Analysis/Analyses/PseudoConstantAnalysis.h"
Tom Care2bbbe502010-09-02 23:30:22 +000048#include "clang/Checker/BugReporter/BugReporter.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000049#include "clang/Checker/BugReporter/BugType.h"
Tom Carea9fbf5b2010-07-27 23:26:07 +000050#include "clang/Checker/PathSensitive/CheckerHelpers.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000051#include "clang/Checker/PathSensitive/CheckerVisitor.h"
Tom Carea7a8a452010-08-12 22:45:47 +000052#include "clang/Checker/PathSensitive/GRCoreEngine.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000053#include "clang/Checker/PathSensitive/SVals.h"
54#include "clang/AST/Stmt.h"
55#include "llvm/ADT/DenseMap.h"
Tom Carea7a8a452010-08-12 22:45:47 +000056#include "llvm/ADT/SmallSet.h"
Chandler Carruth256565b2010-07-07 00:07:37 +000057#include "llvm/Support/ErrorHandling.h"
Tom Carea7a8a452010-08-12 22:45:47 +000058#include <deque>
Tom Caredb2fa8a2010-07-06 21:43:29 +000059
60using namespace clang;
61
62namespace {
63class IdempotentOperationChecker
64 : public CheckerVisitor<IdempotentOperationChecker> {
65 public:
66 static void *getTag();
67 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
Tom Care2bbbe502010-09-02 23:30:22 +000068 void PostVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
Tom Carebc42c532010-08-03 01:55:07 +000069 void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B, GRExprEngine &Eng);
Tom Caredb2fa8a2010-07-06 21:43:29 +000070
71 private:
72 // Our assumption about a particular operation.
Ted Kremenekfe97fa12010-08-02 20:33:02 +000073 enum Assumption { Possible = 0, Impossible, Equal, LHSis1, RHSis1, LHSis0,
Tom Caredb2fa8a2010-07-06 21:43:29 +000074 RHSis0 };
75
76 void UpdateAssumption(Assumption &A, const Assumption &New);
77
Tom Care245adab2010-08-18 21:17:24 +000078 // False positive reduction methods
Tom Care6216dc02010-08-30 19:25:43 +000079 static bool isSelfAssign(const Expr *LHS, const Expr *RHS);
80 static bool isUnused(const Expr *E, AnalysisContext *AC);
Tom Caredf4ca422010-07-16 20:41:41 +000081 static bool isTruncationExtensionAssignment(const Expr *LHS,
82 const Expr *RHS);
Tom Carea7a8a452010-08-12 22:45:47 +000083 static bool PathWasCompletelyAnalyzed(const CFG *C,
84 const CFGBlock *CB,
85 const GRCoreEngine &CE);
Tom Care6216dc02010-08-30 19:25:43 +000086 static bool CanVary(const Expr *Ex,
87 AnalysisContext *AC);
Tom Care245adab2010-08-18 21:17:24 +000088 static bool isConstantOrPseudoConstant(const DeclRefExpr *DR,
89 AnalysisContext *AC);
Tom Caredb34ab72010-08-23 19:51:57 +000090 static bool containsNonLocalVarDecl(const Stmt *S);
Tom Caredb2fa8a2010-07-06 21:43:29 +000091
Tom Care2bbbe502010-09-02 23:30:22 +000092 // Hash table and related data structures
93 struct BinaryOperatorData {
94 BinaryOperatorData() : assumption(Possible), analysisContext(0) {}
95
96 Assumption assumption;
97 AnalysisContext *analysisContext;
98 ExplodedNodeSet explodedNodes; // Set of ExplodedNodes that refer to a
99 // BinaryOperator
100 };
101 typedef llvm::DenseMap<const BinaryOperator *, BinaryOperatorData>
102 AssumptionMap;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000103 AssumptionMap hash;
104};
105}
106
107void *IdempotentOperationChecker::getTag() {
108 static int x = 0;
109 return &x;
110}
111
112void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
113 Eng.registerCheck(new IdempotentOperationChecker());
114}
115
116void IdempotentOperationChecker::PreVisitBinaryOperator(
117 CheckerContext &C,
118 const BinaryOperator *B) {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000119 // Find or create an entry in the hash for this BinaryOperator instance.
120 // If we haven't done a lookup before, it will get default initialized to
Tom Care2bbbe502010-09-02 23:30:22 +0000121 // 'Possible'. At this stage we do not store the ExplodedNode, as it has not
122 // been created yet.
123 BinaryOperatorData &Data = hash[B];
124 Assumption &A = Data.assumption;
Tom Care245adab2010-08-18 21:17:24 +0000125 AnalysisContext *AC = C.getCurrentAnalysisContext();
Tom Care2bbbe502010-09-02 23:30:22 +0000126 Data.analysisContext = AC;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000127
128 // If we already have visited this node on a path that does not contain an
129 // idempotent operation, return immediately.
130 if (A == Impossible)
131 return;
132
Tom Carea7a8a452010-08-12 22:45:47 +0000133 // Retrieve both sides of the operator and determine if they can vary (which
134 // may mean this is a false positive.
Tom Caredb2fa8a2010-07-06 21:43:29 +0000135 const Expr *LHS = B->getLHS();
136 const Expr *RHS = B->getRHS();
Tom Care245adab2010-08-18 21:17:24 +0000137
Tom Caredb34ab72010-08-23 19:51:57 +0000138 // At this stage we can calculate whether each side contains a false positive
139 // that applies to all operators. We only need to calculate this the first
140 // time.
141 bool LHSContainsFalsePositive = false, RHSContainsFalsePositive = false;
Tom Care245adab2010-08-18 21:17:24 +0000142 if (A == Possible) {
Tom Caredb34ab72010-08-23 19:51:57 +0000143 // An expression contains a false positive if it can't vary, or if it
144 // contains a known false positive VarDecl.
145 LHSContainsFalsePositive = !CanVary(LHS, AC)
146 || containsNonLocalVarDecl(LHS);
147 RHSContainsFalsePositive = !CanVary(RHS, AC)
148 || containsNonLocalVarDecl(RHS);
Tom Care245adab2010-08-18 21:17:24 +0000149 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000150
151 const GRState *state = C.getState();
152
153 SVal LHSVal = state->getSVal(LHS);
154 SVal RHSVal = state->getSVal(RHS);
155
156 // If either value is unknown, we can't be 100% sure of all paths.
157 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
158 A = Impossible;
159 return;
160 }
161 BinaryOperator::Opcode Op = B->getOpcode();
162
163 // Dereference the LHS SVal if this is an assign operation
164 switch (Op) {
165 default:
166 break;
167
168 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000169 case BO_AddAssign:
170 case BO_SubAssign:
171 case BO_MulAssign:
172 case BO_DivAssign:
173 case BO_AndAssign:
174 case BO_OrAssign:
175 case BO_XorAssign:
176 case BO_ShlAssign:
177 case BO_ShrAssign:
178 case BO_Assign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000179 // Assign statements have one extra level of indirection
180 if (!isa<Loc>(LHSVal)) {
181 A = Impossible;
182 return;
183 }
184 LHSVal = state->getSVal(cast<Loc>(LHSVal));
185 }
186
187
188 // We now check for various cases which result in an idempotent operation.
189
190 // x op x
191 switch (Op) {
192 default:
193 break; // We don't care about any other operators.
194
195 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000196 case BO_Assign:
Tom Care6216dc02010-08-30 19:25:43 +0000197 // x Assign x can be used to silence unused variable warnings intentionally.
198 // If this is a self assignment and the variable is referenced elsewhere,
199 // then it is a false positive.
200 if (isSelfAssign(LHS, RHS)) {
201 if (!isUnused(LHS, AC)) {
202 UpdateAssumption(A, Equal);
203 return;
204 }
205 else {
206 A = Impossible;
207 return;
208 }
Tom Caredf4ca422010-07-16 20:41:41 +0000209 }
210
John McCall2de56d12010-08-25 11:45:40 +0000211 case BO_SubAssign:
212 case BO_DivAssign:
213 case BO_AndAssign:
214 case BO_OrAssign:
215 case BO_XorAssign:
216 case BO_Sub:
217 case BO_Div:
218 case BO_And:
219 case BO_Or:
220 case BO_Xor:
221 case BO_LOr:
222 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000223 case BO_EQ:
224 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000225 if (LHSVal != RHSVal || LHSContainsFalsePositive
226 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000227 break;
228 UpdateAssumption(A, Equal);
229 return;
230 }
231
232 // x op 1
233 switch (Op) {
234 default:
235 break; // We don't care about any other operators.
236
237 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000238 case BO_MulAssign:
239 case BO_DivAssign:
240 case BO_Mul:
241 case BO_Div:
242 case BO_LOr:
243 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000244 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000245 break;
246 UpdateAssumption(A, RHSis1);
247 return;
248 }
249
250 // 1 op x
251 switch (Op) {
252 default:
253 break; // We don't care about any other operators.
254
255 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000256 case BO_MulAssign:
257 case BO_Mul:
258 case BO_LOr:
259 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000260 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000261 break;
262 UpdateAssumption(A, LHSis1);
263 return;
264 }
265
266 // x op 0
267 switch (Op) {
268 default:
269 break; // We don't care about any other operators.
270
271 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000272 case BO_AddAssign:
273 case BO_SubAssign:
274 case BO_MulAssign:
275 case BO_AndAssign:
276 case BO_OrAssign:
277 case BO_XorAssign:
278 case BO_Add:
279 case BO_Sub:
280 case BO_Mul:
281 case BO_And:
282 case BO_Or:
283 case BO_Xor:
284 case BO_Shl:
285 case BO_Shr:
286 case BO_LOr:
287 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000288 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000289 break;
290 UpdateAssumption(A, RHSis0);
291 return;
292 }
293
294 // 0 op x
295 switch (Op) {
296 default:
297 break; // We don't care about any other operators.
298
299 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000300 //case BO_AddAssign: // Common false positive
301 case BO_SubAssign: // Check only if unsigned
302 case BO_MulAssign:
303 case BO_DivAssign:
304 case BO_AndAssign:
305 //case BO_OrAssign: // Common false positive
306 //case BO_XorAssign: // Common false positive
307 case BO_ShlAssign:
308 case BO_ShrAssign:
309 case BO_Add:
310 case BO_Sub:
311 case BO_Mul:
312 case BO_Div:
313 case BO_And:
314 case BO_Or:
315 case BO_Xor:
316 case BO_Shl:
317 case BO_Shr:
318 case BO_LOr:
319 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000320 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000321 break;
322 UpdateAssumption(A, LHSis0);
323 return;
324 }
325
326 // If we get to this point, there has been a valid use of this operation.
327 A = Impossible;
328}
329
Tom Care2bbbe502010-09-02 23:30:22 +0000330// At the post visit stage, the predecessor ExplodedNode will be the
331// BinaryOperator that was just created. We use this hook to collect the
332// ExplodedNode.
333void IdempotentOperationChecker::PostVisitBinaryOperator(
334 CheckerContext &C,
335 const BinaryOperator *B) {
336 // Add the ExplodedNode we just visited
337 BinaryOperatorData &Data = hash[B];
338 Data.explodedNodes.Add(C.getPredecessor());
339}
340
Tom Caredb2fa8a2010-07-06 21:43:29 +0000341void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000342 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000343 GRExprEngine &Eng) {
Tom Care2bbbe502010-09-02 23:30:22 +0000344 BugType *BT = new BugType("Idempotent operation", "Dead code");
Tom Caredb2fa8a2010-07-06 21:43:29 +0000345 // Iterate over the hash to see if we have any paths with definite
346 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000347 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
348 // Unpack the hash contents
Tom Care2bbbe502010-09-02 23:30:22 +0000349 const BinaryOperatorData &Data = i->second;
350 const Assumption &A = Data.assumption;
351 AnalysisContext *AC = Data.analysisContext;
352 const ExplodedNodeSet &ES = Data.explodedNodes;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000353
Tom Carea7a8a452010-08-12 22:45:47 +0000354 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000355
Tom Carea7a8a452010-08-12 22:45:47 +0000356 if (A == Impossible)
357 continue;
358
359 // If the analyzer did not finish, check to see if we can still emit this
360 // warning
361 if (Eng.hasWorkRemaining()) {
362 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
363 &AC->getParentMap());
364
365 // If we can trace back
366 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
367 CBM->getBlock(B),
368 Eng.getCoreEngine()))
369 continue;
370
371 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000372 }
Tom Carea7a8a452010-08-12 22:45:47 +0000373
Tom Care2bbbe502010-09-02 23:30:22 +0000374 // Select the error message and SourceRanges to report.
Tom Carea7a8a452010-08-12 22:45:47 +0000375 llvm::SmallString<128> buf;
376 llvm::raw_svector_ostream os(buf);
Tom Care2bbbe502010-09-02 23:30:22 +0000377 bool LHSRelevant = false, RHSRelevant = false;
Tom Carea7a8a452010-08-12 22:45:47 +0000378 switch (A) {
379 case Equal:
Tom Care2bbbe502010-09-02 23:30:22 +0000380 LHSRelevant = true;
381 RHSRelevant = true;
John McCall2de56d12010-08-25 11:45:40 +0000382 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000383 os << "Assigned value is always the same as the existing value";
384 else
385 os << "Both operands to '" << B->getOpcodeStr()
386 << "' always have the same value";
387 break;
388 case LHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000389 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000390 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
391 break;
392 case RHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000393 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000394 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
395 break;
396 case LHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000397 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000398 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
399 break;
400 case RHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000401 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000402 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
403 break;
404 case Possible:
405 llvm_unreachable("Operation was never marked with an assumption");
406 case Impossible:
407 llvm_unreachable(0);
408 }
409
Tom Care2bbbe502010-09-02 23:30:22 +0000410 // Add a report for each ExplodedNode
411 for (ExplodedNodeSet::iterator I = ES.begin(), E = ES.end(); I != E; ++I) {
412 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), *I);
413
414 // Add source ranges and visitor hooks
415 if (LHSRelevant) {
416 const Expr *LHS = i->first->getLHS();
417 report->addRange(LHS->getSourceRange());
418 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, LHS);
419 }
420 if (RHSRelevant) {
421 const Expr *RHS = i->first->getRHS();
422 report->addRange(i->first->getRHS()->getSourceRange());
423 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, RHS);
424 }
425
426 BR.EmitReport(report);
427 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000428 }
429}
430
431// Updates the current assumption given the new assumption
432inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
433 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000434// If the assumption is the same, there is nothing to do
435 if (A == New)
436 return;
437
Tom Caredb2fa8a2010-07-06 21:43:29 +0000438 switch (A) {
439 // If we don't currently have an assumption, set it
440 case Possible:
441 A = New;
442 return;
443
444 // If we have determined that a valid state happened, ignore the new
445 // assumption.
446 case Impossible:
447 return;
448
449 // Any other case means that we had a different assumption last time. We don't
450 // currently support mixing assumptions for diagnostic reasons, so we set
451 // our assumption to be impossible.
452 default:
453 A = Impossible;
454 return;
455 }
456}
457
Tom Care6216dc02010-08-30 19:25:43 +0000458// Check for a statement where a variable is self assigned to possibly avoid an
459// unused variable warning.
460bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000461 LHS = LHS->IgnoreParenCasts();
462 RHS = RHS->IgnoreParenCasts();
463
464 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
465 if (!LHS_DR)
466 return false;
467
Tom Careef52bcb2010-08-24 21:09:07 +0000468 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
469 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000470 return false;
471
472 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
473 if (!RHS_DR)
474 return false;
475
Tom Careef52bcb2010-08-24 21:09:07 +0000476 if (VD != RHS_DR->getDecl())
477 return false;
478
Tom Care6216dc02010-08-30 19:25:43 +0000479 return true;
480}
481
482// Returns true if the Expr points to a VarDecl that is not read anywhere
483// outside of self-assignments.
484bool IdempotentOperationChecker::isUnused(const Expr *E,
485 AnalysisContext *AC) {
486 if (!E)
487 return false;
488
489 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
490 if (!DR)
491 return false;
492
493 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
494 if (!VD)
495 return false;
496
Tom Careef52bcb2010-08-24 21:09:07 +0000497 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
498 return false;
499
500 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000501}
502
503// Check for self casts truncating/extending a variable
504bool IdempotentOperationChecker::isTruncationExtensionAssignment(
505 const Expr *LHS,
506 const Expr *RHS) {
507
508 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
509 if (!LHS_DR)
510 return false;
511
512 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
513 if (!VD)
514 return false;
515
516 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
517 if (!RHS_DR)
518 return false;
519
520 if (VD != RHS_DR->getDecl())
521 return false;
522
523 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
524}
525
Tom Carea7a8a452010-08-12 22:45:47 +0000526// Returns false if a path to this block was not completely analyzed, or true
527// otherwise.
528bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
529 const CFG *C,
530 const CFGBlock *CB,
531 const GRCoreEngine &CE) {
532 std::deque<const CFGBlock *> WorkList;
533 llvm::SmallSet<unsigned, 8> Aborted;
534 llvm::SmallSet<unsigned, 128> Visited;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000535
Tom Carea7a8a452010-08-12 22:45:47 +0000536 // Create a set of all aborted blocks
537 typedef GRCoreEngine::BlocksAborted::const_iterator AbortedIterator;
538 for (AbortedIterator I = CE.blocks_aborted_begin(),
539 E = CE.blocks_aborted_end(); I != E; ++I) {
540 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000541
Tom Carea7a8a452010-08-12 22:45:47 +0000542 // The destination block on the BlockEdge is the first block that was not
543 // analyzed.
544 Aborted.insert(BE.getDst()->getBlockID());
Ted Kremenek45329312010-07-17 00:40:32 +0000545 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000546
Tom Carea7a8a452010-08-12 22:45:47 +0000547 // Save the entry block ID for early exiting
548 unsigned EntryBlockID = C->getEntry().getBlockID();
Tom Caredb2fa8a2010-07-06 21:43:29 +0000549
Tom Carea7a8a452010-08-12 22:45:47 +0000550 // Create initial node
551 WorkList.push_back(CB);
552
553 while (!WorkList.empty()) {
554 const CFGBlock *Head = WorkList.front();
555 WorkList.pop_front();
556 Visited.insert(Head->getBlockID());
557
558 // If we found the entry block, then there exists a path from the target
559 // node to the entry point of this function -> the path was completely
560 // analyzed.
561 if (Head->getBlockID() == EntryBlockID)
562 return true;
563
564 // If any of the aborted blocks are on the path to the beginning, then all
565 // paths to this block were not analyzed.
566 if (Aborted.count(Head->getBlockID()))
567 return false;
568
569 // Add the predecessors to the worklist unless we have already visited them
570 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
571 I != Head->pred_end(); ++I)
572 if (!Visited.count((*I)->getBlockID()))
573 WorkList.push_back(*I);
574 }
575
576 // If we get to this point, there is no connection to the entry block or an
577 // aborted block. This path is unreachable and we can report the error.
578 return true;
579}
580
581// Recursive function that determines whether an expression contains any element
582// that varies. This could be due to a compile-time constant like sizeof. An
583// expression may also involve a variable that behaves like a constant. The
584// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000585bool IdempotentOperationChecker::CanVary(const Expr *Ex,
586 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000587 // Parentheses and casts are irrelevant here
588 Ex = Ex->IgnoreParenCasts();
589
590 if (Ex->getLocStart().isMacroID())
591 return false;
592
593 switch (Ex->getStmtClass()) {
594 // Trivially true cases
595 case Stmt::ArraySubscriptExprClass:
596 case Stmt::MemberExprClass:
597 case Stmt::StmtExprClass:
598 case Stmt::CallExprClass:
599 case Stmt::VAArgExprClass:
600 case Stmt::ShuffleVectorExprClass:
601 return true;
602 default:
603 return true;
604
605 // Trivially false cases
606 case Stmt::IntegerLiteralClass:
607 case Stmt::CharacterLiteralClass:
608 case Stmt::FloatingLiteralClass:
609 case Stmt::PredefinedExprClass:
610 case Stmt::ImaginaryLiteralClass:
611 case Stmt::StringLiteralClass:
612 case Stmt::OffsetOfExprClass:
613 case Stmt::CompoundLiteralExprClass:
614 case Stmt::AddrLabelExprClass:
615 case Stmt::TypesCompatibleExprClass:
616 case Stmt::GNUNullExprClass:
617 case Stmt::InitListExprClass:
618 case Stmt::DesignatedInitExprClass:
619 case Stmt::BlockExprClass:
620 case Stmt::BlockDeclRefExprClass:
621 return false;
622
623 // Cases requiring custom logic
624 case Stmt::SizeOfAlignOfExprClass: {
625 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
626 if (!SE->isSizeOf())
627 return false;
628 return SE->getTypeOfArgument()->isVariableArrayType();
629 }
630 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000631 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000632 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000633
634 // The next cases require recursion for subexpressions
635 case Stmt::BinaryOperatorClass: {
636 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Tom Care245adab2010-08-18 21:17:24 +0000637 return CanVary(B->getRHS(), AC)
638 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000639 }
640 case Stmt::UnaryOperatorClass: {
641 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000642 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000643 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000644 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000645 return false;
646 default:
Tom Care245adab2010-08-18 21:17:24 +0000647 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000648 }
649 }
650 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000651 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
652 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000653 case Stmt::ConditionalOperatorClass:
Tom Care6216dc02010-08-30 19:25:43 +0000654 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000655 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000656}
657
Tom Care245adab2010-08-18 21:17:24 +0000658// Returns true if a DeclRefExpr is or behaves like a constant.
659bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000660 const DeclRefExpr *DR,
661 AnalysisContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000662 // Check if the type of the Decl is const-qualified
663 if (DR->getType().isConstQualified())
664 return true;
665
Tom Care50e8ac22010-08-16 21:43:52 +0000666 // Check for an enum
667 if (isa<EnumConstantDecl>(DR->getDecl()))
668 return true;
669
Tom Caredb34ab72010-08-23 19:51:57 +0000670 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
671 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000672 return true;
673
Tom Caredb34ab72010-08-23 19:51:57 +0000674 // Check if the Decl behaves like a constant. This check also takes care of
675 // static variables, which can only change between function calls if they are
676 // modified in the AST.
677 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
678 if (PCA->isPseudoConstant(VD))
679 return true;
680
681 return false;
682}
683
684// Recursively find any substatements containing VarDecl's with storage other
685// than local
686bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
687 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
688
689 if (DR)
690 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
691 if (!VD->hasLocalStorage())
692 return true;
693
694 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
695 ++I)
696 if (const Stmt *child = *I)
697 if (containsNonLocalVarDecl(child))
698 return true;
699
Tom Care50e8ac22010-08-16 21:43:52 +0000700 return false;
701}