blob: 2e85013a76898e357e38523625664886847b4142 [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 Care84c24ed2010-09-07 20:27:56 +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,
Tom Care84c24ed2010-09-07 20:27:56 +0000199 // and the assignment is not a truncation or extension, then it is a false
200 // positive.
Tom Care6216dc02010-08-30 19:25:43 +0000201 if (isSelfAssign(LHS, RHS)) {
Tom Care84c24ed2010-09-07 20:27:56 +0000202 if (!isUnused(LHS, AC) && !isTruncationExtensionAssignment(LHS, RHS)) {
Tom Care6216dc02010-08-30 19:25:43 +0000203 UpdateAssumption(A, Equal);
204 return;
205 }
206 else {
207 A = Impossible;
208 return;
209 }
Tom Caredf4ca422010-07-16 20:41:41 +0000210 }
211
John McCall2de56d12010-08-25 11:45:40 +0000212 case BO_SubAssign:
213 case BO_DivAssign:
214 case BO_AndAssign:
215 case BO_OrAssign:
216 case BO_XorAssign:
217 case BO_Sub:
218 case BO_Div:
219 case BO_And:
220 case BO_Or:
221 case BO_Xor:
222 case BO_LOr:
223 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000224 case BO_EQ:
225 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000226 if (LHSVal != RHSVal || LHSContainsFalsePositive
227 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000228 break;
229 UpdateAssumption(A, Equal);
230 return;
231 }
232
233 // x op 1
234 switch (Op) {
235 default:
236 break; // We don't care about any other operators.
237
238 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000239 case BO_MulAssign:
240 case BO_DivAssign:
241 case BO_Mul:
242 case BO_Div:
243 case BO_LOr:
244 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000245 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000246 break;
247 UpdateAssumption(A, RHSis1);
248 return;
249 }
250
251 // 1 op x
252 switch (Op) {
253 default:
254 break; // We don't care about any other operators.
255
256 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000257 case BO_MulAssign:
258 case BO_Mul:
259 case BO_LOr:
260 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000261 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000262 break;
263 UpdateAssumption(A, LHSis1);
264 return;
265 }
266
267 // x op 0
268 switch (Op) {
269 default:
270 break; // We don't care about any other operators.
271
272 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000273 case BO_AddAssign:
274 case BO_SubAssign:
275 case BO_MulAssign:
276 case BO_AndAssign:
277 case BO_OrAssign:
278 case BO_XorAssign:
279 case BO_Add:
280 case BO_Sub:
281 case BO_Mul:
282 case BO_And:
283 case BO_Or:
284 case BO_Xor:
285 case BO_Shl:
286 case BO_Shr:
287 case BO_LOr:
288 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000289 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000290 break;
291 UpdateAssumption(A, RHSis0);
292 return;
293 }
294
295 // 0 op x
296 switch (Op) {
297 default:
298 break; // We don't care about any other operators.
299
300 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000301 //case BO_AddAssign: // Common false positive
302 case BO_SubAssign: // Check only if unsigned
303 case BO_MulAssign:
304 case BO_DivAssign:
305 case BO_AndAssign:
306 //case BO_OrAssign: // Common false positive
307 //case BO_XorAssign: // Common false positive
308 case BO_ShlAssign:
309 case BO_ShrAssign:
310 case BO_Add:
311 case BO_Sub:
312 case BO_Mul:
313 case BO_Div:
314 case BO_And:
315 case BO_Or:
316 case BO_Xor:
317 case BO_Shl:
318 case BO_Shr:
319 case BO_LOr:
320 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000321 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000322 break;
323 UpdateAssumption(A, LHSis0);
324 return;
325 }
326
327 // If we get to this point, there has been a valid use of this operation.
328 A = Impossible;
329}
330
Tom Care2bbbe502010-09-02 23:30:22 +0000331// At the post visit stage, the predecessor ExplodedNode will be the
332// BinaryOperator that was just created. We use this hook to collect the
333// ExplodedNode.
334void IdempotentOperationChecker::PostVisitBinaryOperator(
335 CheckerContext &C,
336 const BinaryOperator *B) {
337 // Add the ExplodedNode we just visited
338 BinaryOperatorData &Data = hash[B];
339 Data.explodedNodes.Add(C.getPredecessor());
340}
341
Tom Caredb2fa8a2010-07-06 21:43:29 +0000342void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000343 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000344 GRExprEngine &Eng) {
Tom Care2bbbe502010-09-02 23:30:22 +0000345 BugType *BT = new BugType("Idempotent operation", "Dead code");
Tom Caredb2fa8a2010-07-06 21:43:29 +0000346 // Iterate over the hash to see if we have any paths with definite
347 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000348 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
349 // Unpack the hash contents
Tom Care2bbbe502010-09-02 23:30:22 +0000350 const BinaryOperatorData &Data = i->second;
351 const Assumption &A = Data.assumption;
352 AnalysisContext *AC = Data.analysisContext;
353 const ExplodedNodeSet &ES = Data.explodedNodes;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000354
Tom Carea7a8a452010-08-12 22:45:47 +0000355 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000356
Tom Carea7a8a452010-08-12 22:45:47 +0000357 if (A == Impossible)
358 continue;
359
360 // If the analyzer did not finish, check to see if we can still emit this
361 // warning
362 if (Eng.hasWorkRemaining()) {
363 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
364 &AC->getParentMap());
365
366 // If we can trace back
367 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
368 CBM->getBlock(B),
369 Eng.getCoreEngine()))
370 continue;
371
372 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000373 }
Tom Carea7a8a452010-08-12 22:45:47 +0000374
Tom Care2bbbe502010-09-02 23:30:22 +0000375 // Select the error message and SourceRanges to report.
Tom Carea7a8a452010-08-12 22:45:47 +0000376 llvm::SmallString<128> buf;
377 llvm::raw_svector_ostream os(buf);
Tom Care2bbbe502010-09-02 23:30:22 +0000378 bool LHSRelevant = false, RHSRelevant = false;
Tom Carea7a8a452010-08-12 22:45:47 +0000379 switch (A) {
380 case Equal:
Tom Care2bbbe502010-09-02 23:30:22 +0000381 LHSRelevant = true;
382 RHSRelevant = true;
John McCall2de56d12010-08-25 11:45:40 +0000383 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000384 os << "Assigned value is always the same as the existing value";
385 else
386 os << "Both operands to '" << B->getOpcodeStr()
387 << "' always have the same value";
388 break;
389 case LHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000390 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000391 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
392 break;
393 case RHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000394 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000395 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
396 break;
397 case LHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000398 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000399 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
400 break;
401 case RHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000402 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000403 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
404 break;
405 case Possible:
406 llvm_unreachable("Operation was never marked with an assumption");
407 case Impossible:
408 llvm_unreachable(0);
409 }
410
Tom Care2bbbe502010-09-02 23:30:22 +0000411 // Add a report for each ExplodedNode
412 for (ExplodedNodeSet::iterator I = ES.begin(), E = ES.end(); I != E; ++I) {
413 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), *I);
414
415 // Add source ranges and visitor hooks
416 if (LHSRelevant) {
417 const Expr *LHS = i->first->getLHS();
418 report->addRange(LHS->getSourceRange());
419 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, LHS);
420 }
421 if (RHSRelevant) {
422 const Expr *RHS = i->first->getRHS();
423 report->addRange(i->first->getRHS()->getSourceRange());
424 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, RHS);
425 }
426
427 BR.EmitReport(report);
428 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000429 }
430}
431
432// Updates the current assumption given the new assumption
433inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
434 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000435// If the assumption is the same, there is nothing to do
436 if (A == New)
437 return;
438
Tom Caredb2fa8a2010-07-06 21:43:29 +0000439 switch (A) {
440 // If we don't currently have an assumption, set it
441 case Possible:
442 A = New;
443 return;
444
445 // If we have determined that a valid state happened, ignore the new
446 // assumption.
447 case Impossible:
448 return;
449
450 // Any other case means that we had a different assumption last time. We don't
451 // currently support mixing assumptions for diagnostic reasons, so we set
452 // our assumption to be impossible.
453 default:
454 A = Impossible;
455 return;
456 }
457}
458
Tom Care6216dc02010-08-30 19:25:43 +0000459// Check for a statement where a variable is self assigned to possibly avoid an
460// unused variable warning.
461bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000462 LHS = LHS->IgnoreParenCasts();
463 RHS = RHS->IgnoreParenCasts();
464
465 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
466 if (!LHS_DR)
467 return false;
468
Tom Careef52bcb2010-08-24 21:09:07 +0000469 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
470 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000471 return false;
472
473 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
474 if (!RHS_DR)
475 return false;
476
Tom Careef52bcb2010-08-24 21:09:07 +0000477 if (VD != RHS_DR->getDecl())
478 return false;
479
Tom Care6216dc02010-08-30 19:25:43 +0000480 return true;
481}
482
483// Returns true if the Expr points to a VarDecl that is not read anywhere
484// outside of self-assignments.
485bool IdempotentOperationChecker::isUnused(const Expr *E,
486 AnalysisContext *AC) {
487 if (!E)
488 return false;
489
490 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
491 if (!DR)
492 return false;
493
494 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
495 if (!VD)
496 return false;
497
Tom Careef52bcb2010-08-24 21:09:07 +0000498 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
499 return false;
500
501 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000502}
503
504// Check for self casts truncating/extending a variable
505bool IdempotentOperationChecker::isTruncationExtensionAssignment(
506 const Expr *LHS,
507 const Expr *RHS) {
508
509 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
510 if (!LHS_DR)
511 return false;
512
513 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
514 if (!VD)
515 return false;
516
517 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
518 if (!RHS_DR)
519 return false;
520
521 if (VD != RHS_DR->getDecl())
522 return false;
523
524 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
525}
526
Tom Carea7a8a452010-08-12 22:45:47 +0000527// Returns false if a path to this block was not completely analyzed, or true
528// otherwise.
529bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
530 const CFG *C,
531 const CFGBlock *CB,
532 const GRCoreEngine &CE) {
533 std::deque<const CFGBlock *> WorkList;
534 llvm::SmallSet<unsigned, 8> Aborted;
535 llvm::SmallSet<unsigned, 128> Visited;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000536
Tom Carea7a8a452010-08-12 22:45:47 +0000537 // Create a set of all aborted blocks
538 typedef GRCoreEngine::BlocksAborted::const_iterator AbortedIterator;
539 for (AbortedIterator I = CE.blocks_aborted_begin(),
540 E = CE.blocks_aborted_end(); I != E; ++I) {
541 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000542
Tom Carea7a8a452010-08-12 22:45:47 +0000543 // The destination block on the BlockEdge is the first block that was not
544 // analyzed.
545 Aborted.insert(BE.getDst()->getBlockID());
Ted Kremenek45329312010-07-17 00:40:32 +0000546 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000547
Tom Carea7a8a452010-08-12 22:45:47 +0000548 // Save the entry block ID for early exiting
549 unsigned EntryBlockID = C->getEntry().getBlockID();
Tom Caredb2fa8a2010-07-06 21:43:29 +0000550
Tom Carea7a8a452010-08-12 22:45:47 +0000551 // Create initial node
552 WorkList.push_back(CB);
553
554 while (!WorkList.empty()) {
555 const CFGBlock *Head = WorkList.front();
556 WorkList.pop_front();
557 Visited.insert(Head->getBlockID());
558
559 // If we found the entry block, then there exists a path from the target
560 // node to the entry point of this function -> the path was completely
561 // analyzed.
562 if (Head->getBlockID() == EntryBlockID)
563 return true;
564
565 // If any of the aborted blocks are on the path to the beginning, then all
566 // paths to this block were not analyzed.
567 if (Aborted.count(Head->getBlockID()))
568 return false;
569
570 // Add the predecessors to the worklist unless we have already visited them
571 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
572 I != Head->pred_end(); ++I)
573 if (!Visited.count((*I)->getBlockID()))
574 WorkList.push_back(*I);
575 }
576
577 // If we get to this point, there is no connection to the entry block or an
578 // aborted block. This path is unreachable and we can report the error.
579 return true;
580}
581
582// Recursive function that determines whether an expression contains any element
583// that varies. This could be due to a compile-time constant like sizeof. An
584// expression may also involve a variable that behaves like a constant. The
585// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000586bool IdempotentOperationChecker::CanVary(const Expr *Ex,
587 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000588 // Parentheses and casts are irrelevant here
589 Ex = Ex->IgnoreParenCasts();
590
591 if (Ex->getLocStart().isMacroID())
592 return false;
593
594 switch (Ex->getStmtClass()) {
595 // Trivially true cases
596 case Stmt::ArraySubscriptExprClass:
597 case Stmt::MemberExprClass:
598 case Stmt::StmtExprClass:
599 case Stmt::CallExprClass:
600 case Stmt::VAArgExprClass:
601 case Stmt::ShuffleVectorExprClass:
602 return true;
603 default:
604 return true;
605
606 // Trivially false cases
607 case Stmt::IntegerLiteralClass:
608 case Stmt::CharacterLiteralClass:
609 case Stmt::FloatingLiteralClass:
610 case Stmt::PredefinedExprClass:
611 case Stmt::ImaginaryLiteralClass:
612 case Stmt::StringLiteralClass:
613 case Stmt::OffsetOfExprClass:
614 case Stmt::CompoundLiteralExprClass:
615 case Stmt::AddrLabelExprClass:
616 case Stmt::TypesCompatibleExprClass:
617 case Stmt::GNUNullExprClass:
618 case Stmt::InitListExprClass:
619 case Stmt::DesignatedInitExprClass:
620 case Stmt::BlockExprClass:
621 case Stmt::BlockDeclRefExprClass:
622 return false;
623
624 // Cases requiring custom logic
625 case Stmt::SizeOfAlignOfExprClass: {
626 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
627 if (!SE->isSizeOf())
628 return false;
629 return SE->getTypeOfArgument()->isVariableArrayType();
630 }
631 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000632 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000633 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000634
635 // The next cases require recursion for subexpressions
636 case Stmt::BinaryOperatorClass: {
637 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Tom Care245adab2010-08-18 21:17:24 +0000638 return CanVary(B->getRHS(), AC)
639 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000640 }
641 case Stmt::UnaryOperatorClass: {
642 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000643 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000644 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000645 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000646 return false;
647 default:
Tom Care245adab2010-08-18 21:17:24 +0000648 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000649 }
650 }
651 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000652 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
653 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000654 case Stmt::ConditionalOperatorClass:
Tom Care6216dc02010-08-30 19:25:43 +0000655 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000656 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000657}
658
Tom Care245adab2010-08-18 21:17:24 +0000659// Returns true if a DeclRefExpr is or behaves like a constant.
660bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000661 const DeclRefExpr *DR,
662 AnalysisContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000663 // Check if the type of the Decl is const-qualified
664 if (DR->getType().isConstQualified())
665 return true;
666
Tom Care50e8ac22010-08-16 21:43:52 +0000667 // Check for an enum
668 if (isa<EnumConstantDecl>(DR->getDecl()))
669 return true;
670
Tom Caredb34ab72010-08-23 19:51:57 +0000671 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
672 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000673 return true;
674
Tom Caredb34ab72010-08-23 19:51:57 +0000675 // Check if the Decl behaves like a constant. This check also takes care of
676 // static variables, which can only change between function calls if they are
677 // modified in the AST.
678 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
679 if (PCA->isPseudoConstant(VD))
680 return true;
681
682 return false;
683}
684
685// Recursively find any substatements containing VarDecl's with storage other
686// than local
687bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
688 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
689
690 if (DR)
691 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
692 if (!VD->hasLocalStorage())
693 return true;
694
695 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
696 ++I)
697 if (const Stmt *child = *I)
698 if (containsNonLocalVarDecl(child))
699 return true;
700
Tom Care50e8ac22010-08-16 21:43:52 +0000701 return false;
702}