blob: 76f493e6b33950f3b699ad0b3f49905aa0d21d10 [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//
39// Ways to reduce false positives (that need to be implemented):
40// - Don't flag downsizing casts
41// - Improved handling of static/global variables
42// - Per-block marking of incomplete analysis
43// - Handling ~0 values
44// - False positives involving silencing unused variable warnings
45//
46// Other things TODO:
47// - Improved error messages
48// - Handle mixed assumptions (which assumptions can belong together?)
49// - Finer grained false positive control (levels)
50
Tom Care1fafd1d2010-08-06 22:23:07 +000051#include "GRExprEngineExperimentalChecks.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000052#include "clang/Checker/BugReporter/BugType.h"
Tom Carea9fbf5b2010-07-27 23:26:07 +000053#include "clang/Checker/PathSensitive/CheckerHelpers.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000054#include "clang/Checker/PathSensitive/CheckerVisitor.h"
55#include "clang/Checker/PathSensitive/SVals.h"
56#include "clang/AST/Stmt.h"
57#include "llvm/ADT/DenseMap.h"
Chandler Carruth256565b2010-07-07 00:07:37 +000058#include "llvm/Support/ErrorHandling.h"
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 Carebc42c532010-08-03 01:55:07 +000068 void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B, GRExprEngine &Eng);
Tom Caredb2fa8a2010-07-06 21:43:29 +000069
70 private:
71 // Our assumption about a particular operation.
Ted Kremenekfe97fa12010-08-02 20:33:02 +000072 enum Assumption { Possible = 0, Impossible, Equal, LHSis1, RHSis1, LHSis0,
Tom Caredb2fa8a2010-07-06 21:43:29 +000073 RHSis0 };
74
75 void UpdateAssumption(Assumption &A, const Assumption &New);
76
77 /// contains* - Useful recursive methods to see if a statement contains an
78 /// element somewhere. Used in static analysis to reduce false positives.
Tom Caredf4ca422010-07-16 20:41:41 +000079 static bool isParameterSelfAssign(const Expr *LHS, const Expr *RHS);
80 static bool isTruncationExtensionAssignment(const Expr *LHS,
81 const Expr *RHS);
Tom Caredb2fa8a2010-07-06 21:43:29 +000082 static bool containsZeroConstant(const Stmt *S);
83 static bool containsOneConstant(const Stmt *S);
Tom Caredb2fa8a2010-07-06 21:43:29 +000084
85 // Hash table
86 typedef llvm::DenseMap<const BinaryOperator *, Assumption> AssumptionMap;
87 AssumptionMap hash;
88};
89}
90
91void *IdempotentOperationChecker::getTag() {
92 static int x = 0;
93 return &x;
94}
95
96void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
97 Eng.registerCheck(new IdempotentOperationChecker());
98}
99
100void IdempotentOperationChecker::PreVisitBinaryOperator(
101 CheckerContext &C,
102 const BinaryOperator *B) {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000103 // Find or create an entry in the hash for this BinaryOperator instance.
104 // If we haven't done a lookup before, it will get default initialized to
105 // 'Possible'.
106 Assumption &A = hash[B];
Tom Caredb2fa8a2010-07-06 21:43:29 +0000107
108 // If we already have visited this node on a path that does not contain an
109 // idempotent operation, return immediately.
110 if (A == Impossible)
111 return;
112
113 // Skip binary operators containing common false positives
114 if (containsMacro(B) || containsEnum(B) || containsStmt<SizeOfAlignOfExpr>(B)
115 || containsZeroConstant(B) || containsOneConstant(B)
Tom Caredf4ca422010-07-16 20:41:41 +0000116 || containsBuiltinOffsetOf(B) || containsStaticLocal(B)) {
Tom Caredb2fa8a2010-07-06 21:43:29 +0000117 A = Impossible;
118 return;
119 }
120
121 const Expr *LHS = B->getLHS();
122 const Expr *RHS = B->getRHS();
123
124 const GRState *state = C.getState();
125
126 SVal LHSVal = state->getSVal(LHS);
127 SVal RHSVal = state->getSVal(RHS);
128
129 // If either value is unknown, we can't be 100% sure of all paths.
130 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
131 A = Impossible;
132 return;
133 }
134 BinaryOperator::Opcode Op = B->getOpcode();
135
136 // Dereference the LHS SVal if this is an assign operation
137 switch (Op) {
138 default:
139 break;
140
141 // Fall through intentional
142 case BinaryOperator::AddAssign:
143 case BinaryOperator::SubAssign:
144 case BinaryOperator::MulAssign:
145 case BinaryOperator::DivAssign:
146 case BinaryOperator::AndAssign:
147 case BinaryOperator::OrAssign:
148 case BinaryOperator::XorAssign:
149 case BinaryOperator::ShlAssign:
150 case BinaryOperator::ShrAssign:
151 case BinaryOperator::Assign:
152 // Assign statements have one extra level of indirection
153 if (!isa<Loc>(LHSVal)) {
154 A = Impossible;
155 return;
156 }
157 LHSVal = state->getSVal(cast<Loc>(LHSVal));
158 }
159
160
161 // We now check for various cases which result in an idempotent operation.
162
163 // x op x
164 switch (Op) {
165 default:
166 break; // We don't care about any other operators.
167
168 // Fall through intentional
Tom Caredf4ca422010-07-16 20:41:41 +0000169 case BinaryOperator::Assign:
170 // x Assign x has a few more false positives we can check for
171 if (isParameterSelfAssign(RHS, LHS)
172 || isTruncationExtensionAssignment(RHS, LHS)) {
173 A = Impossible;
174 return;
175 }
176
Tom Caredb2fa8a2010-07-06 21:43:29 +0000177 case BinaryOperator::SubAssign:
178 case BinaryOperator::DivAssign:
179 case BinaryOperator::AndAssign:
180 case BinaryOperator::OrAssign:
181 case BinaryOperator::XorAssign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000182 case BinaryOperator::Sub:
183 case BinaryOperator::Div:
184 case BinaryOperator::And:
185 case BinaryOperator::Or:
186 case BinaryOperator::Xor:
187 case BinaryOperator::LOr:
188 case BinaryOperator::LAnd:
189 if (LHSVal != RHSVal)
190 break;
191 UpdateAssumption(A, Equal);
192 return;
193 }
194
195 // x op 1
196 switch (Op) {
197 default:
198 break; // We don't care about any other operators.
199
200 // Fall through intentional
201 case BinaryOperator::MulAssign:
202 case BinaryOperator::DivAssign:
203 case BinaryOperator::Mul:
204 case BinaryOperator::Div:
205 case BinaryOperator::LOr:
206 case BinaryOperator::LAnd:
207 if (!RHSVal.isConstant(1))
208 break;
209 UpdateAssumption(A, RHSis1);
210 return;
211 }
212
213 // 1 op x
214 switch (Op) {
215 default:
216 break; // We don't care about any other operators.
217
218 // Fall through intentional
219 case BinaryOperator::MulAssign:
220 case BinaryOperator::Mul:
221 case BinaryOperator::LOr:
222 case BinaryOperator::LAnd:
223 if (!LHSVal.isConstant(1))
224 break;
225 UpdateAssumption(A, LHSis1);
226 return;
227 }
228
229 // x op 0
230 switch (Op) {
231 default:
232 break; // We don't care about any other operators.
233
234 // Fall through intentional
235 case BinaryOperator::AddAssign:
236 case BinaryOperator::SubAssign:
237 case BinaryOperator::MulAssign:
238 case BinaryOperator::AndAssign:
239 case BinaryOperator::OrAssign:
240 case BinaryOperator::XorAssign:
241 case BinaryOperator::Add:
242 case BinaryOperator::Sub:
243 case BinaryOperator::Mul:
244 case BinaryOperator::And:
245 case BinaryOperator::Or:
246 case BinaryOperator::Xor:
247 case BinaryOperator::Shl:
248 case BinaryOperator::Shr:
249 case BinaryOperator::LOr:
250 case BinaryOperator::LAnd:
251 if (!RHSVal.isConstant(0))
252 break;
253 UpdateAssumption(A, RHSis0);
254 return;
255 }
256
257 // 0 op x
258 switch (Op) {
259 default:
260 break; // We don't care about any other operators.
261
262 // Fall through intentional
263 //case BinaryOperator::AddAssign: // Common false positive
264 case BinaryOperator::SubAssign: // Check only if unsigned
265 case BinaryOperator::MulAssign:
266 case BinaryOperator::DivAssign:
267 case BinaryOperator::AndAssign:
268 //case BinaryOperator::OrAssign: // Common false positive
269 //case BinaryOperator::XorAssign: // Common false positive
270 case BinaryOperator::ShlAssign:
271 case BinaryOperator::ShrAssign:
272 case BinaryOperator::Add:
273 case BinaryOperator::Sub:
274 case BinaryOperator::Mul:
275 case BinaryOperator::Div:
276 case BinaryOperator::And:
277 case BinaryOperator::Or:
278 case BinaryOperator::Xor:
279 case BinaryOperator::Shl:
280 case BinaryOperator::Shr:
281 case BinaryOperator::LOr:
282 case BinaryOperator::LAnd:
283 if (!LHSVal.isConstant(0))
284 break;
285 UpdateAssumption(A, LHSis0);
286 return;
287 }
288
289 // If we get to this point, there has been a valid use of this operation.
290 A = Impossible;
291}
292
293void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000294 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000295 GRExprEngine &Eng) {
Tom Caredb2fa8a2010-07-06 21:43:29 +0000296 // If there is any work remaining we cannot be 100% sure about our warnings
Tom Carebc42c532010-08-03 01:55:07 +0000297 if (Eng.hasWorkRemaining())
Tom Care216b2012010-07-30 21:14:15 +0000298 return;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000299
300 // Iterate over the hash to see if we have any paths with definite
301 // idempotent operations.
302 for (AssumptionMap::const_iterator i =
303 hash.begin(); i != hash.end(); ++i) {
304 if (i->second != Impossible) {
305 // Select the error message.
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000306 const BinaryOperator *B = i->first;
307 llvm::SmallString<128> buf;
308 llvm::raw_svector_ostream os(buf);
309
Tom Caredb2fa8a2010-07-06 21:43:29 +0000310 switch (i->second) {
311 case Equal:
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000312 if (B->getOpcode() == BinaryOperator::Assign)
313 os << "Assigned value is always the same as the existing value";
314 else
315 os << "Both operands to '" << B->getOpcodeStr()
316 << "' always have the same value";
Tom Caredb2fa8a2010-07-06 21:43:29 +0000317 break;
318 case LHSis1:
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000319 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
Tom Caredb2fa8a2010-07-06 21:43:29 +0000320 break;
321 case RHSis1:
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000322 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
Tom Caredb2fa8a2010-07-06 21:43:29 +0000323 break;
324 case LHSis0:
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000325 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
Tom Caredb2fa8a2010-07-06 21:43:29 +0000326 break;
327 case RHSis0:
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000328 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
Tom Caredb2fa8a2010-07-06 21:43:29 +0000329 break;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000330 case Possible:
Chandler Carruth256565b2010-07-07 00:07:37 +0000331 llvm_unreachable("Operation was never marked with an assumption");
Tom Care7dbf8182010-07-07 01:27:17 +0000332 case Impossible:
333 llvm_unreachable(0);
Tom Caredb2fa8a2010-07-06 21:43:29 +0000334 }
335
336 // Create the SourceRange Arrays
337 SourceRange S[2] = { i->first->getLHS()->getSourceRange(),
338 i->first->getRHS()->getSourceRange() };
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000339 BR.EmitBasicReport("Idempotent operation", "Dead code",
340 os.str(), i->first->getOperatorLoc(), S, 2);
Tom Caredb2fa8a2010-07-06 21:43:29 +0000341 }
342 }
343}
344
345// Updates the current assumption given the new assumption
346inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
347 const Assumption &New) {
348 switch (A) {
349 // If we don't currently have an assumption, set it
350 case Possible:
351 A = New;
352 return;
353
354 // If we have determined that a valid state happened, ignore the new
355 // assumption.
356 case Impossible:
357 return;
358
359 // Any other case means that we had a different assumption last time. We don't
360 // currently support mixing assumptions for diagnostic reasons, so we set
361 // our assumption to be impossible.
362 default:
363 A = Impossible;
364 return;
365 }
366}
367
Tom Caredf4ca422010-07-16 20:41:41 +0000368// Check for a statement were a parameter is self assigned (to avoid an unused
369// variable warning)
370bool IdempotentOperationChecker::isParameterSelfAssign(const Expr *LHS,
371 const Expr *RHS) {
372 LHS = LHS->IgnoreParenCasts();
373 RHS = RHS->IgnoreParenCasts();
374
375 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
376 if (!LHS_DR)
377 return false;
378
379 const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(LHS_DR->getDecl());
380 if (!PD)
381 return false;
382
383 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
384 if (!RHS_DR)
385 return false;
386
387 return PD == RHS_DR->getDecl();
388}
389
390// Check for self casts truncating/extending a variable
391bool IdempotentOperationChecker::isTruncationExtensionAssignment(
392 const Expr *LHS,
393 const Expr *RHS) {
394
395 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
396 if (!LHS_DR)
397 return false;
398
399 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
400 if (!VD)
401 return false;
402
403 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
404 if (!RHS_DR)
405 return false;
406
407 if (VD != RHS_DR->getDecl())
408 return false;
409
410 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
411}
412
Tom Caredf4ca422010-07-16 20:41:41 +0000413// Check for a integer or float constant of 0
Tom Caredb2fa8a2010-07-06 21:43:29 +0000414bool IdempotentOperationChecker::containsZeroConstant(const Stmt *S) {
415 const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
416 if (IL && IL->getValue() == 0)
417 return true;
418
419 const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S);
420 if (FL && FL->getValue().isZero())
421 return true;
422
423 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
424 ++I)
425 if (const Stmt *child = *I)
426 if (containsZeroConstant(child))
427 return true;
428
429 return false;
430}
431
Tom Caredf4ca422010-07-16 20:41:41 +0000432// Check for an integer or float constant of 1
Tom Caredb2fa8a2010-07-06 21:43:29 +0000433bool IdempotentOperationChecker::containsOneConstant(const Stmt *S) {
434 const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
435 if (IL && IL->getValue() == 1)
436 return true;
437
Ted Kremenek45329312010-07-17 00:40:32 +0000438 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S)) {
439 const llvm::APFloat &val = FL->getValue();
440 const llvm::APFloat one(val.getSemantics(), 1);
441 if (val.compare(one) == llvm::APFloat::cmpEqual)
442 return true;
443 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000444
445 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
446 ++I)
447 if (const Stmt *child = *I)
448 if (containsOneConstant(child))
449 return true;
450
451 return false;
452}
453