blob: 3d454bed9a483383d68b8c9bb931550ebe0fca82 [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 }
203 LHSVal = state->getSVal(cast<Loc>(LHSVal));
204 }
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];
358 Data.explodedNodes.Add(C.getPredecessor());
359}
360
Tom Caredb2fa8a2010-07-06 21:43:29 +0000361void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000362 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000363 GRExprEngine &Eng) {
Tom Care2bbbe502010-09-02 23:30:22 +0000364 BugType *BT = new BugType("Idempotent operation", "Dead code");
Tom Caredb2fa8a2010-07-06 21:43:29 +0000365 // Iterate over the hash to see if we have any paths with definite
366 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000367 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
368 // Unpack the hash contents
Tom Care2bbbe502010-09-02 23:30:22 +0000369 const BinaryOperatorData &Data = i->second;
370 const Assumption &A = Data.assumption;
371 AnalysisContext *AC = Data.analysisContext;
372 const ExplodedNodeSet &ES = Data.explodedNodes;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000373
Tom Carea7a8a452010-08-12 22:45:47 +0000374 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000375
Tom Carea7a8a452010-08-12 22:45:47 +0000376 if (A == Impossible)
377 continue;
378
379 // If the analyzer did not finish, check to see if we can still emit this
380 // warning
381 if (Eng.hasWorkRemaining()) {
382 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
383 &AC->getParentMap());
384
385 // If we can trace back
386 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
387 CBM->getBlock(B),
388 Eng.getCoreEngine()))
389 continue;
390
391 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000392 }
Tom Carea7a8a452010-08-12 22:45:47 +0000393
Tom Care2bbbe502010-09-02 23:30:22 +0000394 // Select the error message and SourceRanges to report.
Tom Carea7a8a452010-08-12 22:45:47 +0000395 llvm::SmallString<128> buf;
396 llvm::raw_svector_ostream os(buf);
Tom Care2bbbe502010-09-02 23:30:22 +0000397 bool LHSRelevant = false, RHSRelevant = false;
Tom Carea7a8a452010-08-12 22:45:47 +0000398 switch (A) {
399 case Equal:
Tom Care2bbbe502010-09-02 23:30:22 +0000400 LHSRelevant = true;
401 RHSRelevant = true;
John McCall2de56d12010-08-25 11:45:40 +0000402 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000403 os << "Assigned value is always the same as the existing value";
404 else
405 os << "Both operands to '" << B->getOpcodeStr()
406 << "' always have the same value";
407 break;
408 case LHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000409 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000410 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
411 break;
412 case RHSis1:
Tom Care2bbbe502010-09-02 23:30:22 +0000413 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000414 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
415 break;
416 case LHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000417 LHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000418 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
419 break;
420 case RHSis0:
Tom Care2bbbe502010-09-02 23:30:22 +0000421 RHSRelevant = true;
Tom Carea7a8a452010-08-12 22:45:47 +0000422 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
423 break;
424 case Possible:
425 llvm_unreachable("Operation was never marked with an assumption");
426 case Impossible:
427 llvm_unreachable(0);
428 }
429
Tom Care2bbbe502010-09-02 23:30:22 +0000430 // Add a report for each ExplodedNode
431 for (ExplodedNodeSet::iterator I = ES.begin(), E = ES.end(); I != E; ++I) {
432 EnhancedBugReport *report = new EnhancedBugReport(*BT, os.str(), *I);
433
434 // Add source ranges and visitor hooks
435 if (LHSRelevant) {
436 const Expr *LHS = i->first->getLHS();
437 report->addRange(LHS->getSourceRange());
438 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, LHS);
439 }
440 if (RHSRelevant) {
441 const Expr *RHS = i->first->getRHS();
442 report->addRange(i->first->getRHS()->getSourceRange());
443 report->addVisitorCreator(bugreporter::registerVarDeclsLastStore, RHS);
444 }
445
446 BR.EmitReport(report);
447 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000448 }
449}
450
451// Updates the current assumption given the new assumption
452inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
453 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000454// If the assumption is the same, there is nothing to do
455 if (A == New)
456 return;
457
Tom Caredb2fa8a2010-07-06 21:43:29 +0000458 switch (A) {
459 // If we don't currently have an assumption, set it
460 case Possible:
461 A = New;
462 return;
463
464 // If we have determined that a valid state happened, ignore the new
465 // assumption.
466 case Impossible:
467 return;
468
469 // Any other case means that we had a different assumption last time. We don't
470 // currently support mixing assumptions for diagnostic reasons, so we set
471 // our assumption to be impossible.
472 default:
473 A = Impossible;
474 return;
475 }
476}
477
Tom Care6216dc02010-08-30 19:25:43 +0000478// Check for a statement where a variable is self assigned to possibly avoid an
479// unused variable warning.
480bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000481 LHS = LHS->IgnoreParenCasts();
482 RHS = RHS->IgnoreParenCasts();
483
484 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
485 if (!LHS_DR)
486 return false;
487
Tom Careef52bcb2010-08-24 21:09:07 +0000488 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
489 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000490 return false;
491
492 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
493 if (!RHS_DR)
494 return false;
495
Tom Careef52bcb2010-08-24 21:09:07 +0000496 if (VD != RHS_DR->getDecl())
497 return false;
498
Tom Care6216dc02010-08-30 19:25:43 +0000499 return true;
500}
501
502// Returns true if the Expr points to a VarDecl that is not read anywhere
503// outside of self-assignments.
504bool IdempotentOperationChecker::isUnused(const Expr *E,
505 AnalysisContext *AC) {
506 if (!E)
507 return false;
508
509 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
510 if (!DR)
511 return false;
512
513 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
514 if (!VD)
515 return false;
516
Tom Careef52bcb2010-08-24 21:09:07 +0000517 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
518 return false;
519
520 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000521}
522
523// Check for self casts truncating/extending a variable
524bool IdempotentOperationChecker::isTruncationExtensionAssignment(
525 const Expr *LHS,
526 const Expr *RHS) {
527
528 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
529 if (!LHS_DR)
530 return false;
531
532 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
533 if (!VD)
534 return false;
535
536 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
537 if (!RHS_DR)
538 return false;
539
540 if (VD != RHS_DR->getDecl())
541 return false;
542
543 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
544}
545
Tom Carea7a8a452010-08-12 22:45:47 +0000546// Returns false if a path to this block was not completely analyzed, or true
547// otherwise.
548bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
549 const CFG *C,
550 const CFGBlock *CB,
551 const GRCoreEngine &CE) {
Tom Careb0627952010-09-09 02:04:52 +0000552 // Test for reachability from any aborted blocks to this block
Tom Carea7a8a452010-08-12 22:45:47 +0000553 typedef GRCoreEngine::BlocksAborted::const_iterator AbortedIterator;
554 for (AbortedIterator I = CE.blocks_aborted_begin(),
555 E = CE.blocks_aborted_end(); I != E; ++I) {
556 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000557
Tom Carea7a8a452010-08-12 22:45:47 +0000558 // The destination block on the BlockEdge is the first block that was not
Tom Careb0627952010-09-09 02:04:52 +0000559 // analyzed. If we can reach this block from the aborted block, then this
560 // block was not completely analyzed.
561 if (CRA.isReachable(BE.getDst(), CB))
Tom Carea7a8a452010-08-12 22:45:47 +0000562 return false;
Tom Carea7a8a452010-08-12 22:45:47 +0000563 }
564
Tom Careb0627952010-09-09 02:04:52 +0000565 // Verify that this block is reachable from the entry block
566 if (!CRA.isReachable(&C->getEntry(), CB))
567 return false;
568
Tom Carea7a8a452010-08-12 22:45:47 +0000569 // If we get to this point, there is no connection to the entry block or an
570 // aborted block. This path is unreachable and we can report the error.
571 return true;
572}
573
574// Recursive function that determines whether an expression contains any element
575// that varies. This could be due to a compile-time constant like sizeof. An
576// expression may also involve a variable that behaves like a constant. The
577// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000578bool IdempotentOperationChecker::CanVary(const Expr *Ex,
579 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000580 // Parentheses and casts are irrelevant here
581 Ex = Ex->IgnoreParenCasts();
582
583 if (Ex->getLocStart().isMacroID())
584 return false;
585
586 switch (Ex->getStmtClass()) {
587 // Trivially true cases
588 case Stmt::ArraySubscriptExprClass:
589 case Stmt::MemberExprClass:
590 case Stmt::StmtExprClass:
591 case Stmt::CallExprClass:
592 case Stmt::VAArgExprClass:
593 case Stmt::ShuffleVectorExprClass:
594 return true;
595 default:
596 return true;
597
598 // Trivially false cases
599 case Stmt::IntegerLiteralClass:
600 case Stmt::CharacterLiteralClass:
601 case Stmt::FloatingLiteralClass:
602 case Stmt::PredefinedExprClass:
603 case Stmt::ImaginaryLiteralClass:
604 case Stmt::StringLiteralClass:
605 case Stmt::OffsetOfExprClass:
606 case Stmt::CompoundLiteralExprClass:
607 case Stmt::AddrLabelExprClass:
608 case Stmt::TypesCompatibleExprClass:
609 case Stmt::GNUNullExprClass:
610 case Stmt::InitListExprClass:
611 case Stmt::DesignatedInitExprClass:
612 case Stmt::BlockExprClass:
613 case Stmt::BlockDeclRefExprClass:
614 return false;
615
616 // Cases requiring custom logic
617 case Stmt::SizeOfAlignOfExprClass: {
618 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
619 if (!SE->isSizeOf())
620 return false;
621 return SE->getTypeOfArgument()->isVariableArrayType();
622 }
623 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000624 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000625 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000626
627 // The next cases require recursion for subexpressions
628 case Stmt::BinaryOperatorClass: {
629 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Tom Care245adab2010-08-18 21:17:24 +0000630 return CanVary(B->getRHS(), AC)
631 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000632 }
633 case Stmt::UnaryOperatorClass: {
634 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000635 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000636 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000637 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000638 return false;
639 default:
Tom Care245adab2010-08-18 21:17:24 +0000640 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000641 }
642 }
643 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000644 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
645 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000646 case Stmt::ConditionalOperatorClass:
Tom Care6216dc02010-08-30 19:25:43 +0000647 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000648 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000649}
650
Tom Care245adab2010-08-18 21:17:24 +0000651// Returns true if a DeclRefExpr is or behaves like a constant.
652bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000653 const DeclRefExpr *DR,
654 AnalysisContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000655 // Check if the type of the Decl is const-qualified
656 if (DR->getType().isConstQualified())
657 return true;
658
Tom Care50e8ac22010-08-16 21:43:52 +0000659 // Check for an enum
660 if (isa<EnumConstantDecl>(DR->getDecl()))
661 return true;
662
Tom Caredb34ab72010-08-23 19:51:57 +0000663 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
664 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000665 return true;
666
Tom Caredb34ab72010-08-23 19:51:57 +0000667 // Check if the Decl behaves like a constant. This check also takes care of
668 // static variables, which can only change between function calls if they are
669 // modified in the AST.
670 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
671 if (PCA->isPseudoConstant(VD))
672 return true;
673
674 return false;
675}
676
677// Recursively find any substatements containing VarDecl's with storage other
678// than local
679bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
680 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
681
682 if (DR)
683 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
684 if (!VD->hasLocalStorage())
685 return true;
686
687 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
688 ++I)
689 if (const Stmt *child = *I)
690 if (containsNonLocalVarDecl(child))
691 return true;
692
Tom Care50e8ac22010-08-16 21:43:52 +0000693 return false;
694}
Tom Careb0627952010-09-09 02:04:52 +0000695
696// Returns the successor nodes of N whose CFGBlocks cannot reach N's CFGBlock.
697// This effectively gives us a set of points in the ExplodedGraph where
698// subsequent execution could not affect the idempotent operation on this path.
699// This is useful for displaying paths after the point of the error, providing
700// an example of how this idempotent operation cannot change.
701const ExplodedNodeSet IdempotentOperationChecker::getLastRelevantNodes(
702 const CFGBlock *Begin, const ExplodedNode *N) {
703 std::deque<const ExplodedNode *> WorkList;
704 llvm::SmallPtrSet<const ExplodedNode *, 32> Visited;
705 ExplodedNodeSet Result;
706
707 WorkList.push_back(N);
708
709 while (!WorkList.empty()) {
710 const ExplodedNode *Head = WorkList.front();
711 WorkList.pop_front();
712 Visited.insert(Head);
713
714 const ProgramPoint &PP = Head->getLocation();
715 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&PP)) {
716 // Get the CFGBlock and test the reachability
717 const CFGBlock *CB = BE->getBlock();
718
719 // If we cannot reach the beginning CFGBlock from this block, then we are
720 // finished
721 if (!CRA.isReachable(CB, Begin)) {
722 Result.Add(const_cast<ExplodedNode *>(Head));
723 continue;
724 }
725 }
726
727 // Add unvisited children to the worklist
728 for (ExplodedNode::const_succ_iterator I = Head->succ_begin(),
729 E = Head->succ_end(); I != E; ++I)
730 if (!Visited.count(*I))
731 WorkList.push_back(*I);
732 }
733
734 // Return the ExplodedNodes that were found
735 return Result;
736}
737
738bool IdempotentOperationChecker::CFGReachabilityAnalysis::isReachable(
739 const CFGBlock *Src,
740 const CFGBlock *Dst) {
741 const unsigned DstBlockID = Dst->getBlockID();
742
743 // If we haven't analyzed the destination node, run the analysis now
744 if (!analyzed.count(DstBlockID)) {
745 MapReachability(Dst);
746 analyzed.insert(DstBlockID);
747 }
748
749 // Return the cached result
750 return reachable[DstBlockID].count(Src->getBlockID());
751}
752
753// Maps reachability to a common node by walking the predecessors of the
754// destination node.
755void IdempotentOperationChecker::CFGReachabilityAnalysis::MapReachability(
756 const CFGBlock *Dst) {
757 std::deque<const CFGBlock *> WorkList;
758 // Maintain a visited list to ensure we don't get stuck on cycles
759 llvm::SmallSet<unsigned, 32> Visited;
760 ReachableSet &DstReachability = reachable[Dst->getBlockID()];
761
762 // Start searching from the destination node, since we commonly will perform
763 // multiple queries relating to a destination node.
764 WorkList.push_back(Dst);
765
766 bool firstRun = true;
767 while (!WorkList.empty()) {
768 const CFGBlock *Head = WorkList.front();
769 WorkList.pop_front();
770 Visited.insert(Head->getBlockID());
771
772 // Update reachability information for this node -> Dst
773 if (!firstRun)
774 // Don't insert Dst -> Dst unless it was a predecessor of itself
775 DstReachability.insert(Head->getBlockID());
776 else
777 firstRun = false;
778
779 // Add the predecessors to the worklist unless we have already visited them
780 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
781 I != Head->pred_end(); ++I)
782 if (!Visited.count((*I)->getBlockID()))
783 WorkList.push_back(*I);
784 }
785}