blob: 3dcbea491eb7b263011910f91f744d9a2142dccf [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,
85 const GRCoreEngine &CE);
86 static bool CanVary(const Expr *Ex,
87 AnalysisContext *AC);
88 static bool isConstantOrPseudoConstant(const DeclRefExpr *DR,
89 AnalysisContext *AC);
90 static bool containsNonLocalVarDecl(const Stmt *S);
91 const ExplodedNodeSet getLastRelevantNodes(const CFGBlock *Begin,
92 const ExplodedNode *N);
93
94 // Hash table and related data structures
95 struct BinaryOperatorData {
96 BinaryOperatorData() : assumption(Possible), analysisContext(0) {}
97
98 Assumption assumption;
99 AnalysisContext *analysisContext;
100 ExplodedNodeSet explodedNodes; // Set of ExplodedNodes that refer to a
101 // BinaryOperator
102 };
103 typedef llvm::DenseMap<const BinaryOperator *, BinaryOperatorData>
104 AssumptionMap;
105 AssumptionMap hash;
106
107 // A class that performs reachability queries for CFGBlocks. Several internal
108 // checks in this checker require reachability information. The requests all
109 // tend to have a common destination, so we lazily do a predecessor search
110 // from the destination node and cache the results to prevent work
111 // duplication.
112 class CFGReachabilityAnalysis {
113 typedef llvm::SmallSet<unsigned, 32> ReachableSet;
114 typedef llvm::DenseMap<unsigned, ReachableSet> ReachableMap;
115 ReachableSet analyzed;
116 ReachableMap reachable;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000117 public:
Tom Careb0627952010-09-09 02:04:52 +0000118 inline bool isReachable(const CFGBlock *Src, const CFGBlock *Dst);
Tom Caredb2fa8a2010-07-06 21:43:29 +0000119 private:
Tom Careb0627952010-09-09 02:04:52 +0000120 void MapReachability(const CFGBlock *Dst);
121 };
122 CFGReachabilityAnalysis CRA;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000123};
124}
125
126void *IdempotentOperationChecker::getTag() {
127 static int x = 0;
128 return &x;
129}
130
131void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
132 Eng.registerCheck(new IdempotentOperationChecker());
133}
134
135void IdempotentOperationChecker::PreVisitBinaryOperator(
136 CheckerContext &C,
137 const BinaryOperator *B) {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000138 // Find or create an entry in the hash for this BinaryOperator instance.
139 // If we haven't done a lookup before, it will get default initialized to
Tom Care2bbbe502010-09-02 23:30:22 +0000140 // 'Possible'. At this stage we do not store the ExplodedNode, as it has not
141 // been created yet.
142 BinaryOperatorData &Data = hash[B];
143 Assumption &A = Data.assumption;
Tom Care245adab2010-08-18 21:17:24 +0000144 AnalysisContext *AC = C.getCurrentAnalysisContext();
Tom Care2bbbe502010-09-02 23:30:22 +0000145 Data.analysisContext = AC;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000146
147 // If we already have visited this node on a path that does not contain an
148 // idempotent operation, return immediately.
149 if (A == Impossible)
150 return;
151
Tom Carea7a8a452010-08-12 22:45:47 +0000152 // Retrieve both sides of the operator and determine if they can vary (which
153 // may mean this is a false positive.
Tom Caredb2fa8a2010-07-06 21:43:29 +0000154 const Expr *LHS = B->getLHS();
155 const Expr *RHS = B->getRHS();
Tom Care245adab2010-08-18 21:17:24 +0000156
Tom Caredb34ab72010-08-23 19:51:57 +0000157 // At this stage we can calculate whether each side contains a false positive
158 // that applies to all operators. We only need to calculate this the first
159 // time.
160 bool LHSContainsFalsePositive = false, RHSContainsFalsePositive = false;
Tom Care245adab2010-08-18 21:17:24 +0000161 if (A == Possible) {
Tom Caredb34ab72010-08-23 19:51:57 +0000162 // An expression contains a false positive if it can't vary, or if it
163 // contains a known false positive VarDecl.
164 LHSContainsFalsePositive = !CanVary(LHS, AC)
165 || containsNonLocalVarDecl(LHS);
166 RHSContainsFalsePositive = !CanVary(RHS, AC)
167 || containsNonLocalVarDecl(RHS);
Tom Care245adab2010-08-18 21:17:24 +0000168 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000169
170 const GRState *state = C.getState();
171
172 SVal LHSVal = state->getSVal(LHS);
173 SVal RHSVal = state->getSVal(RHS);
174
175 // If either value is unknown, we can't be 100% sure of all paths.
176 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
177 A = Impossible;
178 return;
179 }
180 BinaryOperator::Opcode Op = B->getOpcode();
181
182 // Dereference the LHS SVal if this is an assign operation
183 switch (Op) {
184 default:
185 break;
186
187 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000188 case BO_AddAssign:
189 case BO_SubAssign:
190 case BO_MulAssign:
191 case BO_DivAssign:
192 case BO_AndAssign:
193 case BO_OrAssign:
194 case BO_XorAssign:
195 case BO_ShlAssign:
196 case BO_ShrAssign:
197 case BO_Assign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000198 // Assign statements have one extra level of indirection
199 if (!isa<Loc>(LHSVal)) {
200 A = Impossible;
201 return;
202 }
Ted Kremenek96ebad62010-09-09 07:13:00 +0000203 LHSVal = state->getSVal(cast<Loc>(LHSVal), LHS->getType());
Tom Caredb2fa8a2010-07-06 21:43:29 +0000204 }
205
206
207 // We now check for various cases which result in an idempotent operation.
208
209 // x op x
210 switch (Op) {
211 default:
212 break; // We don't care about any other operators.
213
214 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000215 case BO_Assign:
Tom Care6216dc02010-08-30 19:25:43 +0000216 // x Assign x can be used to silence unused variable warnings intentionally.
217 // If this is a self assignment and the variable is referenced elsewhere,
Tom Care84c24ed2010-09-07 20:27:56 +0000218 // and the assignment is not a truncation or extension, then it is a false
219 // positive.
Tom Care6216dc02010-08-30 19:25:43 +0000220 if (isSelfAssign(LHS, RHS)) {
Tom Care84c24ed2010-09-07 20:27:56 +0000221 if (!isUnused(LHS, AC) && !isTruncationExtensionAssignment(LHS, RHS)) {
Tom Care6216dc02010-08-30 19:25:43 +0000222 UpdateAssumption(A, Equal);
223 return;
224 }
225 else {
226 A = Impossible;
227 return;
228 }
Tom Caredf4ca422010-07-16 20:41:41 +0000229 }
230
John McCall2de56d12010-08-25 11:45:40 +0000231 case BO_SubAssign:
232 case BO_DivAssign:
233 case BO_AndAssign:
234 case BO_OrAssign:
235 case BO_XorAssign:
236 case BO_Sub:
237 case BO_Div:
238 case BO_And:
239 case BO_Or:
240 case BO_Xor:
241 case BO_LOr:
242 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000243 case BO_EQ:
244 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000245 if (LHSVal != RHSVal || LHSContainsFalsePositive
246 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000247 break;
248 UpdateAssumption(A, Equal);
249 return;
250 }
251
252 // x op 1
253 switch (Op) {
254 default:
255 break; // We don't care about any other operators.
256
257 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000258 case BO_MulAssign:
259 case BO_DivAssign:
260 case BO_Mul:
261 case BO_Div:
262 case BO_LOr:
263 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000264 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000265 break;
266 UpdateAssumption(A, RHSis1);
267 return;
268 }
269
270 // 1 op x
271 switch (Op) {
272 default:
273 break; // We don't care about any other operators.
274
275 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000276 case BO_MulAssign:
277 case BO_Mul:
278 case BO_LOr:
279 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000280 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000281 break;
282 UpdateAssumption(A, LHSis1);
283 return;
284 }
285
286 // x op 0
287 switch (Op) {
288 default:
289 break; // We don't care about any other operators.
290
291 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000292 case BO_AddAssign:
293 case BO_SubAssign:
294 case BO_MulAssign:
295 case BO_AndAssign:
296 case BO_OrAssign:
297 case BO_XorAssign:
298 case BO_Add:
299 case BO_Sub:
300 case BO_Mul:
301 case BO_And:
302 case BO_Or:
303 case BO_Xor:
304 case BO_Shl:
305 case BO_Shr:
306 case BO_LOr:
307 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000308 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000309 break;
310 UpdateAssumption(A, RHSis0);
311 return;
312 }
313
314 // 0 op x
315 switch (Op) {
316 default:
317 break; // We don't care about any other operators.
318
319 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000320 //case BO_AddAssign: // Common false positive
321 case BO_SubAssign: // Check only if unsigned
322 case BO_MulAssign:
323 case BO_DivAssign:
324 case BO_AndAssign:
325 //case BO_OrAssign: // Common false positive
326 //case BO_XorAssign: // Common false positive
327 case BO_ShlAssign:
328 case BO_ShrAssign:
329 case BO_Add:
330 case BO_Sub:
331 case BO_Mul:
332 case BO_Div:
333 case BO_And:
334 case BO_Or:
335 case BO_Xor:
336 case BO_Shl:
337 case BO_Shr:
338 case BO_LOr:
339 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000340 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000341 break;
342 UpdateAssumption(A, LHSis0);
343 return;
344 }
345
346 // If we get to this point, there has been a valid use of this operation.
347 A = Impossible;
348}
349
Tom Care2bbbe502010-09-02 23:30:22 +0000350// At the post visit stage, the predecessor ExplodedNode will be the
351// BinaryOperator that was just created. We use this hook to collect the
352// ExplodedNode.
353void IdempotentOperationChecker::PostVisitBinaryOperator(
354 CheckerContext &C,
355 const BinaryOperator *B) {
356 // Add the ExplodedNode we just visited
357 BinaryOperatorData &Data = hash[B];
Ted Kremenek96ebad62010-09-09 07:13:00 +0000358 assert(isa<BinaryOperator>(cast<StmtPoint>(C.getPredecessor()
359 ->getLocation()).getStmt()));
Tom Care2bbbe502010-09-02 23:30:22 +0000360 Data.explodedNodes.Add(C.getPredecessor());
361}
362
Tom Caredb2fa8a2010-07-06 21:43:29 +0000363void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000364 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000365 GRExprEngine &Eng) {
Tom Care2bbbe502010-09-02 23:30:22 +0000366 BugType *BT = new BugType("Idempotent operation", "Dead code");
Tom Caredb2fa8a2010-07-06 21:43:29 +0000367 // Iterate over the hash to see if we have any paths with definite
368 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000369 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
370 // Unpack the hash contents
Tom Care2bbbe502010-09-02 23:30:22 +0000371 const BinaryOperatorData &Data = i->second;
372 const Assumption &A = Data.assumption;
373 AnalysisContext *AC = Data.analysisContext;
374 const ExplodedNodeSet &ES = Data.explodedNodes;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000375
Tom Carea7a8a452010-08-12 22:45:47 +0000376 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000377
Tom Carea7a8a452010-08-12 22:45:47 +0000378 if (A == Impossible)
379 continue;
380
381 // If the analyzer did not finish, check to see if we can still emit this
382 // warning
383 if (Eng.hasWorkRemaining()) {
384 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
385 &AC->getParentMap());
386
387 // If we can trace back
388 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
389 CBM->getBlock(B),
390 Eng.getCoreEngine()))
391 continue;
392
393 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000394 }
Tom Carea7a8a452010-08-12 22:45:47 +0000395
Tom Care2bbbe502010-09-02 23:30:22 +0000396 // Select the error message and SourceRanges to report.
Tom Carea7a8a452010-08-12 22:45:47 +0000397 llvm::SmallString<128> buf;
398 llvm::raw_svector_ostream os(buf);
Tom Care2bbbe502010-09-02 23:30:22 +0000399 bool LHSRelevant = false, RHSRelevant = false;
Tom Carea7a8a452010-08-12 22:45:47 +0000400 switch (A) {
401 case Equal:
Tom Care2bbbe502010-09-02 23:30:22 +0000402 LHSRelevant = true;
403 RHSRelevant = true;
John McCall2de56d12010-08-25 11:45:40 +0000404 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000405 os << "Assigned value is always the same as the existing value";
406 else
407 os << "Both operands to '" << B->getOpcodeStr()
408 << "' always have the same value";
409 break;
410 case LHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000411 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000412 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
413 break;
414 case RHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000415 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000416 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
417 break;
418 case LHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000419 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000420 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
421 break;
422 case RHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000423 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000424 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
425 break;
426 case Possible:
427 llvm_unreachable("Operation was never marked with an assumption");
428 case Impossible:
429 llvm_unreachable(0);
430 }
431
Tom Care2bbbe502010-09-02 23:30:22 +0000432 // Add a report for each ExplodedNode
433 for (ExplodedNodeSet::iterator I = ES.begin(), E = ES.end(); I != E; ++I) {
434 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), *I);
435
436 // Add source ranges and visitor hooks
437 if (LHSRelevant) {
438 const Expr *LHS = i->first->getLHS();
439 report->addRange(LHS->getSourceRange());
440 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, LHS);
441 }
442 if (RHSRelevant) {
443 const Expr *RHS = i->first->getRHS();
444 report->addRange(i->first->getRHS()->getSourceRange());
445 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, RHS);
446 }
447
448 BR.EmitReport(report);
449 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000450 }
451}
452
453// Updates the current assumption given the new assumption
454inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
455 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000456// If the assumption is the same, there is nothing to do
457 if (A == New)
458 return;
459
Tom Caredb2fa8a2010-07-06 21:43:29 +0000460 switch (A) {
461 // If we don't currently have an assumption, set it
462 case Possible:
463 A = New;
464 return;
465
466 // If we have determined that a valid state happened, ignore the new
467 // assumption.
468 case Impossible:
469 return;
470
471 // Any other case means that we had a different assumption last time. We don't
472 // currently support mixing assumptions for diagnostic reasons, so we set
473 // our assumption to be impossible.
474 default:
475 A = Impossible;
476 return;
477 }
478}
479
Tom Care6216dc02010-08-30 19:25:43 +0000480// Check for a statement where a variable is self assigned to possibly avoid an
481// unused variable warning.
482bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000483 LHS = LHS->IgnoreParenCasts();
484 RHS = RHS->IgnoreParenCasts();
485
486 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
487 if (!LHS_DR)
488 return false;
489
Tom Careef52bcb2010-08-24 21:09:07 +0000490 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
491 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000492 return false;
493
494 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
495 if (!RHS_DR)
496 return false;
497
Tom Careef52bcb2010-08-24 21:09:07 +0000498 if (VD != RHS_DR->getDecl())
499 return false;
500
Tom Care6216dc02010-08-30 19:25:43 +0000501 return true;
502}
503
504// Returns true if the Expr points to a VarDecl that is not read anywhere
505// outside of self-assignments.
506bool IdempotentOperationChecker::isUnused(const Expr *E,
507 AnalysisContext *AC) {
508 if (!E)
509 return false;
510
511 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
512 if (!DR)
513 return false;
514
515 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
516 if (!VD)
517 return false;
518
Tom Careef52bcb2010-08-24 21:09:07 +0000519 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
520 return false;
521
522 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000523}
524
525// Check for self casts truncating/extending a variable
526bool IdempotentOperationChecker::isTruncationExtensionAssignment(
527 const Expr *LHS,
528 const Expr *RHS) {
529
530 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
531 if (!LHS_DR)
532 return false;
533
534 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
535 if (!VD)
536 return false;
537
538 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
539 if (!RHS_DR)
540 return false;
541
542 if (VD != RHS_DR->getDecl())
543 return false;
544
545 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
546}
547
Tom Carea7a8a452010-08-12 22:45:47 +0000548// Returns false if a path to this block was not completely analyzed, or true
549// otherwise.
550bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
551 const CFG *C,
552 const CFGBlock *CB,
553 const GRCoreEngine &CE) {
Tom Careb0627952010-09-09 02:04:52 +0000554 // Test for reachability from any aborted blocks to this block
Tom Carea7a8a452010-08-12 22:45:47 +0000555 typedef GRCoreEngine::BlocksAborted::const_iterator AbortedIterator;
556 for (AbortedIterator I = CE.blocks_aborted_begin(),
557 E = CE.blocks_aborted_end(); I != E; ++I) {
558 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000559
Tom Carea7a8a452010-08-12 22:45:47 +0000560 // The destination block on the BlockEdge is the first block that was not
Tom Careb0627952010-09-09 02:04:52 +0000561 // analyzed. If we can reach this block from the aborted block, then this
562 // block was not completely analyzed.
563 if (CRA.isReachable(BE.getDst(), CB))
Tom Carea7a8a452010-08-12 22:45:47 +0000564 return false;
Tom Carea7a8a452010-08-12 22:45:47 +0000565 }
566
Tom Careb0627952010-09-09 02:04:52 +0000567 // Verify that this block is reachable from the entry block
568 if (!CRA.isReachable(&C->getEntry(), CB))
569 return false;
570
Tom Carea7a8a452010-08-12 22:45:47 +0000571 // If we get to this point, there is no connection to the entry block or an
572 // aborted block. This path is unreachable and we can report the error.
573 return true;
574}
575
576// Recursive function that determines whether an expression contains any element
577// that varies. This could be due to a compile-time constant like sizeof. An
578// expression may also involve a variable that behaves like a constant. The
579// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000580bool IdempotentOperationChecker::CanVary(const Expr *Ex,
581 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000582 // Parentheses and casts are irrelevant here
583 Ex = Ex->IgnoreParenCasts();
584
585 if (Ex->getLocStart().isMacroID())
586 return false;
587
588 switch (Ex->getStmtClass()) {
589 // Trivially true cases
590 case Stmt::ArraySubscriptExprClass:
591 case Stmt::MemberExprClass:
592 case Stmt::StmtExprClass:
593 case Stmt::CallExprClass:
594 case Stmt::VAArgExprClass:
595 case Stmt::ShuffleVectorExprClass:
596 return true;
597 default:
598 return true;
599
600 // Trivially false cases
601 case Stmt::IntegerLiteralClass:
602 case Stmt::CharacterLiteralClass:
603 case Stmt::FloatingLiteralClass:
604 case Stmt::PredefinedExprClass:
605 case Stmt::ImaginaryLiteralClass:
606 case Stmt::StringLiteralClass:
607 case Stmt::OffsetOfExprClass:
608 case Stmt::CompoundLiteralExprClass:
609 case Stmt::AddrLabelExprClass:
610 case Stmt::TypesCompatibleExprClass:
611 case Stmt::GNUNullExprClass:
612 case Stmt::InitListExprClass:
613 case Stmt::DesignatedInitExprClass:
614 case Stmt::BlockExprClass:
615 case Stmt::BlockDeclRefExprClass:
616 return false;
617
618 // Cases requiring custom logic
619 case Stmt::SizeOfAlignOfExprClass: {
620 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
621 if (!SE->isSizeOf())
622 return false;
623 return SE->getTypeOfArgument()->isVariableArrayType();
624 }
625 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000626 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000627 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000628
629 // The next cases require recursion for subexpressions
630 case Stmt::BinaryOperatorClass: {
631 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Tom Care245adab2010-08-18 21:17:24 +0000632 return CanVary(B->getRHS(), AC)
633 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000634 }
635 case Stmt::UnaryOperatorClass: {
636 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000637 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000638 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000639 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000640 return false;
641 default:
Tom Care245adab2010-08-18 21:17:24 +0000642 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000643 }
644 }
645 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000646 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
647 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000648 case Stmt::ConditionalOperatorClass:
Tom Care6216dc02010-08-30 19:25:43 +0000649 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000650 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000651}
652
Tom Care245adab2010-08-18 21:17:24 +0000653// Returns true if a DeclRefExpr is or behaves like a constant.
654bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000655 const DeclRefExpr *DR,
656 AnalysisContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000657 // Check if the type of the Decl is const-qualified
658 if (DR->getType().isConstQualified())
659 return true;
660
Tom Care50e8ac22010-08-16 21:43:52 +0000661 // Check for an enum
662 if (isa<EnumConstantDecl>(DR->getDecl()))
663 return true;
664
Tom Caredb34ab72010-08-23 19:51:57 +0000665 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
666 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000667 return true;
668
Tom Caredb34ab72010-08-23 19:51:57 +0000669 // Check if the Decl behaves like a constant. This check also takes care of
670 // static variables, which can only change between function calls if they are
671 // modified in the AST.
672 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
673 if (PCA->isPseudoConstant(VD))
674 return true;
675
676 return false;
677}
678
679// Recursively find any substatements containing VarDecl's with storage other
680// than local
681bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
682 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
683
684 if (DR)
685 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
686 if (!VD->hasLocalStorage())
687 return true;
688
689 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
690 ++I)
691 if (const Stmt *child = *I)
692 if (containsNonLocalVarDecl(child))
693 return true;
694
Tom Care50e8ac22010-08-16 21:43:52 +0000695 return false;
696}
Tom Careb0627952010-09-09 02:04:52 +0000697
698// Returns the successor nodes of N whose CFGBlocks cannot reach N's CFGBlock.
699// This effectively gives us a set of points in the ExplodedGraph where
700// subsequent execution could not affect the idempotent operation on this path.
701// This is useful for displaying paths after the point of the error, providing
702// an example of how this idempotent operation cannot change.
703const ExplodedNodeSet IdempotentOperationChecker::getLastRelevantNodes(
704 const CFGBlock *Begin, const ExplodedNode *N) {
705 std::deque<const ExplodedNode *> WorkList;
706 llvm::SmallPtrSet<const ExplodedNode *, 32> Visited;
707 ExplodedNodeSet Result;
708
709 WorkList.push_back(N);
710
711 while (!WorkList.empty()) {
712 const ExplodedNode *Head = WorkList.front();
713 WorkList.pop_front();
714 Visited.insert(Head);
715
716 const ProgramPoint &PP = Head->getLocation();
717 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&PP)) {
718 // Get the CFGBlock and test the reachability
719 const CFGBlock *CB = BE->getBlock();
720
721 // If we cannot reach the beginning CFGBlock from this block, then we are
722 // finished
723 if (!CRA.isReachable(CB, Begin)) {
724 Result.Add(const_cast<ExplodedNode *>(Head));
725 continue;
726 }
727 }
728
729 // Add unvisited children to the worklist
730 for (ExplodedNode::const_succ_iterator I = Head->succ_begin(),
731 E = Head->succ_end(); I != E; ++I)
732 if (!Visited.count(*I))
733 WorkList.push_back(*I);
734 }
735
736 // Return the ExplodedNodes that were found
737 return Result;
738}
739
740bool IdempotentOperationChecker::CFGReachabilityAnalysis::isReachable(
741 const CFGBlock *Src,
742 const CFGBlock *Dst) {
743 const unsigned DstBlockID = Dst->getBlockID();
744
745 // If we haven't analyzed the destination node, run the analysis now
746 if (!analyzed.count(DstBlockID)) {
747 MapReachability(Dst);
748 analyzed.insert(DstBlockID);
749 }
750
751 // Return the cached result
752 return reachable[DstBlockID].count(Src->getBlockID());
753}
754
755// Maps reachability to a common node by walking the predecessors of the
756// destination node.
757void IdempotentOperationChecker::CFGReachabilityAnalysis::MapReachability(
758 const CFGBlock *Dst) {
759 std::deque<const CFGBlock *> WorkList;
760 // Maintain a visited list to ensure we don't get stuck on cycles
761 llvm::SmallSet<unsigned, 32> Visited;
762 ReachableSet &DstReachability = reachable[Dst->getBlockID()];
763
764 // Start searching from the destination node, since we commonly will perform
765 // multiple queries relating to a destination node.
766 WorkList.push_back(Dst);
767
768 bool firstRun = true;
769 while (!WorkList.empty()) {
770 const CFGBlock *Head = WorkList.front();
771 WorkList.pop_front();
772 Visited.insert(Head->getBlockID());
773
774 // Update reachability information for this node -> Dst
775 if (!firstRun)
776 // Don't insert Dst -> Dst unless it was a predecessor of itself
777 DstReachability.insert(Head->getBlockID());
778 else
779 firstRun = false;
780
781 // Add the predecessors to the worklist unless we have already visited them
782 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
783 I != Head->pred_end(); ++I)
784 if (!Visited.count((*I)->getBlockID()))
785 WorkList.push_back(*I);
786 }
787}