blob: 3d4be1a11937b57c187268ced04537d86f8af3df [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 Caredb2fa8a2010-07-06 21:43:29 +000048#include "clang/Checker/BugReporter/BugType.h"
Tom Carea9fbf5b2010-07-27 23:26:07 +000049#include "clang/Checker/PathSensitive/CheckerHelpers.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000050#include "clang/Checker/PathSensitive/CheckerVisitor.h"
Tom Carea7a8a452010-08-12 22:45:47 +000051#include "clang/Checker/PathSensitive/GRCoreEngine.h"
Tom Caredb2fa8a2010-07-06 21:43:29 +000052#include "clang/Checker/PathSensitive/SVals.h"
53#include "clang/AST/Stmt.h"
54#include "llvm/ADT/DenseMap.h"
Tom Carea7a8a452010-08-12 22:45:47 +000055#include "llvm/ADT/SmallSet.h"
Chandler Carruth256565b2010-07-07 00:07:37 +000056#include "llvm/Support/ErrorHandling.h"
Tom Carea7a8a452010-08-12 22:45:47 +000057#include <deque>
Tom Caredb2fa8a2010-07-06 21:43:29 +000058
59using namespace clang;
60
61namespace {
62class IdempotentOperationChecker
63 : public CheckerVisitor<IdempotentOperationChecker> {
64 public:
65 static void *getTag();
66 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
Tom Carebc42c532010-08-03 01:55:07 +000067 void VisitEndAnalysis(ExplodedGraph &G, BugReporter &B, GRExprEngine &Eng);
Tom Caredb2fa8a2010-07-06 21:43:29 +000068
69 private:
70 // Our assumption about a particular operation.
Ted Kremenekfe97fa12010-08-02 20:33:02 +000071 enum Assumption { Possible = 0, Impossible, Equal, LHSis1, RHSis1, LHSis0,
Tom Caredb2fa8a2010-07-06 21:43:29 +000072 RHSis0 };
73
74 void UpdateAssumption(Assumption &A, const Assumption &New);
75
Tom Care245adab2010-08-18 21:17:24 +000076 // False positive reduction methods
Tom Care6216dc02010-08-30 19:25:43 +000077 static bool isSelfAssign(const Expr *LHS, const Expr *RHS);
78 static bool isUnused(const Expr *E, AnalysisContext *AC);
Tom Caredf4ca422010-07-16 20:41:41 +000079 static bool isTruncationExtensionAssignment(const Expr *LHS,
80 const Expr *RHS);
Tom Carea7a8a452010-08-12 22:45:47 +000081 static bool PathWasCompletelyAnalyzed(const CFG *C,
82 const CFGBlock *CB,
83 const GRCoreEngine &CE);
Tom Care6216dc02010-08-30 19:25:43 +000084 static bool CanVary(const Expr *Ex,
85 AnalysisContext *AC);
Tom Care245adab2010-08-18 21:17:24 +000086 static bool isConstantOrPseudoConstant(const DeclRefExpr *DR,
87 AnalysisContext *AC);
Tom Caredb34ab72010-08-23 19:51:57 +000088 static bool containsNonLocalVarDecl(const Stmt *S);
Tom Caredb2fa8a2010-07-06 21:43:29 +000089
90 // Hash table
Tom Carea7a8a452010-08-12 22:45:47 +000091 typedef llvm::DenseMap<const BinaryOperator *,
92 std::pair<Assumption, AnalysisContext*> >
93 AssumptionMap;
Tom Caredb2fa8a2010-07-06 21:43:29 +000094 AssumptionMap hash;
95};
96}
97
98void *IdempotentOperationChecker::getTag() {
99 static int x = 0;
100 return &x;
101}
102
103void clang::RegisterIdempotentOperationChecker(GRExprEngine &Eng) {
104 Eng.registerCheck(new IdempotentOperationChecker());
105}
106
107void IdempotentOperationChecker::PreVisitBinaryOperator(
108 CheckerContext &C,
109 const BinaryOperator *B) {
Ted Kremenekfe97fa12010-08-02 20:33:02 +0000110 // Find or create an entry in the hash for this BinaryOperator instance.
111 // If we haven't done a lookup before, it will get default initialized to
112 // 'Possible'.
Tom Carea7a8a452010-08-12 22:45:47 +0000113 std::pair<Assumption, AnalysisContext *> &Data = hash[B];
114 Assumption &A = Data.first;
Tom Care245adab2010-08-18 21:17:24 +0000115 AnalysisContext *AC = C.getCurrentAnalysisContext();
116 Data.second = AC;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000117
118 // If we already have visited this node on a path that does not contain an
119 // idempotent operation, return immediately.
120 if (A == Impossible)
121 return;
122
Tom Carea7a8a452010-08-12 22:45:47 +0000123 // Retrieve both sides of the operator and determine if they can vary (which
124 // may mean this is a false positive.
Tom Caredb2fa8a2010-07-06 21:43:29 +0000125 const Expr *LHS = B->getLHS();
126 const Expr *RHS = B->getRHS();
Tom Care245adab2010-08-18 21:17:24 +0000127
Tom Caredb34ab72010-08-23 19:51:57 +0000128 // At this stage we can calculate whether each side contains a false positive
129 // that applies to all operators. We only need to calculate this the first
130 // time.
131 bool LHSContainsFalsePositive = false, RHSContainsFalsePositive = false;
Tom Care245adab2010-08-18 21:17:24 +0000132 if (A == Possible) {
Tom Caredb34ab72010-08-23 19:51:57 +0000133 // An expression contains a false positive if it can't vary, or if it
134 // contains a known false positive VarDecl.
135 LHSContainsFalsePositive = !CanVary(LHS, AC)
136 || containsNonLocalVarDecl(LHS);
137 RHSContainsFalsePositive = !CanVary(RHS, AC)
138 || containsNonLocalVarDecl(RHS);
Tom Care245adab2010-08-18 21:17:24 +0000139 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000140
141 const GRState *state = C.getState();
142
143 SVal LHSVal = state->getSVal(LHS);
144 SVal RHSVal = state->getSVal(RHS);
145
146 // If either value is unknown, we can't be 100% sure of all paths.
147 if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
148 A = Impossible;
149 return;
150 }
151 BinaryOperator::Opcode Op = B->getOpcode();
152
153 // Dereference the LHS SVal if this is an assign operation
154 switch (Op) {
155 default:
156 break;
157
158 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000159 case BO_AddAssign:
160 case BO_SubAssign:
161 case BO_MulAssign:
162 case BO_DivAssign:
163 case BO_AndAssign:
164 case BO_OrAssign:
165 case BO_XorAssign:
166 case BO_ShlAssign:
167 case BO_ShrAssign:
168 case BO_Assign:
Tom Caredb2fa8a2010-07-06 21:43:29 +0000169 // Assign statements have one extra level of indirection
170 if (!isa<Loc>(LHSVal)) {
171 A = Impossible;
172 return;
173 }
174 LHSVal = state->getSVal(cast<Loc>(LHSVal));
175 }
176
177
178 // We now check for various cases which result in an idempotent operation.
179
180 // x op x
181 switch (Op) {
182 default:
183 break; // We don't care about any other operators.
184
185 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000186 case BO_Assign:
Tom Care6216dc02010-08-30 19:25:43 +0000187 // x Assign x can be used to silence unused variable warnings intentionally.
188 // If this is a self assignment and the variable is referenced elsewhere,
189 // then it is a false positive.
190 if (isSelfAssign(LHS, RHS)) {
191 if (!isUnused(LHS, AC)) {
192 UpdateAssumption(A, Equal);
193 return;
194 }
195 else {
196 A = Impossible;
197 return;
198 }
Tom Caredf4ca422010-07-16 20:41:41 +0000199 }
200
John McCall2de56d12010-08-25 11:45:40 +0000201 case BO_SubAssign:
202 case BO_DivAssign:
203 case BO_AndAssign:
204 case BO_OrAssign:
205 case BO_XorAssign:
206 case BO_Sub:
207 case BO_Div:
208 case BO_And:
209 case BO_Or:
210 case BO_Xor:
211 case BO_LOr:
212 case BO_LAnd:
Tom Care9edd4d02010-08-27 22:50:47 +0000213 case BO_EQ:
214 case BO_NE:
Tom Caredb34ab72010-08-23 19:51:57 +0000215 if (LHSVal != RHSVal || LHSContainsFalsePositive
216 || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000217 break;
218 UpdateAssumption(A, Equal);
219 return;
220 }
221
222 // x op 1
223 switch (Op) {
224 default:
225 break; // We don't care about any other operators.
226
227 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000228 case BO_MulAssign:
229 case BO_DivAssign:
230 case BO_Mul:
231 case BO_Div:
232 case BO_LOr:
233 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000234 if (!RHSVal.isConstant(1) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000235 break;
236 UpdateAssumption(A, RHSis1);
237 return;
238 }
239
240 // 1 op x
241 switch (Op) {
242 default:
243 break; // We don't care about any other operators.
244
245 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000246 case BO_MulAssign:
247 case BO_Mul:
248 case BO_LOr:
249 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000250 if (!LHSVal.isConstant(1) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000251 break;
252 UpdateAssumption(A, LHSis1);
253 return;
254 }
255
256 // x op 0
257 switch (Op) {
258 default:
259 break; // We don't care about any other operators.
260
261 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000262 case BO_AddAssign:
263 case BO_SubAssign:
264 case BO_MulAssign:
265 case BO_AndAssign:
266 case BO_OrAssign:
267 case BO_XorAssign:
268 case BO_Add:
269 case BO_Sub:
270 case BO_Mul:
271 case BO_And:
272 case BO_Or:
273 case BO_Xor:
274 case BO_Shl:
275 case BO_Shr:
276 case BO_LOr:
277 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000278 if (!RHSVal.isConstant(0) || RHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000279 break;
280 UpdateAssumption(A, RHSis0);
281 return;
282 }
283
284 // 0 op x
285 switch (Op) {
286 default:
287 break; // We don't care about any other operators.
288
289 // Fall through intentional
John McCall2de56d12010-08-25 11:45:40 +0000290 //case BO_AddAssign: // Common false positive
291 case BO_SubAssign: // Check only if unsigned
292 case BO_MulAssign:
293 case BO_DivAssign:
294 case BO_AndAssign:
295 //case BO_OrAssign: // Common false positive
296 //case BO_XorAssign: // Common false positive
297 case BO_ShlAssign:
298 case BO_ShrAssign:
299 case BO_Add:
300 case BO_Sub:
301 case BO_Mul:
302 case BO_Div:
303 case BO_And:
304 case BO_Or:
305 case BO_Xor:
306 case BO_Shl:
307 case BO_Shr:
308 case BO_LOr:
309 case BO_LAnd:
Tom Caredb34ab72010-08-23 19:51:57 +0000310 if (!LHSVal.isConstant(0) || LHSContainsFalsePositive)
Tom Caredb2fa8a2010-07-06 21:43:29 +0000311 break;
312 UpdateAssumption(A, LHSis0);
313 return;
314 }
315
316 // If we get to this point, there has been a valid use of this operation.
317 A = Impossible;
318}
319
320void IdempotentOperationChecker::VisitEndAnalysis(ExplodedGraph &G,
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000321 BugReporter &BR,
Tom Carebc42c532010-08-03 01:55:07 +0000322 GRExprEngine &Eng) {
Tom Caredb2fa8a2010-07-06 21:43:29 +0000323 // Iterate over the hash to see if we have any paths with definite
324 // idempotent operations.
Tom Carea7a8a452010-08-12 22:45:47 +0000325 for (AssumptionMap::const_iterator i = hash.begin(); i != hash.end(); ++i) {
326 // Unpack the hash contents
327 const std::pair<Assumption, AnalysisContext *> &Data = i->second;
328 const Assumption &A = Data.first;
329 AnalysisContext *AC = Data.second;
Ted Kremenek3e5637f2010-07-27 18:49:08 +0000330
Tom Carea7a8a452010-08-12 22:45:47 +0000331 const BinaryOperator *B = i->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000332
Tom Carea7a8a452010-08-12 22:45:47 +0000333 if (A == Impossible)
334 continue;
335
336 // If the analyzer did not finish, check to see if we can still emit this
337 // warning
338 if (Eng.hasWorkRemaining()) {
339 const CFGStmtMap *CBM = CFGStmtMap::Build(AC->getCFG(),
340 &AC->getParentMap());
341
342 // If we can trace back
343 if (!PathWasCompletelyAnalyzed(AC->getCFG(),
344 CBM->getBlock(B),
345 Eng.getCoreEngine()))
346 continue;
347
348 delete CBM;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000349 }
Tom Carea7a8a452010-08-12 22:45:47 +0000350
351 // Select the error message.
352 llvm::SmallString<128> buf;
353 llvm::raw_svector_ostream os(buf);
354 switch (A) {
355 case Equal:
John McCall2de56d12010-08-25 11:45:40 +0000356 if (B->getOpcode() == BO_Assign)
Tom Carea7a8a452010-08-12 22:45:47 +0000357 os << "Assigned value is always the same as the existing value";
358 else
359 os << "Both operands to '" << B->getOpcodeStr()
360 << "' always have the same value";
361 break;
362 case LHSis1:
363 os << "The left operand to '" << B->getOpcodeStr() << "' is always 1";
364 break;
365 case RHSis1:
366 os << "The right operand to '" << B->getOpcodeStr() << "' is always 1";
367 break;
368 case LHSis0:
369 os << "The left operand to '" << B->getOpcodeStr() << "' is always 0";
370 break;
371 case RHSis0:
372 os << "The right operand to '" << B->getOpcodeStr() << "' is always 0";
373 break;
374 case Possible:
375 llvm_unreachable("Operation was never marked with an assumption");
376 case Impossible:
377 llvm_unreachable(0);
378 }
379
380 // Create the SourceRange Arrays
381 SourceRange S[2] = { i->first->getLHS()->getSourceRange(),
382 i->first->getRHS()->getSourceRange() };
383 BR.EmitBasicReport("Idempotent operation", "Dead code",
384 os.str(), i->first->getOperatorLoc(), S, 2);
Tom Caredb2fa8a2010-07-06 21:43:29 +0000385 }
386}
387
388// Updates the current assumption given the new assumption
389inline void IdempotentOperationChecker::UpdateAssumption(Assumption &A,
390 const Assumption &New) {
Tom Cared8421ed2010-08-27 22:35:28 +0000391// If the assumption is the same, there is nothing to do
392 if (A == New)
393 return;
394
Tom Caredb2fa8a2010-07-06 21:43:29 +0000395 switch (A) {
396 // If we don't currently have an assumption, set it
397 case Possible:
398 A = New;
399 return;
400
401 // If we have determined that a valid state happened, ignore the new
402 // assumption.
403 case Impossible:
404 return;
405
406 // Any other case means that we had a different assumption last time. We don't
407 // currently support mixing assumptions for diagnostic reasons, so we set
408 // our assumption to be impossible.
409 default:
410 A = Impossible;
411 return;
412 }
413}
414
Tom Care6216dc02010-08-30 19:25:43 +0000415// Check for a statement where a variable is self assigned to possibly avoid an
416// unused variable warning.
417bool IdempotentOperationChecker::isSelfAssign(const Expr *LHS, const Expr *RHS) {
Tom Caredf4ca422010-07-16 20:41:41 +0000418 LHS = LHS->IgnoreParenCasts();
419 RHS = RHS->IgnoreParenCasts();
420
421 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS);
422 if (!LHS_DR)
423 return false;
424
Tom Careef52bcb2010-08-24 21:09:07 +0000425 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
426 if (!VD)
Tom Caredf4ca422010-07-16 20:41:41 +0000427 return false;
428
429 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS);
430 if (!RHS_DR)
431 return false;
432
Tom Careef52bcb2010-08-24 21:09:07 +0000433 if (VD != RHS_DR->getDecl())
434 return false;
435
Tom Care6216dc02010-08-30 19:25:43 +0000436 return true;
437}
438
439// Returns true if the Expr points to a VarDecl that is not read anywhere
440// outside of self-assignments.
441bool IdempotentOperationChecker::isUnused(const Expr *E,
442 AnalysisContext *AC) {
443 if (!E)
444 return false;
445
446 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
447 if (!DR)
448 return false;
449
450 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
451 if (!VD)
452 return false;
453
Tom Careef52bcb2010-08-24 21:09:07 +0000454 if (AC->getPseudoConstantAnalysis()->wasReferenced(VD))
455 return false;
456
457 return true;
Tom Caredf4ca422010-07-16 20:41:41 +0000458}
459
460// Check for self casts truncating/extending a variable
461bool IdempotentOperationChecker::isTruncationExtensionAssignment(
462 const Expr *LHS,
463 const Expr *RHS) {
464
465 const DeclRefExpr *LHS_DR = dyn_cast<DeclRefExpr>(LHS->IgnoreParenCasts());
466 if (!LHS_DR)
467 return false;
468
469 const VarDecl *VD = dyn_cast<VarDecl>(LHS_DR->getDecl());
470 if (!VD)
471 return false;
472
473 const DeclRefExpr *RHS_DR = dyn_cast<DeclRefExpr>(RHS->IgnoreParenCasts());
474 if (!RHS_DR)
475 return false;
476
477 if (VD != RHS_DR->getDecl())
478 return false;
479
480 return dyn_cast<DeclRefExpr>(RHS->IgnoreParens()) == NULL;
481}
482
Tom Carea7a8a452010-08-12 22:45:47 +0000483// Returns false if a path to this block was not completely analyzed, or true
484// otherwise.
485bool IdempotentOperationChecker::PathWasCompletelyAnalyzed(
486 const CFG *C,
487 const CFGBlock *CB,
488 const GRCoreEngine &CE) {
489 std::deque<const CFGBlock *> WorkList;
490 llvm::SmallSet<unsigned, 8> Aborted;
491 llvm::SmallSet<unsigned, 128> Visited;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000492
Tom Carea7a8a452010-08-12 22:45:47 +0000493 // Create a set of all aborted blocks
494 typedef GRCoreEngine::BlocksAborted::const_iterator AbortedIterator;
495 for (AbortedIterator I = CE.blocks_aborted_begin(),
496 E = CE.blocks_aborted_end(); I != E; ++I) {
497 const BlockEdge &BE = I->first;
Tom Caredb2fa8a2010-07-06 21:43:29 +0000498
Tom Carea7a8a452010-08-12 22:45:47 +0000499 // The destination block on the BlockEdge is the first block that was not
500 // analyzed.
501 Aborted.insert(BE.getDst()->getBlockID());
Ted Kremenek45329312010-07-17 00:40:32 +0000502 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000503
Tom Carea7a8a452010-08-12 22:45:47 +0000504 // Save the entry block ID for early exiting
505 unsigned EntryBlockID = C->getEntry().getBlockID();
Tom Caredb2fa8a2010-07-06 21:43:29 +0000506
Tom Carea7a8a452010-08-12 22:45:47 +0000507 // Create initial node
508 WorkList.push_back(CB);
509
510 while (!WorkList.empty()) {
511 const CFGBlock *Head = WorkList.front();
512 WorkList.pop_front();
513 Visited.insert(Head->getBlockID());
514
515 // If we found the entry block, then there exists a path from the target
516 // node to the entry point of this function -> the path was completely
517 // analyzed.
518 if (Head->getBlockID() == EntryBlockID)
519 return true;
520
521 // If any of the aborted blocks are on the path to the beginning, then all
522 // paths to this block were not analyzed.
523 if (Aborted.count(Head->getBlockID()))
524 return false;
525
526 // Add the predecessors to the worklist unless we have already visited them
527 for (CFGBlock::const_pred_iterator I = Head->pred_begin();
528 I != Head->pred_end(); ++I)
529 if (!Visited.count((*I)->getBlockID()))
530 WorkList.push_back(*I);
531 }
532
533 // If we get to this point, there is no connection to the entry block or an
534 // aborted block. This path is unreachable and we can report the error.
535 return true;
536}
537
538// Recursive function that determines whether an expression contains any element
539// that varies. This could be due to a compile-time constant like sizeof. An
540// expression may also involve a variable that behaves like a constant. The
541// function returns true if the expression varies, and false otherwise.
Tom Care245adab2010-08-18 21:17:24 +0000542bool IdempotentOperationChecker::CanVary(const Expr *Ex,
543 AnalysisContext *AC) {
Tom Carea7a8a452010-08-12 22:45:47 +0000544 // Parentheses and casts are irrelevant here
545 Ex = Ex->IgnoreParenCasts();
546
547 if (Ex->getLocStart().isMacroID())
548 return false;
549
550 switch (Ex->getStmtClass()) {
551 // Trivially true cases
552 case Stmt::ArraySubscriptExprClass:
553 case Stmt::MemberExprClass:
554 case Stmt::StmtExprClass:
555 case Stmt::CallExprClass:
556 case Stmt::VAArgExprClass:
557 case Stmt::ShuffleVectorExprClass:
558 return true;
559 default:
560 return true;
561
562 // Trivially false cases
563 case Stmt::IntegerLiteralClass:
564 case Stmt::CharacterLiteralClass:
565 case Stmt::FloatingLiteralClass:
566 case Stmt::PredefinedExprClass:
567 case Stmt::ImaginaryLiteralClass:
568 case Stmt::StringLiteralClass:
569 case Stmt::OffsetOfExprClass:
570 case Stmt::CompoundLiteralExprClass:
571 case Stmt::AddrLabelExprClass:
572 case Stmt::TypesCompatibleExprClass:
573 case Stmt::GNUNullExprClass:
574 case Stmt::InitListExprClass:
575 case Stmt::DesignatedInitExprClass:
576 case Stmt::BlockExprClass:
577 case Stmt::BlockDeclRefExprClass:
578 return false;
579
580 // Cases requiring custom logic
581 case Stmt::SizeOfAlignOfExprClass: {
582 const SizeOfAlignOfExpr *SE = cast<const SizeOfAlignOfExpr>(Ex);
583 if (!SE->isSizeOf())
584 return false;
585 return SE->getTypeOfArgument()->isVariableArrayType();
586 }
587 case Stmt::DeclRefExprClass:
Tom Care6216dc02010-08-30 19:25:43 +0000588 // Check for constants/pseudoconstants
Tom Care245adab2010-08-18 21:17:24 +0000589 return !isConstantOrPseudoConstant(cast<DeclRefExpr>(Ex), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000590
591 // The next cases require recursion for subexpressions
592 case Stmt::BinaryOperatorClass: {
593 const BinaryOperator *B = cast<const BinaryOperator>(Ex);
Tom Care245adab2010-08-18 21:17:24 +0000594 return CanVary(B->getRHS(), AC)
595 || CanVary(B->getLHS(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000596 }
597 case Stmt::UnaryOperatorClass: {
598 const UnaryOperator *U = cast<const UnaryOperator>(Ex);
Eli Friedmande7e6622010-08-13 01:36:11 +0000599 // Handle trivial case first
Tom Carea7a8a452010-08-12 22:45:47 +0000600 switch (U->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +0000601 case UO_Extension:
Tom Carea7a8a452010-08-12 22:45:47 +0000602 return false;
603 default:
Tom Care245adab2010-08-18 21:17:24 +0000604 return CanVary(U->getSubExpr(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000605 }
606 }
607 case Stmt::ChooseExprClass:
Tom Care245adab2010-08-18 21:17:24 +0000608 return CanVary(cast<const ChooseExpr>(Ex)->getChosenSubExpr(
609 AC->getASTContext()), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000610 case Stmt::ConditionalOperatorClass:
Tom Care6216dc02010-08-30 19:25:43 +0000611 return CanVary(cast<const ConditionalOperator>(Ex)->getCond(), AC);
Tom Carea7a8a452010-08-12 22:45:47 +0000612 }
Tom Caredb2fa8a2010-07-06 21:43:29 +0000613}
614
Tom Care245adab2010-08-18 21:17:24 +0000615// Returns true if a DeclRefExpr is or behaves like a constant.
616bool IdempotentOperationChecker::isConstantOrPseudoConstant(
Tom Care6216dc02010-08-30 19:25:43 +0000617 const DeclRefExpr *DR,
618 AnalysisContext *AC) {
Tom Care245adab2010-08-18 21:17:24 +0000619 // Check if the type of the Decl is const-qualified
620 if (DR->getType().isConstQualified())
621 return true;
622
Tom Care50e8ac22010-08-16 21:43:52 +0000623 // Check for an enum
624 if (isa<EnumConstantDecl>(DR->getDecl()))
625 return true;
626
Tom Caredb34ab72010-08-23 19:51:57 +0000627 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
628 if (!VD)
Tom Care245adab2010-08-18 21:17:24 +0000629 return true;
630
Tom Caredb34ab72010-08-23 19:51:57 +0000631 // Check if the Decl behaves like a constant. This check also takes care of
632 // static variables, which can only change between function calls if they are
633 // modified in the AST.
634 PseudoConstantAnalysis *PCA = AC->getPseudoConstantAnalysis();
635 if (PCA->isPseudoConstant(VD))
636 return true;
637
638 return false;
639}
640
641// Recursively find any substatements containing VarDecl's with storage other
642// than local
643bool IdempotentOperationChecker::containsNonLocalVarDecl(const Stmt *S) {
644 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
645
646 if (DR)
647 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
648 if (!VD->hasLocalStorage())
649 return true;
650
651 for (Stmt::const_child_iterator I = S->child_begin(); I != S->child_end();
652 ++I)
653 if (const Stmt *child = *I)
654 if (containsNonLocalVarDecl(child))
655 return true;
656
Tom Care50e8ac22010-08-16 21:43:52 +0000657 return false;
658}