blob: fbf25ba4a81d5e71e0da18c9e59651bf1a679d2b [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> {
Tom Careb0627952010-09-09 02:04:52 +000065public:
66 static void *getTag();
67 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
68 void PostVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
69 void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B, GRExprEngine &Eng);
70
71private:
72 // Our assumption about a particular operation.
73 enum Assumption { Possible = 0, Impossible, Equal, LHSis1, RHSis1, LHSis0,
74 RHSis0 };
75
76 void UpdateAssumption(Assumption &A, const Assumption &New);
77
78 // False positive reduction methods
79 static bool isSelfAssign(const Expr *LHS, const Expr *RHS);
80 static bool isUnused(const Expr *E, AnalysisContext *AC);
81 static bool isTruncationExtensionAssignment(const Expr *LHS,
82 const Expr *RHS);
83 bool PathWasCompletelyAnalyzed(const CFG *C,
84 const CFGBlock *CB,
Ted Kremenek33d46262010-11-13 05:04:52 +000085 const CFGStmtMap *CBM,
Tom Careb0627952010-09-09 02:04:52 +000086 const GRCoreEngine &CE);
87 static bool CanVary(const Expr *Ex,
88 AnalysisContext *AC);
89 static bool isConstantOrPseudoConstant(const DeclRefExpr *DR,
90 AnalysisContext *AC);
91 static bool containsNonLocalVarDecl(const Stmt *S);
92 const ExplodedNodeSet getLastRelevantNodes(const CFGBlock *Begin,
93 const ExplodedNode *N);
94
95 // Hash table and related data structures
96 struct BinaryOperatorData {
97 BinaryOperatorData() : assumption(Possible), analysisContext(0) {}
98
99 Assumption assumption;
100 AnalysisContext *analysisContext;
101 ExplodedNodeSet explodedNodes; // Set of ExplodedNodes that refer to a
102 // BinaryOperator
103 };
104 typedef llvm::DenseMap<const BinaryOperator *, BinaryOperatorData>
105 AssumptionMap;
106 AssumptionMap hash;
107
108 // A class that performs reachability queries for CFGBlocks. Several internal
109 // checks in this checker require reachability information. The requests all
110 // tend to have a common destination, so we lazily do a predecessor search
111 // from the destination node and cache the results to prevent work
112 // duplication.
113 class CFGReachabilityAnalysis {
114 typedef llvm::SmallSet<unsigned, 32> ReachableSet;
115 typedef llvm::DenseMap<unsigned, ReachableSet> ReachableMap;
116 ReachableSet analyzed;
117 ReachableMap reachable;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000118 public:
Tom Careb0627952010-09-09 02:04:52 +0000119 inline bool isReachable(const CFGBlock *Src, const CFGBlock *Dst);
Tom Caredb2fa8a2010-07-06 21:43:29 +0000120 private:
Tom Careb0627952010-09-09 02:04:52 +0000121 void MapReachability(const CFGBlock *Dst);
122 };
123 CFGReachabilityAnalysis CRA;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000124};
125}
126
127void *IdempotentOperationChecker::getTag() {
128 static int x = 0;
129 return &x;
130}
131
132void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
133 Eng.registerCheck(new IdempotentOperationChecker());
134}
135
136void IdempotentOperationChecker::PreVisitBinaryOperator(
137 CheckerContext &C,
138 const BinaryOperator *B) {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000139 // Find or create an entry in the hash for this BinaryOperator instance.
140 // If we haven't done a lookup before, it will get default initialized to
Tom Care2bbbe502010-09-02 23:30:22 +0000141 // 'Possible'. At this stage we do not store the ExplodedNode, as it has not
142 // been created yet.
143 BinaryOperatorData &Data = hash[B];
144 Assumption &A = Data.assumption;
Tom Care245adab2010-08-18 21:17:24 +0000145 AnalysisContext *AC = C.getCurrentAnalysisContext();
Tom Care2bbbe502010-09-02 23:30:22 +0000146 Data.analysisContext = AC;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000147
148 // If we already have visited this node on a path that does not contain an
149 // idempotent operation, return immediately.
150 if (A == Impossible)
151 return;
152
Tom Carea7a8a452010-08-12 22:45:47 +0000153 // Retrieve both sides of the operator and determine if they can vary (which
154 // may mean this is a false positive.
Tom Caredb2fa8a2010-07-06 21:43:29 +0000155 const Expr *LHS = B->getLHS();
156 const Expr *RHS = B->getRHS();
Tom Care245adab2010-08-18 21:17:24 +0000157
Tom Caredb34ab72010-08-23 19:51:57 +0000158 // At this stage we can calculate whether each side contains a false positive
159 // that applies to all operators. We only need to calculate this the first
160 // time.
161 bool LHSContainsFalsePositive = false, RHSContainsFalsePositive = false;
Tom Care245adab2010-08-18 21:17:24 +0000162 if (A == Possible) {
Tom Caredb34ab72010-08-23 19:51:57 +0000163 // An expression contains a false positive if it can't vary, or if it
164 // contains a known false positive VarDecl.
165 LHSContainsFalsePositive = !CanVary(LHS, AC)
166 || containsNonLocalVarDecl(LHS);
167 RHSContainsFalsePositive = !CanVary(RHS, AC)
168 || containsNonLocalVarDecl(RHS);
Tom Care245adab2010-08-18 21:17:24 +0000169 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000170
171 const GRState *state = C.getState();
172
173 SVal LHSVal = state->getSVal(LHS);
174 SVal RHSVal = state->getSVal(RHS);
175
176 // If either value is unknown, we can't be 100% sure of all paths.
177 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
178 A = Impossible;
179 return;
180 }
181 BinaryOperator::Opcode Op = B->getOpcode();
182
183 // Dereference the LHS SVal if this is an assign operation
184 switch (Op) {
185 default:
186 break;
187
188 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000189 case BO_AddAssign:
190 case BO_SubAssign:
191 case BO_MulAssign:
192 case BO_DivAssign:
193 case BO_AndAssign:
194 case BO_OrAssign:
195 case BO_XorAssign:
196 case BO_ShlAssign:
197 case BO_ShrAssign:
198 case BO_Assign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000199 // Assign statements have one extra level of indirection
200 if (!isa<Loc>(LHSVal)) {
201 A = Impossible;
202 return;
203 }
Ted Kremenek96ebad62010-09-09 07:13:00 +0000204 LHSVal = state->getSVal(cast<Loc>(LHSVal), LHS->getType());
Tom Caredb2fa8a2010-07-06 21:43:29 +0000205 }
206
207
208 // We now check for various cases which result in an idempotent operation.
209
210 // x op x
211 switch (Op) {
212 default:
213 break; // We don't care about any other operators.
214
215 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000216 case BO_Assign:
Tom Care6216dc02010-08-30 19:25:43 +0000217 // x Assign x can be used to silence unused variable warnings intentionally.
218 // If this is a self assignment and the variable is referenced elsewhere,
Tom Care84c24ed2010-09-07 20:27:56 +0000219 // and the assignment is not a truncation or extension, then it is a false
220 // positive.
Tom Care6216dc02010-08-30 19:25:43 +0000221 if (isSelfAssign(LHS, RHS)) {
Tom Care84c24ed2010-09-07 20:27:56 +0000222 if (!isUnused(LHS, AC) && !isTruncationExtensionAssignment(LHS, RHS)) {
Tom Care6216dc02010-08-30 19:25:43 +0000223 UpdateAssumption(A, Equal);
224 return;
225 }
226 else {
227 A = Impossible;
228 return;
229 }
Tom Caredf4ca422010-07-16 20:41:41 +0000230 }
231
John McCall2de56d12010-08-25 11:45:40 +0000232 case BO_SubAssign:
233 case BO_DivAssign:
234 case BO_AndAssign:
235 case BO_OrAssign:
236 case BO_XorAssign:
237 case BO_Sub:
238 case BO_Div:
239 case BO_And:
240 case BO_Or:
241 case BO_Xor:
242 case BO_LOr:
243 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000244 case BO_EQ:
245 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000246 if (LHSVal != RHSVal || LHSContainsFalsePositive
247 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000248 break;
249 UpdateAssumption(A, Equal);
250 return;
251 }
252
253 // x op 1
254 switch (Op) {
255 default:
256 break; // We don't care about any other operators.
257
258 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000259 case BO_MulAssign:
260 case BO_DivAssign:
261 case BO_Mul:
262 case BO_Div:
263 case BO_LOr:
264 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000265 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000266 break;
267 UpdateAssumption(A, RHSis1);
268 return;
269 }
270
271 // 1 op x
272 switch (Op) {
273 default:
274 break; // We don't care about any other operators.
275
276 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000277 case BO_MulAssign:
278 case BO_Mul:
279 case BO_LOr:
280 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000281 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000282 break;
283 UpdateAssumption(A, LHSis1);
284 return;
285 }
286
287 // x op 0
288 switch (Op) {
289 default:
290 break; // We don't care about any other operators.
291
292 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000293 case BO_AddAssign:
294 case BO_SubAssign:
295 case BO_MulAssign:
296 case BO_AndAssign:
297 case BO_OrAssign:
298 case BO_XorAssign:
299 case BO_Add:
300 case BO_Sub:
301 case BO_Mul:
302 case BO_And:
303 case BO_Or:
304 case BO_Xor:
305 case BO_Shl:
306 case BO_Shr:
307 case BO_LOr:
308 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000309 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000310 break;
311 UpdateAssumption(A, RHSis0);
312 return;
313 }
314
315 // 0 op x
316 switch (Op) {
317 default:
318 break; // We don't care about any other operators.
319
320 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000321 //case BO_AddAssign: // Common false positive
322 case BO_SubAssign: // Check only if unsigned
323 case BO_MulAssign:
324 case BO_DivAssign:
325 case BO_AndAssign:
326 //case BO_OrAssign: // Common false positive
327 //case BO_XorAssign: // Common false positive
328 case BO_ShlAssign:
329 case BO_ShrAssign:
330 case BO_Add:
331 case BO_Sub:
332 case BO_Mul:
333 case BO_Div:
334 case BO_And:
335 case BO_Or:
336 case BO_Xor:
337 case BO_Shl:
338 case BO_Shr:
339 case BO_LOr:
340 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000341 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000342 break;
343 UpdateAssumption(A, LHSis0);
344 return;
345 }
346
347 // If we get to this point, there has been a valid use of this operation.
348 A = Impossible;
349}
350
Tom Care2bbbe502010-09-02 23:30:22 +0000351// At the post visit stage, the predecessor ExplodedNode will be the
352// BinaryOperator that was just created. We use this hook to collect the
353// ExplodedNode.
354void IdempotentOperationChecker::PostVisitBinaryOperator(
355 CheckerContext &C,
356 const BinaryOperator *B) {
357 // Add the ExplodedNode we just visited
358 BinaryOperatorData &Data = hash[B];
Ted Kremenek96ebad62010-09-09 07:13:00 +0000359 assert(isa<BinaryOperator>(cast<StmtPoint>(C.getPredecessor()
360 ->getLocation()).getStmt()));
Tom Care2bbbe502010-09-02 23:30:22 +0000361 Data.explodedNodes.Add(C.getPredecessor());
362}
363
Tom Caredb2fa8a2010-07-06 21:43:29 +0000364void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000365 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000366 GRExprEngine &Eng) {
Tom Care2bbbe502010-09-02 23:30:22 +0000367 BugType *BT = new BugType("Idempotent operation", "Dead code");
Tom Caredb2fa8a2010-07-06 21:43:29 +0000368 // Iterate over the hash to see if we have any paths with definite
369 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000370 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
371 // Unpack the hash contents
Tom Care2bbbe502010-09-02 23:30:22 +0000372 const BinaryOperatorData &Data = i->second;
373 const Assumption &A = Data.assumption;
374 AnalysisContext *AC = Data.analysisContext;
375 const ExplodedNodeSet &ES = Data.explodedNodes;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000376
Tom Carea7a8a452010-08-12 22:45:47 +0000377 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000378
Tom Carea7a8a452010-08-12 22:45:47 +0000379 if (A == Impossible)
380 continue;
381
382 // If the analyzer did not finish, check to see if we can still emit this
383 // warning
384 if (Eng.hasWorkRemaining()) {
385 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
386 &AC->getParentMap());
387
388 // If we can trace back
389 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
Ted Kremenek33d46262010-11-13 05:04:52 +0000390 CBM->getBlock(B), CBM,
Tom Carea7a8a452010-08-12 22:45:47 +0000391 Eng.getCoreEngine()))
392 continue;
393
394 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000395 }
Tom Carea7a8a452010-08-12 22:45:47 +0000396
Tom Care2bbbe502010-09-02 23:30:22 +0000397 // Select the error message and SourceRanges to report.
Tom Carea7a8a452010-08-12 22:45:47 +0000398 llvm::SmallString<128> buf;
399 llvm::raw_svector_ostream os(buf);
Tom Care2bbbe502010-09-02 23:30:22 +0000400 bool LHSRelevant = false, RHSRelevant = false;
Tom Carea7a8a452010-08-12 22:45:47 +0000401 switch (A) {
402 case Equal:
Tom Care2bbbe502010-09-02 23:30:22 +0000403 LHSRelevant = true;
404 RHSRelevant = true;
John McCall2de56d12010-08-25 11:45:40 +0000405 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000406 os << "Assigned value is always the same as the existing value";
407 else
408 os << "Both operands to '" << B->getOpcodeStr()
409 << "' always have the same value";
410 break;
411 case LHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000412 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000413 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
414 break;
415 case RHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000416 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000417 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
418 break;
419 case LHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000420 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000421 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
422 break;
423 case RHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000424 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000425 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
426 break;
427 case Possible:
428 llvm_unreachable("Operation was never marked with an assumption");
429 case Impossible:
430 llvm_unreachable(0);
431 }
432
Tom Care2bbbe502010-09-02 23:30:22 +0000433 // Add a report for each ExplodedNode
434 for (ExplodedNodeSet::iterator I = ES.begin(), E = ES.end(); I != E; ++I) {
435 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), *I);
436
437 // Add source ranges and visitor hooks
438 if (LHSRelevant) {
439 const Expr *LHS = i->first->getLHS();
440 report->addRange(LHS->getSourceRange());
441 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, LHS);
442 }
443 if (RHSRelevant) {
444 const Expr *RHS = i->first->getRHS();
445 report->addRange(i->first->getRHS()->getSourceRange());
446 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, RHS);
447 }
448
449 BR.EmitReport(report);
450 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000451 }
452}
453
454// Updates the current assumption given the new assumption
455inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
456 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000457// If the assumption is the same, there is nothing to do
458 if (A == New)
459 return;
460
Tom Caredb2fa8a2010-07-06 21:43:29 +0000461 switch (A) {
462 // If we don't currently have an assumption, set it
463 case Possible:
464 A = New;
465 return;
466
467 // If we have determined that a valid state happened, ignore the new
468 // assumption.
469 case Impossible:
470 return;
471
472 // Any other case means that we had a different assumption last time. We don't
473 // currently support mixing assumptions for diagnostic reasons, so we set
474 // our assumption to be impossible.
475 default:
476 A = Impossible;
477 return;
478 }
479}
480
Tom Care6216dc02010-08-30 19:25:43 +0000481// Check for a statement where a variable is self assigned to possibly avoid an
482// unused variable warning.
483bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000484 LHS = LHS->IgnoreParenCasts();
485 RHS = RHS->IgnoreParenCasts();
486
487 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
488 if (!LHS_DR)
489 return false;
490
Tom Careef52bcb2010-08-24 21:09:07 +0000491 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
492 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000493 return false;
494
495 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
496 if (!RHS_DR)
497 return false;
498
Tom Careef52bcb2010-08-24 21:09:07 +0000499 if (VD != RHS_DR->getDecl())
500 return false;
501
Tom Care6216dc02010-08-30 19:25:43 +0000502 return true;
503}
504
505// Returns true if the Expr points to a VarDecl that is not read anywhere
506// outside of self-assignments.
507bool IdempotentOperationChecker::isUnused(const Expr *E,
508 AnalysisContext *AC) {
509 if (!E)
510 return false;
511
512 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
513 if (!DR)
514 return false;
515
516 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
517 if (!VD)
518 return false;
519
Tom Careef52bcb2010-08-24 21:09:07 +0000520 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
521 return false;
522
523 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000524}
525
526// Check for self casts truncating/extending a variable
527bool IdempotentOperationChecker::isTruncationExtensionAssignment(
528 const Expr *LHS,
529 const Expr *RHS) {
530
531 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
532 if (!LHS_DR)
533 return false;
534
535 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
536 if (!VD)
537 return false;
538
539 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
540 if (!RHS_DR)
541 return false;
542
543 if (VD != RHS_DR->getDecl())
544 return false;
545
John McCallf6a16482010-12-04 03:47:34 +0000546 return dyn_cast<DeclRefExpr>(RHS->IgnoreParenLValueCasts()) == NULL;
Tom Caredf4ca422010-07-16 20:41:41 +0000547}
548
Tom Carea7a8a452010-08-12 22:45:47 +0000549// Returns false if a path to this block was not completely analyzed, or true
550// otherwise.
551bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
552 const CFG *C,
553 const CFGBlock *CB,
Ted Kremenek33d46262010-11-13 05:04:52 +0000554 const CFGStmtMap *CBM,
Tom Carea7a8a452010-08-12 22:45:47 +0000555 const GRCoreEngine &CE) {
Tom Careb0627952010-09-09 02:04:52 +0000556 // Test for reachability from any aborted blocks to this block
Tom Carea7a8a452010-08-12 22:45:47 +0000557 typedef GRCoreEngine::BlocksAborted::const_iterator AbortedIterator;
558 for (AbortedIterator I = CE.blocks_aborted_begin(),
559 E = CE.blocks_aborted_end(); I != E; ++I) {
560 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000561
Tom Carea7a8a452010-08-12 22:45:47 +0000562 // The destination block on the BlockEdge is the first block that was not
Tom Careb0627952010-09-09 02:04:52 +0000563 // analyzed. If we can reach this block from the aborted block, then this
564 // block was not completely analyzed.
565 if (CRA.isReachable(BE.getDst(), CB))
Tom Carea7a8a452010-08-12 22:45:47 +0000566 return false;
Tom Carea7a8a452010-08-12 22:45:47 +0000567 }
Ted Kremenek33d46262010-11-13 05:04:52 +0000568
569 // For the items still on the worklist, see if they are in blocks that
570 // can eventually reach 'CB'.
571 class VisitWL : public GRWorkList::Visitor {
572 const CFGStmtMap *CBM;
573 const CFGBlock *TargetBlock;
574 CFGReachabilityAnalysis &CRA;
575 public:
576 VisitWL(const CFGStmtMap *cbm, const CFGBlock *targetBlock,
577 CFGReachabilityAnalysis &cra)
578 : CBM(cbm), TargetBlock(targetBlock), CRA(cra) {}
579 virtual bool Visit(const GRWorkListUnit &U) {
580 ProgramPoint P = U.getNode()->getLocation();
581 const CFGBlock *B = 0;
582 if (StmtPoint *SP = dyn_cast<StmtPoint>(&P)) {
583 B = CBM->getBlock(SP->getStmt());
584 }
Ted Kremeneked023662010-11-13 05:12:26 +0000585 else if (BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
586 B = BE->getDst();
587 }
588 else if (BlockEntrance *BEnt = dyn_cast<BlockEntrance>(&P)) {
589 B = BEnt->getBlock();
590 }
591 else if (BlockExit *BExit = dyn_cast<BlockExit>(&P)) {
592 B = BExit->getBlock();
593 }
Ted Kremenek33d46262010-11-13 05:04:52 +0000594 if (!B)
595 return true;
596
597 return CRA.isReachable(B, TargetBlock);
598 }
599 };
600 VisitWL visitWL(CBM, CB, CRA);
601 // Were there any items in the worklist that could potentially reach
602 // this block?
603 if (CE.getWorkList()->VisitItemsInWorkList(visitWL))
604 return false;
Tom Carea7a8a452010-08-12 22:45:47 +0000605
Tom Careb0627952010-09-09 02:04:52 +0000606 // Verify that this block is reachable from the entry block
607 if (!CRA.isReachable(&C->getEntry(), CB))
608 return false;
609
Tom Carea7a8a452010-08-12 22:45:47 +0000610 // If we get to this point, there is no connection to the entry block or an
611 // aborted block. This path is unreachable and we can report the error.
612 return true;
613}
614
615// Recursive function that determines whether an expression contains any element
616// that varies. This could be due to a compile-time constant like sizeof. An
617// expression may also involve a variable that behaves like a constant. The
618// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000619bool IdempotentOperationChecker::CanVary(const Expr *Ex,
620 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000621 // Parentheses and casts are irrelevant here
622 Ex = Ex->IgnoreParenCasts();
623
624 if (Ex->getLocStart().isMacroID())
625 return false;
626
627 switch (Ex->getStmtClass()) {
628 // Trivially true cases
629 case Stmt::ArraySubscriptExprClass:
630 case Stmt::MemberExprClass:
631 case Stmt::StmtExprClass:
632 case Stmt::CallExprClass:
633 case Stmt::VAArgExprClass:
634 case Stmt::ShuffleVectorExprClass:
635 return true;
636 default:
637 return true;
638
639 // Trivially false cases
640 case Stmt::IntegerLiteralClass:
641 case Stmt::CharacterLiteralClass:
642 case Stmt::FloatingLiteralClass:
643 case Stmt::PredefinedExprClass:
644 case Stmt::ImaginaryLiteralClass:
645 case Stmt::StringLiteralClass:
646 case Stmt::OffsetOfExprClass:
647 case Stmt::CompoundLiteralExprClass:
648 case Stmt::AddrLabelExprClass:
Francois Pichetf1872372010-12-08 22:35:30 +0000649 case Stmt::BinaryTypeTraitExprClass:
Tom Carea7a8a452010-08-12 22:45:47 +0000650 case Stmt::GNUNullExprClass:
651 case Stmt::InitListExprClass:
652 case Stmt::DesignatedInitExprClass:
653 case Stmt::BlockExprClass:
654 case Stmt::BlockDeclRefExprClass:
655 return false;
656
657 // Cases requiring custom logic
658 case Stmt::SizeOfAlignOfExprClass: {
659 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
660 if (!SE->isSizeOf())
661 return false;
662 return SE->getTypeOfArgument()->isVariableArrayType();
663 }
664 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000665 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000666 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000667
668 // The next cases require recursion for subexpressions
669 case Stmt::BinaryOperatorClass: {
670 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Ted Kremenek74faec22010-10-29 01:06:54 +0000671
672 // Exclude cases involving pointer arithmetic. These are usually
673 // false positives.
674 if (B->getOpcode() == BO_Sub || B->getOpcode() == BO_Add)
675 if (B->getLHS()->getType()->getAs<PointerType>())
676 return false;
677
Tom Care245adab2010-08-18 21:17:24 +0000678 return CanVary(B->getRHS(), AC)
679 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000680 }
681 case Stmt::UnaryOperatorClass: {
682 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000683 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000684 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000685 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000686 return false;
687 default:
Tom Care245adab2010-08-18 21:17:24 +0000688 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000689 }
690 }
691 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000692 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
693 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000694 case Stmt::ConditionalOperatorClass:
Tom Care6216dc02010-08-30 19:25:43 +0000695 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000696 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000697}
698
Tom Care245adab2010-08-18 21:17:24 +0000699// Returns true if a DeclRefExpr is or behaves like a constant.
700bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000701 const DeclRefExpr *DR,
702 AnalysisContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000703 // Check if the type of the Decl is const-qualified
704 if (DR->getType().isConstQualified())
705 return true;
706
Tom Care50e8ac22010-08-16 21:43:52 +0000707 // Check for an enum
708 if (isa<EnumConstantDecl>(DR->getDecl()))
709 return true;
710
Tom Caredb34ab72010-08-23 19:51:57 +0000711 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
712 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000713 return true;
714
Tom Caredb34ab72010-08-23 19:51:57 +0000715 // Check if the Decl behaves like a constant. This check also takes care of
716 // static variables, which can only change between function calls if they are
717 // modified in the AST.
718 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
719 if (PCA->isPseudoConstant(VD))
720 return true;
721
722 return false;
723}
724
725// Recursively find any substatements containing VarDecl's with storage other
726// than local
727bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
728 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
729
730 if (DR)
731 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
732 if (!VD->hasLocalStorage())
733 return true;
734
735 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
736 ++I)
737 if (const Stmt *child = *I)
738 if (containsNonLocalVarDecl(child))
739 return true;
740
Tom Care50e8ac22010-08-16 21:43:52 +0000741 return false;
742}
Tom Careb0627952010-09-09 02:04:52 +0000743
744// Returns the successor nodes of N whose CFGBlocks cannot reach N's CFGBlock.
745// This effectively gives us a set of points in the ExplodedGraph where
746// subsequent execution could not affect the idempotent operation on this path.
747// This is useful for displaying paths after the point of the error, providing
748// an example of how this idempotent operation cannot change.
749const ExplodedNodeSet IdempotentOperationChecker::getLastRelevantNodes(
750 const CFGBlock *Begin, const ExplodedNode *N) {
751 std::deque<const ExplodedNode *> WorkList;
752 llvm::SmallPtrSet<const ExplodedNode *, 32> Visited;
753 ExplodedNodeSet Result;
754
755 WorkList.push_back(N);
756
757 while (!WorkList.empty()) {
758 const ExplodedNode *Head = WorkList.front();
759 WorkList.pop_front();
760 Visited.insert(Head);
761
762 const ProgramPoint &PP = Head->getLocation();
763 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&PP)) {
764 // Get the CFGBlock and test the reachability
765 const CFGBlock *CB = BE->getBlock();
766
767 // If we cannot reach the beginning CFGBlock from this block, then we are
768 // finished
769 if (!CRA.isReachable(CB, Begin)) {
770 Result.Add(const_cast<ExplodedNode *>(Head));
771 continue;
772 }
773 }
774
775 // Add unvisited children to the worklist
776 for (ExplodedNode::const_succ_iterator I = Head->succ_begin(),
777 E = Head->succ_end(); I != E; ++I)
778 if (!Visited.count(*I))
779 WorkList.push_back(*I);
780 }
781
782 // Return the ExplodedNodes that were found
783 return Result;
784}
785
786bool IdempotentOperationChecker::CFGReachabilityAnalysis::isReachable(
787 const CFGBlock *Src,
788 const CFGBlock *Dst) {
789 const unsigned DstBlockID = Dst->getBlockID();
790
791 // If we haven't analyzed the destination node, run the analysis now
792 if (!analyzed.count(DstBlockID)) {
793 MapReachability(Dst);
794 analyzed.insert(DstBlockID);
795 }
796
797 // Return the cached result
798 return reachable[DstBlockID].count(Src->getBlockID());
799}
800
801// Maps reachability to a common node by walking the predecessors of the
802// destination node.
803void IdempotentOperationChecker::CFGReachabilityAnalysis::MapReachability(
804 const CFGBlock *Dst) {
805 std::deque<const CFGBlock *> WorkList;
806 // Maintain a visited list to ensure we don't get stuck on cycles
807 llvm::SmallSet<unsigned, 32> Visited;
808 ReachableSet &DstReachability = reachable[Dst->getBlockID()];
809
810 // Start searching from the destination node, since we commonly will perform
811 // multiple queries relating to a destination node.
812 WorkList.push_back(Dst);
813
814 bool firstRun = true;
815 while (!WorkList.empty()) {
816 const CFGBlock *Head = WorkList.front();
817 WorkList.pop_front();
818 Visited.insert(Head->getBlockID());
819
820 // Update reachability information for this node -> Dst
821 if (!firstRun)
822 // Don't insert Dst -> Dst unless it was a predecessor of itself
823 DstReachability.insert(Head->getBlockID());
824 else
825 firstRun = false;
826
827 // Add the predecessors to the worklist unless we have already visited them
828 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
829 I != Head->pred_end(); ++I)
830 if (!Visited.count((*I)->getBlockID()))
831 WorkList.push_back(*I);
832 }
833}