blob: 95d488c6af620d7857a81b485f3d45269af5d693 [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 Caredf4ca422010-07-16 20:41:41 +000051#include "GRExprEngineInternalChecks.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000052#include "clang/Checker/BugReporter/BugType.h"
53#include "clang/Checker/PathSensitive/CheckerVisitor.h"
54#include "clang/Checker/PathSensitive/SVals.h"
55#include "clang/AST/Stmt.h"
56#include "llvm/ADT/DenseMap.h"
Chandler Carruth256565b2010-07-07 00:07:37 +000057#include "llvm/Support/ErrorHandling.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000058
59using namespace clang;
60
61namespace {
62class IdempotentOperationChecker
63 : public CheckerVisitor<IdempotentOperationChecker> {
64 public:
65 static void *getTag();
66 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
67 void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B,
68 bool hasWorkRemaining);
69
70 private:
71 // Our assumption about a particular operation.
72 enum Assumption { Possible, Impossible, Equal, LHSis1, RHSis1, LHSis0,
73 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.
79 static bool containsMacro(const Stmt *S);
80 static bool containsEnum(const Stmt *S);
Tom Caredf4ca422010-07-16 20:41:41 +000081 static bool containsStaticLocal(const Stmt *S);
82 static bool isParameterSelfAssign(const Expr *LHS, const Expr *RHS);
83 static bool isTruncationExtensionAssignment(const Expr *LHS,
84 const Expr *RHS);
Tom Caredb2fa8a2010-07-06 21:43:29 +000085 static bool containsBuiltinOffsetOf(const Stmt *S);
86 static bool containsZeroConstant(const Stmt *S);
87 static bool containsOneConstant(const Stmt *S);
88 template <class T> static bool containsStmt(const Stmt *S) {
89 if (isa<T>(S))
90 return true;
91
92 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
93 ++I)
94 if (const Stmt *child = *I)
95 if (containsStmt<T>(child))
96 return true;
97
98 return false;
99 }
100
101 // Hash table
102 typedef llvm::DenseMap<const BinaryOperator *, Assumption> AssumptionMap;
103 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) {
119 // Find or create an entry in the hash for this BinaryOperator instance
120 AssumptionMap::iterator i = hash.find(B);
121 Assumption &A = i == hash.end() ? hash[B] : i->second;
122
123 // If we had to create an entry, initialise the value to Possible
124 if (i == hash.end())
125 A = Possible;
126
127 // If we already have visited this node on a path that does not contain an
128 // idempotent operation, return immediately.
129 if (A == Impossible)
130 return;
131
132 // Skip binary operators containing common false positives
133 if (containsMacro(B) || containsEnum(B) || containsStmt<SizeOfAlignOfExpr>(B)
134 || containsZeroConstant(B) || containsOneConstant(B)
Tom Caredf4ca422010-07-16 20:41:41 +0000135 || containsBuiltinOffsetOf(B) || containsStaticLocal(B)) {
Tom Caredb2fa8a2010-07-06 21:43:29 +0000136 A = Impossible;
137 return;
138 }
139
140 const Expr *LHS = B->getLHS();
141 const Expr *RHS = B->getRHS();
142
143 const GRState *state = C.getState();
144
145 SVal LHSVal = state->getSVal(LHS);
146 SVal RHSVal = state->getSVal(RHS);
147
148 // If either value is unknown, we can't be 100% sure of all paths.
149 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
150 A = Impossible;
151 return;
152 }
153 BinaryOperator::Opcode Op = B->getOpcode();
154
155 // Dereference the LHS SVal if this is an assign operation
156 switch (Op) {
157 default:
158 break;
159
160 // Fall through intentional
161 case BinaryOperator::AddAssign:
162 case BinaryOperator::SubAssign:
163 case BinaryOperator::MulAssign:
164 case BinaryOperator::DivAssign:
165 case BinaryOperator::AndAssign:
166 case BinaryOperator::OrAssign:
167 case BinaryOperator::XorAssign:
168 case BinaryOperator::ShlAssign:
169 case BinaryOperator::ShrAssign:
170 case BinaryOperator::Assign:
171 // Assign statements have one extra level of indirection
172 if (!isa<Loc>(LHSVal)) {
173 A = Impossible;
174 return;
175 }
176 LHSVal = state->getSVal(cast<Loc>(LHSVal));
177 }
178
179
180 // We now check for various cases which result in an idempotent operation.
181
182 // x op x
183 switch (Op) {
184 default:
185 break; // We don't care about any other operators.
186
187 // Fall through intentional
Tom Caredf4ca422010-07-16 20:41:41 +0000188 case BinaryOperator::Assign:
189 // x Assign x has a few more false positives we can check for
190 if (isParameterSelfAssign(RHS, LHS)
191 || isTruncationExtensionAssignment(RHS, LHS)) {
192 A = Impossible;
193 return;
194 }
195
Tom Caredb2fa8a2010-07-06 21:43:29 +0000196 case BinaryOperator::SubAssign:
197 case BinaryOperator::DivAssign:
198 case BinaryOperator::AndAssign:
199 case BinaryOperator::OrAssign:
200 case BinaryOperator::XorAssign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000201 case BinaryOperator::Sub:
202 case BinaryOperator::Div:
203 case BinaryOperator::And:
204 case BinaryOperator::Or:
205 case BinaryOperator::Xor:
206 case BinaryOperator::LOr:
207 case BinaryOperator::LAnd:
208 if (LHSVal != RHSVal)
209 break;
210 UpdateAssumption(A, Equal);
211 return;
212 }
213
214 // x op 1
215 switch (Op) {
216 default:
217 break; // We don't care about any other operators.
218
219 // Fall through intentional
220 case BinaryOperator::MulAssign:
221 case BinaryOperator::DivAssign:
222 case BinaryOperator::Mul:
223 case BinaryOperator::Div:
224 case BinaryOperator::LOr:
225 case BinaryOperator::LAnd:
226 if (!RHSVal.isConstant(1))
227 break;
228 UpdateAssumption(A, RHSis1);
229 return;
230 }
231
232 // 1 op x
233 switch (Op) {
234 default:
235 break; // We don't care about any other operators.
236
237 // Fall through intentional
238 case BinaryOperator::MulAssign:
239 case BinaryOperator::Mul:
240 case BinaryOperator::LOr:
241 case BinaryOperator::LAnd:
242 if (!LHSVal.isConstant(1))
243 break;
244 UpdateAssumption(A, LHSis1);
245 return;
246 }
247
248 // x op 0
249 switch (Op) {
250 default:
251 break; // We don't care about any other operators.
252
253 // Fall through intentional
254 case BinaryOperator::AddAssign:
255 case BinaryOperator::SubAssign:
256 case BinaryOperator::MulAssign:
257 case BinaryOperator::AndAssign:
258 case BinaryOperator::OrAssign:
259 case BinaryOperator::XorAssign:
260 case BinaryOperator::Add:
261 case BinaryOperator::Sub:
262 case BinaryOperator::Mul:
263 case BinaryOperator::And:
264 case BinaryOperator::Or:
265 case BinaryOperator::Xor:
266 case BinaryOperator::Shl:
267 case BinaryOperator::Shr:
268 case BinaryOperator::LOr:
269 case BinaryOperator::LAnd:
270 if (!RHSVal.isConstant(0))
271 break;
272 UpdateAssumption(A, RHSis0);
273 return;
274 }
275
276 // 0 op x
277 switch (Op) {
278 default:
279 break; // We don't care about any other operators.
280
281 // Fall through intentional
282 //case BinaryOperator::AddAssign: // Common false positive
283 case BinaryOperator::SubAssign: // Check only if unsigned
284 case BinaryOperator::MulAssign:
285 case BinaryOperator::DivAssign:
286 case BinaryOperator::AndAssign:
287 //case BinaryOperator::OrAssign: // Common false positive
288 //case BinaryOperator::XorAssign: // Common false positive
289 case BinaryOperator::ShlAssign:
290 case BinaryOperator::ShrAssign:
291 case BinaryOperator::Add:
292 case BinaryOperator::Sub:
293 case BinaryOperator::Mul:
294 case BinaryOperator::Div:
295 case BinaryOperator::And:
296 case BinaryOperator::Or:
297 case BinaryOperator::Xor:
298 case BinaryOperator::Shl:
299 case BinaryOperator::Shr:
300 case BinaryOperator::LOr:
301 case BinaryOperator::LAnd:
302 if (!LHSVal.isConstant(0))
303 break;
304 UpdateAssumption(A, LHSis0);
305 return;
306 }
307
308 // If we get to this point, there has been a valid use of this operation.
309 A = Impossible;
310}
311
312void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
313 BugReporter &B,
314 bool hasWorkRemaining) {
315 // If there is any work remaining we cannot be 100% sure about our warnings
316 if (hasWorkRemaining)
317 return;
318
319 // Iterate over the hash to see if we have any paths with definite
320 // idempotent operations.
321 for (AssumptionMap::const_iterator i =
322 hash.begin(); i != hash.end(); ++i) {
323 if (i->second != Impossible) {
324 // Select the error message.
Chandler Carruth12080d42010-07-07 00:36:56 +0000325 const char *msg = 0;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000326 switch (i->second) {
327 case Equal:
328 msg = "idempotent operation; both operands are always equal in value";
329 break;
330 case LHSis1:
331 msg = "idempotent operation; the left operand is always 1";
332 break;
333 case RHSis1:
334 msg = "idempotent operation; the right operand is always 1";
335 break;
336 case LHSis0:
337 msg = "idempotent operation; the left operand is always 0";
338 break;
339 case RHSis0:
340 msg = "idempotent operation; the right operand is always 0";
341 break;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000342 case Possible:
Chandler Carruth256565b2010-07-07 00:07:37 +0000343 llvm_unreachable("Operation was never marked with an assumption");
Tom Care7dbf8182010-07-07 01:27:17 +0000344 case Impossible:
345 llvm_unreachable(0);
Tom Caredb2fa8a2010-07-06 21:43:29 +0000346 }
347
348 // Create the SourceRange Arrays
349 SourceRange S[2] = { i->first->getLHS()->getSourceRange(),
350 i->first->getRHS()->getSourceRange() };
Ted Kremenekb6986882010-07-27 17:52:52 +0000351 B.EmitBasicReport("Idempotent operation", "Dead code",
352 msg, i->first->getOperatorLoc(),
Tom Caredb2fa8a2010-07-06 21:43:29 +0000353 S, 2);
354 }
355 }
356}
357
358// Updates the current assumption given the new assumption
359inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
360 const Assumption &New) {
361 switch (A) {
362 // If we don't currently have an assumption, set it
363 case Possible:
364 A = New;
365 return;
366
367 // If we have determined that a valid state happened, ignore the new
368 // assumption.
369 case Impossible:
370 return;
371
372 // Any other case means that we had a different assumption last time. We don't
373 // currently support mixing assumptions for diagnostic reasons, so we set
374 // our assumption to be impossible.
375 default:
376 A = Impossible;
377 return;
378 }
379}
380
381// Recursively find any substatements containing macros
382bool IdempotentOperationChecker::containsMacro(const Stmt *S) {
383 if (S->getLocStart().isMacroID())
384 return true;
385
386 if (S->getLocEnd().isMacroID())
387 return true;
388
389 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
390 ++I)
391 if (const Stmt *child = *I)
392 if (containsMacro(child))
393 return true;
394
395 return false;
396}
397
398// Recursively find any substatements containing enum constants
399bool IdempotentOperationChecker::containsEnum(const Stmt *S) {
400 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
401
402 if (DR && isa<EnumConstantDecl>(DR->getDecl()))
403 return true;
404
405 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
406 ++I)
407 if (const Stmt *child = *I)
408 if (containsEnum(child))
409 return true;
410
411 return false;
412}
413
Tom Caredf4ca422010-07-16 20:41:41 +0000414// Recursively find any substatements containing static vars
415bool IdempotentOperationChecker::containsStaticLocal(const Stmt *S) {
416 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
417
418 if (DR)
419 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
420 if (VD->isStaticLocal())
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 (containsStaticLocal(child))
427 return true;
428
429 return false;
430}
431
432// Check for a statement were a parameter is self assigned (to avoid an unused
433// variable warning)
434bool IdempotentOperationChecker::isParameterSelfAssign(const Expr *LHS,
435 const Expr *RHS) {
436 LHS = LHS->IgnoreParenCasts();
437 RHS = RHS->IgnoreParenCasts();
438
439 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
440 if (!LHS_DR)
441 return false;
442
443 const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(LHS_DR->getDecl());
444 if (!PD)
445 return false;
446
447 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
448 if (!RHS_DR)
449 return false;
450
451 return PD == RHS_DR->getDecl();
452}
453
454// Check for self casts truncating/extending a variable
455bool IdempotentOperationChecker::isTruncationExtensionAssignment(
456 const Expr *LHS,
457 const Expr *RHS) {
458
459 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
460 if (!LHS_DR)
461 return false;
462
463 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
464 if (!VD)
465 return false;
466
467 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
468 if (!RHS_DR)
469 return false;
470
471 if (VD != RHS_DR->getDecl())
472 return false;
473
474 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
475}
476
477
Tom Caredb2fa8a2010-07-06 21:43:29 +0000478// Recursively find any substatements containing __builtin_offset_of
479bool IdempotentOperationChecker::containsBuiltinOffsetOf(const Stmt *S) {
480 const UnaryOperator *UO = dyn_cast<UnaryOperator>(S);
481
482 if (UO && UO->getOpcode() == UnaryOperator::OffsetOf)
483 return true;
484
485 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
486 ++I)
487 if (const Stmt *child = *I)
488 if (containsBuiltinOffsetOf(child))
489 return true;
490
491 return false;
492}
493
Tom Caredf4ca422010-07-16 20:41:41 +0000494// Check for a integer or float constant of 0
Tom Caredb2fa8a2010-07-06 21:43:29 +0000495bool IdempotentOperationChecker::containsZeroConstant(const Stmt *S) {
496 const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
497 if (IL && IL->getValue() == 0)
498 return true;
499
500 const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S);
501 if (FL && FL->getValue().isZero())
502 return true;
503
504 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
505 ++I)
506 if (const Stmt *child = *I)
507 if (containsZeroConstant(child))
508 return true;
509
510 return false;
511}
512
Tom Caredf4ca422010-07-16 20:41:41 +0000513// Check for an integer or float constant of 1
Tom Caredb2fa8a2010-07-06 21:43:29 +0000514bool IdempotentOperationChecker::containsOneConstant(const Stmt *S) {
515 const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(S);
516 if (IL && IL->getValue() == 1)
517 return true;
518
Ted Kremenek45329312010-07-17 00:40:32 +0000519 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(S)) {
520 const llvm::APFloat &val = FL->getValue();
521 const llvm::APFloat one(val.getSemantics(), 1);
522 if (val.compare(one) == llvm::APFloat::cmpEqual)
523 return true;
524 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000525
526 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
527 ++I)
528 if (const Stmt *child = *I)
529 if (containsOneConstant(child))
530 return true;
531
532 return false;
533}
534